요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
.. 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 <[email protected]>
: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 in
producer/consumer mode.
Producer/consumer mode is where if the producer were to fill up the
buffer before the consumer could free up anything, the producer
will stop writing to the buffer. This will lose most recent events.
Overwrite mode is where if the producer were to fill up the buffer
before the consumer could free up anything, the producer will
overwrite 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 writing
before the previous writer may continue. This is very important to the
algorithm. The writers act like a "stack". The way interrupts works
enforces 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 and
the interrupt doing a write as well.
Readers can happen at any time. But no two readers may run at the
same time, nor can a reader preempt/interrupt another reader. A reader
cannot preempt/interrupt a writer, but it may read/consume from the
buffer at the same time as a writer is writing, but the reader must be
on another processor to do so. A reader may read on its own processor
and 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 not
part of the ring buffer.
The head_page, tail_page and commit_page are all initialized to point
to the same page.
The reader page is initialized to have its next pointer pointing to
the head page, and its previous pointer pointing to a page before
the head page.
The reader has its own page to use. At start up time, this page is
allocated but is not attached to the list. When the reader wants
to 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 will
become part of the ring buffer and the head_page will be removed.
The page after the inserted page (old reader_page) will become the
new head page.
Once the new page is given to the reader, the reader could do what
it wants with it, as long as a writer has left that page.
A sample of how the reader page is swapped: Note this does not
show the head page in the buffer, it is for demonstrating a swap
only.
::
+------+
|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 buffer
since the reader page still points to the next location in the ring
buffer.
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 the
writer stack. A writer that preempts another writer will not move the
commit page.
When data is written into the ring buffer, a position is reserved
in the ring buffer and passed back to the writer. When the writer
is finished writing data into that position, it commits the write.
Another write (or a read) may take place at anytime during this
transaction. If another write happens it must finish before continuing
with 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 was
committed without preempting another write. When a write that
preempted another write is committed, it only becomes a pending commit
and 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 (before
committing).
The tail page is always equal to or after the commit page. It may
be several pages ahead. If the tail page catches up to the commit
page then no more writes may take place (regardless of the mode
of 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 page
and possibly the tail page. That is when the commit (and tail) page has been
swapped with the reader page. This is because the head page is always
part of the ring buffer, but the reader page is not. Whenever there
has 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 commit
move back into the ring buffer.
The reader cannot swap a page into the ring buffer if the commit page
is still on that page. If the read meets the last commit (real commit
not 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/consumer
mode, 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 moving
of 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 2
least significant bits of the address to be used as flags, since
they 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 is
the 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 to
change 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 serialize
the readers. But the writers will never take a lock to write to the
ring 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, it
will also use cmpxchg. If the flag bit in the pointer to the
head page does not have the HEADER flag set, the compare will fail
and 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 |
+------+
+---+ +---+ +---+
| |--->| |--->| |
| |<---| |<---| |
+---+ +---+ +---+
^ | ^ |
| +---------------+ |
+-----H-------------+
The reader sets the reader page next pointer as HEADER to the page after
the head page::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ v
| +---+ +---+ +---+
| | |--->| |--->| |
| | |<---| |<---| |<-+
| +---+ +---+ +---+ |
| ^ | ^ | |
| | +---------------+ | |
| +-----H-------------+ |
+--------------------------------------+
It does a cmpxchg with the pointer to the previous head page to make it
point to the reader page. Note that the new pointer does not have the HEADER
flag set. This action atomically moves the head page forward::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ v
| ^ +---+ +---+ +---+
| | | |-->| |-->| |
| | | |<--| |<--| |<-+
| | +---+ +---+ +---+ |
| | | ^ | |
| | +-------------+ | |
| +-----------------------------+ |
+------------------------------------+
After the new head page is set, the previous pointer of the head page is
updated to the reader page::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | |-->| |-->| |
| | | | | |<--| |<-+
| | +---+ +---+ +---+ |
| | | ^ | |
| | +-------------+ | |
| +-----------------------------+ |
+------------------------------------+
+------+
|buffer| RING BUFFER
|page |-------H-----------+ <--- New head page
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | | | |-->| |
| | New | | | |<--| |<-+
| | Reader +---+ +---+ +---+ |
| | page ----^ | |
| | | |
| +-----------------------------+ |
+------------------------------------+
Another important point: The page that the reader page points back to
by its previous pointer (the one that now points to the new head page)
never points back to the reader page. That is because the reader page is
not part of the ring buffer. Traversing the ring buffer via the next pointers
will always stay in the ring buffer. Traversing the ring buffer via the
prev pointers may not.
Note, the way to determine a reader page is simply by examining the previous
pointer of the page. If the next pointer of the previous page does not
point back to the original page, then the original page is a reader page::
+--------+
| reader | next +----+
| page |-------->| |<====== (buffer page)
+--------+ +----+
| | ^
| v | next
prev | +----+
+------------->| |
+----+
The way the head page moves forward:
When the tail page meets the head page and the buffer is in overwrite mode
and more writes take place, the head page must be moved forward before the
writer may move the tail page. The way this is done is that the writer
performs a cmpxchg to convert the pointer to the head page from the HEADER
flag to have the UPDATE flag set. Once this is done, the reader will
not be able to swap the head page from the buffer, nor will it be able to
move the head page, until the writer is finished with the move.
This eliminates any races that the reader can have on the writer. The reader
must spin, and this is why the reader cannot preempt the writer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The following page will be made into the new head page::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the new head page has been set, we can set the old head page
pointer back to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the head page has been moved, the tail page may now move forward::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The above are the trivial updates. Now for the more complex scenarios.
As stated before, if enough writes preempt the first write, the
tail page may make it all the way around the buffer and meet the commit
page. At this time, we must start dropping writes (usually with some kind
of warning to the user). But what happens if the commit was still on the
reader page? The commit page is not part of the ring buffer. The tail page
must account for this::
reader page commit page
| |
v |
+---+ |
| |<----------+
| |
| |------+
+---+ |
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
^
|
tail page
If the tail page were to simply push the head page forward, the commit when
leaving the reader page would not be pointing to the correct page.
The solution to this is to test if the commit page is on the reader page
before pushing the head page. If it is, then it can be assumed that the
tail page wrapped the buffer, and we must drop new writes.
This is not a race condition, because the commit page can only be moved
by the outermost writer (the writer that was preempted).
This means that the commit will not move while a writer is moving the
tail page. The reader cannot swap the reader page if it is also being
used as the commit page. The reader can simply check that the commit
is off the reader page. Once the commit page leaves the reader page
it will never go back on it unless a reader does another swap with the
buffer page that is also the commit page.
Nested writes
-------------
In the pushing forward of the tail page we must first push forward
the head page if the head page is the next page. If the head page
is not the next page, the tail page is simply updated with a cmpxchg.
Only writers move the tail page. This must be done atomically to protect
against nested writers::
temp_page = tail_page
next_page = temp_page->next
cmpxchg(tail_page, temp_page, next_page)
The above will update the tail page if it is still pointing to the expected
page. If this fails, a nested write pushed it forward, the current write
does not need to push it::
temp page
|
v
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Nested write comes in and moves the tail page forward::
tail page (moved by nested writer)
temp page |
| |
v v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The above would fail the cmpxchg, but since the tail page has already
been moved forward, the writer will just try again to reserve storage
on the new tail page.
But the moving of the head page is a bit more complex::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The write converts the head page pointer to UPDATE::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But if a nested writer preempts here, it will see that the next
page is a head page, but it is also nested. It will detect that
it is nested and will save that information. The detection is the
fact that it sees the UPDATE flag instead of a HEADER or NORMAL
pointer.
The nested writer will set the new head page pointer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But it will not reset the update back to normal. Only the writer
that converted a pointer from HEAD to UPDATE will convert it back
to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the nested writer finishes, the outermost writer will convert
the UPDATE pointer to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
It can be even more complex if several nested writes came in and moved
the tail page ahead several pages::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The write converts the head page pointer to UPDATE::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Next writer comes in, and sees the update and sets up the new
head page::
(second writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The nested writer moves the tail page forward. But does not set the old
update page to NORMAL because it is not the outermost writer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Another writer preempts and sees the page after the tail page is a head page.
It changes it from HEAD to UPDATE::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-U->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The writer will move the head page forward::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-U->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But now that the third writer did change the HEAD flag to UPDATE it
will convert it to normal::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Then it will move the tail page, and return back to the second writer::
(second writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The second writer will fail to move the tail page because it was already
moved, so it will try again and add its data to the new tail page.
It will return to the first writer::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The first writer cannot know atomically if the tail page moved
while it updates the HEAD page. It will then update the head page to
what it thinks is the new head page::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Since the cmpxchg returns the old value of the pointer the first writer
will see it succeeded in updating the pointer from NORMAL to HEAD.
But as we can see, this is not good enough. It must also check to see
if the tail page is either where it use to be or on the next page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
If tail page != A and tail page != B, then it must reset the pointer
back to NORMAL. The fact that it only needs to worry about nested
writers means that it only needs to check this after setting the HEAD page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Now the writer can update the head page. This is also why the head page must
remain in UPDATE and only reset by the outermost writer. This prevents
the reader from seeing the incorrect head page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서 정보와 용어
1-65이 문서는 Red Hat Inc.가 2009년에 저작권을 보유한 Steven Rostedt의 글이며 GNU Free Documentation License 1.2와 GPL v2로 이중 라이선스된다. Mathieu Desnoyers, Huang Ying, Hidetoshi Seto, Frederic Weisbecker가 검토했으며 Linux 2.6.31을 대상으로 작성되었다.
쓰기·읽기 위치와 링 바깥의 reader page를 구분하는 문서의 용어를 정리한다.
`cmpxchg`는 하드웨어가 지원하는 원자적 트랜잭션이다. `R = cmpxchg(A, C, B)`는 현재 `A`가 `C`와 같을 때만 `A`를 `B`로 바꾸고, 갱신 성공 여부와 관계없이 이전 `A` 값을 `R`에 넣는다.
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.
따라서 `R == C`를 비교하면 갱신이 성공했는지 확인할 수 있다.
비교와 대입을 하나의 원자적 연산으로 수행하고 이전 값을 반환한다.
.. 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 <[email protected]>
: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.
일반 링 버퍼와 동시성 규칙
66-107링 버퍼는 overwrite 모드 또는 producer/consumer 모드로 사용할 수 있다.
consumer가 공간을 비우기 전에 producer가 버퍼를 채웠을 때의 정책이 다르다.
같은 CPU별 버퍼에서 두 writer가 동시에 쓸 수는 없다. 다만 한 writer를 다른 writer가 인터럽트할 수 있으며, 새 writer는 이전 writer가 계속하기 전에 반드시 쓰기를 끝내야 한다. 이 성질은 알고리즘의 핵심으로, writer들은 인터럽트 동작이 강제하는 스택처럼 행동한다.
writer1 start
<preempted> writer2 start
<preempted> writer3 start
writer3 finishes
writer2 finishes
writer1 finishes
나중에 진입한 writer가 먼저 완료되는 LIFO 순서를 지킨다.
이는 writer가 인터럽트에 의해 선점되고 그 인터럽트도 쓰기를 수행하는 상황과 같다.
reader는 언제든 실행될 수 있지만 두 reader가 동시에 실행되어서는 안 되며, 한 reader가 다른 reader를 선점하거나 인터럽트할 수도 없다. reader는 writer를 선점하거나 인터럽트할 수 없다. 다른 프로세서에서는 writer가 쓰는 동안 동시에 읽거나 소비할 수 있다. reader는 자기 프로세서에서 읽다가 writer에게 선점될 수 있다.
허용되는 선점과 병행 실행 조건을 정리한다.
The Generic Ring Buffer
-----------------------
The ring buffer can be used in either an overwrite mode or in
producer/consumer mode.
Producer/consumer mode is where if the producer were to fill up the
buffer before the consumer could free up anything, the producer
will stop writing to the buffer. This will lose most recent events.
Overwrite mode is where if the producer were to fill up the buffer
before the consumer could free up anything, the producer will
overwrite 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 writing
before the previous writer may continue. This is very important to the
algorithm. The writers act like a "stack". The way interrupts works
enforces 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 and
the interrupt doing a write as well.
Readers can happen at any time. But no two readers may run at the
same time, nor can a reader preempt/interrupt another reader. A reader
cannot preempt/interrupt a writer, but it may read/consume from the
buffer at the same time as a writer is writing, but the reader must be
on another processor to do so. A reader may read on its own processor
and 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.
초기화와 reader page 교환
108-190링 버퍼는 연결 리스트로 이어진 페이지 목록으로 구성된다. 초기화할 때 링 버퍼에 속하지 않는 reader 전용 페이지를 할당하고, `head_page`, `tail_page`, `commit_page`는 모두 같은 버퍼 페이지를 가리키게 한다.
reader page의 `next`는 head page를 가리키고 `previous`는 head page 바로 앞의 버퍼 페이지를 가리키도록 초기화한다. 시작 시 reader page는 할당되어 있지만 리스트에는 붙어 있지 않다.
reader가 읽으려 할 때 자기 페이지가 비어 있으면 reader page와 `head_page`를 교환한다. 이전 reader page는 링 버퍼의 일부가 되고, 기존 head page는 링에서 빠져 reader에게 전달된다. 삽입된 이전 reader page 다음의 페이지가 새 head page가 된다.
새 페이지가 reader에게 넘어간 뒤에는 writer가 그 페이지를 떠난 상태라는 조건 아래 reader가 자유롭게 사용할 수 있다. 원문의 연속 그림은 head page 자체의 역할을 모두 표시하기 위한 것이 아니라 이 교환만 설명한다.
링 바깥의 빈 reader page를 링에 넣고 현재 head page를 reader 전용 페이지로 꺼낸다.
원문의 네 단계 ASCII 그림을 역할 변화로 다시 구성했다.
원문의 단계별 화살표를 next와 previous 포인터 갱신 순서로 분리했다.
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 not
part of the ring buffer.
The head_page, tail_page and commit_page are all initialized to point
to the same page.
The reader page is initialized to have its next pointer pointing to
the head page, and its previous pointer pointing to a page before
the head page.
The reader has its own page to use. At start up time, this page is
allocated but is not attached to the list. When the reader wants
to 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 will
become part of the ring buffer and the head_page will be removed.
The page after the inserted page (old reader_page) will become the
new head page.
Once the new page is given to the reader, the reader could do what
it wants with it, as long as a writer has left that page.
A sample of how the reader page is swapped: Note this does not
show the head page in the buffer, it is for demonstrating a swap
only.
::
+------+
|reader| RING BUFFER
|page |
+------+
+---+ +---+ +---+
| |-->| |-->| |
| |<--| |<--| |
+---+ +---+ +---+
^ | ^ |
| +-------------+ |
+-----------------+
+------+
|reader| RING BUFFER
|page |-------------------+
+------+ v
| +---+ +---+ +---+
| | |-->| |-->| |
| | |<--| |<--| |<-+
| +---+ +---+ +---+ |
| ^ | ^ | |
| | +-------------+ | |
| +-----------------+ |
+------------------------------------+
+------+
|reader| RING BUFFER
|page |-------------------+
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | |-->| |-->| |
| | | | | |<--| |<-+
| | +---+ +---+ +---+ |
| | | ^ | |
| | +-------------+ | |
| +-----------------------------+ |
+------------------------------------+
+------+
|buffer| RING BUFFER
|page |-------------------+
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | | | |-->| |
| | New | | | |<--| |<-+
| | Reader +---+ +---+ +---+ |
| | page ----^ | |
| | | |
| +-----------------------------+ |
+------------------------------------+
commit·tail과 함께 교환되는 특수 사례
191-235링 버퍼에 커밋된 내용이 한 버퍼 페이지보다 적으면 교환되는 페이지가 `commit_page`이자 `tail_page`일 수 있다. 이 경우도 알고리즘상 유효하다. writer가 reader page였던 페이지를 떠나면 그 페이지는 링 버퍼로 들어가며, reader page의 연결은 여전히 링의 다음 위치를 가리킨다.
부분적으로 채워진 페이지를 reader가 꺼내도 writer가 빠져나갈 때 연결 관계가 링으로 복귀한다.
하나의 링 밖 페이지가 세 역할을 동시에 가질 때도 각 포인터의 의미는 유지된다.
reader와 writer가 공유하는 네 포인터의 책임을 구분한다.
`commit_page`는 writer 스택의 가장 바깥 writer만 갱신한다. 다른 writer를 선점한 중첩 writer는 commit 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 buffer
since the reader page still points to the next location in the ring
buffer.
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 the
writer stack. A writer that preempts another writer will not move the
commit page.
쓰기 예약과 전체 commit
236-318링 버퍼에 데이터를 쓸 때 먼저 위치를 예약해 writer에게 돌려준다. writer가 그 위치에 데이터를 모두 쓰면 쓰기를 commit한다. 이 트랜잭션 도중 다른 쓰기나 읽기가 언제든 발생할 수 있으며, 새 쓰기가 시작되면 이전 쓰기가 계속되기 전에 반드시 끝나야 한다.
예약 시 tail이 전진하고 commit이 끝나면 그 위치가 다음 쓰기 기준이 된다.
두 writer의 예약과 commit이 슬롯에 표시되는 상태를 분리했다.
첫 번째 writer가 예약한 뒤 두 번째 writer가 선점하면 두 번째 writer도 다음 공간을 예약한다. 두 번째 writer가 먼저 commit해도 그 기록은 `pending commit`일 뿐 `full commit`이 아니다. 첫 번째 writer가 commit해야 연속된 두 예약이 모두 written이 되고 마지막 full commit과 tail이 같은 끝 위치에 도달한다.
안쪽 writer의 commit은 바깥 writer가 끝날 때까지 보류된다.
commit pointer는 다른 쓰기를 선점하지 않고 commit된 마지막 쓰기 위치를 가리킨다. 선점해 들어온 writer가 commit하면 처음에는 pending commit이며, 모든 바깥 쓰기가 commit된 뒤에야 full commit이 된다.
`commit_page`는 마지막 full commit이 있는 페이지를 가리키고, `tail_page`는 아직 commit하기 전의 마지막 쓰기가 있는 페이지를 가리킨다. tail page는 언제나 commit page와 같거나 그 뒤에 있으며 여러 페이지 앞설 수 있다. tail이 링을 돌아 commit page를 따라잡으면 overwrite와 producer/consumer 어느 모드에서도 더 쓸 수 없다.
When data is written into the ring buffer, a position is reserved
in the ring buffer and passed back to the writer. When the writer
is finished writing data into that position, it commits the write.
Another write (or a read) may take place at anytime during this
transaction. If another write happens it must finish before continuing
with 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 was
committed without preempting another write. When a write that
preempted another write is committed, it only becomes a pending commit
and 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 (before
committing).
The tail page is always equal to or after the commit page. It may
be several pages ahead. If the tail page catches up to the commit
page then no more writes may take place (regardless of the mode
of the ring buffer: overwrite and produce/consumer).
페이지 순서와 head 충돌
319-416일반적인 페이지 순서는 `head page`, `commit page`, `tail page`다.
링을 읽기 방향으로 따라가면 head, commit, tail이 이 순서로 나타난다.
예외적으로 head page가 commit page와 때로는 tail page보다 뒤에 있을 수 있다. commit page와 tail page가 reader page와 교환되어 링 밖에 나간 경우다. head page는 항상 링 버퍼의 일부지만 reader page는 그렇지 않다. 한 페이지보다 적은 데이터만 commit된 상태에서 reader가 교환하면 commit page를 꺼내게 된다.
이때 tail과 commit이 링 버퍼로 돌아오더라도 head page는 움직이지 않는다. commit page가 아직 reader page에 있으면 reader는 새 페이지를 링에 교환해 넣을 수 없다. 읽기가 마지막 실제 full commit에 닿았다면 pending이나 reserved 데이터는 읽을 수 없고, 다음 full commit이 끝날 때까지 버퍼는 비어 있는 것으로 간주한다.
commit 페이지가 링 밖 reader page에 있을 때 head의 상대 위치가 달라진다.
reader가 실제 commit을 만난 뒤 새 full commit 전까지 빈 버퍼로 처리하는 경로다.
tail이 head page를 만나면 overwrite 모드에서는 head를 한 페이지 앞으로 밀고, producer/consumer 모드에서는 쓰기가 실패한다.
tail이 head를 덮기 전에 읽기 시작점을 한 페이지 전진시킨다.
reader page는 여전히 이전 head page를 가리킬 수 있지만, 실제 교환이 일어날 때는 가장 최근의 head page를 사용한다.
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 page
and possibly the tail page. That is when the commit (and tail) page has been
swapped with the reader page. This is because the head page is always
part of the ring buffer, but the reader page is not. Whenever there
has 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 commit
move back into the ring buffer.
The reader cannot swap a page into the ring buffer if the commit page
is still on that page. If the read meets the last commit (real commit
not 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/consumer
mode, 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.
포인터 상태 비트와 잠금 없는 writer
417-493잠금 없는 알고리즘의 핵심은 `head_page` 포인터의 이동과 reader의 페이지 교환을 결합하는 것이다. 페이지를 가리키는 포인터 안에 상태 플래그를 넣는다. 각 페이지는 메모리에서 4바이트 정렬되므로 주소의 하위 2비트는 항상 0이고 플래그로 사용할 수 있다. 실제 주소를 얻을 때는 플래그 비트를 마스킹한다.
MASK = ~3
address & MASK
주소의 하위 2비트로 head 이동과 writer 갱신 상태를 표시한다.
플래그는 페이지 자체가 아니라 그 페이지를 가리키는 연결 포인터에 들어간다.
`-H->` 포인터는 다음 페이지가 reader가 교환해 꺼낼 head page임을 뜻한다. tail page가 이 head 포인터를 만나면 `cmpxchg`로 포인터를 `HEADER`에서 `UPDATE` 상태로 바꾼다.
writer가 head를 이동하는 동안 reader의 교환을 막는다.
reader 접근은 reader끼리 직렬화할 수 있는 잠금을 사용해야 하지만 writer는 링 버퍼에 쓸 때 잠금을 전혀 잡지 않는다. 따라서 알고리즘은 reader 하나와 스택 형태로만 선점하는 writer들을 고려하면 된다.
reader가 페이지를 교환할 때도 `cmpxchg`를 사용한다. head page로 가는 포인터에 `HEADER` 플래그가 없으면 비교가 실패하고 reader는 새 head page를 찾아 다시 시도한다. `UPDATE`와 `HEADER`는 같은 포인터에 동시에 설정되지 않는다.
Making the Ring Buffer Lockless:
--------------------------------
The main idea behind the lockless algorithm is to combine the moving
of 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 2
least significant bits of the address to be used as flags, since
they 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 is
the 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 to
change 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 serialize
the readers. But the writers will never take a lock to write to the
ring 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, it
will also use cmpxchg. If the flag bit in the pointer to the
head page does not have the HEADER flag set, the compare will fail
and 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.
reader의 원자적 페이지 교환
494-592reader는 먼저 reader page의 `next` 포인터가 현재 head page 다음 페이지를 `HEADER` 상태로 가리키게 한다.
그다음 이전 head page를 가리키던 앞 페이지의 포인터를 `cmpxchg`로 reader page를 가리키게 바꾼다. 새 포인터에는 `HEADER`를 설정하지 않는다. 이 한 번의 원자적 동작으로 head page가 앞으로 이동한다.
새 head page가 정해지면 그 페이지의 `previous` 포인터를 reader page로 갱신한다. 결과적으로 이전 reader page는 링 안의 buffer page가 되고, 이전 head page는 링 밖의 새 reader page가 된다.
준비한 연결을 cmpxchg 한 번으로 공개한 뒤 역방향 연결을 정리한다.
비교 대상이 바뀌었으면 writer가 head를 이동한 것이므로 새 위치에서 전체 절차를 반복한다.
링 바깥 reader page 때문에 next와 previous 순회 특성이 다르다.
reader page의 `previous`가 가리키는 페이지는 reader page를 다시 가리키지 않는다. reader page는 링 버퍼의 일부가 아니기 때문이다. 따라서 `next`로 순회하면 항상 링 안에 있지만 `previous`로 순회하면 그렇지 않을 수 있다.
어떤 페이지가 reader page인지 판별하려면 그 페이지의 `previous`를 확인한다. 이전 페이지의 `next`가 원래 페이지를 다시 가리키지 않는다면 원래 페이지가 reader page다.
양방향 링크가 서로 되돌아오지 않는 지점을 찾는다.
The reader swaps the reader page as follows::
+------+
|reader| RING BUFFER
|page |
+------+
+---+ +---+ +---+
| |--->| |--->| |
| |<---| |<---| |
+---+ +---+ +---+
^ | ^ |
| +---------------+ |
+-----H-------------+
The reader sets the reader page next pointer as HEADER to the page after
the head page::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ v
| +---+ +---+ +---+
| | |--->| |--->| |
| | |<---| |<---| |<-+
| +---+ +---+ +---+ |
| ^ | ^ | |
| | +---------------+ | |
| +-----H-------------+ |
+--------------------------------------+
It does a cmpxchg with the pointer to the previous head page to make it
point to the reader page. Note that the new pointer does not have the HEADER
flag set. This action atomically moves the head page forward::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ v
| ^ +---+ +---+ +---+
| | | |-->| |-->| |
| | | |<--| |<--| |<-+
| | +---+ +---+ +---+ |
| | | ^ | |
| | +-------------+ | |
| +-----------------------------+ |
+------------------------------------+
After the new head page is set, the previous pointer of the head page is
updated to the reader page::
+------+
|reader| RING BUFFER
|page |-------H-----------+
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | |-->| |-->| |
| | | | | |<--| |<-+
| | +---+ +---+ +---+ |
| | | ^ | |
| | +-------------+ | |
| +-----------------------------+ |
+------------------------------------+
+------+
|buffer| RING BUFFER
|page |-------H-----------+ <--- New head page
+------+ <---------------+ v
| ^ +---+ +---+ +---+
| | | | | |-->| |
| | New | | | |<--| |<-+
| | Reader +---+ +---+ +---+ |
| | page ----^ | |
| | | |
| +-----------------------------+ |
+------------------------------------+
Another important point: The page that the reader page points back to
by its previous pointer (the one that now points to the new head page)
never points back to the reader page. That is because the reader page is
not part of the ring buffer. Traversing the ring buffer via the next pointers
will always stay in the ring buffer. Traversing the ring buffer via the
prev pointers may not.
Note, the way to determine a reader page is simply by examining the previous
pointer of the page. If the next pointer of the previous page does not
point back to the original page, then the original page is a reader page::
+--------+
| reader | next +----+
| page |-------->| |<====== (buffer page)
+--------+ +----+
| | ^
| v | next
prev | +----+
+------------->| |
+----+
writer가 head를 전진시키는 기본 경로
593-653overwrite 모드에서 tail page가 head page를 만나고 쓰기가 계속되면 writer가 tail을 움직이기 전에 head를 앞으로 이동해야 한다. writer는 `cmpxchg`로 head page를 가리키는 포인터를 `HEADER`에서 `UPDATE`로 바꾼다.
`UPDATE`가 설정되면 writer가 이동을 끝낼 때까지 reader는 head page를 교환하거나 움직일 수 없다. 이렇게 reader와 writer 사이의 경쟁을 제거한다. reader는 writer가 끝날 때까지 회전해야 하므로 reader가 writer를 선점해서는 안 된다.
HEADER 연결을 UPDATE로 잠시 소유한 뒤 다음 페이지를 새 head로 지정한다.
원문의 연속 ASCII 그림을 포인터 상태와 이동 주체로 나타냈다.
이전 head 연결을 잠근 동안 바로 다음 연결에 새 head 표식을 먼저 세운다.
The way the head page moves forward:
When the tail page meets the head page and the buffer is in overwrite mode
and more writes take place, the head page must be moved forward before the
writer may move the tail page. The way this is done is that the writer
performs a cmpxchg to convert the pointer to the head page from the HEADER
flag to have the UPDATE flag set. Once this is done, the reader will
not be able to swap the head page from the buffer, nor will it be able to
move the head page, until the writer is finished with the move.
This eliminates any races that the reader can have on the writer. The reader
must spin, and this is why the reader cannot preempt the writer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The following page will be made into the new head page::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the new head page has been set, we can set the old head page
pointer back to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the head page has been moved, the tail page may now move forward::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
commit이 reader page에 남은 복잡한 경우
654-699앞의 경우는 단순한 갱신이다. 첫 writer를 충분히 많은 중첩 쓰기가 선점하면 tail page가 링을 한 바퀴 돌아 commit page를 만날 수 있다. 이때부터는 보통 사용자에게 경고하면서 새 쓰기를 버려야 한다.
더 복잡한 경우는 commit이 아직 reader page에 있을 때다. commit page가 링 버퍼의 일부가 아니므로 tail page가 이를 고려해야 한다. tail이 단순히 head를 앞으로 밀면 commit이 reader page를 떠날 때 올바른 페이지를 가리키지 않게 된다.
해결책은 head를 밀기 전에 commit page가 reader page에 있는지 검사하는 것이다. 그렇다면 tail이 버퍼를 한 바퀴 돌았다고 보고 새 쓰기를 버린다.
링 밖 commit을 지나쳐 덮어쓰지 않도록 head 이동 전에 포화 상태를 판정한다.
commit이 링 안인지 reader page인지에 따라 overwrite 가능 여부가 갈린다.
이 검사는 경쟁 조건이 아니다. commit page는 선점당한 가장 바깥 writer만 옮길 수 있으므로 다른 writer가 tail을 움직이는 동안 commit은 움직이지 않는다. reader도 reader page가 commit page로 쓰이는 동안에는 페이지를 교환할 수 없다.
reader는 commit이 reader page를 벗어났는지만 확인하면 된다. 한 번 reader page를 떠난 commit은 reader가 다시 commit page인 버퍼 페이지와 교환하지 않는 한 그 reader page로 돌아가지 않는다.
The above are the trivial updates. Now for the more complex scenarios.
As stated before, if enough writes preempt the first write, the
tail page may make it all the way around the buffer and meet the commit
page. At this time, we must start dropping writes (usually with some kind
of warning to the user). But what happens if the commit was still on the
reader page? The commit page is not part of the ring buffer. The tail page
must account for this::
reader page commit page
| |
v |
+---+ |
| |<----------+
| |
| |------+
+---+ |
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
^
|
tail page
If the tail page were to simply push the head page forward, the commit when
leaving the reader page would not be pointing to the correct page.
The solution to this is to test if the commit page is on the reader page
before pushing the head page. If it is, then it can be assumed that the
tail page wrapped the buffer, and we must drop new writes.
This is not a race condition, because the commit page can only be moved
by the outermost writer (the writer that was preempted).
This means that the commit will not move while a writer is moving the
tail page. The reader cannot swap the reader page if it is also being
used as the commit page. The reader can simply check that the commit
is off the reader page. Once the commit page leaves the reader page
it will never go back on it unless a reader does another swap with the
buffer page that is also the commit page.
중첩 쓰기의 tail 원자 갱신
700-744tail page를 앞으로 밀 때 다음 페이지가 head page라면 먼저 head를 전진시켜야 한다. 다음 페이지가 head가 아니면 `cmpxchg`로 tail page만 갱신한다.
tail page를 움직이는 주체는 writer뿐이며, 중첩 writer로부터 보호하기 위해 다음 갱신을 원자적으로 수행해야 한다.
temp_page = tail_page
next_page = temp_page->next
cmpxchg(tail_page, temp_page, next_page)
tail이 여전히 예상한 `temp_page`를 가리킬 때만 `next_page`로 바뀐다. `cmpxchg`가 실패했다면 중첩 writer가 이미 tail을 전진시킨 것이므로 현재 writer가 다시 밀 필요는 없다.
실패를 충돌이 아니라 이미 완료된 전진으로 해석하고 새 tail에서 예약을 다시 시도한다.
반환된 이전 tail 값으로 현재 writer의 다음 행동을 결정한다.
중첩 writer가 먼저 tail을 옮긴 뒤 바깥 writer의 `cmpxchg`는 실패한다. 그러나 tail은 이미 앞으로 갔으므로 writer는 새 tail page에서 저장 공간 예약을 다시 시도하면 된다.
Nested writes
-------------
In the pushing forward of the tail page we must first push forward
the head page if the head page is the next page. If the head page
is not the next page, the tail page is simply updated with a cmpxchg.
Only writers move the tail page. This must be done atomically to protect
against nested writers::
temp_page = tail_page
next_page = temp_page->next
cmpxchg(tail_page, temp_page, next_page)
The above will update the tail page if it is still pointing to the expected
page. If this fails, a nested write pushed it forward, the current write
does not need to push it::
temp page
|
v
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Nested write comes in and moves the tail page forward::
tail page (moved by nested writer)
temp page |
| |
v v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The above would fail the cmpxchg, but since the tail page has already
been moved forward, the writer will just try again to reserve storage
on the new tail page.
한 단계 중첩에서 head 이동 소유권
745-805head page 이동은 더 복잡하다. 바깥 writer가 head 포인터를 `HEADER`에서 `UPDATE`로 바꾼 직후 중첩 writer가 선점할 수 있다.
중첩 writer는 다음 페이지가 head page이면서 자신이 중첩 상태임을 알아낸다. `HEADER`나 `NORMAL`이 아니라 `UPDATE` 플래그를 본다는 사실로 이를 감지하고 그 정보를 보존한다.
중첩 writer는 다음 페이지를 새 head page로 설정하지만 오래된 `UPDATE` 포인터를 `NORMAL`로 되돌리지 않는다. `HEADER`를 `UPDATE`로 직접 바꾼 writer만 그 `UPDATE`를 다시 `NORMAL`로 바꿀 수 있다.
UPDATE를 만든 writer만 상태를 해제해 reader가 중간 상태를 보지 않게 한다.
중첩 writer가 새 head를 만든 뒤에도 reader 차단은 바깥 writer가 복귀할 때까지 유지된다.
각 writer가 자신이 획득한 포인터 상태만 해제한다.
중첩 writer가 끝나면 가장 바깥 writer가 남아 있던 `UPDATE` 포인터를 `NORMAL`로 바꾼다.
But the moving of the head page is a bit more complex::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The write converts the head page pointer to UPDATE::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But if a nested writer preempts here, it will see that the next
page is a head page, but it is also nested. It will detect that
it is nested and will save that information. The detection is the
fact that it sees the UPDATE flag instead of a HEADER or NORMAL
pointer.
The nested writer will set the new head page pointer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But it will not reset the update back to normal. Only the writer
that converted a pointer from HEAD to UPDATE will convert it back
to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
After the nested writer finishes, the outermost writer will convert
the UPDATE pointer to NORMAL::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
여러 중첩 writer와 잘못된 head 복구
806-983여러 중첩 쓰기가 들어와 tail page를 여러 페이지 앞으로 옮기면 상황이 더 복잡해진다. 첫 번째 writer는 head 연결을 `HEADER`에서 `UPDATE`로 바꾼다.
두 번째 writer는 `UPDATE`를 보고 다음 연결에 새 `HEADER`를 설정한 뒤 tail을 전진시킨다. 자신이 가장 바깥 writer가 아니므로 첫 번째 writer가 만든 오래된 `UPDATE`는 `NORMAL`로 바꾸지 않는다.
세 번째 writer가 다시 선점하면 tail 다음의 `HEADER`를 `UPDATE`로 바꾸고 그 다음 페이지를 새 head로 전진시킨다. 세 번째 writer는 자신이 바꾼 `UPDATE`의 소유자이므로 그 연결은 `NORMAL`로 복원한 뒤 tail을 옮기고 두 번째 writer로 돌아간다.
각 writer가 획득한 UPDATE만 해제하면서 head와 tail을 단계적으로 전진시킨다.
원문의 writer별 상태 그림을 한 단계씩 비교한다.
두 번째 writer는 tail이 이미 움직였으므로 자신의 tail `cmpxchg`에 실패한다. 그러면 새 tail page에서 데이터 예약을 다시 시도하고 첫 번째 writer로 돌아간다.
첫 번째 writer는 자신이 head page를 갱신하는 동안 tail page가 이동했는지를 하나의 원자 연산으로 알 수 없다. 따라서 자신이 새 head라고 생각하는 페이지에 `HEADER`를 설정할 수 있고, 그 결과 잠시 `HEADER`가 두 곳에 존재할 수 있다.
`cmpxchg`가 이전 포인터 값을 반환하므로 첫 번째 writer는 `NORMAL`에서 `HEADER`로의 변경 자체가 성공했음을 알 수 있다. 하지만 그것만으로 충분하지 않다. tail page가 원래 위치 `A` 또는 바로 다음 페이지 `B`에 있는지도 확인해야 한다.
tail이 예상 범위를 벗어났다면 중첩 writer가 이미 더 먼 head를 만들었으므로 잘못 만든 HEADER를 취소한다.
head 후보를 만든 뒤 tail의 실제 위치로 중첩 전진 정도를 판별한다.
tail이 `A`도 `B`도 아니면 첫 writer는 자신이 바꾼 포인터를 `NORMAL`로 되돌려야 한다. 경쟁 상대가 같은 CPU에서 스택 형태로 들어오는 중첩 writer뿐이므로 `HEADER`를 설정한 뒤 이 검사를 수행해도 충분하다.
잘못된 후보를 정리한 뒤 writer는 실제 head page를 갱신할 수 있다. 이 과정에서도 원래 head 연결은 가장 바깥 writer가 끝낼 때까지 `UPDATE`로 남아 있어야 한다. 그래야 reader가 중간에 만들어진 잘못된 head page를 관찰하지 않는다.
첫 writer가 복귀한 뒤 tail 위치로 후보의 유효성을 확인하고 실제 head만 공개한다.
UPDATE 장벽이 중간의 잘못된 head 후보를 reader로부터 숨긴다.
It can be even more complex if several nested writes came in and moved
the tail page ahead several pages::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-H->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The write converts the head page pointer to UPDATE::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Next writer comes in, and sees the update and sets up the new
head page::
(second writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The nested writer moves the tail page forward. But does not set the old
update page to NORMAL because it is not the outermost writer::
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Another writer preempts and sees the page after the tail page is a head page.
It changes it from HEAD to UPDATE::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-U->| |--->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The writer will move the head page forward::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-U->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
But now that the third writer did change the HEAD flag to UPDATE it
will convert it to normal::
(third writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Then it will move the tail page, and return back to the second writer::
(second writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The second writer will fail to move the tail page because it was already
moved, so it will try again and add its data to the new tail page.
It will return to the first writer::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
The first writer cannot know atomically if the tail page moved
while it updates the HEAD page. It will then update the head page to
what it thinks is the new head page::
(first writer)
tail page
|
v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Since the cmpxchg returns the old value of the pointer the first writer
will see it succeeded in updating the pointer from NORMAL to HEAD.
But as we can see, this is not good enough. It must also check to see
if the tail page is either where it use to be or on the next page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |-H->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
If tail page != A and tail page != B, then it must reset the pointer
back to NORMAL. The fact that it only needs to worry about nested
writers means that it only needs to check this after setting the HEAD page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |-U->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
Now the writer can update the head page. This is also why the head page must
remain in UPDATE and only reset by the outermost writer. This prevents
the reader from seeing the incorrect head page::
(first writer)
A B tail page
| | |
v v v
+---+ +---+ +---+ +---+
<---| |--->| |--->| |--->| |-H->
--->| |<---| |<---| |<---| |<---
+---+ +---+ +---+ +---+
요약·해설
ring-buffer-design.rst:1-983Linux 추적 링 버퍼의 overwrite·producer/consumer 모드, reader page 교환, reserve와 full commit, 주소 하위 비트의 HEADER·UPDATE 상태, 중첩 writer가 head와 tail을 잠금 없이 옮기는 알고리즘을 설명합니다.
writer는 같은 CPU에서 인터럽트 중첩 순서에 따라 스택처럼 완료되며, 가장 바깥 writer만 full commit과 자신이 획득한 UPDATE 상태를 마무리합니다. reader는 별도 페이지를 원자적으로 교환하고, HEADER가 바뀌었거나 UPDATE 중이면 새 head를 찾아 재시도합니다.
핵심 불변식은 tail이 commit을 추월하지 않는 것, reader가 pending commit을 보지 않는 것, UPDATE를 만든 writer만 이를 NORMAL로 되돌리는 것입니다. 여러 중첩 writer가 임시 head 후보를 만들더라도 tail 위치를 사후 검사해 잘못된 HEADER를 제거합니다.