← Documents Documentation/trace/ring-buffer-design.rst GitHub 원문 ↗

Linux 6.18.37 · Tracing

잠금 없는 링 버퍼 설계

Linux 추적 링 버퍼의 overwrite·producer/consumer 모드, reader page 교환, reserve와 full commit, 주소 하위 비트의 HEADER·UPDATE 상태, 중첩 writer가 head와 tail을 잠금 없이 옮기는 알고리즘을 설명합니다.

Source pathDocumentation/trace/ring-buffer-design.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

요약·해설

ring-buffer-design.rst:1-983

Linux 추적 링 버퍼의 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를 제거합니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 .. SPDX-License-Identifier: GPL-2.0 OR GFDL-1.2-no-invariants-only
2
3 ===========================
4 Lockless Ring Buffer Design
5 ===========================
6
7 Copyright 2009 Red Hat Inc.
8
9 :Author: Steven Rostedt <[email protected]>
10 :License: The GNU Free Documentation License, Version 1.2
11 (dual licensed under the GPL v2)
12 :Reviewers: Mathieu Desnoyers, Huang Ying, Hidetoshi Seto,
13 and Frederic Weisbecker.
14
15
16 Written for: 2.6.31
17
18 Terminology used in this Document
19 ---------------------------------
20
21 tail
22 - where new writes happen in the ring buffer.
23
24 head
25 - where new reads happen in the ring buffer.
26
27 producer
28 - the task that writes into the ring buffer (same as writer)
29
30 writer
31 - same as producer
32
33 consumer
34 - the task that reads from the buffer (same as reader)
35
36 reader
37 - same as consumer.
38
39 reader_page
40 - A page outside the ring buffer used solely (for the most part)
41 by the reader.
42
43 head_page
44 - a pointer to the page that the reader will use next
45
46 tail_page
47 - a pointer to the page that will be written to next
48
49 commit_page
50 - a pointer to the page with the last finished non-nested write.
51
52 cmpxchg
53 - hardware-assisted atomic transaction that performs the following::
54
55 A = B if previous A == C
56
57 R = cmpxchg(A, C, B) is saying that we replace A with B if and only
58 if current A is equal to C, and we put the old (current)
59 A into R
60
61 R gets the previous A regardless if A is updated with B or not.
62
63 To see if the update was successful a compare of ``R == C``
64 may be used.
65
66 The Generic Ring Buffer
67 -----------------------
68
69 The ring buffer can be used in either an overwrite mode or in
70 producer/consumer mode.
71
72 Producer/consumer mode is where if the producer were to fill up the
73 buffer before the consumer could free up anything, the producer
74 will stop writing to the buffer. This will lose most recent events.
75
76 Overwrite mode is where if the producer were to fill up the buffer
77 before the consumer could free up anything, the producer will
78 overwrite the older data. This will lose the oldest events.
79
80 No two writers can write at the same time (on the same per-cpu buffer),
81 but a writer may interrupt another writer, but it must finish writing
82 before the previous writer may continue. This is very important to the
83 algorithm. The writers act like a "stack". The way interrupts works
84 enforces this behavior::
85
86
87 writer1 start
88 <preempted> writer2 start
89 <preempted> writer3 start
90 writer3 finishes
91 writer2 finishes
92 writer1 finishes
93
94 This is very much like a writer being preempted by an interrupt and
95 the interrupt doing a write as well.
96
97 Readers can happen at any time. But no two readers may run at the
98 same time, nor can a reader preempt/interrupt another reader. A reader
99 cannot preempt/interrupt a writer, but it may read/consume from the
100 buffer at the same time as a writer is writing, but the reader must be
101 on another processor to do so. A reader may read on its own processor
102 and can be preempted by a writer.
103
104 A writer can preempt a reader, but a reader cannot preempt a writer.
105 But a reader can read the buffer at the same time (on another processor)
106 as a writer.
107
108 The ring buffer is made up of a list of pages held together by a linked list.
109
110 At initialization a reader page is allocated for the reader that is not
111 part of the ring buffer.
112
113 The head_page, tail_page and commit_page are all initialized to point
114 to the same page.
115
116 The reader page is initialized to have its next pointer pointing to
117 the head page, and its previous pointer pointing to a page before
118 the head page.
119
120 The reader has its own page to use. At start up time, this page is
121 allocated but is not attached to the list. When the reader wants
122 to read from the buffer, if its page is empty (like it is on start-up),
123 it will swap its page with the head_page. The old reader page will
124 become part of the ring buffer and the head_page will be removed.
125 The page after the inserted page (old reader_page) will become the
126 new head page.
127
128 Once the new page is given to the reader, the reader could do what
129 it wants with it, as long as a writer has left that page.
130
131 A sample of how the reader page is swapped: Note this does not
132 show the head page in the buffer, it is for demonstrating a swap
133 only.
134
135 ::
136
137 +------+
138 |reader| RING BUFFER
139 |page |
140 +------+
141 +---+ +---+ +---+
142 | |-->| |-->| |
143 | |<--| |<--| |
144 +---+ +---+ +---+
145 ^ | ^ |
146 | +-------------+ |
147 +-----------------+
148
149
150 +------+
151 |reader| RING BUFFER
152 |page |-------------------+
153 +------+ v
154 | +---+ +---+ +---+
155 | | |-->| |-->| |
156 | | |<--| |<--| |<-+
157 | +---+ +---+ +---+ |
158 | ^ | ^ | |
159 | | +-------------+ | |
160 | +-----------------+ |
161 +------------------------------------+
162
163 +------+
164 |reader| RING BUFFER
165 |page |-------------------+
166 +------+ <---------------+ v
167 | ^ +---+ +---+ +---+
168 | | | |-->| |-->| |
169 | | | | | |<--| |<-+
170 | | +---+ +---+ +---+ |
171 | | | ^ | |
172 | | +-------------+ | |
173 | +-----------------------------+ |
174 +------------------------------------+
175
176 +------+
177 |buffer| RING BUFFER
178 |page |-------------------+
179 +------+ <---------------+ v
180 | ^ +---+ +---+ +---+
181 | | | | | |-->| |
182 | | New | | | |<--| |<-+
183 | | Reader +---+ +---+ +---+ |
184 | | page ----^ | |
185 | | | |
186 | +-----------------------------+ |
187 +------------------------------------+
188
189
190
191 It is possible that the page swapped is the commit page and the tail page,
192 if what is in the ring buffer is less than what is held in a buffer page.
193
194 ::
195
196 reader page commit page tail page
197 | | |
198 v | |
199 +---+ | |
200 | |<----------+ |
201 | |<------------------------+
202 | |------+
203 +---+ |
204 |
205 v
206 +---+ +---+ +---+ +---+
207 <---| |--->| |--->| |--->| |--->
208 --->| |<---| |<---| |<---| |<---
209 +---+ +---+ +---+ +---+
210
211 This case is still valid for this algorithm.
212 When the writer leaves the page, it simply goes into the ring buffer
213 since the reader page still points to the next location in the ring
214 buffer.
215
216
217 The main pointers:
218
219 reader page
220 - The page used solely by the reader and is not part
221 of the ring buffer (may be swapped in)
222
223 head page
224 - the next page in the ring buffer that will be swapped
225 with the reader page.
226
227 tail page
228 - the page where the next write will take place.
229
230 commit page
231 - the page that last finished a write.
232
233 The commit page only is updated by the outermost writer in the
234 writer stack. A writer that preempts another writer will not move the
235 commit page.
236
237 When data is written into the ring buffer, a position is reserved
238 in the ring buffer and passed back to the writer. When the writer
239 is finished writing data into that position, it commits the write.
240
241 Another write (or a read) may take place at anytime during this
242 transaction. If another write happens it must finish before continuing
243 with the previous write.
244
245
246 Write reserve::
247
248 Buffer page
249 +---------+
250 |written |
251 +---------+ <--- given back to writer (current commit)
252 |reserved |
253 +---------+ <--- tail pointer
254 | empty |
255 +---------+
256
257 Write commit::
258
259 Buffer page
260 +---------+
261 |written |
262 +---------+
263 |written |
264 +---------+ <--- next position for write (current commit)
265 | empty |
266 +---------+
267
268
269 If a write happens after the first reserve::
270
271 Buffer page
272 +---------+
273 |written |
274 +---------+ <-- current commit
275 |reserved |
276 +---------+ <--- given back to second writer
277 |reserved |
278 +---------+ <--- tail pointer
279
280 After second writer commits::
281
282
283 Buffer page
284 +---------+
285 |written |
286 +---------+ <--(last full commit)
287 |reserved |
288 +---------+
289 |pending |
290 |commit |
291 +---------+ <--- tail pointer
292
293 When the first writer commits::
294
295 Buffer page
296 +---------+
297 |written |
298 +---------+
299 |written |
300 +---------+
301 |written |
302 +---------+ <--(last full commit and tail pointer)
303
304
305 The commit pointer points to the last write location that was
306 committed without preempting another write. When a write that
307 preempted another write is committed, it only becomes a pending commit
308 and will not be a full commit until all writes have been committed.
309
310 The commit page points to the page that has the last full commit.
311 The tail page points to the page with the last write (before
312 committing).
313
314 The tail page is always equal to or after the commit page. It may
315 be several pages ahead. If the tail page catches up to the commit
316 page then no more writes may take place (regardless of the mode
317 of the ring buffer: overwrite and produce/consumer).
318
319 The order of pages is::
320
321 head page
322 commit page
323 tail page
324
325 Possible scenario::
326
327 tail page
328 head page commit page |
329 | | |
330 v v v
331 +---+ +---+ +---+ +---+
332 <---| |--->| |--->| |--->| |--->
333 --->| |<---| |<---| |<---| |<---
334 +---+ +---+ +---+ +---+
335
336 There is a special case that the head page is after either the commit page
337 and possibly the tail page. That is when the commit (and tail) page has been
338 swapped with the reader page. This is because the head page is always
339 part of the ring buffer, but the reader page is not. Whenever there
340 has been less than a full page that has been committed inside the ring buffer,
341 and a reader swaps out a page, it will be swapping out the commit page.
342
343 ::
344
345 reader page commit page tail page
346 | | |
347 v | |
348 +---+ | |
349 | |<----------+ |
350 | |<------------------------+
351 | |------+
352 +---+ |
353 |
354 v
355 +---+ +---+ +---+ +---+
356 <---| |--->| |--->| |--->| |--->
357 --->| |<---| |<---| |<---| |<---
358 +---+ +---+ +---+ +---+
359 ^
360 |
361 head page
362
363
364 In this case, the head page will not move when the tail and commit
365 move back into the ring buffer.
366
367 The reader cannot swap a page into the ring buffer if the commit page
368 is still on that page. If the read meets the last commit (real commit
369 not pending or reserved), then there is nothing more to read.
370 The buffer is considered empty until another full commit finishes.
371
372 When the tail meets the head page, if the buffer is in overwrite mode,
373 the head page will be pushed ahead one. If the buffer is in producer/consumer
374 mode, the write will fail.
375
376 Overwrite mode::
377
378 tail page
379 |
380 v
381 +---+ +---+ +---+ +---+
382 <---| |--->| |--->| |--->| |--->
383 --->| |<---| |<---| |<---| |<---
384 +---+ +---+ +---+ +---+
385 ^
386 |
387 head page
388
389
390 tail page
391 |
392 v
393 +---+ +---+ +---+ +---+
394 <---| |--->| |--->| |--->| |--->
395 --->| |<---| |<---| |<---| |<---
396 +---+ +---+ +---+ +---+
397 ^
398 |
399 head page
400
401
402 tail page
403 |
404 v
405 +---+ +---+ +---+ +---+
406 <---| |--->| |--->| |--->| |--->
407 --->| |<---| |<---| |<---| |<---
408 +---+ +---+ +---+ +---+
409 ^
410 |
411 head page
412
413 Note, the reader page will still point to the previous head page.
414 But when a swap takes place, it will use the most recent head page.
415
416
417 Making the Ring Buffer Lockless:
418 --------------------------------
419
420 The main idea behind the lockless algorithm is to combine the moving
421 of the head_page pointer with the swapping of pages with the reader.
422 State flags are placed inside the pointer to the page. To do this,
423 each page must be aligned in memory by 4 bytes. This will allow the 2
424 least significant bits of the address to be used as flags, since
425 they will always be zero for the address. To get the address,
426 simply mask out the flags::
427
428 MASK = ~3
429
430 address & MASK
431
432 Two flags will be kept by these two bits:
433
434 HEADER
435 - the page being pointed to is a head page
436
437 UPDATE
438 - the page being pointed to is being updated by a writer
439 and was or is about to be a head page.
440
441 ::
442
443 reader page
444 |
445 v
446 +---+
447 | |------+
448 +---+ |
449 |
450 v
451 +---+ +---+ +---+ +---+
452 <---| |--->| |-H->| |--->| |--->
453 --->| |<---| |<---| |<---| |<---
454 +---+ +---+ +---+ +---+
455
456
457 The above pointer "-H->" would have the HEADER flag set. That is
458 the next page is the next page to be swapped out by the reader.
459 This pointer means the next page is the head page.
460
461 When the tail page meets the head pointer, it will use cmpxchg to
462 change the pointer to the UPDATE state::
463
464
465 tail page
466 |
467 v
468 +---+ +---+ +---+ +---+
469 <---| |--->| |-H->| |--->| |--->
470 --->| |<---| |<---| |<---| |<---
471 +---+ +---+ +---+ +---+
472
473 tail page
474 |
475 v
476 +---+ +---+ +---+ +---+
477 <---| |--->| |-U->| |--->| |--->
478 --->| |<---| |<---| |<---| |<---
479 +---+ +---+ +---+ +---+
480
481 "-U->" represents a pointer in the UPDATE state.
482
483 Any access to the reader will need to take some sort of lock to serialize
484 the readers. But the writers will never take a lock to write to the
485 ring buffer. This means we only need to worry about a single reader,
486 and writes only preempt in "stack" formation.
487
488 When the reader tries to swap the page with the ring buffer, it
489 will also use cmpxchg. If the flag bit in the pointer to the
490 head page does not have the HEADER flag set, the compare will fail
491 and the reader will need to look for the new head page and try again.
492 Note, the flags UPDATE and HEADER are never set at the same time.
493
494 The reader swaps the reader page as follows::
495
496 +------+
497 |reader| RING BUFFER
498 |page |
499 +------+
500 +---+ +---+ +---+
501 | |--->| |--->| |
502 | |<---| |<---| |
503 +---+ +---+ +---+
504 ^ | ^ |
505 | +---------------+ |
506 +-----H-------------+
507
508 The reader sets the reader page next pointer as HEADER to the page after
509 the head page::
510
511
512 +------+
513 |reader| RING BUFFER
514 |page |-------H-----------+
515 +------+ v
516 | +---+ +---+ +---+
517 | | |--->| |--->| |
518 | | |<---| |<---| |<-+
519 | +---+ +---+ +---+ |
520 | ^ | ^ | |
521 | | +---------------+ | |
522 | +-----H-------------+ |
523 +--------------------------------------+
524
525 It does a cmpxchg with the pointer to the previous head page to make it
526 point to the reader page. Note that the new pointer does not have the HEADER
527 flag set. This action atomically moves the head page forward::
528
529 +------+
530 |reader| RING BUFFER
531 |page |-------H-----------+
532 +------+ v
533 | ^ +---+ +---+ +---+
534 | | | |-->| |-->| |
535 | | | |<--| |<--| |<-+
536 | | +---+ +---+ +---+ |
537 | | | ^ | |
538 | | +-------------+ | |
539 | +-----------------------------+ |
540 +------------------------------------+
541
542 After the new head page is set, the previous pointer of the head page is
543 updated to the reader page::
544
545 +------+
546 |reader| RING BUFFER
547 |page |-------H-----------+
548 +------+ <---------------+ v
549 | ^ +---+ +---+ +---+
550 | | | |-->| |-->| |
551 | | | | | |<--| |<-+
552 | | +---+ +---+ +---+ |
553 | | | ^ | |
554 | | +-------------+ | |
555 | +-----------------------------+ |
556 +------------------------------------+
557
558 +------+
559 |buffer| RING BUFFER
560 |page |-------H-----------+ <--- New head page
561 +------+ <---------------+ v
562 | ^ +---+ +---+ +---+
563 | | | | | |-->| |
564 | | New | | | |<--| |<-+
565 | | Reader +---+ +---+ +---+ |
566 | | page ----^ | |
567 | | | |
568 | +-----------------------------+ |
569 +------------------------------------+
570
571 Another important point: The page that the reader page points back to
572 by its previous pointer (the one that now points to the new head page)
573 never points back to the reader page. That is because the reader page is
574 not part of the ring buffer. Traversing the ring buffer via the next pointers
575 will always stay in the ring buffer. Traversing the ring buffer via the
576 prev pointers may not.
577
578 Note, the way to determine a reader page is simply by examining the previous
579 pointer of the page. If the next pointer of the previous page does not
580 point back to the original page, then the original page is a reader page::
581
582
583 +--------+
584 | reader | next +----+
585 | page |-------->| |<====== (buffer page)
586 +--------+ +----+
587 | | ^
588 | v | next
589 prev | +----+
590 +------------->| |
591 +----+
592
593 The way the head page moves forward:
594
595 When the tail page meets the head page and the buffer is in overwrite mode
596 and more writes take place, the head page must be moved forward before the
597 writer may move the tail page. The way this is done is that the writer
598 performs a cmpxchg to convert the pointer to the head page from the HEADER
599 flag to have the UPDATE flag set. Once this is done, the reader will
600 not be able to swap the head page from the buffer, nor will it be able to
601 move the head page, until the writer is finished with the move.
602
603 This eliminates any races that the reader can have on the writer. The reader
604 must spin, and this is why the reader cannot preempt the writer::
605
606 tail page
607 |
608 v
609 +---+ +---+ +---+ +---+
610 <---| |--->| |-H->| |--->| |--->
611 --->| |<---| |<---| |<---| |<---
612 +---+ +---+ +---+ +---+
613
614 tail page
615 |
616 v
617 +---+ +---+ +---+ +---+
618 <---| |--->| |-U->| |--->| |--->
619 --->| |<---| |<---| |<---| |<---
620 +---+ +---+ +---+ +---+
621
622 The following page will be made into the new head page::
623
624 tail page
625 |
626 v
627 +---+ +---+ +---+ +---+
628 <---| |--->| |-U->| |-H->| |--->
629 --->| |<---| |<---| |<---| |<---
630 +---+ +---+ +---+ +---+
631
632 After the new head page has been set, we can set the old head page
633 pointer back to NORMAL::
634
635 tail page
636 |
637 v
638 +---+ +---+ +---+ +---+
639 <---| |--->| |--->| |-H->| |--->
640 --->| |<---| |<---| |<---| |<---
641 +---+ +---+ +---+ +---+
642
643 After the head page has been moved, the tail page may now move forward::
644
645 tail page
646 |
647 v
648 +---+ +---+ +---+ +---+
649 <---| |--->| |--->| |-H->| |--->
650 --->| |<---| |<---| |<---| |<---
651 +---+ +---+ +---+ +---+
652
653
654 The above are the trivial updates. Now for the more complex scenarios.
655
656
657 As stated before, if enough writes preempt the first write, the
658 tail page may make it all the way around the buffer and meet the commit
659 page. At this time, we must start dropping writes (usually with some kind
660 of warning to the user). But what happens if the commit was still on the
661 reader page? The commit page is not part of the ring buffer. The tail page
662 must account for this::
663
664
665 reader page commit page
666 | |
667 v |
668 +---+ |
669 | |<----------+
670 | |
671 | |------+
672 +---+ |
673 |
674 v
675 +---+ +---+ +---+ +---+
676 <---| |--->| |-H->| |--->| |--->
677 --->| |<---| |<---| |<---| |<---
678 +---+ +---+ +---+ +---+
679 ^
680 |
681 tail page
682
683 If the tail page were to simply push the head page forward, the commit when
684 leaving the reader page would not be pointing to the correct page.
685
686 The solution to this is to test if the commit page is on the reader page
687 before pushing the head page. If it is, then it can be assumed that the
688 tail page wrapped the buffer, and we must drop new writes.
689
690 This is not a race condition, because the commit page can only be moved
691 by the outermost writer (the writer that was preempted).
692 This means that the commit will not move while a writer is moving the
693 tail page. The reader cannot swap the reader page if it is also being
694 used as the commit page. The reader can simply check that the commit
695 is off the reader page. Once the commit page leaves the reader page
696 it will never go back on it unless a reader does another swap with the
697 buffer page that is also the commit page.
698
699
700 Nested writes
701 -------------
702
703 In the pushing forward of the tail page we must first push forward
704 the head page if the head page is the next page. If the head page
705 is not the next page, the tail page is simply updated with a cmpxchg.
706
707 Only writers move the tail page. This must be done atomically to protect
708 against nested writers::
709
710 temp_page = tail_page
711 next_page = temp_page->next
712 cmpxchg(tail_page, temp_page, next_page)
713
714 The above will update the tail page if it is still pointing to the expected
715 page. If this fails, a nested write pushed it forward, the current write
716 does not need to push it::
717
718
719 temp page
720 |
721 v
722 tail page
723 |
724 v
725 +---+ +---+ +---+ +---+
726 <---| |--->| |--->| |--->| |--->
727 --->| |<---| |<---| |<---| |<---
728 +---+ +---+ +---+ +---+
729
730 Nested write comes in and moves the tail page forward::
731
732 tail page (moved by nested writer)
733 temp page |
734 | |
735 v v
736 +---+ +---+ +---+ +---+
737 <---| |--->| |--->| |--->| |--->
738 --->| |<---| |<---| |<---| |<---
739 +---+ +---+ +---+ +---+
740
741 The above would fail the cmpxchg, but since the tail page has already
742 been moved forward, the writer will just try again to reserve storage
743 on the new tail page.
744
745 But the moving of the head page is a bit more complex::
746
747 tail page
748 |
749 v
750 +---+ +---+ +---+ +---+
751 <---| |--->| |-H->| |--->| |--->
752 --->| |<---| |<---| |<---| |<---
753 +---+ +---+ +---+ +---+
754
755 The write converts the head page pointer to UPDATE::
756
757 tail page
758 |
759 v
760 +---+ +---+ +---+ +---+
761 <---| |--->| |-U->| |--->| |--->
762 --->| |<---| |<---| |<---| |<---
763 +---+ +---+ +---+ +---+
764
765 But if a nested writer preempts here, it will see that the next
766 page is a head page, but it is also nested. It will detect that
767 it is nested and will save that information. The detection is the
768 fact that it sees the UPDATE flag instead of a HEADER or NORMAL
769 pointer.
770
771 The nested writer will set the new head page pointer::
772
773 tail page
774 |
775 v
776 +---+ +---+ +---+ +---+
777 <---| |--->| |-U->| |-H->| |--->
778 --->| |<---| |<---| |<---| |<---
779 +---+ +---+ +---+ +---+
780
781 But it will not reset the update back to normal. Only the writer
782 that converted a pointer from HEAD to UPDATE will convert it back
783 to NORMAL::
784
785 tail page
786 |
787 v
788 +---+ +---+ +---+ +---+
789 <---| |--->| |-U->| |-H->| |--->
790 --->| |<---| |<---| |<---| |<---
791 +---+ +---+ +---+ +---+
792
793 After the nested writer finishes, the outermost writer will convert
794 the UPDATE pointer to NORMAL::
795
796
797 tail page
798 |
799 v
800 +---+ +---+ +---+ +---+
801 <---| |--->| |--->| |-H->| |--->
802 --->| |<---| |<---| |<---| |<---
803 +---+ +---+ +---+ +---+
804
805
806 It can be even more complex if several nested writes came in and moved
807 the tail page ahead several pages::
808
809
810 (first writer)
811
812 tail page
813 |
814 v
815 +---+ +---+ +---+ +---+
816 <---| |--->| |-H->| |--->| |--->
817 --->| |<---| |<---| |<---| |<---
818 +---+ +---+ +---+ +---+
819
820 The write converts the head page pointer to UPDATE::
821
822 tail page
823 |
824 v
825 +---+ +---+ +---+ +---+
826 <---| |--->| |-U->| |--->| |--->
827 --->| |<---| |<---| |<---| |<---
828 +---+ +---+ +---+ +---+
829
830 Next writer comes in, and sees the update and sets up the new
831 head page::
832
833 (second writer)
834
835 tail page
836 |
837 v
838 +---+ +---+ +---+ +---+
839 <---| |--->| |-U->| |-H->| |--->
840 --->| |<---| |<---| |<---| |<---
841 +---+ +---+ +---+ +---+
842
843 The nested writer moves the tail page forward. But does not set the old
844 update page to NORMAL because it is not the outermost writer::
845
846 tail page
847 |
848 v
849 +---+ +---+ +---+ +---+
850 <---| |--->| |-U->| |-H->| |--->
851 --->| |<---| |<---| |<---| |<---
852 +---+ +---+ +---+ +---+
853
854 Another writer preempts and sees the page after the tail page is a head page.
855 It changes it from HEAD to UPDATE::
856
857 (third writer)
858
859 tail page
860 |
861 v
862 +---+ +---+ +---+ +---+
863 <---| |--->| |-U->| |-U->| |--->
864 --->| |<---| |<---| |<---| |<---
865 +---+ +---+ +---+ +---+
866
867 The writer will move the head page forward::
868
869
870 (third writer)
871
872 tail page
873 |
874 v
875 +---+ +---+ +---+ +---+
876 <---| |--->| |-U->| |-U->| |-H->
877 --->| |<---| |<---| |<---| |<---
878 +---+ +---+ +---+ +---+
879
880 But now that the third writer did change the HEAD flag to UPDATE it
881 will convert it to normal::
882
883
884 (third writer)
885
886 tail page
887 |
888 v
889 +---+ +---+ +---+ +---+
890 <---| |--->| |-U->| |--->| |-H->
891 --->| |<---| |<---| |<---| |<---
892 +---+ +---+ +---+ +---+
893
894
895 Then it will move the tail page, and return back to the second writer::
896
897
898 (second writer)
899
900 tail page
901 |
902 v
903 +---+ +---+ +---+ +---+
904 <---| |--->| |-U->| |--->| |-H->
905 --->| |<---| |<---| |<---| |<---
906 +---+ +---+ +---+ +---+
907
908
909 The second writer will fail to move the tail page because it was already
910 moved, so it will try again and add its data to the new tail page.
911 It will return to the first writer::
912
913
914 (first writer)
915
916 tail page
917 |
918 v
919 +---+ +---+ +---+ +---+
920 <---| |--->| |-U->| |--->| |-H->
921 --->| |<---| |<---| |<---| |<---
922 +---+ +---+ +---+ +---+
923
924 The first writer cannot know atomically if the tail page moved
925 while it updates the HEAD page. It will then update the head page to
926 what it thinks is the new head page::
927
928
929 (first writer)
930
931 tail page
932 |
933 v
934 +---+ +---+ +---+ +---+
935 <---| |--->| |-U->| |-H->| |-H->
936 --->| |<---| |<---| |<---| |<---
937 +---+ +---+ +---+ +---+
938
939 Since the cmpxchg returns the old value of the pointer the first writer
940 will see it succeeded in updating the pointer from NORMAL to HEAD.
941 But as we can see, this is not good enough. It must also check to see
942 if the tail page is either where it use to be or on the next page::
943
944
945 (first writer)
946
947 A B tail page
948 | | |
949 v v v
950 +---+ +---+ +---+ +---+
951 <---| |--->| |-U->| |-H->| |-H->
952 --->| |<---| |<---| |<---| |<---
953 +---+ +---+ +---+ +---+
954
955 If tail page != A and tail page != B, then it must reset the pointer
956 back to NORMAL. The fact that it only needs to worry about nested
957 writers means that it only needs to check this after setting the HEAD page::
958
959
960 (first writer)
961
962 A B tail page
963 | | |
964 v v v
965 +---+ +---+ +---+ +---+
966 <---| |--->| |-U->| |--->| |-H->
967 --->| |<---| |<---| |<---| |<---
968 +---+ +---+ +---+ +---+
969
970 Now the writer can update the head page. This is also why the head page must
971 remain in UPDATE and only reset by the outermost writer. This prevents
972 the reader from seeing the incorrect head page::
973
974
975 (first writer)
976
977 A B tail page
978 | | |
979 v v v
980 +---+ +---+ +---+ +---+
981 <---| |--->| |--->| |--->| |-H->
982 --->| |<---| |<---| |<---| |<---
983 +---+ +---+ +---+ +---+
984

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을 대상으로 작성되었다.

