983 lines · 30.6 KB · Text
RawDownload
.. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.2-no-invariants-only ===========================Lockless Ring Buffer Design=========================== Copyright 2009 Red Hat Inc. :Author:   Steven Rostedt <srostedt@redhat.com>:License:  The GNU Free Documentation License, Version 1.2           (dual licensed under the GPL v2):Reviewers:  Mathieu Desnoyers, Huang Ying, Hidetoshi Seto,	     and Frederic Weisbecker.  Written for: 2.6.31 Terminology used in this Document--------------------------------- tail	- where new writes happen in the ring buffer. head	- where new reads happen in the ring buffer. producer	- the task that writes into the ring buffer (same as writer) writer	- same as producer consumer	- the task that reads from the buffer (same as reader) reader	- same as consumer. reader_page	- A page outside the ring buffer used solely (for the most part)	  by the reader. head_page	- a pointer to the page that the reader will use next tail_page	- a pointer to the page that will be written to next commit_page	- a pointer to the page with the last finished non-nested write. cmpxchg	- hardware-assisted atomic transaction that performs the following:: 	    A = B if previous A == C 	    R = cmpxchg(A, C, B) is saying that we replace A with B if and only		if current A is equal to C, and we put the old (current)		A into R 	    R gets the previous A regardless if A is updated with B or not. 	  To see if the update was successful a compare of ``R == C``	  may be used. The Generic Ring Buffer----------------------- The ring buffer can be used in either an overwrite mode or inproducer/consumer mode. Producer/consumer mode is where if the producer were to fill up thebuffer before the consumer could free up anything, the producerwill stop writing to the buffer. This will lose most recent events. Overwrite mode is where if the producer were to fill up the bufferbefore the consumer could free up anything, the producer willoverwrite the older data. This will lose the oldest events. No two writers can write at the same time (on the same per-cpu buffer),but a writer may interrupt another writer, but it must finish writingbefore the previous writer may continue. This is very important to thealgorithm. The writers act like a "stack". The way interrupts worksenforces this behavior::    writer1 start     <preempted> writer2 start         <preempted> writer3 start                     writer3 finishes                 writer2 finishes  writer1 finishes This is very much like a writer being preempted by an interrupt andthe interrupt doing a write as well. Readers can happen at any time. But no two readers may run at thesame time, nor can a reader preempt/interrupt another reader. A readercannot preempt/interrupt a writer, but it may read/consume from thebuffer at the same time as a writer is writing, but the reader must beon another processor to do so. A reader may read on its own processorand can be preempted by a writer. A writer can preempt a reader, but a reader cannot preempt a writer.But a reader can read the buffer at the same time (on another processor)as a writer. The ring buffer is made up of a list of pages held together by a linked list. At initialization a reader page is allocated for the reader that is notpart of the ring buffer. The head_page, tail_page and commit_page are all initialized to pointto the same page. The reader page is initialized to have its next pointer pointing tothe head page, and its previous pointer pointing to a page beforethe head page. The reader has its own page to use. At start up time, this page isallocated but is not attached to the list. When the reader wantsto read from the buffer, if its page is empty (like it is on start-up),it will swap its page with the head_page. The old reader page willbecome part of the ring buffer and the head_page will be removed.The page after the inserted page (old reader_page) will become thenew head page. Once the new page is given to the reader, the reader could do whatit wants with it, as long as a writer has left that page. A sample of how the reader page is swapped: Note this does notshow the head page in the buffer, it is for demonstrating a swaponly. ::   +------+  |reader|          RING BUFFER  |page  |  +------+                  +---+   +---+   +---+                  |   |-->|   |-->|   |                  |   |<--|   |<--|   |                  +---+   +---+   +---+                   ^ |             ^ |                   | +-------------+ |                   +-----------------+    +------+  |reader|          RING BUFFER  |page  |-------------------+  +------+                   v    |             +---+   +---+   +---+    |             |   |-->|   |-->|   |    |             |   |<--|   |<--|   |<-+    |             +---+   +---+   +---+  |    |              ^ |             ^ |   |    |              | +-------------+ |   |    |              +-----------------+   |    +------------------------------------+   +------+  |reader|          RING BUFFER  |page  |-------------------+  +------+ <---------------+ v    |  ^          +---+   +---+   +---+    |  |          |   |-->|   |-->|   |    |  |          |   |   |   |<--|   |<-+    |  |          +---+   +---+   +---+  |    |  |             |             ^ |   |    |  |             +-------------+ |   |    |  +-----------------------------+   |    +------------------------------------+   +------+  |buffer|          RING BUFFER  |page  |-------------------+  +------+ <---------------+ v    |  ^          +---+   +---+   +---+    |  |          |   |   |   |-->|   |    |  |  New     |   |   |   |<--|   |<-+    |  | Reader   +---+   +---+   +---+  |    |  |  page ----^                 |   |    |  |                             |   |    |  +-----------------------------+   |    +------------------------------------+   It is possible that the page swapped is the commit page and the tail page,if what is in the ring buffer is less than what is held in a buffer page. ::             reader page    commit page   tail page                |              |             |                v              |             |               +---+           |             |               |   |<----------+             |               |   |<------------------------+               |   |------+               +---+      |                          |                          v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+ This case is still valid for this algorithm.When the writer leaves the page, it simply goes into the ring buffersince the reader page still points to the next location in the ringbuffer.  The main pointers:   reader page	    - The page used solely by the reader and is not part              of the ring buffer (may be swapped in)   head page	    - the next page in the ring buffer that will be swapped              with the reader page.   tail page	    - the page where the next write will take place.   commit page	    - the page that last finished a write. The commit page only is updated by the outermost writer in thewriter stack. A writer that preempts another writer will not move thecommit page. When data is written into the ring buffer, a position is reservedin the ring buffer and passed back to the writer. When the writeris finished writing data into that position, it commits the write. Another write (or a read) may take place at anytime during thistransaction. If another write happens it must finish before continuingwith the previous write.     Write reserve::        Buffer page      +---------+      |written  |      +---------+  <--- given back to writer (current commit)      |reserved |      +---------+ <--- tail pointer      | empty   |      +---------+    Write commit::        Buffer page      +---------+      |written  |      +---------+      |written  |      +---------+  <--- next position for write (current commit)      | empty   |      +---------+   If a write happens after the first reserve::        Buffer page      +---------+      |written  |      +---------+  <-- current commit      |reserved |      +---------+  <--- given back to second writer      |reserved |      +---------+ <--- tail pointer   After second writer commits::         Buffer page      +---------+      |written  |      +---------+  <--(last full commit)      |reserved |      +---------+      |pending  |      |commit   |      +---------+ <--- tail pointer   When the first writer commits::        Buffer page      +---------+      |written  |      +---------+      |written  |      +---------+      |written  |      +---------+  <--(last full commit and tail pointer)  The commit pointer points to the last write location that wascommitted without preempting another write. When a write thatpreempted another write is committed, it only becomes a pending commitand will not be a full commit until all writes have been committed. The commit page points to the page that has the last full commit.The tail page points to the page with the last write (beforecommitting). The tail page is always equal to or after the commit page. It maybe several pages ahead. If the tail page catches up to the commitpage then no more writes may take place (regardless of the modeof the ring buffer: overwrite and produce/consumer). The order of pages is::  head page commit page tail page Possible scenario::                                tail page    head page         commit page  |        |                 |        |        v                 v        v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+ There is a special case that the head page is after either the commit pageand possibly the tail page. That is when the commit (and tail) page has beenswapped with the reader page. This is because the head page is alwayspart of the ring buffer, but the reader page is not. Whenever therehas been less than a full page that has been committed inside the ring buffer,and a reader swaps out a page, it will be swapping out the commit page. ::             reader page    commit page   tail page                |              |             |                v              |             |               +---+           |             |               |   |<----------+             |               |   |<------------------------+               |   |------+               +---+      |                          |                          v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+                          ^                          |                      head page  In this case, the head page will not move when the tail and commitmove back into the ring buffer. The reader cannot swap a page into the ring buffer if the commit pageis still on that page. If the read meets the last commit (real commitnot pending or reserved), then there is nothing more to read.The buffer is considered empty until another full commit finishes. When the tail meets the head page, if the buffer is in overwrite mode,the head page will be pushed ahead one. If the buffer is in producer/consumermode, the write will fail. Overwrite mode::               tail page                 |                 v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+                          ^                          |                      head page                tail page                 |                 v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+                                   ^                                   |                               head page                        tail page                          |                          v      +---+    +---+    +---+    +---+  <---|   |--->|   |--->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+                                   ^                                   |                               head page Note, the reader page will still point to the previous head page.But when a swap takes place, it will use the most recent head page.  Making the Ring Buffer Lockless:-------------------------------- The main idea behind the lockless algorithm is to combine the movingof the head_page pointer with the swapping of pages with the reader.State flags are placed inside the pointer to the page. To do this,each page must be aligned in memory by 4 bytes. This will allow the 2least significant bits of the address to be used as flags, sincethey will always be zero for the address. To get the address,simply mask out the flags::   MASK = ~3   address & MASK Two flags will be kept by these two bits:    HEADER	- the page being pointed to is a head page    UPDATE	- the page being pointed to is being updated by a writer          and was or is about to be a head page. :: 	      reader page		  |		  v		+---+		|   |------+		+---+      |			    |			    v	+---+    +---+    +---+    +---+    <---|   |--->|   |-H->|   |--->|   |--->    --->|   |<---|   |<---|   |<---|   |<---	+---+    +---+    +---+    +---+  The above pointer "-H->" would have the HEADER flag set. That isthe next page is the next page to be swapped out by the reader.This pointer means the next page is the head page. When the tail page meets the head pointer, it will use cmpxchg tochange the pointer to the UPDATE state::                tail page                 |                 v      +---+    +---+    +---+    +---+  <---|   |--->|   |-H->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+               tail page                 |                 v      +---+    +---+    +---+    +---+  <---|   |--->|   |-U->|   |--->|   |--->  --->|   |<---|   |<---|   |<---|   |<---      +---+    +---+    +---+    +---+ "-U->" represents a pointer in the UPDATE state. Any access to the reader will need to take some sort of lock to serializethe readers. But the writers will never take a lock to write to thering buffer. This means we only need to worry about a single reader,and writes only preempt in "stack" formation. When the reader tries to swap the page with the ring buffer, itwill also use cmpxchg. If the flag bit in the pointer to thehead page does not have the HEADER flag set, the compare will failand the reader will need to look for the new head page and try again.Note, the flags UPDATE and HEADER are never set at the same time. The reader swaps the reader page as follows::   +------+  |reader|          RING BUFFER  |page  |  +------+                  +---+    +---+    +---+

Lines 1–500 of 983.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t