링 버퍼 핵심 용어
용어
`tail`링 버퍼에서 새 쓰기가 일어나는 위치
`head`링 버퍼에서 새 읽기가 일어나는 위치
`producer`링 버퍼에 쓰는 태스크; writer와 같음
`writer`producer와 같음
`consumer`버퍼에서 읽는 태스크; reader와 같음
`reader`consumer와 같음
`reader_page`대부분 reader만 사용하며 링 버퍼 바깥에 있는 페이지
`head_page`reader가 다음에 사용할 페이지를 가리키는 포인터
`tail_page`다음 쓰기가 수행될 페이지를 가리키는 포인터
`commit_page`중첩되지 않은 쓰기 중 마지막으로 완료된 쓰기가 있는 페이지를 가리키는 포인터

쓰기·읽기 위치와 링 바깥의 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`를 비교하면 갱신이 성공했는지 확인할 수 있다.

cmpxchg 원자적 비교·교환
현재 A 읽기이전 A를 R에 저장
A == CA를 B로 교체
A != CA를 변경하지 않음
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 모드로 사용할 수 있다.

링 버퍼 동작 모드
모드버퍼가 찼을 때유실되는 이벤트
producer/consumerproducer가 쓰기를 중단가장 최근 이벤트
overwrite오래된 데이터를 덮어씀가장 오래된 이벤트

consumer가 공간을 비우기 전에 producer가 버퍼를 채웠을 때의 정책이 다르다.

같은 CPU별 버퍼에서 두 writer가 동시에 쓸 수는 없다. 다만 한 writer를 다른 writer가 인터럽트할 수 있으며, 새 writer는 이전 writer가 계속하기 전에 반드시 쓰기를 끝내야 한다. 이 성질은 알고리즘의 핵심으로, writer들은 인터럽트 동작이 강제하는 스택처럼 행동한다.

  writer1 start
     <preempted> writer2 start
         <preempted> writer3 start
                     writer3 finishes
                 writer2 finishes
  writer1 finishes
writer 스택 규칙
writer1 시작writer2가 선점
writer2 시작writer3가 선점
writer3 완료writer2 재개·완료
writer1 재개writer1 완료

나중에 진입한 writer가 먼저 완료되는 LIFO 순서를 지킨다.

이는 writer가 인터럽트에 의해 선점되고 그 인터럽트도 쓰기를 수행하는 상황과 같다.

reader는 언제든 실행될 수 있지만 두 reader가 동시에 실행되어서는 안 되며, 한 reader가 다른 reader를 선점하거나 인터럽트할 수도 없다. reader는 writer를 선점하거나 인터럽트할 수 없다. 다른 프로세서에서는 writer가 쓰는 동안 동시에 읽거나 소비할 수 있다. reader는 자기 프로세서에서 읽다가 writer에게 선점될 수 있다.

reader와 writer 동시성
관계허용 여부조건
writer가 writer 선점허용중첩 writer가 먼저 완료
reader가 reader 선점불가reader 직렬화 필요
reader가 writer 선점불가writer 진행을 방해하지 않음
writer가 reader 선점허용reader는 나중에 재개
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 교환
빈 reader pagenext=head, previous=head의 이전 페이지
교환 준비reader page를 head 위치에 연결
기존 head 분리이전 reader page는 버퍼 페이지가 됨
기존 head 전달새 reader page가 됨
삽입 페이지의 다음새 head page

링 바깥의 빈 reader page를 링에 넣고 현재 head page를 reader 전용 페이지로 꺼낸다.

교환 전후 페이지 역할
페이지교환 전교환 후
기존 reader page링 바깥의 빈 reader 전용 페이지링 안의 buffer page
기존 head page다음 읽기 대상링 바깥의 새 reader page
기존 head의 다음 페이지일반 buffer page새 head page

원문의 네 단계 ASCII 그림을 역할 변화로 다시 구성했다.

reader 교환의 링크 재배선
reader.next기존 head
head 이전 페이지.next기존 reader page
기존 reader page.next새 head
새 head.previous기존 reader page
기존 head새 reader page로 분리

원문의 단계별 화살표를 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의 연결은 여전히 링의 다음 위치를 가리킨다.

commit·tail 페이지 교환
reader page가 commit·tail을 가리킴커밋 데이터가 한 페이지 미만
reader가 페이지 교환commit·tail 페이지가 링 밖 reader page가 됨
writer가 페이지를 떠남교환해 넣은 페이지가 링의 쓰기 위치가 됨
reader 연결 유지다음 버퍼 위치로 계속 진행

부분적으로 채워진 페이지를 reader가 꺼내도 writer가 빠져나갈 때 연결 관계가 링으로 복귀한다.

reader·commit·tail 포인터 중첩
포인터같은 페이지를 가리킬 때의 의미
reader pagereader가 소비할 현재 페이지
commit page그 페이지 안의 마지막 full commit
tail page그 페이지 안의 마지막 예약 위치
head page링 안에서 reader page 다음에 읽을 페이지

하나의 링 밖 페이지가 세 역할을 동시에 가질 때도 각 포인터의 의미는 유지된다.

주요 페이지 포인터
포인터역할
reader pagereader만 사용하며 링에 속하지 않지만 교환되어 들어갈 수 있는 페이지
head page다음에 reader page와 교환될 링 버퍼 페이지
tail page다음 쓰기가 수행될 페이지
commit page마지막으로 쓰기를 완료한 페이지

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한다. 이 트랜잭션 도중 다른 쓰기나 읽기가 언제든 발생할 수 있으며, 새 쓰기가 시작되면 이전 쓰기가 계속되기 전에 반드시 끝나야 한다.

단일 writer의 reserve와 commit
단계기존 영역새 영역포인터
reserve 전writtenemptycommit은 마지막 written
reservewrittenreservedtail은 reserved 뒤
commitwrittenwrittencurrent commit은 다음 쓰기 위치

예약 시 tail이 전진하고 commit이 끝나면 그 위치가 다음 쓰기 기준이 된다.

중첩 예약 슬롯 상태
시점writer1 슬롯writer2 슬롯full commit
writer1 reservereservedempty이전 written까지
writer2 reservereservedreserved이전 written까지
writer2 commitreservedpending commit변화 없음
writer1 commitwrittenwrittenwriter2 슬롯까지 전진

두 writer의 예약과 commit이 슬롯에 표시되는 상태를 분리했다.

첫 번째 writer가 예약한 뒤 두 번째 writer가 선점하면 두 번째 writer도 다음 공간을 예약한다. 두 번째 writer가 먼저 commit해도 그 기록은 `pending commit`일 뿐 `full commit`이 아니다. 첫 번째 writer가 commit해야 연속된 두 예약이 모두 written이 되고 마지막 full commit과 tail이 같은 끝 위치에 도달한다.

중첩 writer commit 승격
writer1 reservecommit 뒤에 reserved
writer2 reservetail을 더 전진
writer2 commitpending commit
writer1 commitwriter1과 writer2 모두 full commit
commit과 tail마지막 연속 written 위치

안쪽 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 page다음 읽기·교환 대상
중간 buffer pages커밋된 데이터
commit page마지막 full commit
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이 끝날 때까지 버퍼는 비어 있는 것으로 간주한다.

일반 순서와 교환 예외
상태링 안 순서링 밖
일반head → commit → tailreader page
부분 페이지 교환head가 commit·tail의 다음 위치reader page가 commit·tail 역할도 보유
읽기 한계마지막 full commit까지pending·reserved는 미노출

commit 페이지가 링 밖 reader page에 있을 때 head의 상대 위치가 달라진다.

commit이 링 밖에 있을 때 읽기 종료
reader가 reader page 소비마지막 full commit 도달
pending 또는 reserved 확인아직 읽지 않음
읽을 데이터 없음버퍼를 empty로 보고
가장 바깥 writer commit새 full commit 공개

reader가 실제 commit을 만난 뒤 새 full commit 전까지 빈 버퍼로 처리하는 경로다.

tail이 head page를 만나면 overwrite 모드에서는 head를 한 페이지 앞으로 밀고, producer/consumer 모드에서는 쓰기가 실패한다.

overwrite에서 tail과 head 충돌
tail의 다음이 head버퍼가 가득 참
head를 한 페이지 전진가장 오래된 페이지 포기
tail 전진새 쓰기 공간 확보

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
포인터 상태 비트
상태의미표기
NORMAL일반 페이지 연결`-->`
HEADER포인터가 가리키는 다음 페이지가 head page`-H->`
UPDATEwriter가 해당 연결을 갱신 중이며 이전 또는 곧 head가 될 페이지`-U->`

주소의 하위 2비트로 head 이동과 writer 갱신 상태를 표시한다.

H와 U 연결 해석
연결다음 페이지reader 동작
`pageA -H-> pageB`pageB가 headpageB를 교환 대상으로 사용 가능
`pageA -U-> pageB`pageB 관련 head 이동 중교환하지 않고 재시도
`pageA --> pageB`일반 연결head 후보가 아님

플래그는 페이지 자체가 아니라 그 페이지를 가리키는 연결 포인터에 들어간다.

`-H->` 포인터는 다음 페이지가 reader가 교환해 꺼낼 head page임을 뜻한다. tail page가 이 head 포인터를 만나면 `cmpxchg`로 포인터를 `HEADER`에서 `UPDATE` 상태로 바꾼다.

head 포인터 상태 전환
HEADERtail이 head 포인터를 만남
cmpxchgHEADER → UPDATE
UPDATEwriter가 head 이동 독점
새 HEADER 설정이전 UPDATE를 NORMAL로 복원

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-592

reader는 먼저 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가 된다.

reader 원자적 교환 순서
reader.next 준비head 다음 페이지를 HEADER로 가리킴
이전 head의 앞 포인터 cmpxchgreader page로 원자 교체
새 head 확정새 head.previous를 reader page로 갱신
역할 교환기존 reader는 buffer, 기존 head는 reader

준비한 연결을 cmpxchg 한 번으로 공개한 뒤 역방향 연결을 정리한다.

reader swap cmpxchg 결과
예상 HEADER 읽기교환용 연결 준비
cmpxchg 성공reader page 삽입·기존 head 분리
cmpxchg 실패HEADER 또는 주소가 변경됨
새 head 탐색교환 준비부터 재시도

비교 대상이 바뀌었으면 writer가 head를 이동한 것이므로 새 위치에서 전체 절차를 반복한다.

교환 중 포인터 불변식
검사보장
링의 `next` 포인터 순회항상 링 버퍼 안에 머묾
링의 `previous` 포인터 순회reader page로 나갈 수 있음
reader page의 previous 대상그 페이지의 next는 reader page를 가리키지 않고 새 head를 가리킴

링 바깥 reader page 때문에 next와 previous 순회 특성이 다르다.

reader page의 `previous`가 가리키는 페이지는 reader page를 다시 가리키지 않는다. reader page는 링 버퍼의 일부가 아니기 때문이다. 따라서 `next`로 순회하면 항상 링 안에 있지만 `previous`로 순회하면 그렇지 않을 수 있다.

어떤 페이지가 reader page인지 판별하려면 그 페이지의 `previous`를 확인한다. 이전 페이지의 `next`가 원래 페이지를 다시 가리키지 않는다면 원래 페이지가 reader page다.

reader page 식별
후보 페이지 PP.previous = Q
Q.next 검사Q.next != P
불일치P는 링 밖 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-653

overwrite 모드에서 tail page가 head page를 만나고 쓰기가 계속되면 writer가 tail을 움직이기 전에 head를 앞으로 이동해야 한다. writer는 `cmpxchg`로 head page를 가리키는 포인터를 `HEADER`에서 `UPDATE`로 바꾼다.

`UPDATE`가 설정되면 writer가 이동을 끝낼 때까지 reader는 head page를 교환하거나 움직일 수 없다. 이렇게 reader와 writer 사이의 경쟁을 제거한다. reader는 writer가 끝날 때까지 회전해야 하므로 reader가 writer를 선점해서는 안 된다.

writer의 기본 head 이동
tail 다음 = headHEADER 연결 확인
cmpxchg H → Ureader 교환 차단
다음 페이지에 HEADER새 head page 지정
이전 UPDATE → NORMAL오래된 head 연결 복원
tail 전진새 쓰기 위치 확보

HEADER 연결을 UPDATE로 잠시 소유한 뒤 다음 페이지를 새 head로 지정한다.

기본 상태 전이
순서이전 head 연결새 head 연결tail
1HEADERNORMAL이전 head 앞
2UPDATENORMAL대기
3UPDATEHEADER대기
4NORMALHEADER대기
5NORMALHEADER한 페이지 전진

원문의 연속 ASCII 그림을 포인터 상태와 이동 주체로 나타냈다.

H-U-H 포인터 배치
P0 -H→ P1P1이 기존 head
P0 -U→ P1P0 연결 갱신 중
P1 -H→ P2P2를 새 head로 지정
P0 → P1이전 연결 NORMAL
tail = P1writer 전진

이전 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이 버퍼를 한 바퀴 돌았다고 보고 새 쓰기를 버린다.

reader page의 commit 감지
tail이 head 도달commit 위치 검사
commit != reader page일반 overwrite head 이동
commit == reader pagetail이 링을 한 바퀴 돈 상태
새 쓰기버리고 경고

링 밖 commit을 지나쳐 덮어쓰지 않도록 head 이동 전에 포화 상태를 판정한다.

commit 위치별 tail 처리
commit 위치tail 해석조치
링 안의 commit page아직 commit을 따라잡지 않음필요하면 head를 밀고 tail 전진
링 밖 reader pagetail이 전체 링을 순환해 commit에 도달새 쓰기 drop
reader page를 떠난 뒤다시 교환되기 전에는 돌아오지 않음reader가 위치를 안정적으로 검사

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-744

tail 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가 다시 밀 필요는 없다.

중첩 writer와 tail cmpxchg
temp_page = tail_pagenext_page 계산
중첩 writer 없음cmpxchg 성공·tail 전진
중첩 writer가 선점중첩 writer가 tail 전진
바깥 cmpxchg 실패새 tail에서 저장 공간 재예약

실패를 충돌이 아니라 이미 완료된 전진으로 해석하고 새 tail에서 예약을 다시 시도한다.

tail cmpxchg 결과
비교 결과원인현재 writer
성공tail이 temp_page에 그대로 있음next_page에서 예약 계속
실패중첩 writer가 tail을 이동새 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-805

head page 이동은 더 복잡하다. 바깥 writer가 head 포인터를 `HEADER`에서 `UPDATE`로 바꾼 직후 중첩 writer가 선점할 수 있다.

중첩 writer는 다음 페이지가 head page이면서 자신이 중첩 상태임을 알아낸다. `HEADER`나 `NORMAL`이 아니라 `UPDATE` 플래그를 본다는 사실로 이를 감지하고 그 정보를 보존한다.

중첩 writer는 다음 페이지를 새 head page로 설정하지만 오래된 `UPDATE` 포인터를 `NORMAL`로 되돌리지 않는다. `HEADER`를 `UPDATE`로 직접 바꾼 writer만 그 `UPDATE`를 다시 `NORMAL`로 바꿀 수 있다.

중첩 head 이동의 소유권
바깥 writerHEADER → UPDATE
중첩 writer가 UPDATE 발견중첩 상태 기록
중첩 writer다음 연결에 HEADER 설정
중첩 writertail 이동 후 종료; UPDATE 유지
바깥 writer 재개자신의 UPDATE → NORMAL

UPDATE를 만든 writer만 상태를 해제해 reader가 중간 상태를 보지 않게 한다.

UPDATE 소유자 복귀
old head 연결 UPDATEreader가 회전
new head 연결 HEADER중첩 writer가 공개
중첩 writer 종료UPDATE 그대로
소유 writer 복귀UPDATE를 NORMAL로 해제
reader 재시도최신 HEADER 사용

중첩 writer가 새 head를 만든 뒤에도 reader 차단은 바깥 writer가 복귀할 때까지 유지된다.

상태 변경 책임
writer설정해제
바깥 writer기존 head의 HEADER를 UPDATE로 변경중첩 쓰기 종료 후 UPDATE를 NORMAL로 변경
중첩 writer새 head 연결에 HEADER 설정바깥 writer 소유 UPDATE는 유지

각 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의 중첩 이동
writer1H1: HEADER → UPDATE
writer2H2: HEADER 설정·tail 전진; H1 UPDATE 유지
writer3H2: HEADER → UPDATE
writer3H3: HEADER 설정·H2 NORMAL·tail 전진
writer2 재개tail cmpxchg 실패·새 tail에 데이터 예약
writer1 재개head 후보 사후 검증

각 writer가 획득한 UPDATE만 해제하면서 head와 tail을 단계적으로 전진시킨다.

중첩 writer별 포인터 변화
단계H1 연결H2 연결H3 연결tail
writer1 진입UPDATENORMALNORMAL첫 위치
writer2 head 설정UPDATEHEADERNORMAL한 칸 전진
writer3 진입UPDATEUPDATENORMAL두 번째 위치
writer3 head 설정UPDATEUPDATEHEADER대기
writer3 완료UPDATENORMALHEADER한 칸 더 전진

원문의 writer별 상태 그림을 한 단계씩 비교한다.

두 번째 writer는 tail이 이미 움직였으므로 자신의 tail `cmpxchg`에 실패한다. 그러면 새 tail page에서 데이터 예약을 다시 시도하고 첫 번째 writer로 돌아간다.

첫 번째 writer는 자신이 head page를 갱신하는 동안 tail page가 이동했는지를 하나의 원자 연산으로 알 수 없다. 따라서 자신이 새 head라고 생각하는 페이지에 `HEADER`를 설정할 수 있고, 그 결과 잠시 `HEADER`가 두 곳에 존재할 수 있다.

`cmpxchg`가 이전 포인터 값을 반환하므로 첫 번째 writer는 `NORMAL`에서 `HEADER`로의 변경 자체가 성공했음을 알 수 있다. 하지만 그것만으로 충분하지 않다. tail page가 원래 위치 `A` 또는 바로 다음 페이지 `B`에 있는지도 확인해야 한다.

첫 writer의 head 후보 사후 검사
조건판정조치
tail == Atail이 이동하지 않음설정한 HEADER 유지
tail == B한 단계 이동설정한 HEADER 유지 가능
tail != A && tail != B중첩 writer가 두 단계 이상 이동첫 writer가 설정한 포인터를 NORMAL로 재설정

tail이 예상 범위를 벗어났다면 중첩 writer가 이미 더 먼 head를 만들었으므로 잘못 만든 HEADER를 취소한다.

A/B tail 검증
후보 HEADER 설정tail 읽기
tail = A후보 유효
tail = B후보 유효 범위
tail이 A·B 밖후보 HEADER 제거
최신 HEADER중첩 writer가 만든 head 유지

head 후보를 만든 뒤 tail의 실제 위치로 중첩 전진 정도를 판별한다.

tail이 `A`도 `B`도 아니면 첫 writer는 자신이 바꾼 포인터를 `NORMAL`로 되돌려야 한다. 경쟁 상대가 같은 CPU에서 스택 형태로 들어오는 중첩 writer뿐이므로 `HEADER`를 설정한 뒤 이 검사를 수행해도 충분하다.

잘못된 후보를 정리한 뒤 writer는 실제 head page를 갱신할 수 있다. 이 과정에서도 원래 head 연결은 가장 바깥 writer가 끝낼 때까지 `UPDATE`로 남아 있어야 한다. 그래야 reader가 중간에 만들어진 잘못된 head page를 관찰하지 않는다.

잘못된 HEADER 복구
첫 writer가 후보 HEADER 설정cmpxchg 성공
tail 위치 검사A 또는 B인지 확인
예상 밖 tail후보 HEADER → NORMAL
실제 최신 HEADER 유지reader에는 UPDATE로 차단
가장 바깥 writer 완료오래된 UPDATE → NORMAL

첫 writer가 복귀한 뒤 tail 위치로 후보의 유효성을 확인하고 실제 head만 공개한다.

reader에게 공개되는 상태
시점reader가 보는 상태행동
중첩 이동 중오래된 연결 UPDATE회전하며 대기
후보가 두 개여전히 UPDATE로 차단잘못된 HEADER를 소비하지 않음
사후 검사 완료최신 HEADER 하나새 head에서 교환 재시도
바깥 writer 종료UPDATE가 NORMAL정상 읽기 진행

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->
  --->|   |<---|   |<---|   |<---|   |<---
      +---+    +---+    +---+    +---+