← Documents Documentation/RCU/Design/Data-Structures/Data-Structures.rst GitHub 원문 ↗

Linux 6.18.37 · RCU

TREE_RCU의 자료구조 둘러보기

TREE_RCU의 rcu_state, rcu_node, rcu_segcblist, rcu_data, rcu_head와 task_struct 상태가 결합 트리와 grace period를 구현하는 방식을 설명합니다.

Source pathDocumentation/RCU/Design/Data-Structures/Data-Structures.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

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

1. 요약·해설

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

요약·해설

Data-Structures.rst:1-1196

TREE_RCU가 전역 grace-period 상태를 계층적으로 분산하고 CPU별 quiescent state와 callback을 확장성 있게 처리하는 자료구조 설계 안내서입니다.

2. 영어 원문 전체

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

원문 전체 펼치기
1 ===================================================
2 A Tour Through TREE_RCU's Data Structures [LWN.net]
3 ===================================================
4
5 December 18, 2016
6
7 This article was contributed by Paul E. McKenney
8
9 Introduction
10 ============
11
12 This document describes RCU's major data structures and their relationship
13 to each other.
14
15 Data-Structure Relationships
16 ============================
17
18 RCU is for all intents and purposes a large state machine, and its
19 data structures maintain the state in such a way as to allow RCU readers
20 to execute extremely quickly, while also processing the RCU grace periods
21 requested by updaters in an efficient and extremely scalable fashion.
22 The efficiency and scalability of RCU updaters is provided primarily
23 by a combining tree, as shown below:
24
25 .. kernel-figure:: BigTreeClassicRCU.svg
26
27 This diagram shows an enclosing ``rcu_state`` structure containing a tree
28 of ``rcu_node`` structures. Each leaf node of the ``rcu_node`` tree has up
29 to 16 ``rcu_data`` structures associated with it, so that there are
30 ``NR_CPUS`` number of ``rcu_data`` structures, one for each possible CPU.
31 This structure is adjusted at boot time, if needed, to handle the common
32 case where ``nr_cpu_ids`` is much less than ``NR_CPUs``.
33 For example, a number of Linux distributions set ``NR_CPUs=4096``,
34 which results in a three-level ``rcu_node`` tree.
35 If the actual hardware has only 16 CPUs, RCU will adjust itself
36 at boot time, resulting in an ``rcu_node`` tree with only a single node.
37
38 The purpose of this combining tree is to allow per-CPU events
39 such as quiescent states, dyntick-idle transitions,
40 and CPU hotplug operations to be processed efficiently
41 and scalably.
42 Quiescent states are recorded by the per-CPU ``rcu_data`` structures,
43 and other events are recorded by the leaf-level ``rcu_node``
44 structures.
45 All of these events are combined at each level of the tree until finally
46 grace periods are completed at the tree's root ``rcu_node``
47 structure.
48 A grace period can be completed at the root once every CPU
49 (or, in the case of ``CONFIG_PREEMPT_RCU``, task)
50 has passed through a quiescent state.
51 Once a grace period has completed, record of that fact is propagated
52 back down the tree.
53
54 As can be seen from the diagram, on a 64-bit system
55 a two-level tree with 64 leaves can accommodate 1,024 CPUs, with a fanout
56 of 64 at the root and a fanout of 16 at the leaves.
57
58 +-----------------------------------------------------------------------+
59 | **Quick Quiz**: |
60 +-----------------------------------------------------------------------+
61 | Why isn't the fanout at the leaves also 64? |
62 +-----------------------------------------------------------------------+
63 | **Answer**: |
64 +-----------------------------------------------------------------------+
65 | Because there are more types of events that affect the leaf-level |
66 | ``rcu_node`` structures than further up the tree. Therefore, if the |
67 | leaf ``rcu_node`` structures have fanout of 64, the contention on |
68 | these structures' ``->structures`` becomes excessive. Experimentation |
69 | on a wide variety of systems has shown that a fanout of 16 works well |
70 | for the leaves of the ``rcu_node`` tree. |
71 | |
72 | Of course, further experience with systems having hundreds or |
73 | thousands of CPUs may demonstrate that the fanout for the non-leaf |
74 | ``rcu_node`` structures must also be reduced. Such reduction can be |
75 | easily carried out when and if it proves necessary. In the meantime, |
76 | if you are using such a system and running into contention problems |
77 | on the non-leaf ``rcu_node`` structures, you may use the |
78 | ``CONFIG_RCU_FANOUT`` kernel configuration parameter to reduce the |
79 | non-leaf fanout as needed. |
80 | |
81 | Kernels built for systems with strong NUMA characteristics might |
82 | also need to adjust ``CONFIG_RCU_FANOUT`` so that the domains of |
83 | the ``rcu_node`` structures align with hardware boundaries. |
84 | However, there has thus far been no need for this. |
85 +-----------------------------------------------------------------------+
86
87 If your system has more than 1,024 CPUs (or more than 512 CPUs on a
88 32-bit system), then RCU will automatically add more levels to the tree.
89 For example, if you are crazy enough to build a 64-bit system with
90 65,536 CPUs, RCU would configure the ``rcu_node`` tree as follows:
91
92 .. kernel-figure:: HugeTreeClassicRCU.svg
93
94 RCU currently permits up to a four-level tree, which on a 64-bit system
95 accommodates up to 4,194,304 CPUs, though only a mere 524,288 CPUs for
96 32-bit systems. On the other hand, you can set both
97 ``CONFIG_RCU_FANOUT`` and ``CONFIG_RCU_FANOUT_LEAF`` to be as small as
98 2, which would result in a 16-CPU test using a 4-level tree. This can be
99 useful for testing large-system capabilities on small test machines.
100
101 This multi-level combining tree allows us to get most of the performance
102 and scalability benefits of partitioning, even though RCU grace-period
103 detection is inherently a global operation. The trick here is that only
104 the last CPU to report a quiescent state into a given ``rcu_node``
105 structure need advance to the ``rcu_node`` structure at the next level
106 up the tree. This means that at the leaf-level ``rcu_node`` structure,
107 only one access out of sixteen will progress up the tree. For the
108 internal ``rcu_node`` structures, the situation is even more extreme:
109 Only one access out of sixty-four will progress up the tree. Because the
110 vast majority of the CPUs do not progress up the tree, the lock
111 contention remains roughly constant up the tree. No matter how many CPUs
112 there are in the system, at most 64 quiescent-state reports per grace
113 period will progress all the way to the root ``rcu_node`` structure,
114 thus ensuring that the lock contention on that root ``rcu_node``
115 structure remains acceptably low.
116
117 In effect, the combining tree acts like a big shock absorber, keeping
118 lock contention under control at all tree levels regardless of the level
119 of loading on the system.
120
121 RCU updaters wait for normal grace periods by registering RCU callbacks,
122 either directly via ``call_rcu()`` or indirectly via
123 ``synchronize_rcu()`` and friends. RCU callbacks are represented by
124 ``rcu_head`` structures, which are queued on ``rcu_data`` structures
125 while they are waiting for a grace period to elapse, as shown in the
126 following figure:
127
128 .. kernel-figure:: BigTreePreemptRCUBHdyntickCB.svg
129
130 This figure shows how ``TREE_RCU``'s and ``PREEMPT_RCU``'s major data
131 structures are related. Lesser data structures will be introduced with
132 the algorithms that make use of them.
133
134 Note that each of the data structures in the above figure has its own
135 synchronization:
136
137 #. Each ``rcu_state`` structures has a lock and a mutex, and some fields
138 are protected by the corresponding root ``rcu_node`` structure's lock.
139 #. Each ``rcu_node`` structure has a spinlock.
140 #. The fields in ``rcu_data`` are private to the corresponding CPU,
141 although a few can be read and written by other CPUs.
142
143 It is important to note that different data structures can have very
144 different ideas about the state of RCU at any given time. For but one
145 example, awareness of the start or end of a given RCU grace period
146 propagates slowly through the data structures. This slow propagation is
147 absolutely necessary for RCU to have good read-side performance. If this
148 balkanized implementation seems foreign to you, one useful trick is to
149 consider each instance of these data structures to be a different
150 person, each having the usual slightly different view of reality.
151
152 The general role of each of these data structures is as follows:
153
154 #. ``rcu_state``: This structure forms the interconnection between the
155 ``rcu_node`` and ``rcu_data`` structures, tracks grace periods,
156 serves as short-term repository for callbacks orphaned by CPU-hotplug
157 events, maintains ``rcu_barrier()`` state, tracks expedited
158 grace-period state, and maintains state used to force quiescent
159 states when grace periods extend too long,
160 #. ``rcu_node``: This structure forms the combining tree that propagates
161 quiescent-state information from the leaves to the root, and also
162 propagates grace-period information from the root to the leaves. It
163 provides local copies of the grace-period state in order to allow
164 this information to be accessed in a synchronized manner without
165 suffering the scalability limitations that would otherwise be imposed
166 by global locking. In ``CONFIG_PREEMPT_RCU`` kernels, it manages the
167 lists of tasks that have blocked while in their current RCU read-side
168 critical section. In ``CONFIG_PREEMPT_RCU`` with
169 ``CONFIG_RCU_BOOST``, it manages the per-\ ``rcu_node``
170 priority-boosting kernel threads (kthreads) and state. Finally, it
171 records CPU-hotplug state in order to determine which CPUs should be
172 ignored during a given grace period.
173 #. ``rcu_data``: This per-CPU structure is the focus of quiescent-state
174 detection and RCU callback queuing. It also tracks its relationship
175 to the corresponding leaf ``rcu_node`` structure to allow
176 more-efficient propagation of quiescent states up the ``rcu_node``
177 combining tree. Like the ``rcu_node`` structure, it provides a local
178 copy of the grace-period information to allow for-free synchronized
179 access to this information from the corresponding CPU. Finally, this
180 structure records past dyntick-idle state for the corresponding CPU
181 and also tracks statistics.
182 #. ``rcu_head``: This structure represents RCU callbacks, and is the
183 only structure allocated and managed by RCU users. The ``rcu_head``
184 structure is normally embedded within the RCU-protected data
185 structure.
186
187 If all you wanted from this article was a general notion of how RCU's
188 data structures are related, you are done. Otherwise, each of the
189 following sections give more details on the ``rcu_state``, ``rcu_node``
190 and ``rcu_data`` data structures.
191
192 The ``rcu_state`` Structure
193 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
194
195 The ``rcu_state`` structure is the base structure that represents the
196 state of RCU in the system. This structure forms the interconnection
197 between the ``rcu_node`` and ``rcu_data`` structures, tracks grace
198 periods, contains the lock used to synchronize with CPU-hotplug events,
199 and maintains state used to force quiescent states when grace periods
200 extend too long,
201
202 A few of the ``rcu_state`` structure's fields are discussed, singly and
203 in groups, in the following sections. The more specialized fields are
204 covered in the discussion of their use.
205
206 Relationship to rcu_node and rcu_data Structures
207 ''''''''''''''''''''''''''''''''''''''''''''''''
208
209 This portion of the ``rcu_state`` structure is declared as follows:
210
211 ::
212
213 1 struct rcu_node node[NUM_RCU_NODES];
214 2 struct rcu_node *level[NUM_RCU_LVLS + 1];
215 3 struct rcu_data __percpu *rda;
216
217 +-----------------------------------------------------------------------+
218 | **Quick Quiz**: |
219 +-----------------------------------------------------------------------+
220 | Wait a minute! You said that the ``rcu_node`` structures formed a |
221 | tree, but they are declared as a flat array! What gives? |
222 +-----------------------------------------------------------------------+
223 | **Answer**: |
224 +-----------------------------------------------------------------------+
225 | The tree is laid out in the array. The first node In the array is the |
226 | head, the next set of nodes in the array are children of the head |
227 | node, and so on until the last set of nodes in the array are the |
228 | leaves. |
229 | See the following diagrams to see how this works. |
230 +-----------------------------------------------------------------------+
231
232 The ``rcu_node`` tree is embedded into the ``->node[]`` array as shown
233 in the following figure:
234
235 .. kernel-figure:: TreeMapping.svg
236
237 One interesting consequence of this mapping is that a breadth-first
238 traversal of the tree is implemented as a simple linear scan of the
239 array, which is in fact what the ``rcu_for_each_node_breadth_first()``
240 macro does. This macro is used at the beginning and ends of grace
241 periods.
242
243 Each entry of the ``->level`` array references the first ``rcu_node``
244 structure on the corresponding level of the tree, for example, as shown
245 below:
246
247 .. kernel-figure:: TreeMappingLevel.svg
248
249 The zero\ :sup:`th` element of the array references the root
250 ``rcu_node`` structure, the first element references the first child of
251 the root ``rcu_node``, and finally the second element references the
252 first leaf ``rcu_node`` structure.
253
254 For whatever it is worth, if you draw the tree to be tree-shaped rather
255 than array-shaped, it is easy to draw a planar representation:
256
257 .. kernel-figure:: TreeLevel.svg
258
259 Finally, the ``->rda`` field references a per-CPU pointer to the
260 corresponding CPU's ``rcu_data`` structure.
261
262 All of these fields are constant once initialization is complete, and
263 therefore need no protection.
264
265 Grace-Period Tracking
266 '''''''''''''''''''''
267
268 This portion of the ``rcu_state`` structure is declared as follows:
269
270 ::
271
272 1 unsigned long gp_seq;
273
274 RCU grace periods are numbered, and the ``->gp_seq`` field contains the
275 current grace-period sequence number. The bottom two bits are the state
276 of the current grace period, which can be zero for not yet started or
277 one for in progress. In other words, if the bottom two bits of
278 ``->gp_seq`` are zero, then RCU is idle. Any other value in the bottom
279 two bits indicates that something is broken. This field is protected by
280 the root ``rcu_node`` structure's ``->lock`` field.
281
282 There are ``->gp_seq`` fields in the ``rcu_node`` and ``rcu_data``
283 structures as well. The fields in the ``rcu_state`` structure represent
284 the most current value, and those of the other structures are compared
285 in order to detect the beginnings and ends of grace periods in a
286 distributed fashion. The values flow from ``rcu_state`` to ``rcu_node``
287 (down the tree from the root to the leaves) to ``rcu_data``.
288
289 +-----------------------------------------------------------------------+
290 | **Quick Quiz**: |
291 +-----------------------------------------------------------------------+
292 | Given that the root rcu_node structure has a gp_seq field, |
293 | why does RCU maintain a separate gp_seq in the rcu_state structure? |
294 | Why not just use the root rcu_node's gp_seq as the official record |
295 | and update it directly when starting a new grace period? |
296 +-----------------------------------------------------------------------+
297 | **Answer**: |
298 +-----------------------------------------------------------------------+
299 | On single-node RCU trees (where the root node is also a leaf), |
300 | updating the root node's gp_seq immediately would create unnecessary |
301 | lock contention. Here's why: |
302 | |
303 | If we did rcu_seq_start() directly on the root node's gp_seq: |
304 | |
305 | 1. All CPUs would immediately see their node's gp_seq from their rdp's|
306 | gp_seq, in rcu_pending(). They would all then invoke the RCU-core. |
307 | 2. Which calls note_gp_changes() and try to acquire the node lock. |
308 | 3. But rnp->qsmask isn't initialized yet (happens later in |
309 | rcu_gp_init()) |
310 | 4. So each CPU would acquire the lock, find it can't determine if it |
311 | needs to report quiescent state (no qsmask), update rdp->gp_seq, |
312 | and release the lock. |
313 | 5. Result: Lots of lock acquisitions with no grace period progress |
314 | |
315 | By having a separate rcu_state.gp_seq, we can increment the official |
316 | grace period counter without immediately affecting what CPUs see in |
317 | their nodes. The hierarchical propagation in rcu_gp_init() then |
318 | updates the root node's gp_seq and qsmask together under the same lock|
319 | acquisition, avoiding this useless contention. |
320 +-----------------------------------------------------------------------+
321
322 Miscellaneous
323 '''''''''''''
324
325 This portion of the ``rcu_state`` structure is declared as follows:
326
327 ::
328
329 1 unsigned long gp_max;
330 2 char abbr;
331 3 char *name;
332
333 The ``->gp_max`` field tracks the duration of the longest grace period
334 in jiffies. It is protected by the root ``rcu_node``'s ``->lock``.
335
336 The ``->name`` and ``->abbr`` fields distinguish between preemptible RCU
337 (“rcu_preempt” and “p”) and non-preemptible RCU (“rcu_sched” and “s”).
338 These fields are used for diagnostic and tracing purposes.
339
340 The ``rcu_node`` Structure
341 ~~~~~~~~~~~~~~~~~~~~~~~~~~
342
343 The ``rcu_node`` structures form the combining tree that propagates
344 quiescent-state information from the leaves to the root and also that
345 propagates grace-period information from the root down to the leaves.
346 They provides local copies of the grace-period state in order to allow
347 this information to be accessed in a synchronized manner without
348 suffering the scalability limitations that would otherwise be imposed by
349 global locking. In ``CONFIG_PREEMPT_RCU`` kernels, they manage the lists
350 of tasks that have blocked while in their current RCU read-side critical
351 section. In ``CONFIG_PREEMPT_RCU`` with ``CONFIG_RCU_BOOST``, they
352 manage the per-\ ``rcu_node`` priority-boosting kernel threads
353 (kthreads) and state. Finally, they record CPU-hotplug state in order to
354 determine which CPUs should be ignored during a given grace period.
355
356 The ``rcu_node`` structure's fields are discussed, singly and in groups,
357 in the following sections.
358
359 Connection to Combining Tree
360 ''''''''''''''''''''''''''''
361
362 This portion of the ``rcu_node`` structure is declared as follows:
363
364 ::
365
366 1 struct rcu_node *parent;
367 2 u8 level;
368 3 u8 grpnum;
369 4 unsigned long grpmask;
370 5 int grplo;
371 6 int grphi;
372
373 The ``->parent`` pointer references the ``rcu_node`` one level up in the
374 tree, and is ``NULL`` for the root ``rcu_node``. The RCU implementation
375 makes heavy use of this field to push quiescent states up the tree. The
376 ``->level`` field gives the level in the tree, with the root being at
377 level zero, its children at level one, and so on. The ``->grpnum`` field
378 gives this node's position within the children of its parent, so this
379 number can range between 0 and 31 on 32-bit systems and between 0 and 63
380 on 64-bit systems. The ``->level`` and ``->grpnum`` fields are used only
381 during initialization and for tracing. The ``->grpmask`` field is the
382 bitmask counterpart of ``->grpnum``, and therefore always has exactly
383 one bit set. This mask is used to clear the bit corresponding to this
384 ``rcu_node`` structure in its parent's bitmasks, which are described
385 later. Finally, the ``->grplo`` and ``->grphi`` fields contain the
386 lowest and highest numbered CPU served by this ``rcu_node`` structure,
387 respectively.
388
389 All of these fields are constant, and thus do not require any
390 synchronization.
391
392 Synchronization
393 '''''''''''''''
394
395 This field of the ``rcu_node`` structure is declared as follows:
396
397 ::
398
399 1 raw_spinlock_t lock;
400
401 This field is used to protect the remaining fields in this structure,
402 unless otherwise stated. That said, all of the fields in this structure
403 can be accessed without locking for tracing purposes. Yes, this can
404 result in confusing traces, but better some tracing confusion than to be
405 heisenbugged out of existence.
406
407 .. _grace-period-tracking-1:
408
409 Grace-Period Tracking
410 '''''''''''''''''''''
411
412 This portion of the ``rcu_node`` structure is declared as follows:
413
414 ::
415
416 1 unsigned long gp_seq;
417 2 unsigned long gp_seq_needed;
418
419 The ``rcu_node`` structures' ``->gp_seq`` fields are the counterparts of
420 the field of the same name in the ``rcu_state`` structure. They each may
421 lag up to one step behind their ``rcu_state`` counterpart. If the bottom
422 two bits of a given ``rcu_node`` structure's ``->gp_seq`` field is zero,
423 then this ``rcu_node`` structure believes that RCU is idle.
424
425 The ``>gp_seq`` field of each ``rcu_node`` structure is updated at the
426 beginning and the end of each grace period.
427
428 The ``->gp_seq_needed`` fields record the furthest-in-the-future grace
429 period request seen by the corresponding ``rcu_node`` structure. The
430 request is considered fulfilled when the value of the ``->gp_seq`` field
431 equals or exceeds that of the ``->gp_seq_needed`` field.
432
433 +-----------------------------------------------------------------------+
434 | **Quick Quiz**: |
435 +-----------------------------------------------------------------------+
436 | Suppose that this ``rcu_node`` structure doesn't see a request for a |
437 | very long time. Won't wrapping of the ``->gp_seq`` field cause |
438 | problems? |
439 +-----------------------------------------------------------------------+
440 | **Answer**: |
441 +-----------------------------------------------------------------------+
442 | No, because if the ``->gp_seq_needed`` field lags behind the |
443 | ``->gp_seq`` field, the ``->gp_seq_needed`` field will be updated at |
444 | the end of the grace period. Modulo-arithmetic comparisons therefore |
445 | will always get the correct answer, even with wrapping. |
446 +-----------------------------------------------------------------------+
447
448 Quiescent-State Tracking
449 ''''''''''''''''''''''''
450
451 These fields manage the propagation of quiescent states up the combining
452 tree.
453
454 This portion of the ``rcu_node`` structure has fields as follows:
455
456 ::
457
458 1 unsigned long qsmask;
459 2 unsigned long expmask;
460 3 unsigned long qsmaskinit;
461 4 unsigned long expmaskinit;
462
463 The ``->qsmask`` field tracks which of this ``rcu_node`` structure's
464 children still need to report quiescent states for the current normal
465 grace period. Such children will have a value of 1 in their
466 corresponding bit. Note that the leaf ``rcu_node`` structures should be
467 thought of as having ``rcu_data`` structures as their children.
468 Similarly, the ``->expmask`` field tracks which of this ``rcu_node``
469 structure's children still need to report quiescent states for the
470 current expedited grace period. An expedited grace period has the same
471 conceptual properties as a normal grace period, but the expedited
472 implementation accepts extreme CPU overhead to obtain much lower
473 grace-period latency, for example, consuming a few tens of microseconds
474 worth of CPU time to reduce grace-period duration from milliseconds to
475 tens of microseconds. The ``->qsmaskinit`` field tracks which of this
476 ``rcu_node`` structure's children cover for at least one online CPU.
477 This mask is used to initialize ``->qsmask``, and ``->expmaskinit`` is
478 used to initialize ``->expmask`` and the beginning of the normal and
479 expedited grace periods, respectively.
480
481 +-----------------------------------------------------------------------+
482 | **Quick Quiz**: |
483 +-----------------------------------------------------------------------+
484 | Why are these bitmasks protected by locking? Come on, haven't you |
485 | heard of atomic instructions??? |
486 +-----------------------------------------------------------------------+
487 | **Answer**: |
488 +-----------------------------------------------------------------------+
489 | Lockless grace-period computation! Such a tantalizing possibility! |
490 | But consider the following sequence of events: |
491 | |
492 | #. CPU 0 has been in dyntick-idle mode for quite some time. When it |
493 | wakes up, it notices that the current RCU grace period needs it to |
494 | report in, so it sets a flag where the scheduling clock interrupt |
495 | will find it. |
496 | #. Meanwhile, CPU 1 is running ``force_quiescent_state()``, and |
497 | notices that CPU 0 has been in dyntick idle mode, which qualifies |
498 | as an extended quiescent state. |
499 | #. CPU 0's scheduling clock interrupt fires in the middle of an RCU |
500 | read-side critical section, and notices that the RCU core needs |
501 | something, so commences RCU softirq processing. |
502 | #. CPU 0's softirq handler executes and is just about ready to report |
503 | its quiescent state up the ``rcu_node`` tree. |
504 | #. But CPU 1 beats it to the punch, completing the current grace |
505 | period and starting a new one. |
506 | #. CPU 0 now reports its quiescent state for the wrong grace period. |
507 | That grace period might now end before the RCU read-side critical |
508 | section. If that happens, disaster will ensue. |
509 | |
510 | So the locking is absolutely required in order to coordinate clearing |
511 | of the bits with updating of the grace-period sequence number in |
512 | ``->gp_seq``. |
513 +-----------------------------------------------------------------------+
514
515 Blocked-Task Management
516 '''''''''''''''''''''''
517
518 ``PREEMPT_RCU`` allows tasks to be preempted in the midst of their RCU
519 read-side critical sections, and these tasks must be tracked explicitly.
520 The details of exactly why and how they are tracked will be covered in a
521 separate article on RCU read-side processing. For now, it is enough to
522 know that the ``rcu_node`` structure tracks them.
523
524 ::
525
526 1 struct list_head blkd_tasks;
527 2 struct list_head *gp_tasks;
528 3 struct list_head *exp_tasks;
529 4 bool wait_blkd_tasks;
530
531 The ``->blkd_tasks`` field is a list header for the list of blocked and
532 preempted tasks. As tasks undergo context switches within RCU read-side
533 critical sections, their ``task_struct`` structures are enqueued (via
534 the ``task_struct``'s ``->rcu_node_entry`` field) onto the head of the
535 ``->blkd_tasks`` list for the leaf ``rcu_node`` structure corresponding
536 to the CPU on which the outgoing context switch executed. As these tasks
537 later exit their RCU read-side critical sections, they remove themselves
538 from the list. This list is therefore in reverse time order, so that if
539 one of the tasks is blocking the current grace period, all subsequent
540 tasks must also be blocking that same grace period. Therefore, a single
541 pointer into this list suffices to track all tasks blocking a given
542 grace period. That pointer is stored in ``->gp_tasks`` for normal grace
543 periods and in ``->exp_tasks`` for expedited grace periods. These last
544 two fields are ``NULL`` if either there is no grace period in flight or
545 if there are no blocked tasks preventing that grace period from
546 completing. If either of these two pointers is referencing a task that
547 removes itself from the ``->blkd_tasks`` list, then that task must
548 advance the pointer to the next task on the list, or set the pointer to
549 ``NULL`` if there are no subsequent tasks on the list.
550
551 For example, suppose that tasks T1, T2, and T3 are all hard-affinitied
552 to the largest-numbered CPU in the system. Then if task T1 blocked in an
553 RCU read-side critical section, then an expedited grace period started,
554 then task T2 blocked in an RCU read-side critical section, then a normal
555 grace period started, and finally task 3 blocked in an RCU read-side
556 critical section, then the state of the last leaf ``rcu_node``
557 structure's blocked-task list would be as shown below:
558
559 .. kernel-figure:: blkd_task.svg
560
561 Task T1 is blocking both grace periods, task T2 is blocking only the
562 normal grace period, and task T3 is blocking neither grace period. Note
563 that these tasks will not remove themselves from this list immediately
564 upon resuming execution. They will instead remain on the list until they
565 execute the outermost ``rcu_read_unlock()`` that ends their RCU
566 read-side critical section.
567
568 The ``->wait_blkd_tasks`` field indicates whether or not the current
569 grace period is waiting on a blocked task.
570
571 Sizing the ``rcu_node`` Array
572 '''''''''''''''''''''''''''''
573
574 The ``rcu_node`` array is sized via a series of C-preprocessor
575 expressions as follows:
576
577 ::
578
579 1 #ifdef CONFIG_RCU_FANOUT
580 2 #define RCU_FANOUT CONFIG_RCU_FANOUT
581 3 #else
582 4 # ifdef CONFIG_64BIT
583 5 # define RCU_FANOUT 64
584 6 # else
585 7 # define RCU_FANOUT 32
586 8 # endif
587 9 #endif
588 10
589 11 #ifdef CONFIG_RCU_FANOUT_LEAF
590 12 #define RCU_FANOUT_LEAF CONFIG_RCU_FANOUT_LEAF
591 13 #else
592 14 # ifdef CONFIG_64BIT
593 15 # define RCU_FANOUT_LEAF 64
594 16 # else
595 17 # define RCU_FANOUT_LEAF 32
596 18 # endif
597 19 #endif
598 20
599 21 #define RCU_FANOUT_1 (RCU_FANOUT_LEAF)
600 22 #define RCU_FANOUT_2 (RCU_FANOUT_1 * RCU_FANOUT)
601 23 #define RCU_FANOUT_3 (RCU_FANOUT_2 * RCU_FANOUT)
602 24 #define RCU_FANOUT_4 (RCU_FANOUT_3 * RCU_FANOUT)
603 25
604 26 #if NR_CPUS <= RCU_FANOUT_1
605 27 # define RCU_NUM_LVLS 1
606 28 # define NUM_RCU_LVL_0 1
607 29 # define NUM_RCU_NODES NUM_RCU_LVL_0
608 30 # define NUM_RCU_LVL_INIT { NUM_RCU_LVL_0 }
609 31 # define RCU_NODE_NAME_INIT { "rcu_node_0" }
610 32 # define RCU_FQS_NAME_INIT { "rcu_node_fqs_0" }
611 33 # define RCU_EXP_NAME_INIT { "rcu_node_exp_0" }
612 34 #elif NR_CPUS <= RCU_FANOUT_2
613 35 # define RCU_NUM_LVLS 2
614 36 # define NUM_RCU_LVL_0 1
615 37 # define NUM_RCU_LVL_1 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
616 38 # define NUM_RCU_NODES (NUM_RCU_LVL_0 + NUM_RCU_LVL_1)
617 39 # define NUM_RCU_LVL_INIT { NUM_RCU_LVL_0, NUM_RCU_LVL_1 }
618 40 # define RCU_NODE_NAME_INIT { "rcu_node_0", "rcu_node_1" }
619 41 # define RCU_FQS_NAME_INIT { "rcu_node_fqs_0", "rcu_node_fqs_1" }
620 42 # define RCU_EXP_NAME_INIT { "rcu_node_exp_0", "rcu_node_exp_1" }
621 43 #elif NR_CPUS <= RCU_FANOUT_3
622 44 # define RCU_NUM_LVLS 3
623 45 # define NUM_RCU_LVL_0 1
624 46 # define NUM_RCU_LVL_1 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
625 47 # define NUM_RCU_LVL_2 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
626 48 # define NUM_RCU_NODES (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2)
627 49 # define NUM_RCU_LVL_INIT { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2 }
628 50 # define RCU_NODE_NAME_INIT { "rcu_node_0", "rcu_node_1", "rcu_node_2" }
629 51 # define RCU_FQS_NAME_INIT { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2" }
630 52 # define RCU_EXP_NAME_INIT { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2" }
631 53 #elif NR_CPUS <= RCU_FANOUT_4
632 54 # define RCU_NUM_LVLS 4
633 55 # define NUM_RCU_LVL_0 1
634 56 # define NUM_RCU_LVL_1 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_3)
635 57 # define NUM_RCU_LVL_2 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
636 58 # define NUM_RCU_LVL_3 DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
637 59 # define NUM_RCU_NODES (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2 + NUM_RCU_LVL_3)
638 60 # define NUM_RCU_LVL_INIT { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2, NUM_RCU_LVL_3 }
639 61 # define RCU_NODE_NAME_INIT { "rcu_node_0", "rcu_node_1", "rcu_node_2", "rcu_node_3" }
640 62 # define RCU_FQS_NAME_INIT { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2", "rcu_node_fqs_3" }
641 63 # define RCU_EXP_NAME_INIT { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2", "rcu_node_exp_3" }
642 64 #else
643 65 # error "CONFIG_RCU_FANOUT insufficient for NR_CPUS"
644 66 #endif
645
646 The maximum number of levels in the ``rcu_node`` structure is currently
647 limited to four, as specified by lines 21-24 and the structure of the
648 subsequent “if” statement. For 32-bit systems, this allows
649 16*32*32*32=524,288 CPUs, which should be sufficient for the next few
650 years at least. For 64-bit systems, 16*64*64*64=4,194,304 CPUs is
651 allowed, which should see us through the next decade or so. This
652 four-level tree also allows kernels built with ``CONFIG_RCU_FANOUT=8``
653 to support up to 4096 CPUs, which might be useful in very large systems
654 having eight CPUs per socket (but please note that no one has yet shown
655 any measurable performance degradation due to misaligned socket and
656 ``rcu_node`` boundaries). In addition, building kernels with a full four
657 levels of ``rcu_node`` tree permits better testing of RCU's
658 combining-tree code.
659
660 The ``RCU_FANOUT`` symbol controls how many children are permitted at
661 each non-leaf level of the ``rcu_node`` tree. If the
662 ``CONFIG_RCU_FANOUT`` Kconfig option is not specified, it is set based
663 on the word size of the system, which is also the Kconfig default.
664
665 The ``RCU_FANOUT_LEAF`` symbol controls how many CPUs are handled by
666 each leaf ``rcu_node`` structure. Experience has shown that allowing a
667 given leaf ``rcu_node`` structure to handle 64 CPUs, as permitted by the
668 number of bits in the ``->qsmask`` field on a 64-bit system, results in
669 excessive contention for the leaf ``rcu_node`` structures' ``->lock``
670 fields. The number of CPUs per leaf ``rcu_node`` structure is therefore
671 limited to 16 given the default value of ``CONFIG_RCU_FANOUT_LEAF``. If
672 ``CONFIG_RCU_FANOUT_LEAF`` is unspecified, the value selected is based
673 on the word size of the system, just as for ``CONFIG_RCU_FANOUT``.
674 Lines 11-19 perform this computation.
675
676 Lines 21-24 compute the maximum number of CPUs supported by a
677 single-level (which contains a single ``rcu_node`` structure),
678 two-level, three-level, and four-level ``rcu_node`` tree, respectively,
679 given the fanout specified by ``RCU_FANOUT`` and ``RCU_FANOUT_LEAF``.
680 These numbers of CPUs are retained in the ``RCU_FANOUT_1``,
681 ``RCU_FANOUT_2``, ``RCU_FANOUT_3``, and ``RCU_FANOUT_4`` C-preprocessor
682 variables, respectively.
683
684 These variables are used to control the C-preprocessor ``#if`` statement
685 spanning lines 26-66 that computes the number of ``rcu_node`` structures
686 required for each level of the tree, as well as the number of levels
687 required. The number of levels is placed in the ``NUM_RCU_LVLS``
688 C-preprocessor variable by lines 27, 35, 44, and 54. The number of
689 ``rcu_node`` structures for the topmost level of the tree is always
690 exactly one, and this value is unconditionally placed into
691 ``NUM_RCU_LVL_0`` by lines 28, 36, 45, and 55. The rest of the levels
692 (if any) of the ``rcu_node`` tree are computed by dividing the maximum
693 number of CPUs by the fanout supported by the number of levels from the
694 current level down, rounding up. This computation is performed by
695 lines 37, 46-47, and 56-58. Lines 31-33, 40-42, 50-52, and 62-63 create
696 initializers for lockdep lock-class names. Finally, lines 64-66 produce
697 an error if the maximum number of CPUs is too large for the specified
698 fanout.
699
700 The ``rcu_segcblist`` Structure
701 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
702
703 The ``rcu_segcblist`` structure maintains a segmented list of callbacks
704 as follows:
705
706 ::
707
708 1 #define RCU_DONE_TAIL 0
709 2 #define RCU_WAIT_TAIL 1
710 3 #define RCU_NEXT_READY_TAIL 2
711 4 #define RCU_NEXT_TAIL 3
712 5 #define RCU_CBLIST_NSEGS 4
713 6
714 7 struct rcu_segcblist {
715 8 struct rcu_head *head;
716 9 struct rcu_head **tails[RCU_CBLIST_NSEGS];
717 10 unsigned long gp_seq[RCU_CBLIST_NSEGS];
718 11 long len;
719 12 long len_lazy;
720 13 };
721
722 The segments are as follows:
723
724 #. ``RCU_DONE_TAIL``: Callbacks whose grace periods have elapsed. These
725 callbacks are ready to be invoked.
726 #. ``RCU_WAIT_TAIL``: Callbacks that are waiting for the current grace
727 period. Note that different CPUs can have different ideas about which
728 grace period is current, hence the ``->gp_seq`` field.
729 #. ``RCU_NEXT_READY_TAIL``: Callbacks waiting for the next grace period
730 to start.
731 #. ``RCU_NEXT_TAIL``: Callbacks that have not yet been associated with a
732 grace period.
733
734 The ``->head`` pointer references the first callback or is ``NULL`` if
735 the list contains no callbacks (which is *not* the same as being empty).
736 Each element of the ``->tails[]`` array references the ``->next``
737 pointer of the last callback in the corresponding segment of the list,
738 or the list's ``->head`` pointer if that segment and all previous
739 segments are empty. If the corresponding segment is empty but some
740 previous segment is not empty, then the array element is identical to
741 its predecessor. Older callbacks are closer to the head of the list, and
742 new callbacks are added at the tail. This relationship between the
743 ``->head`` pointer, the ``->tails[]`` array, and the callbacks is shown
744 in this diagram:
745
746 .. kernel-figure:: nxtlist.svg
747
748 In this figure, the ``->head`` pointer references the first RCU callback
749 in the list. The ``->tails[RCU_DONE_TAIL]`` array element references the
750 ``->head`` pointer itself, indicating that none of the callbacks is
751 ready to invoke. The ``->tails[RCU_WAIT_TAIL]`` array element references
752 callback CB 2's ``->next`` pointer, which indicates that CB 1 and CB 2
753 are both waiting on the current grace period, give or take possible
754 disagreements about exactly which grace period is the current one. The
755 ``->tails[RCU_NEXT_READY_TAIL]`` array element references the same RCU
756 callback that ``->tails[RCU_WAIT_TAIL]`` does, which indicates that
757 there are no callbacks waiting on the next RCU grace period. The
758 ``->tails[RCU_NEXT_TAIL]`` array element references CB 4's ``->next``
759 pointer, indicating that all the remaining RCU callbacks have not yet
760 been assigned to an RCU grace period. Note that the
761 ``->tails[RCU_NEXT_TAIL]`` array element always references the last RCU
762 callback's ``->next`` pointer unless the callback list is empty, in
763 which case it references the ``->head`` pointer.
764
765 There is one additional important special case for the
766 ``->tails[RCU_NEXT_TAIL]`` array element: It can be ``NULL`` when this
767 list is *disabled*. Lists are disabled when the corresponding CPU is
768 offline or when the corresponding CPU's callbacks are offloaded to a
769 kthread, both of which are described elsewhere.
770
771 CPUs advance their callbacks from the ``RCU_NEXT_TAIL`` to the
772 ``RCU_NEXT_READY_TAIL`` to the ``RCU_WAIT_TAIL`` to the
773 ``RCU_DONE_TAIL`` list segments as grace periods advance.
774
775 The ``->gp_seq[]`` array records grace-period numbers corresponding to
776 the list segments. This is what allows different CPUs to have different
777 ideas as to which is the current grace period while still avoiding
778 premature invocation of their callbacks. In particular, this allows CPUs
779 that go idle for extended periods to determine which of their callbacks
780 are ready to be invoked after reawakening.
781
782 The ``->len`` counter contains the number of callbacks in ``->head``,
783 and the ``->len_lazy`` contains the number of those callbacks that are
784 known to only free memory, and whose invocation can therefore be safely
785 deferred.
786
787 .. important::
788
789 It is the ``->len`` field that determines whether or
790 not there are callbacks associated with this ``rcu_segcblist``
791 structure, *not* the ``->head`` pointer. The reason for this is that all
792 the ready-to-invoke callbacks (that is, those in the ``RCU_DONE_TAIL``
793 segment) are extracted all at once at callback-invocation time
794 (``rcu_do_batch``), due to which ``->head`` may be set to NULL if there
795 are no not-done callbacks remaining in the ``rcu_segcblist``. If
796 callback invocation must be postponed, for example, because a
797 high-priority process just woke up on this CPU, then the remaining
798 callbacks are placed back on the ``RCU_DONE_TAIL`` segment and
799 ``->head`` once again points to the start of the segment. In short, the
800 head field can briefly be ``NULL`` even though the CPU has callbacks
801 present the entire time. Therefore, it is not appropriate to test the
802 ``->head`` pointer for ``NULL``.
803
804 In contrast, the ``->len`` and ``->len_lazy`` counts are adjusted only
805 after the corresponding callbacks have been invoked. This means that the
806 ``->len`` count is zero only if the ``rcu_segcblist`` structure really
807 is devoid of callbacks. Of course, off-CPU sampling of the ``->len``
808 count requires careful use of appropriate synchronization, for example,
809 memory barriers. This synchronization can be a bit subtle, particularly
810 in the case of ``rcu_barrier()``.
811
812 The ``rcu_data`` Structure
813 ~~~~~~~~~~~~~~~~~~~~~~~~~~
814
815 The ``rcu_data`` maintains the per-CPU state for the RCU subsystem. The
816 fields in this structure may be accessed only from the corresponding CPU
817 (and from tracing) unless otherwise stated. This structure is the focus
818 of quiescent-state detection and RCU callback queuing. It also tracks
819 its relationship to the corresponding leaf ``rcu_node`` structure to
820 allow more-efficient propagation of quiescent states up the ``rcu_node``
821 combining tree. Like the ``rcu_node`` structure, it provides a local
822 copy of the grace-period information to allow for-free synchronized
823 access to this information from the corresponding CPU. Finally, this
824 structure records past dyntick-idle state for the corresponding CPU and
825 also tracks statistics.
826
827 The ``rcu_data`` structure's fields are discussed, singly and in groups,
828 in the following sections.
829
830 Connection to Other Data Structures
831 '''''''''''''''''''''''''''''''''''
832
833 This portion of the ``rcu_data`` structure is declared as follows:
834
835 ::
836
837 1 int cpu;
838 2 struct rcu_node *mynode;
839 3 unsigned long grpmask;
840 4 bool beenonline;
841
842 The ``->cpu`` field contains the number of the corresponding CPU and the
843 ``->mynode`` field references the corresponding ``rcu_node`` structure.
844 The ``->mynode`` is used to propagate quiescent states up the combining
845 tree. These two fields are constant and therefore do not require
846 synchronization.
847
848 The ``->grpmask`` field indicates the bit in the ``->mynode->qsmask``
849 corresponding to this ``rcu_data`` structure, and is also used when
850 propagating quiescent states. The ``->beenonline`` flag is set whenever
851 the corresponding CPU comes online, which means that the debugfs tracing
852 need not dump out any ``rcu_data`` structure for which this flag is not
853 set.
854
855 Quiescent-State and Grace-Period Tracking
856 '''''''''''''''''''''''''''''''''''''''''
857
858 This portion of the ``rcu_data`` structure is declared as follows:
859
860 ::
861
862 1 unsigned long gp_seq;
863 2 unsigned long gp_seq_needed;
864 3 bool cpu_no_qs;
865 4 bool core_needs_qs;
866 5 bool gpwrap;
867
868 The ``->gp_seq`` field is the counterpart of the field of the same name
869 in the ``rcu_state`` and ``rcu_node`` structures. The
870 ``->gp_seq_needed`` field is the counterpart of the field of the same
871 name in the rcu_node structure. They may each lag up to one behind their
872 ``rcu_node`` counterparts, but in ``CONFIG_NO_HZ_IDLE`` and
873 ``CONFIG_NO_HZ_FULL`` kernels can lag arbitrarily far behind for CPUs in
874 dyntick-idle mode (but these counters will catch up upon exit from
875 dyntick-idle mode). If the lower two bits of a given ``rcu_data``
876 structure's ``->gp_seq`` are zero, then this ``rcu_data`` structure
877 believes that RCU is idle.
878
879 +-----------------------------------------------------------------------+
880 | **Quick Quiz**: |
881 +-----------------------------------------------------------------------+
882 | All this replication of the grace period numbers can only cause |
883 | massive confusion. Why not just keep a global sequence number and be |
884 | done with it??? |
885 +-----------------------------------------------------------------------+
886 | **Answer**: |
887 +-----------------------------------------------------------------------+
888 | Because if there was only a single global sequence numbers, there |
889 | would need to be a single global lock to allow safely accessing and |
890 | updating it. And if we are not going to have a single global lock, we |
891 | need to carefully manage the numbers on a per-node basis. Recall from |
892 | the answer to a previous Quick Quiz that the consequences of applying |
893 | a previously sampled quiescent state to the wrong grace period are |
894 | quite severe. |
895 +-----------------------------------------------------------------------+
896
897 The ``->cpu_no_qs`` flag indicates that the CPU has not yet passed
898 through a quiescent state, while the ``->core_needs_qs`` flag indicates
899 that the RCU core needs a quiescent state from the corresponding CPU.
900 The ``->gpwrap`` field indicates that the corresponding CPU has remained
901 idle for so long that the ``gp_seq`` counter is in danger of overflow,
902 which will cause the CPU to disregard the values of its counters on its
903 next exit from idle.
904
905 RCU Callback Handling
906 '''''''''''''''''''''
907
908 In the absence of CPU-hotplug events, RCU callbacks are invoked by the
909 same CPU that registered them. This is strictly a cache-locality
910 optimization: callbacks can and do get invoked on CPUs other than the
911 one that registered them. After all, if the CPU that registered a given
912 callback has gone offline before the callback can be invoked, there
913 really is no other choice.
914
915 This portion of the ``rcu_data`` structure is declared as follows:
916
917 ::
918
919 1 struct rcu_segcblist cblist;
920 2 long qlen_last_fqs_check;
921 3 unsigned long n_cbs_invoked;
922 4 unsigned long n_nocbs_invoked;
923 5 unsigned long n_cbs_orphaned;
924 6 unsigned long n_cbs_adopted;
925 7 unsigned long n_force_qs_snap;
926 8 long blimit;
927
928 The ``->cblist`` structure is the segmented callback list described
929 earlier. The CPU advances the callbacks in its ``rcu_data`` structure
930 whenever it notices that another RCU grace period has completed. The CPU
931 detects the completion of an RCU grace period by noticing that the value
932 of its ``rcu_data`` structure's ``->gp_seq`` field differs from that of
933 its leaf ``rcu_node`` structure. Recall that each ``rcu_node``
934 structure's ``->gp_seq`` field is updated at the beginnings and ends of
935 each grace period.
936
937 The ``->qlen_last_fqs_check`` and ``->n_force_qs_snap`` coordinate the
938 forcing of quiescent states from ``call_rcu()`` and friends when
939 callback lists grow excessively long.
940
941 The ``->n_cbs_invoked``, ``->n_cbs_orphaned``, and ``->n_cbs_adopted``
942 fields count the number of callbacks invoked, sent to other CPUs when
943 this CPU goes offline, and received from other CPUs when those other
944 CPUs go offline. The ``->n_nocbs_invoked`` is used when the CPU's
945 callbacks are offloaded to a kthread.
946
947 Finally, the ``->blimit`` counter is the maximum number of RCU callbacks
948 that may be invoked at a given time.
949
950 Dyntick-Idle Handling
951 '''''''''''''''''''''
952
953 This portion of the ``rcu_data`` structure is declared as follows:
954
955 ::
956
957 1 int watching_snap;
958 2 unsigned long dynticks_fqs;
959
960 The ``->watching_snap`` field is used to take a snapshot of the
961 corresponding CPU's dyntick-idle state when forcing quiescent states,
962 and is therefore accessed from other CPUs. Finally, the
963 ``->dynticks_fqs`` field is used to count the number of times this CPU
964 is determined to be in dyntick-idle state, and is used for tracing and
965 debugging purposes.
966
967 This portion of the rcu_data structure is declared as follows:
968
969 ::
970
971 1 long nesting;
972 2 long nmi_nesting;
973 3 atomic_t dynticks;
974 4 bool rcu_need_heavy_qs;
975 5 bool rcu_urgent_qs;
976
977 These fields in the rcu_data structure maintain the per-CPU dyntick-idle
978 state for the corresponding CPU. The fields may be accessed only from
979 the corresponding CPU (and from tracing) unless otherwise stated.
980
981 The ``->nesting`` field counts the nesting depth of process
982 execution, so that in normal circumstances this counter has value zero
983 or one. NMIs, irqs, and tracers are counted by the
984 ``->nmi_nesting`` field. Because NMIs cannot be masked, changes
985 to this variable have to be undertaken carefully using an algorithm
986 provided by Andy Lutomirski. The initial transition from idle adds one,
987 and nested transitions add two, so that a nesting level of five is
988 represented by a ``->nmi_nesting`` value of nine. This counter
989 can therefore be thought of as counting the number of reasons why this
990 CPU cannot be permitted to enter dyntick-idle mode, aside from
991 process-level transitions.
992
993 However, it turns out that when running in non-idle kernel context, the
994 Linux kernel is fully capable of entering interrupt handlers that never
995 exit and perhaps also vice versa. Therefore, whenever the
996 ``->nesting`` field is incremented up from zero, the
997 ``->nmi_nesting`` field is set to a large positive number, and
998 whenever the ``->nesting`` field is decremented down to zero,
999 the ``->nmi_nesting`` field is set to zero. Assuming that
1000 the number of misnested interrupts is not sufficient to overflow the
1001 counter, this approach corrects the ``->nmi_nesting`` field
1002 every time the corresponding CPU enters the idle loop from process
1003 context.
1005 The ``->dynticks`` field counts the corresponding CPU's transitions to
1006 and from either dyntick-idle or user mode, so that this counter has an
1007 even value when the CPU is in dyntick-idle mode or user mode and an odd
1008 value otherwise. The transitions to/from user mode need to be counted
1009 for user mode adaptive-ticks support (see Documentation/timers/no_hz.rst).
1011 The ``->rcu_need_heavy_qs`` field is used to record the fact that the
1012 RCU core code would really like to see a quiescent state from the
1013 corresponding CPU, so much so that it is willing to call for
1014 heavy-weight dyntick-counter operations. This flag is checked by RCU's
1015 context-switch and ``cond_resched()`` code, which provide a momentary
1016 idle sojourn in response.
1018 Finally, the ``->rcu_urgent_qs`` field is used to record the fact that
1019 the RCU core code would really like to see a quiescent state from the
1020 corresponding CPU, with the various other fields indicating just how
1021 badly RCU wants this quiescent state. This flag is checked by RCU's
1022 context-switch path (``rcu_note_context_switch``) and the cond_resched
1023 code.
1025 +-----------------------------------------------------------------------+
1026 | **Quick Quiz**: |
1027 +-----------------------------------------------------------------------+
1028 | Why not simply combine the ``->nesting`` and |
1029 | ``->nmi_nesting`` counters into a single counter that just |
1030 | counts the number of reasons that the corresponding CPU is non-idle? |
1031 +-----------------------------------------------------------------------+
1032 | **Answer**: |
1033 +-----------------------------------------------------------------------+
1034 | Because this would fail in the presence of interrupts whose handlers |
1035 | never return and of handlers that manage to return from a made-up |
1036 | interrupt. |
1037 +-----------------------------------------------------------------------+
1039 Additional fields are present for some special-purpose builds, and are
1040 discussed separately.
1042 The ``rcu_head`` Structure
1043 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1045 Each ``rcu_head`` structure represents an RCU callback. These structures
1046 are normally embedded within RCU-protected data structures whose
1047 algorithms use asynchronous grace periods. In contrast, when using
1048 algorithms that block waiting for RCU grace periods, RCU users need not
1049 provide ``rcu_head`` structures.
1051 The ``rcu_head`` structure has fields as follows:
1053 ::
1055 1 struct rcu_head *next;
1056 2 void (*func)(struct rcu_head *head);
1058 The ``->next`` field is used to link the ``rcu_head`` structures
1059 together in the lists within the ``rcu_data`` structures. The ``->func``
1060 field is a pointer to the function to be called when the callback is
1061 ready to be invoked, and this function is passed a pointer to the
1062 ``rcu_head`` structure. However, ``kfree_rcu()`` uses the ``->func``
1063 field to record the offset of the ``rcu_head`` structure within the
1064 enclosing RCU-protected data structure.
1066 Both of these fields are used internally by RCU. From the viewpoint of
1067 RCU users, this structure is an opaque “cookie”.
1069 +-----------------------------------------------------------------------+
1070 | **Quick Quiz**: |
1071 +-----------------------------------------------------------------------+
1072 | Given that the callback function ``->func`` is passed a pointer to |
1073 | the ``rcu_head`` structure, how is that function supposed to find the |
1074 | beginning of the enclosing RCU-protected data structure? |
1075 +-----------------------------------------------------------------------+
1076 | **Answer**: |
1077 +-----------------------------------------------------------------------+
1078 | In actual practice, there is a separate callback function per type of |
1079 | RCU-protected data structure. The callback function can therefore use |
1080 | the ``container_of()`` macro in the Linux kernel (or other |
1081 | pointer-manipulation facilities in other software environments) to |
1082 | find the beginning of the enclosing structure. |
1083 +-----------------------------------------------------------------------+
1085 RCU-Specific Fields in the ``task_struct`` Structure
1086 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1088 The ``CONFIG_PREEMPT_RCU`` implementation uses some additional fields in
1089 the ``task_struct`` structure:
1091 ::
1093 1 #ifdef CONFIG_PREEMPT_RCU
1094 2 int rcu_read_lock_nesting;
1095 3 union rcu_special rcu_read_unlock_special;
1096 4 struct list_head rcu_node_entry;
1097 5 struct rcu_node *rcu_blocked_node;
1098 6 #endif /* #ifdef CONFIG_PREEMPT_RCU */
1099 7 #ifdef CONFIG_TASKS_RCU
1100 8 unsigned long rcu_tasks_nvcsw;
1101 9 bool rcu_tasks_holdout;
1102 10 struct list_head rcu_tasks_holdout_list;
1103 11 int rcu_tasks_idle_cpu;
1104 12 #endif /* #ifdef CONFIG_TASKS_RCU */
1106 The ``->rcu_read_lock_nesting`` field records the nesting level for RCU
1107 read-side critical sections, and the ``->rcu_read_unlock_special`` field
1108 is a bitmask that records special conditions that require
1109 ``rcu_read_unlock()`` to do additional work. The ``->rcu_node_entry``
1110 field is used to form lists of tasks that have blocked within
1111 preemptible-RCU read-side critical sections and the
1112 ``->rcu_blocked_node`` field references the ``rcu_node`` structure whose
1113 list this task is a member of, or ``NULL`` if it is not blocked within a
1114 preemptible-RCU read-side critical section.
1116 The ``->rcu_tasks_nvcsw`` field tracks the number of voluntary context
1117 switches that this task had undergone at the beginning of the current
1118 tasks-RCU grace period, ``->rcu_tasks_holdout`` is set if the current
1119 tasks-RCU grace period is waiting on this task,
1120 ``->rcu_tasks_holdout_list`` is a list element enqueuing this task on
1121 the holdout list, and ``->rcu_tasks_idle_cpu`` tracks which CPU this
1122 idle task is running, but only if the task is currently running, that
1123 is, if the CPU is currently idle.
1125 Accessor Functions
1126 ~~~~~~~~~~~~~~~~~~
1128 The following listing shows the ``rcu_get_root()``,
1129 ``rcu_for_each_node_breadth_first`` and ``rcu_for_each_leaf_node()``
1130 function and macros:
1132 ::
1134 1 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
1135 2 {
1136 3 return &rsp->node[0];
1137 4 }
1138 5
1139 6 #define rcu_for_each_node_breadth_first(rsp, rnp) \
1140 7 for ((rnp) = &(rsp)->node[0]; \
1141 8 (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)
1142 9
1143 10 #define rcu_for_each_leaf_node(rsp, rnp) \
1144 11 for ((rnp) = (rsp)->level[NUM_RCU_LVLS - 1]; \
1145 12 (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)
1147 The ``rcu_get_root()`` simply returns a pointer to the first element of
1148 the specified ``rcu_state`` structure's ``->node[]`` array, which is the
1149 root ``rcu_node`` structure.
1151 As noted earlier, the ``rcu_for_each_node_breadth_first()`` macro takes
1152 advantage of the layout of the ``rcu_node`` structures in the
1153 ``rcu_state`` structure's ``->node[]`` array, performing a breadth-first
1154 traversal by simply traversing the array in order. Similarly, the
1155 ``rcu_for_each_leaf_node()`` macro traverses only the last part of the
1156 array, thus traversing only the leaf ``rcu_node`` structures.
1158 +-----------------------------------------------------------------------+
1159 | **Quick Quiz**: |
1160 +-----------------------------------------------------------------------+
1161 | What does ``rcu_for_each_leaf_node()`` do if the ``rcu_node`` tree |
1162 | contains only a single node? |
1163 +-----------------------------------------------------------------------+
1164 | **Answer**: |
1165 +-----------------------------------------------------------------------+
1166 | In the single-node case, ``rcu_for_each_leaf_node()`` traverses the |
1167 | single node. |
1168 +-----------------------------------------------------------------------+
1170 Summary
1171 ~~~~~~~
1173 So the state of RCU is represented by an ``rcu_state`` structure, which
1174 contains a combining tree of ``rcu_node`` and ``rcu_data`` structures.
1175 Finally, in ``CONFIG_NO_HZ_IDLE`` kernels, each CPU's dyntick-idle state
1176 is tracked by dynticks-related fields in the ``rcu_data`` structure. If
1177 you made it this far, you are well prepared to read the code
1178 walkthroughs in the other articles in this series.
1180 Acknowledgments
1181 ~~~~~~~~~~~~~~~
1183 I owe thanks to Cyrill Gorcunov, Mathieu Desnoyers, Dhaval Giani, Paul
1184 Turner, Abhishek Srivastava, Matt Kowalczyk, and Serge Hallyn for
1185 helping me get this document into a more human-readable state.
1187 Legal Statement
1188 ~~~~~~~~~~~~~~~
1190 This work represents the view of the author and does not necessarily
1191 represent the view of IBM.
1193 Linux is a registered trademark of Linus Torvalds.
1195 Other company, product, and service names may be trademarks or service
1196 marks of others.

3. 한국어 전문 번역

영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.

문서의 목적과 RCU 상태 기계

1-14

이 글은 2016년 12월 18일 Paul E. McKenney가 기고한 TREE_RCU 자료구조 안내서입니다. RCU의 주요 자료구조가 어떤 상태를 보관하고 서로 어떻게 연결되는지를 설명합니다.

RCU는 실질적으로 큰 상태 기계입니다. 자료구조는 reader가 극도로 빠르게 실행되는 동시에 updater가 요청한 grace period를 효율적이고 확장성 있게 처리할 수 있도록 그 상태를 분산해 유지합니다.

===================================================
A Tour Through TREE_RCU's Data Structures [LWN.net]
===================================================

December 18, 2016

This article was contributed by Paul E. McKenney

Introduction
============

This document describes RCU's major data structures and their relationship
to each other.

결합 트리의 구성과 확장성

15-119

`rcu_state`는 `rcu_node` 결합 트리를 감싸고, 각 leaf `rcu_node`에는 최대 16개의 `rcu_data`가 연결됩니다. 가능한 CPU마다 하나씩 있으므로 `rcu_data`는 `NR_CPUS`개입니다. 부팅 때 `nr_cpu_ids`가 `NR_CPUS`보다 훨씬 작은 흔한 경우에는 실제 CPU 규모에 맞춰 트리를 줄입니다. 예를 들어 `NR_CPUS=4096`인 배포판 커널도 실제 CPU가 16개면 단일 `rcu_node`로 조정됩니다.

Per-CPU quiescent state는 `rcu_data`가 기록하고 dyntick-idle 전환과 CPU hotplug 같은 다른 사건은 leaf `rcu_node`가 기록합니다. 각 단계가 자식의 결과를 결합해 root까지 올리며, 모든 CPU 또는 `CONFIG_PREEMPT_RCU`의 모든 관련 task가 quiescent state를 지나면 root에서 grace period를 끝낼 수 있습니다. 완료 사실은 다시 root에서 leaf 방향으로 내려갑니다.

일반 결합 트리
rcu_stateroot rcu_nodeup to 64 leaf rcu_node entriesup to 16 rcu_data per leafone rcu_data per possible CPU

64비트 2단계 구성은 root fanout 64와 leaf fanout 16으로 최대 1,024 CPU를 수용합니다.

Leaf fanout을 64로 하지 않는 이유는 leaf가 상위 node보다 더 많은 종류의 사건을 처리해 lock 경합이 과도해지기 때문입니다. 여러 시스템에서 fanout 16이 잘 동작했습니다. 매우 큰 시스템에서 non-leaf 경합이 생기면 `CONFIG_RCU_FANOUT`을 줄일 수 있고, 강한 NUMA 특성이 있으면 `rcu_node` 영역을 하드웨어 경계에 맞추는 조정도 고려할 수 있지만 지금까지 필요하다고 입증되지는 않았습니다.

1,024 CPU를 넘는 64비트 시스템 또는 512 CPU를 넘는 32비트 시스템에는 단계가 자동으로 추가됩니다. 65,536 CPU의 64비트 시스템은 다단계 트리를 쓰며, 현재 최대 4단계까지 허용해 64비트에서 4,194,304 CPU, 32비트에서 524,288 CPU를 수용합니다. 반대로 `CONFIG_RCU_FANOUT`과 `CONFIG_RCU_FANOUT_LEAF`를 2로 낮추면 16 CPU 장비에서도 4단계 코드를 시험할 수 있습니다.

대규모 결합 트리
many per-CPU reportsleaf combines up to 16 reportsinternal node combines up to 64 child reportsroot sees at most 64 final reportsgrace period completes

CPU 수가 늘면 중간 단계가 추가되지만 보고를 위로 넘기는 자식은 각 node에서 마지막 하나뿐입니다.

결합 트리는 본질적으로 전역 연산인 grace-period detection에 partitioning의 이점을 부여합니다. Leaf에서는 16번 중 마지막 보고 하나만 상위로 진행하고 internal node에서는 64번 중 하나만 진행합니다. CPU 수와 관계없이 root까지 도달하는 quiescent-state 보고는 grace period당 최대 64개이므로 root lock 경합은 낮게 유지됩니다. 즉 이 트리는 모든 단계의 부하와 lock 경합을 흡수하는 완충 장치입니다.

결합 트리 규모
구성의미
64-bit, 2 levels64 x 16 = 1,024 CPUs
32-bit, 2 levels32 x 16 = 512 CPUs
64-bit, 4 levels최대 4,194,304 CPUs
32-bit, 4 levels최대 524,288 CPUs

Word size와 fanout에 따라 수용 가능한 CPU 수와 트리 단계가 정해집니다.

Data-Structure Relationships
============================

RCU is for all intents and purposes a large state machine, and its
data structures maintain the state in such a way as to allow RCU readers
to execute extremely quickly, while also processing the RCU grace periods
requested by updaters in an efficient and extremely scalable fashion.
The efficiency and scalability of RCU updaters is provided primarily
by a combining tree, as shown below:

.. kernel-figure:: BigTreeClassicRCU.svg

This diagram shows an enclosing ``rcu_state`` structure containing a tree
of ``rcu_node`` structures. Each leaf node of the ``rcu_node`` tree has up
to 16 ``rcu_data`` structures associated with it, so that there are
``NR_CPUS`` number of ``rcu_data`` structures, one for each possible CPU.
This structure is adjusted at boot time, if needed, to handle the common
case where ``nr_cpu_ids`` is much less than ``NR_CPUs``.
For example, a number of Linux distributions set ``NR_CPUs=4096``,
which results in a three-level ``rcu_node`` tree.
If the actual hardware has only 16 CPUs, RCU will adjust itself
at boot time, resulting in an ``rcu_node`` tree with only a single node.

The purpose of this combining tree is to allow per-CPU events
such as quiescent states, dyntick-idle transitions,
and CPU hotplug operations to be processed efficiently
and scalably.
Quiescent states are recorded by the per-CPU ``rcu_data`` structures,
and other events are recorded by the leaf-level ``rcu_node``
structures.
All of these events are combined at each level of the tree until finally
grace periods are completed at the tree's root ``rcu_node``
structure.
A grace period can be completed at the root once every CPU
(or, in the case of ``CONFIG_PREEMPT_RCU``, task)
has passed through a quiescent state.
Once a grace period has completed, record of that fact is propagated
back down the tree.

As can be seen from the diagram, on a 64-bit system
a two-level tree with 64 leaves can accommodate 1,024 CPUs, with a fanout
of 64 at the root and a fanout of 16 at the leaves.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Why isn't the fanout at the leaves also 64?                           |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Because there are more types of events that affect the leaf-level     |
| ``rcu_node`` structures than further up the tree. Therefore, if the   |
| leaf ``rcu_node`` structures have fanout of 64, the contention on     |
| these structures' ``->structures`` becomes excessive. Experimentation |
| on a wide variety of systems has shown that a fanout of 16 works well |
| for the leaves of the ``rcu_node`` tree.                              |
|                                                                       |
| Of course, further experience with systems having hundreds or         |
| thousands of CPUs may demonstrate that the fanout for the non-leaf    |
| ``rcu_node`` structures must also be reduced. Such reduction can be   |
| easily carried out when and if it proves necessary. In the meantime,  |
| if you are using such a system and running into contention problems   |
| on the non-leaf ``rcu_node`` structures, you may use the              |
| ``CONFIG_RCU_FANOUT`` kernel configuration parameter to reduce the    |
| non-leaf fanout as needed.                                            |
|                                                                       |
| Kernels built for systems with strong NUMA characteristics might      |
| also need to adjust ``CONFIG_RCU_FANOUT`` so that the domains of      |
| the ``rcu_node`` structures align with hardware boundaries.           |
| However, there has thus far been no need for this.                    |
+-----------------------------------------------------------------------+

If your system has more than 1,024 CPUs (or more than 512 CPUs on a
32-bit system), then RCU will automatically add more levels to the tree.
For example, if you are crazy enough to build a 64-bit system with
65,536 CPUs, RCU would configure the ``rcu_node`` tree as follows:

.. kernel-figure:: HugeTreeClassicRCU.svg

RCU currently permits up to a four-level tree, which on a 64-bit system
accommodates up to 4,194,304 CPUs, though only a mere 524,288 CPUs for
32-bit systems. On the other hand, you can set both
``CONFIG_RCU_FANOUT`` and ``CONFIG_RCU_FANOUT_LEAF`` to be as small as
2, which would result in a 16-CPU test using a 4-level tree. This can be
useful for testing large-system capabilities on small test machines.

This multi-level combining tree allows us to get most of the performance
and scalability benefits of partitioning, even though RCU grace-period
detection is inherently a global operation. The trick here is that only
the last CPU to report a quiescent state into a given ``rcu_node``
structure need advance to the ``rcu_node`` structure at the next level
up the tree. This means that at the leaf-level ``rcu_node`` structure,
only one access out of sixteen will progress up the tree. For the
internal ``rcu_node`` structures, the situation is even more extreme:
Only one access out of sixty-four will progress up the tree. Because the
vast majority of the CPUs do not progress up the tree, the lock
contention remains roughly constant up the tree. No matter how many CPUs
there are in the system, at most 64 quiescent-state reports per grace
period will progress all the way to the root ``rcu_node`` structure,
thus ensuring that the lock contention on that root ``rcu_node``
structure remains acceptably low.

In effect, the combining tree acts like a big shock absorber, keeping
lock contention under control at all tree levels regardless of the level
of loading on the system.

Callback 연결, 동기화와 구조별 역할

120-190

Updater는 `call_rcu()`를 직접 호출하거나 `synchronize_rcu()` 계열을 간접적으로 사용해 normal grace period를 기다립니다. Callback은 `rcu_head`로 표현되고 grace period가 지나는 동안 `rcu_data`의 queue에 놓입니다. TREE_RCU와 PREEMPT_RCU의 큰 구조는 `rcu_state`, `rcu_node`, per-CPU `rcu_data`, 그 안의 callback list로 이어집니다.

Callback 대기 경로
updater registers rcu_headcallback queued on rcu_datarcu_node tree completes grace periodcompletion propagates to rcu_datacallback becomes invokable

사용자가 등록한 rcu_head는 CPU별 목록에서 grace-period 진행 상태를 따라 이동합니다.

각 구조에는 별도 동기화가 있습니다. `rcu_state`에는 lock과 mutex가 있고 일부 field는 root `rcu_node` lock이 보호합니다. 각 `rcu_node`에는 spinlock이 있습니다. `rcu_data` field는 대체로 해당 CPU 전용이지만 일부는 다른 CPU도 읽고 씁니다. Grace period 시작과 종료에 대한 인식은 구조 사이에 천천히 전파되며, 이 서로 다른 관점은 read-side 성능을 위한 의도적인 분산입니다.

`rcu_state`는 `rcu_node`와 `rcu_data`를 연결하고 grace period, CPU-hotplug가 남긴 callback, `rcu_barrier()` 상태, expedited grace period, 오래 걸리는 grace period의 forced quiescent state 상태를 관리합니다. `rcu_node`는 quiescent state를 위로 결합하고 grace-period 상태를 아래로 전파하며 전역 lock 없이 동기화된 local copy를 제공합니다. PREEMPT_RCU에서는 read section 안에서 block된 task list를, RCU_BOOST와 함께라면 node별 priority-boost kthread 상태를, 또한 CPU-hotplug 상태를 관리합니다.

Per-CPU `rcu_data`는 quiescent-state detection과 callback queue의 중심이며 leaf `rcu_node`와의 관계, grace-period local copy, 과거 dyntick-idle 상태와 통계를 보관합니다. `rcu_head`는 RCU 사용자가 할당하고 관리하는 유일한 구조로, 보통 RCU가 보호하는 객체 안에 삽입됩니다.

주요 자료구조의 역할
구조핵심 책임
rcu_state전역 GP, tree 연결, hotplug/barrier/expedited/FQS
rcu_nodeQS 상향 결합, GP 하향 전파, blocked task와 hotplug
rcu_dataCPU별 QS detection, callback queue, dyntick와 통계
rcu_head사용자 객체에 삽입되는 callback 표현

전역 상태, 트리 결합, CPU별 처리와 사용자 callback을 분리합니다.


RCU updaters wait for normal grace periods by registering RCU callbacks,
either directly via ``call_rcu()`` or indirectly via
``synchronize_rcu()`` and friends. RCU callbacks are represented by
``rcu_head`` structures, which are queued on ``rcu_data`` structures
while they are waiting for a grace period to elapse, as shown in the
following figure:

.. kernel-figure:: BigTreePreemptRCUBHdyntickCB.svg

This figure shows how ``TREE_RCU``'s and ``PREEMPT_RCU``'s major data
structures are related. Lesser data structures will be introduced with
the algorithms that make use of them.

Note that each of the data structures in the above figure has its own
synchronization:

#. Each ``rcu_state`` structures has a lock and a mutex, and some fields
   are protected by the corresponding root ``rcu_node`` structure's lock.
#. Each ``rcu_node`` structure has a spinlock.
#. The fields in ``rcu_data`` are private to the corresponding CPU,
   although a few can be read and written by other CPUs.

It is important to note that different data structures can have very
different ideas about the state of RCU at any given time. For but one
example, awareness of the start or end of a given RCU grace period
propagates slowly through the data structures. This slow propagation is
absolutely necessary for RCU to have good read-side performance. If this
balkanized implementation seems foreign to you, one useful trick is to
consider each instance of these data structures to be a different
person, each having the usual slightly different view of reality.

The general role of each of these data structures is as follows:

#. ``rcu_state``: This structure forms the interconnection between the
   ``rcu_node`` and ``rcu_data`` structures, tracks grace periods,
   serves as short-term repository for callbacks orphaned by CPU-hotplug
   events, maintains ``rcu_barrier()`` state, tracks expedited
   grace-period state, and maintains state used to force quiescent
   states when grace periods extend too long,
#. ``rcu_node``: This structure forms the combining tree that propagates
   quiescent-state information from the leaves to the root, and also
   propagates grace-period information from the root to the leaves. It
   provides local copies of the grace-period state in order to allow
   this information to be accessed in a synchronized manner without
   suffering the scalability limitations that would otherwise be imposed
   by global locking. In ``CONFIG_PREEMPT_RCU`` kernels, it manages the
   lists of tasks that have blocked while in their current RCU read-side
   critical section. In ``CONFIG_PREEMPT_RCU`` with
   ``CONFIG_RCU_BOOST``, it manages the per-\ ``rcu_node``
   priority-boosting kernel threads (kthreads) and state. Finally, it
   records CPU-hotplug state in order to determine which CPUs should be
   ignored during a given grace period.
#. ``rcu_data``: This per-CPU structure is the focus of quiescent-state
   detection and RCU callback queuing. It also tracks its relationship
   to the corresponding leaf ``rcu_node`` structure to allow
   more-efficient propagation of quiescent states up the ``rcu_node``
   combining tree. Like the ``rcu_node`` structure, it provides a local
   copy of the grace-period information to allow for-free synchronized
   access to this information from the corresponding CPU. Finally, this
   structure records past dyntick-idle state for the corresponding CPU
   and also tracks statistics.
#. ``rcu_head``: This structure represents RCU callbacks, and is the
   only structure allocated and managed by RCU users. The ``rcu_head``
   structure is normally embedded within the RCU-protected data
   structure.

If all you wanted from this article was a general notion of how RCU's
data structures are related, you are done. Otherwise, each of the
following sections give more details on the ``rcu_state``, ``rcu_node``
and ``rcu_data`` data structures.

rcu_state의 node 배열과 level 매핑

191-264

`rcu_state`는 시스템 전체 RCU 상태의 기반입니다. `rcu_node`와 `rcu_data`를 연결하고 grace period를 추적하며 CPU-hotplug 동기화 lock과 오래 지속되는 grace period를 강제로 진전시키는 상태를 보관합니다. 여기서는 그중 관계를 나타내는 `node`, `level`, `rda` field를 다룹니다.

`struct rcu_node node[NUM_RCU_NODES]`는 트리를 평평한 배열로 저장합니다. 배열 첫 원소가 root이고, 그 다음 묶음이 root의 자식이며, 마지막 묶음이 leaf입니다. 따라서 `rcu_for_each_node_breadth_first()`는 배열을 선형 scan하는 것만으로 breadth-first traversal을 구현합니다. 이 순회는 grace period 시작과 종료에 사용됩니다.

트리를 배열에 배치
node[0]: rootnext array range: level 1next array range: level 2last array range: leaf nodes

TreeMapping.svg의 핵심은 계층별 node를 breadth-first 순서로 연속 배치하는 것입니다.

`struct rcu_node *level[NUM_RCU_LVLS + 1]`의 각 원소는 해당 단계 첫 `rcu_node`를 가리킵니다. `level[0]`은 root, `level[1]`은 root의 첫 자식, `level[2]`는 첫 leaf를 가리키는 식입니다. 배열 모양을 트리로 펼치면 교차 없는 평면 표현을 얻을 수 있습니다.

level[] 인덱스
원소대상
level[0]root rcu_node
level[1]root의 첫 child
level[2]첫 leaf rcu_node
level[NUM_RCU_LVLS]배열 끝 경계

각 pointer가 배열 안에서 해당 트리 단계가 시작되는 위치를 표시합니다.

`struct rcu_data __percpu *rda`는 해당 CPU의 `rcu_data`를 찾는 per-CPU pointer입니다. `node[]`, `level[]`, `rda` 관계 field는 초기화가 끝난 뒤 상수이므로 별도 보호가 필요 없습니다.

rcu_state 연결 관계
rcu_statenode[] combining treelevel[] level boundariesrda per-CPU pointers

하나의 전역 구조가 평면 배열, 단계 시작 pointer와 CPU별 state를 함께 연결합니다.


The ``rcu_state`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``rcu_state`` structure is the base structure that represents the
state of RCU in the system. This structure forms the interconnection
between the ``rcu_node`` and ``rcu_data`` structures, tracks grace
periods, contains the lock used to synchronize with CPU-hotplug events,
and maintains state used to force quiescent states when grace periods
extend too long,

A few of the ``rcu_state`` structure's fields are discussed, singly and
in groups, in the following sections. The more specialized fields are
covered in the discussion of their use.

Relationship to rcu_node and rcu_data Structures
''''''''''''''''''''''''''''''''''''''''''''''''

This portion of the ``rcu_state`` structure is declared as follows:

::

     1   struct rcu_node node[NUM_RCU_NODES];
     2   struct rcu_node *level[NUM_RCU_LVLS + 1];
     3   struct rcu_data __percpu *rda;

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Wait a minute! You said that the ``rcu_node`` structures formed a     |
| tree, but they are declared as a flat array! What gives?              |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| The tree is laid out in the array. The first node In the array is the |
| head, the next set of nodes in the array are children of the head     |
| node, and so on until the last set of nodes in the array are the      |
| leaves.                                                               |
| See the following diagrams to see how this works.                     |
+-----------------------------------------------------------------------+

The ``rcu_node`` tree is embedded into the ``->node[]`` array as shown
in the following figure:

.. kernel-figure:: TreeMapping.svg

One interesting consequence of this mapping is that a breadth-first
traversal of the tree is implemented as a simple linear scan of the
array, which is in fact what the ``rcu_for_each_node_breadth_first()``
macro does. This macro is used at the beginning and ends of grace
periods.

Each entry of the ``->level`` array references the first ``rcu_node``
structure on the corresponding level of the tree, for example, as shown
below:

.. kernel-figure:: TreeMappingLevel.svg

The zero\ :sup:`th` element of the array references the root
``rcu_node`` structure, the first element references the first child of
the root ``rcu_node``, and finally the second element references the
first leaf ``rcu_node`` structure.

For whatever it is worth, if you draw the tree to be tree-shaped rather
than array-shaped, it is easy to draw a planar representation:

.. kernel-figure:: TreeLevel.svg

Finally, the ``->rda`` field references a per-CPU pointer to the
corresponding CPU's ``rcu_data`` structure.

All of these fields are constant once initialization is complete, and
therefore need no protection.

rcu_state의 grace-period 번호와 진단 field

265-339

`rcu_state.gp_seq`는 현재 grace-period sequence number입니다. 아래 두 bit가 0이면 아직 시작되지 않은 idle 상태이고 1이면 진행 중입니다. 그 밖의 아래 두 bit 값은 오류입니다. 이 field는 root `rcu_node->lock`이 보호합니다.

`rcu_node`와 `rcu_data`에도 `gp_seq`가 있습니다. `rcu_state` 값이 가장 최신이며 시작·종료를 분산 감지할 수 있도록 root에서 leaf 방향의 `rcu_node`, 이어서 `rcu_data`로 흘러갑니다.

Root `rcu_node`에 이미 `gp_seq`가 있어도 `rcu_state`에 공식 값을 따로 두는 이유는 단일-node 트리의 불필요한 lock 경합을 막기 위해서입니다. Root 값을 즉시 증가시키면 모든 CPU의 `rcu_pending()`이 변화를 보고 RCU core와 `note_gp_changes()`를 호출해 node lock을 잡습니다. 그러나 `rcu_gp_init()`이 아직 `qsmask`를 초기화하지 않았으므로 각 CPU는 진전에 기여하지 못한 채 자기 `rdp->gp_seq`만 갱신하고 lock을 놓습니다.

별도 gp_seq가 피하는 경합
increment rcu_state.gp_seqrcu_gp_init prepares qsmasklock root rcu_nodepublish node gp_seq and qsmask togetherCPUs begin useful reporting

공식 번호와 CPU에 보이는 node 상태를 나누어 qsmask와 gp_seq를 한 lock 구간에서 함께 공개합니다.

`rcu_state.gp_seq`를 별도로 증가시키면 CPU가 보는 root 값은 바로 바뀌지 않습니다. 이후 `rcu_gp_init()`의 계층 전파가 root `gp_seq`와 `qsmask`를 같은 lock 획득에서 갱신해 무의미한 경쟁을 없앱니다.

`gp_max`는 지금까지 가장 오래 걸린 grace period의 길이를 jiffies로 기록하며 root node lock이 보호합니다. `name`과 `abbr`은 preemptible RCU의 `rcu_preempt`/`p`와 non-preemptible RCU의 `rcu_sched`/`s`를 구분하며 진단과 tracing에 사용됩니다.

Grace-Period Tracking
'''''''''''''''''''''

This portion of the ``rcu_state`` structure is declared as follows:

::

     1   unsigned long gp_seq;

RCU grace periods are numbered, and the ``->gp_seq`` field contains the
current grace-period sequence number. The bottom two bits are the state
of the current grace period, which can be zero for not yet started or
one for in progress. In other words, if the bottom two bits of
``->gp_seq`` are zero, then RCU is idle. Any other value in the bottom
two bits indicates that something is broken. This field is protected by
the root ``rcu_node`` structure's ``->lock`` field.

There are ``->gp_seq`` fields in the ``rcu_node`` and ``rcu_data``
structures as well. The fields in the ``rcu_state`` structure represent
the most current value, and those of the other structures are compared
in order to detect the beginnings and ends of grace periods in a
distributed fashion. The values flow from ``rcu_state`` to ``rcu_node``
(down the tree from the root to the leaves) to ``rcu_data``.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Given that the root rcu_node structure has a gp_seq field,            |
| why does RCU maintain a separate gp_seq in the rcu_state structure?   |
| Why not just use the root rcu_node's gp_seq as the official record    |
| and update it directly when starting a new grace period?              |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| On single-node RCU trees (where the root node is also a leaf),        |
| updating the root node's gp_seq immediately would create unnecessary  |
| lock contention. Here's why:                                          |
|                                                                       |
| If we did rcu_seq_start() directly on the root node's gp_seq:         |
|                                                                       |
| 1. All CPUs would immediately see their node's gp_seq from their rdp's|
|    gp_seq, in rcu_pending(). They would all then invoke the RCU-core. |
| 2. Which calls note_gp_changes() and try to acquire the node lock.    |
| 3. But rnp->qsmask isn't initialized yet (happens later in            |
|    rcu_gp_init())                                                     |
| 4. So each CPU would acquire the lock, find it can't determine if it  |
|    needs to report quiescent state (no qsmask), update rdp->gp_seq,   |
|    and release the lock.                                              |
| 5. Result: Lots of lock acquisitions with no grace period progress    |
|                                                                       |
| By having a separate rcu_state.gp_seq, we can increment the official  |
| grace period counter without immediately affecting what CPUs see in   |
| their nodes. The hierarchical propagation in rcu_gp_init() then       |
| updates the root node's gp_seq and qsmask together under the same lock|
| acquisition, avoiding this useless contention.                        |
+-----------------------------------------------------------------------+

Miscellaneous
'''''''''''''

This portion of the ``rcu_state`` structure is declared as follows:

::

     1   unsigned long gp_max;
     2   char abbr;
     3   char *name;

The ``->gp_max`` field tracks the duration of the longest grace period
in jiffies. It is protected by the root ``rcu_node``'s ``->lock``.

The ``->name`` and ``->abbr`` fields distinguish between preemptible RCU
(“rcu_preempt” and “p”) and non-preemptible RCU (“rcu_sched” and “s”).
These fields are used for diagnostic and tracing purposes.

rcu_node의 트리 연결, lock과 GP 추적

340-447

`rcu_node`는 quiescent-state 정보를 leaf에서 root로 올리고 grace-period 정보를 root에서 leaf로 내리는 결합 트리의 node입니다. 전역 lock 병목 없이 동기화해 접근할 수 있는 local grace-period copy를 제공합니다. PREEMPT_RCU에서는 block된 reader task를, RCU_BOOST에서는 node별 boosting kthread와 상태를, 그리고 grace period에서 무시해야 할 CPU를 판정하는 hotplug 상태를 관리합니다.

`parent`는 한 단계 위 node를 가리키며 root에서는 `NULL`입니다. `level`은 root 0부터 시작하는 깊이, `grpnum`은 부모 자식 중 위치로 32비트에서 0~31, 64비트에서 0~63입니다. `grpmask`는 `grpnum`에 대응해 bit 하나만 켠 mask이며 부모 bitmask에서 이 node의 bit를 지울 때 사용합니다. `grplo`와 `grphi`는 이 node가 담당하는 최저·최고 CPU 번호입니다. 모두 초기화 뒤 상수입니다.

rcu_node 트리 연결 field
field의미
parent상위 rcu_node, root는 NULL
levelroot=0인 트리 깊이
grpnum / grpmask부모 안의 자식 번호와 one-bit mask
grplo / grphi담당 CPU 번호 범위

상향 보고와 담당 CPU 범위를 상수 metadata로 표현합니다.

`raw_spinlock_t lock`은 별도 설명이 없는 나머지 field를 보호합니다. Tracing은 lock 없이 모든 field를 읽을 수 있어 서로 어긋난 trace를 만들 수 있지만, 관찰 자체가 timing bug를 없애는 것보다는 낫다는 선택입니다.

Node의 `gp_seq`는 `rcu_state.gp_seq`보다 최대 한 단계 늦을 수 있고 아래 두 bit가 0이면 이 node 관점에서 RCU가 idle입니다. 각 grace period의 시작과 끝에 갱신됩니다. `gp_seq_needed`는 이 node가 본 가장 먼 미래의 grace-period 요청을 기록하며 `gp_seq`가 같거나 더 앞서면 요청이 충족됩니다.

Sequence number가 wrap해도 문제없습니다. `gp_seq_needed`가 `gp_seq`보다 뒤처지면 grace period 끝에 갱신되므로 두 값의 거리는 제한되고 modulo arithmetic 비교가 올바르게 동작합니다.

Node GP 상태의 흐름
rcu_state.gp_seq advancesrcu_node.gp_seq catches upcompare gp_seq_neededrequest fulfilled when gp_seq reaches need

전역 상태보다 한 단계 늦을 수 있는 local copy가 요청 완료 여부를 판정합니다.

The ``rcu_node`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``rcu_node`` structures form the combining tree that propagates
quiescent-state information from the leaves to the root and also that
propagates grace-period information from the root down to the leaves.
They provides local copies of the grace-period state in order to allow
this information to be accessed in a synchronized manner without
suffering the scalability limitations that would otherwise be imposed by
global locking. In ``CONFIG_PREEMPT_RCU`` kernels, they manage the lists
of tasks that have blocked while in their current RCU read-side critical
section. In ``CONFIG_PREEMPT_RCU`` with ``CONFIG_RCU_BOOST``, they
manage the per-\ ``rcu_node`` priority-boosting kernel threads
(kthreads) and state. Finally, they record CPU-hotplug state in order to
determine which CPUs should be ignored during a given grace period.

The ``rcu_node`` structure's fields are discussed, singly and in groups,
in the following sections.

Connection to Combining Tree
''''''''''''''''''''''''''''

This portion of the ``rcu_node`` structure is declared as follows:

::

     1   struct rcu_node *parent;
     2   u8 level;
     3   u8 grpnum;
     4   unsigned long grpmask;
     5   int grplo;
     6   int grphi;

The ``->parent`` pointer references the ``rcu_node`` one level up in the
tree, and is ``NULL`` for the root ``rcu_node``. The RCU implementation
makes heavy use of this field to push quiescent states up the tree. The
``->level`` field gives the level in the tree, with the root being at
level zero, its children at level one, and so on. The ``->grpnum`` field
gives this node's position within the children of its parent, so this
number can range between 0 and 31 on 32-bit systems and between 0 and 63
on 64-bit systems. The ``->level`` and ``->grpnum`` fields are used only
during initialization and for tracing. The ``->grpmask`` field is the
bitmask counterpart of ``->grpnum``, and therefore always has exactly
one bit set. This mask is used to clear the bit corresponding to this
``rcu_node`` structure in its parent's bitmasks, which are described
later. Finally, the ``->grplo`` and ``->grphi`` fields contain the
lowest and highest numbered CPU served by this ``rcu_node`` structure,
respectively.

All of these fields are constant, and thus do not require any
synchronization.

Synchronization
'''''''''''''''

This field of the ``rcu_node`` structure is declared as follows:

::

     1   raw_spinlock_t lock;

This field is used to protect the remaining fields in this structure,
unless otherwise stated. That said, all of the fields in this structure
can be accessed without locking for tracing purposes. Yes, this can
result in confusing traces, but better some tracing confusion than to be
heisenbugged out of existence.

.. _grace-period-tracking-1:

Grace-Period Tracking
'''''''''''''''''''''

This portion of the ``rcu_node`` structure is declared as follows:

::

     1   unsigned long gp_seq;
     2   unsigned long gp_seq_needed;

The ``rcu_node`` structures' ``->gp_seq`` fields are the counterparts of
the field of the same name in the ``rcu_state`` structure. They each may
lag up to one step behind their ``rcu_state`` counterpart. If the bottom
two bits of a given ``rcu_node`` structure's ``->gp_seq`` field is zero,
then this ``rcu_node`` structure believes that RCU is idle.

The ``>gp_seq`` field of each ``rcu_node`` structure is updated at the
beginning and the end of each grace period.

The ``->gp_seq_needed`` fields record the furthest-in-the-future grace
period request seen by the corresponding ``rcu_node`` structure. The
request is considered fulfilled when the value of the ``->gp_seq`` field
equals or exceeds that of the ``->gp_seq_needed`` field.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Suppose that this ``rcu_node`` structure doesn't see a request for a  |
| very long time. Won't wrapping of the ``->gp_seq`` field cause        |
| problems?                                                             |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| No, because if the ``->gp_seq_needed`` field lags behind the          |
| ``->gp_seq`` field, the ``->gp_seq_needed`` field will be updated at  |
| the end of the grace period. Modulo-arithmetic comparisons therefore  |
| will always get the correct answer, even with wrapping.               |
+-----------------------------------------------------------------------+

rcu_node의 quiescent-state bitmask

448-514

`qsmask`는 현재 normal grace period에서 아직 quiescent state를 보고해야 하는 자식을 bit 1로 표시합니다. Leaf `rcu_node`에서는 자식을 `rcu_data`라고 생각하면 됩니다. `expmask`는 expedited grace period에 같은 역할을 합니다. Expedited GP는 normal GP와 개념은 같지만 수 millisecond를 수십 microsecond로 줄이기 위해 수십 microsecond 규모의 극단적인 CPU 비용을 받아들입니다.

`qsmaskinit`는 온라인 CPU를 하나 이상 포함하는 자식을 표시해 normal GP 시작 때 `qsmask`의 초기값이 됩니다. `expmaskinit`도 expedited GP 시작 때 `expmask`를 초기화합니다.

Quiescent-state mask
field대상
qsmask현재 normal GP의 미보고 자식
expmask현재 expedited GP의 미보고 자식
qsmaskinit온라인 CPU가 있는 자식의 normal 초기 mask
expmaskinitexpedited 초기 mask

진행 중 mask와 다음 초기값을 normal/expedited로 나눕니다.

Atomic bit operation만으로 lock을 없앨 수는 없습니다. 예를 들어 CPU 0이 오래 dyntick-idle에 있다가 깨어 현재 GP의 보고가 필요하다는 flag를 남기고, CPU 1이 `force_quiescent_state()`에서 CPU 0의 extended quiescent state를 발견할 수 있습니다. 그 사이 CPU 0의 scheduling-clock interrupt가 RCU read-side critical section 도중 발생해 softirq 보고를 준비할 수 있습니다.

CPU 1이 먼저 현재 GP를 끝내고 새 GP를 시작한 뒤 CPU 0이 이전 관찰을 새 GP에 보고하면, 새 GP가 아직 끝나지 않은 read section보다 먼저 종료될 수 있습니다. 따라서 bit clear와 `gp_seq` 갱신을 반드시 같은 locking 규칙으로 조정해야 합니다.

Lock 없는 보고가 만드는 잘못된 GP 귀속
CPU0 leaves dyntick-idleCPU1 samples old extended QSCPU0 enters RCU read section and prepares reportCPU1 completes old GP and starts new GPstale CPU0 report could clear new GP bitlock couples qsmask clear with gp_seq

이전 GP에서 얻은 quiescent-state 관찰이 다음 GP에 적용되지 않게 sequence와 mask를 함께 보호합니다.

Quiescent-State Tracking
''''''''''''''''''''''''

These fields manage the propagation of quiescent states up the combining
tree.

This portion of the ``rcu_node`` structure has fields as follows:

::

     1   unsigned long qsmask;
     2   unsigned long expmask;
     3   unsigned long qsmaskinit;
     4   unsigned long expmaskinit;

The ``->qsmask`` field tracks which of this ``rcu_node`` structure's
children still need to report quiescent states for the current normal
grace period. Such children will have a value of 1 in their
corresponding bit. Note that the leaf ``rcu_node`` structures should be
thought of as having ``rcu_data`` structures as their children.
Similarly, the ``->expmask`` field tracks which of this ``rcu_node``
structure's children still need to report quiescent states for the
current expedited grace period. An expedited grace period has the same
conceptual properties as a normal grace period, but the expedited
implementation accepts extreme CPU overhead to obtain much lower
grace-period latency, for example, consuming a few tens of microseconds
worth of CPU time to reduce grace-period duration from milliseconds to
tens of microseconds. The ``->qsmaskinit`` field tracks which of this
``rcu_node`` structure's children cover for at least one online CPU.
This mask is used to initialize ``->qsmask``, and ``->expmaskinit`` is
used to initialize ``->expmask`` and the beginning of the normal and
expedited grace periods, respectively.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Why are these bitmasks protected by locking? Come on, haven't you     |
| heard of atomic instructions???                                       |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Lockless grace-period computation! Such a tantalizing possibility!    |
| But consider the following sequence of events:                        |
|                                                                       |
| #. CPU 0 has been in dyntick-idle mode for quite some time. When it   |
|    wakes up, it notices that the current RCU grace period needs it to |
|    report in, so it sets a flag where the scheduling clock interrupt  |
|    will find it.                                                      |
| #. Meanwhile, CPU 1 is running ``force_quiescent_state()``, and       |
|    notices that CPU 0 has been in dyntick idle mode, which qualifies  |
|    as an extended quiescent state.                                    |
| #. CPU 0's scheduling clock interrupt fires in the middle of an RCU   |
|    read-side critical section, and notices that the RCU core needs    |
|    something, so commences RCU softirq processing.                    |
| #. CPU 0's softirq handler executes and is just about ready to report |
|    its quiescent state up the ``rcu_node`` tree.                      |
| #. But CPU 1 beats it to the punch, completing the current grace      |
|    period and starting a new one.                                     |
| #. CPU 0 now reports its quiescent state for the wrong grace period.  |
|    That grace period might now end before the RCU read-side critical  |
|    section. If that happens, disaster will ensue.                     |
|                                                                       |
| So the locking is absolutely required in order to coordinate clearing |
| of the bits with updating of the grace-period sequence number in      |
| ``->gp_seq``.                                                         |
+-----------------------------------------------------------------------+

PREEMPT_RCU의 blocked task 관리

515-570

PREEMPT_RCU에서는 task가 RCU read-side critical section 도중 preempt될 수 있으므로 이를 명시적으로 추적합니다. `blkd_tasks`는 block되거나 preempt된 task의 list head입니다. Task가 read section 안에서 context switch되면 해당 CPU의 leaf `rcu_node` list 앞쪽에 `task_struct.rcu_node_entry`로 들어가고, 나중에 가장 바깥 `rcu_read_unlock()`을 실행할 때 스스로 제거됩니다.

List는 역시간 순서입니다. 어떤 task가 현재 grace period를 막으면 그보다 뒤에 들어온 task도 같은 GP를 막으므로 pointer 하나면 경계를 나타낼 수 있습니다. Normal GP는 `gp_tasks`, expedited GP는 `exp_tasks`가 그 pointer입니다. GP가 없거나 막는 task가 없으면 `NULL`입니다. 가리키던 task가 list에서 나갈 때 다음 task로 전진시키거나 후속 task가 없으면 `NULL`로 바꿔야 합니다.

예시에서 CPU affinity가 가장 큰 CPU에 고정된 T1이 read section에서 block된 뒤 expedited GP가 시작되고, T2가 block된 뒤 normal GP가 시작되며, 마지막으로 T3가 block됩니다. 이때 T1은 두 GP를 모두, T2는 normal GP만 막고 T3는 어느 GP도 막지 않습니다. Task가 다시 실행됐다는 이유만으로 list에서 즉시 빠지지 않고 outermost unlock까지 남습니다.

Blocked-task list의 시간 경계
T1 blocksexpedited GP startsT2 blocksnormal GP startsT3 blocksT1 blocks both; T2 normal only; T3 neither

List 앞에는 최근 block task가 오고 gp_tasks와 exp_tasks가 각 GP를 막는 가장 오래된 경계를 가리킵니다.

`wait_blkd_tasks`는 현재 grace period가 blocked task를 기다리고 있는지를 표시합니다.

Blocked-Task Management
'''''''''''''''''''''''

``PREEMPT_RCU`` allows tasks to be preempted in the midst of their RCU
read-side critical sections, and these tasks must be tracked explicitly.
The details of exactly why and how they are tracked will be covered in a
separate article on RCU read-side processing. For now, it is enough to
know that the ``rcu_node`` structure tracks them.

::

     1   struct list_head blkd_tasks;
     2   struct list_head *gp_tasks;
     3   struct list_head *exp_tasks;
     4   bool wait_blkd_tasks;

The ``->blkd_tasks`` field is a list header for the list of blocked and
preempted tasks. As tasks undergo context switches within RCU read-side
critical sections, their ``task_struct`` structures are enqueued (via
the ``task_struct``'s ``->rcu_node_entry`` field) onto the head of the
``->blkd_tasks`` list for the leaf ``rcu_node`` structure corresponding
to the CPU on which the outgoing context switch executed. As these tasks
later exit their RCU read-side critical sections, they remove themselves
from the list. This list is therefore in reverse time order, so that if
one of the tasks is blocking the current grace period, all subsequent
tasks must also be blocking that same grace period. Therefore, a single
pointer into this list suffices to track all tasks blocking a given
grace period. That pointer is stored in ``->gp_tasks`` for normal grace
periods and in ``->exp_tasks`` for expedited grace periods. These last
two fields are ``NULL`` if either there is no grace period in flight or
if there are no blocked tasks preventing that grace period from
completing. If either of these two pointers is referencing a task that
removes itself from the ``->blkd_tasks`` list, then that task must
advance the pointer to the next task on the list, or set the pointer to
``NULL`` if there are no subsequent tasks on the list.

For example, suppose that tasks T1, T2, and T3 are all hard-affinitied
to the largest-numbered CPU in the system. Then if task T1 blocked in an
RCU read-side critical section, then an expedited grace period started,
then task T2 blocked in an RCU read-side critical section, then a normal
grace period started, and finally task 3 blocked in an RCU read-side
critical section, then the state of the last leaf ``rcu_node``
structure's blocked-task list would be as shown below:

.. kernel-figure:: blkd_task.svg

Task T1 is blocking both grace periods, task T2 is blocking only the
normal grace period, and task T3 is blocking neither grace period. Note
that these tasks will not remove themselves from this list immediately
upon resuming execution. They will instead remain on the list until they
execute the outermost ``rcu_read_unlock()`` that ends their RCU
read-side critical section.

The ``->wait_blkd_tasks`` field indicates whether or not the current
grace period is waiting on a blocked task.

rcu_node 배열 크기와 fanout 계산

571-699

`rcu_node` 배열 크기는 C preprocessor 식으로 정합니다. `CONFIG_RCU_FANOUT`이 지정되면 non-leaf fanout으로 쓰고, 그렇지 않으면 word size에 따라 64비트는 64, 32비트는 32를 선택합니다. `CONFIG_RCU_FANOUT_LEAF`도 leaf가 담당할 CPU 수를 정합니다.

64비트 `qsmask`는 이론상 leaf 하나가 64 CPU를 다룰 수 있지만 실제로는 leaf lock 경합이 과도해져 기본 leaf fanout을 16으로 제한합니다. `RCU_FANOUT_1`부터 `_4`까지는 leaf fanout에 non-leaf fanout을 단계별로 곱해 1~4단계 트리가 지원할 최대 CPU 수를 계산합니다.

Fanout 누적 계산
symbol계산
RCU_FANOUT_1RCU_FANOUT_LEAF
RCU_FANOUT_2FANOUT_1 x RCU_FANOUT
RCU_FANOUT_3FANOUT_2 x RCU_FANOUT
RCU_FANOUT_4FANOUT_3 x RCU_FANOUT

Leaf 수용량에 internal fanout을 단계마다 곱합니다.

`NR_CPUS`가 각 한계 이하인지 lines 26~66의 `#if`가 검사해 `RCU_NUM_LVLS`와 단계별 `NUM_RCU_LVL_n`을 선택합니다. Top level은 언제나 node 하나입니다. 아래 단계의 node 수는 최대 CPU 수를 현재 단계 아래의 총 fanout으로 나누고 올림해 구합니다. `NUM_RCU_NODES`는 모든 단계의 합이며 `NUM_RCU_LVL_INIT`은 단계별 수의 initializer입니다.

`RCU_NODE_NAME_INIT`, `RCU_FQS_NAME_INIT`, `RCU_EXP_NAME_INIT`은 lockdep lock-class 이름 initializer를 만듭니다. 지정한 fanout으로 `NR_CPUS`를 수용할 수 없으면 compile-time error를 냅니다.

현재 최대 4단계이므로 32비트는 16*32*32*32=524,288 CPU, 64비트는 16*64*64*64=4,194,304 CPU를 지원합니다. `CONFIG_RCU_FANOUT=8`인 4단계 커널도 4,096 CPU를 지원해 socket당 8 CPU 같은 배치를 시험할 수 있지만 socket과 `rcu_node` 경계 불일치가 측정 가능한 성능 저하를 일으킨 사례는 아직 없습니다. 4단계 build는 작은 장비에서 결합 트리 code를 더 깊게 시험하는 데도 유용합니다.

Sizing the ``rcu_node`` Array
'''''''''''''''''''''''''''''

The ``rcu_node`` array is sized via a series of C-preprocessor
expressions as follows:

::

    1 #ifdef CONFIG_RCU_FANOUT
    2 #define RCU_FANOUT CONFIG_RCU_FANOUT
    3 #else
    4 # ifdef CONFIG_64BIT
    5 # define RCU_FANOUT 64
    6 # else
    7 # define RCU_FANOUT 32
    8 # endif
    9 #endif
   10
   11 #ifdef CONFIG_RCU_FANOUT_LEAF
   12 #define RCU_FANOUT_LEAF CONFIG_RCU_FANOUT_LEAF
   13 #else
   14 # ifdef CONFIG_64BIT
   15 # define RCU_FANOUT_LEAF 64
   16 # else
   17 # define RCU_FANOUT_LEAF 32
   18 # endif
   19 #endif
   20
   21 #define RCU_FANOUT_1        (RCU_FANOUT_LEAF)
   22 #define RCU_FANOUT_2        (RCU_FANOUT_1 * RCU_FANOUT)
   23 #define RCU_FANOUT_3        (RCU_FANOUT_2 * RCU_FANOUT)
   24 #define RCU_FANOUT_4        (RCU_FANOUT_3 * RCU_FANOUT)
   25
   26 #if NR_CPUS <= RCU_FANOUT_1
   27 #  define RCU_NUM_LVLS        1
   28 #  define NUM_RCU_LVL_0        1
   29 #  define NUM_RCU_NODES        NUM_RCU_LVL_0
   30 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0 }
   31 #  define RCU_NODE_NAME_INIT  { "rcu_node_0" }
   32 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0" }
   33 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0" }
   34 #elif NR_CPUS <= RCU_FANOUT_2
   35 #  define RCU_NUM_LVLS        2
   36 #  define NUM_RCU_LVL_0        1
   37 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
   38 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1)
   39 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1 }
   40 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1" }
   41 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1" }
   42 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1" }
   43 #elif NR_CPUS <= RCU_FANOUT_3
   44 #  define RCU_NUM_LVLS        3
   45 #  define NUM_RCU_LVL_0        1
   46 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
   47 #  define NUM_RCU_LVL_2        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
   48 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2)
   49 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2 }
   50 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1", "rcu_node_2" }
   51 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2" }
   52 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2" }
   53 #elif NR_CPUS <= RCU_FANOUT_4
   54 #  define RCU_NUM_LVLS        4
   55 #  define NUM_RCU_LVL_0        1
   56 #  define NUM_RCU_LVL_1        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_3)
   57 #  define NUM_RCU_LVL_2        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_2)
   58 #  define NUM_RCU_LVL_3        DIV_ROUND_UP(NR_CPUS, RCU_FANOUT_1)
   59 #  define NUM_RCU_NODES        (NUM_RCU_LVL_0 + NUM_RCU_LVL_1 + NUM_RCU_LVL_2 + NUM_RCU_LVL_3)
   60 #  define NUM_RCU_LVL_INIT    { NUM_RCU_LVL_0, NUM_RCU_LVL_1, NUM_RCU_LVL_2, NUM_RCU_LVL_3 }
   61 #  define RCU_NODE_NAME_INIT  { "rcu_node_0", "rcu_node_1", "rcu_node_2", "rcu_node_3" }
   62 #  define RCU_FQS_NAME_INIT   { "rcu_node_fqs_0", "rcu_node_fqs_1", "rcu_node_fqs_2", "rcu_node_fqs_3" }
   63 #  define RCU_EXP_NAME_INIT   { "rcu_node_exp_0", "rcu_node_exp_1", "rcu_node_exp_2", "rcu_node_exp_3" }
   64 #else
   65 # error "CONFIG_RCU_FANOUT insufficient for NR_CPUS"
   66 #endif

The maximum number of levels in the ``rcu_node`` structure is currently
limited to four, as specified by lines 21-24 and the structure of the
subsequent “if” statement. For 32-bit systems, this allows
16*32*32*32=524,288 CPUs, which should be sufficient for the next few
years at least. For 64-bit systems, 16*64*64*64=4,194,304 CPUs is
allowed, which should see us through the next decade or so. This
four-level tree also allows kernels built with ``CONFIG_RCU_FANOUT=8``
to support up to 4096 CPUs, which might be useful in very large systems
having eight CPUs per socket (but please note that no one has yet shown
any measurable performance degradation due to misaligned socket and
``rcu_node`` boundaries). In addition, building kernels with a full four
levels of ``rcu_node`` tree permits better testing of RCU's
combining-tree code.

The ``RCU_FANOUT`` symbol controls how many children are permitted at
each non-leaf level of the ``rcu_node`` tree. If the
``CONFIG_RCU_FANOUT`` Kconfig option is not specified, it is set based
on the word size of the system, which is also the Kconfig default.

The ``RCU_FANOUT_LEAF`` symbol controls how many CPUs are handled by
each leaf ``rcu_node`` structure. Experience has shown that allowing a
given leaf ``rcu_node`` structure to handle 64 CPUs, as permitted by the
number of bits in the ``->qsmask`` field on a 64-bit system, results in
excessive contention for the leaf ``rcu_node`` structures' ``->lock``
fields. The number of CPUs per leaf ``rcu_node`` structure is therefore
limited to 16 given the default value of ``CONFIG_RCU_FANOUT_LEAF``. If
``CONFIG_RCU_FANOUT_LEAF`` is unspecified, the value selected is based
on the word size of the system, just as for ``CONFIG_RCU_FANOUT``.
Lines 11-19 perform this computation.

Lines 21-24 compute the maximum number of CPUs supported by a
single-level (which contains a single ``rcu_node`` structure),
two-level, three-level, and four-level ``rcu_node`` tree, respectively,
given the fanout specified by ``RCU_FANOUT`` and ``RCU_FANOUT_LEAF``.
These numbers of CPUs are retained in the ``RCU_FANOUT_1``,
``RCU_FANOUT_2``, ``RCU_FANOUT_3``, and ``RCU_FANOUT_4`` C-preprocessor
variables, respectively.

These variables are used to control the C-preprocessor ``#if`` statement
spanning lines 26-66 that computes the number of ``rcu_node`` structures
required for each level of the tree, as well as the number of levels
required. The number of levels is placed in the ``NUM_RCU_LVLS``
C-preprocessor variable by lines 27, 35, 44, and 54. The number of
``rcu_node`` structures for the topmost level of the tree is always
exactly one, and this value is unconditionally placed into
``NUM_RCU_LVL_0`` by lines 28, 36, 45, and 55. The rest of the levels
(if any) of the ``rcu_node`` tree are computed by dividing the maximum
number of CPUs by the fanout supported by the number of levels from the
current level down, rounding up. This computation is performed by
lines 37, 46-47, and 56-58. Lines 31-33, 40-42, 50-52, and 62-63 create
initializers for lockdep lock-class names. Finally, lines 64-66 produce
an error if the maximum number of CPUs is too large for the specified
fanout.

rcu_segcblist의 네 callback 구간

700-811

`rcu_segcblist`는 callback 하나의 linked list를 네 논리 구간으로 나눕니다. `RCU_DONE_TAIL`은 grace period가 끝나 호출할 수 있는 callback, `RCU_WAIT_TAIL`은 현재 GP를 기다리는 callback, `RCU_NEXT_READY_TAIL`은 다음 GP 시작을 기다리는 callback, `RCU_NEXT_TAIL`은 아직 어느 GP에도 연결되지 않은 callback입니다. CPU마다 현재 GP에 대한 관점이 다를 수 있어 각 구간에 `gp_seq[]`가 대응합니다.

Segmented callback list
segment상태
RCU_DONE_TAILGP 완료, 호출 가능
RCU_WAIT_TAIL현재 GP 대기
RCU_NEXT_READY_TAIL다음 GP 시작 대기
RCU_NEXT_TAIL아직 GP 미배정

오래된 callback은 head 쪽에 있고 새 callback은 tail에 추가됩니다.

`head`는 첫 callback을 가리키며 callback이 전혀 없으면 `NULL`일 수 있습니다. 각 `tails[]` 원소는 해당 구간의 마지막 callback의 `next` pointer를 가리킵니다. 해당 구간과 앞 구간이 모두 비면 list의 `head` pointer 자체를 가리키고, 해당 구간만 비었다면 직전 `tails[]`와 같은 pointer가 됩니다.

그림의 예에서는 `head`가 CB1을 가리킵니다. DONE tail이 `head` 자체를 가리켜 호출 가능한 callback은 없습니다. WAIT tail은 CB2의 `next`를 가리켜 CB1과 CB2가 현재 GP를 기다립니다. NEXT_READY tail도 같은 위치이므로 다음 GP 시작을 기다리는 callback은 없습니다. NEXT tail은 CB4의 `next`를 가리켜 CB3과 CB4가 아직 GP에 배정되지 않았음을 나타냅니다. NEXT tail은 보통 마지막 callback의 `next`이고 빈 list에서는 `head` pointer입니다.

Callback 구간 전진
RCU_NEXT_TAIL: unassignedRCU_NEXT_READY_TAIL: next GPRCU_WAIT_TAIL: current GPRCU_DONE_TAIL: readyrcu_do_batch invokes

Grace period가 진행될 때 CPU가 callback의 논리 경계를 head 방향으로 이동시킵니다.

예외적으로 `tails[RCU_NEXT_TAIL]`이 `NULL`이면 list가 disabled 상태입니다. CPU가 offline이거나 callback을 kthread에 offload할 때 이렇게 됩니다. `gp_seq[]` 덕분에 오래 idle했던 CPU도 깨어난 뒤 자기 callback 중 무엇을 호출할 수 있는지 판단하며 서로 다른 CPU의 GP 관점 차이 때문에 너무 일찍 호출하지 않습니다.

`len`은 전체 callback 수이고 `len_lazy`는 그중 memory free만 수행해 안전하게 미룰 수 있다고 알려진 callback 수입니다. Callback 유무를 판정할 때는 `head`가 아니라 반드시 `len`을 사용해야 합니다.

`rcu_do_batch()`는 DONE 구간을 한꺼번에 떼어내므로 다른 구간이 없으면 처리 도중 `head`가 잠시 `NULL`이 될 수 있습니다. 고우선순위 process가 깨어 callback 처리를 미루면 남은 callback을 DONE 구간에 다시 넣고 `head`도 복구합니다. 이 동안 callback은 계속 존재하지만 head만 일시적으로 NULL입니다. 반면 `len`과 `len_lazy`는 callback이 실제 호출된 뒤에만 줄어 `len==0`이 진짜 빈 상태를 뜻합니다. 다른 CPU가 `len`을 sample하려면 memory barrier 등 적절한 동기화가 필요하며 `rcu_barrier()`에서는 특히 미묘합니다.

The ``rcu_segcblist`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``rcu_segcblist`` structure maintains a segmented list of callbacks
as follows:

::

    1 #define RCU_DONE_TAIL        0
    2 #define RCU_WAIT_TAIL        1
    3 #define RCU_NEXT_READY_TAIL  2
    4 #define RCU_NEXT_TAIL        3
    5 #define RCU_CBLIST_NSEGS     4
    6
    7 struct rcu_segcblist {
    8   struct rcu_head *head;
    9   struct rcu_head **tails[RCU_CBLIST_NSEGS];
   10   unsigned long gp_seq[RCU_CBLIST_NSEGS];
   11   long len;
   12   long len_lazy;
   13 };

The segments are as follows:

#. ``RCU_DONE_TAIL``: Callbacks whose grace periods have elapsed. These
   callbacks are ready to be invoked.
#. ``RCU_WAIT_TAIL``: Callbacks that are waiting for the current grace
   period. Note that different CPUs can have different ideas about which
   grace period is current, hence the ``->gp_seq`` field.
#. ``RCU_NEXT_READY_TAIL``: Callbacks waiting for the next grace period
   to start.
#. ``RCU_NEXT_TAIL``: Callbacks that have not yet been associated with a
   grace period.

The ``->head`` pointer references the first callback or is ``NULL`` if
the list contains no callbacks (which is *not* the same as being empty).
Each element of the ``->tails[]`` array references the ``->next``
pointer of the last callback in the corresponding segment of the list,
or the list's ``->head`` pointer if that segment and all previous
segments are empty. If the corresponding segment is empty but some
previous segment is not empty, then the array element is identical to
its predecessor. Older callbacks are closer to the head of the list, and
new callbacks are added at the tail. This relationship between the
``->head`` pointer, the ``->tails[]`` array, and the callbacks is shown
in this diagram:

.. kernel-figure:: nxtlist.svg

In this figure, the ``->head`` pointer references the first RCU callback
in the list. The ``->tails[RCU_DONE_TAIL]`` array element references the
``->head`` pointer itself, indicating that none of the callbacks is
ready to invoke. The ``->tails[RCU_WAIT_TAIL]`` array element references
callback CB 2's ``->next`` pointer, which indicates that CB 1 and CB 2
are both waiting on the current grace period, give or take possible
disagreements about exactly which grace period is the current one. The
``->tails[RCU_NEXT_READY_TAIL]`` array element references the same RCU
callback that ``->tails[RCU_WAIT_TAIL]`` does, which indicates that
there are no callbacks waiting on the next RCU grace period. The
``->tails[RCU_NEXT_TAIL]`` array element references CB 4's ``->next``
pointer, indicating that all the remaining RCU callbacks have not yet
been assigned to an RCU grace period. Note that the
``->tails[RCU_NEXT_TAIL]`` array element always references the last RCU
callback's ``->next`` pointer unless the callback list is empty, in
which case it references the ``->head`` pointer.

There is one additional important special case for the
``->tails[RCU_NEXT_TAIL]`` array element: It can be ``NULL`` when this
list is *disabled*. Lists are disabled when the corresponding CPU is
offline or when the corresponding CPU's callbacks are offloaded to a
kthread, both of which are described elsewhere.

CPUs advance their callbacks from the ``RCU_NEXT_TAIL`` to the
``RCU_NEXT_READY_TAIL`` to the ``RCU_WAIT_TAIL`` to the
``RCU_DONE_TAIL`` list segments as grace periods advance.

The ``->gp_seq[]`` array records grace-period numbers corresponding to
the list segments. This is what allows different CPUs to have different
ideas as to which is the current grace period while still avoiding
premature invocation of their callbacks. In particular, this allows CPUs
that go idle for extended periods to determine which of their callbacks
are ready to be invoked after reawakening.

The ``->len`` counter contains the number of callbacks in ``->head``,
and the ``->len_lazy`` contains the number of those callbacks that are
known to only free memory, and whose invocation can therefore be safely
deferred.

.. important::

   It is the ``->len`` field that determines whether or
   not there are callbacks associated with this ``rcu_segcblist``
   structure, *not* the ``->head`` pointer. The reason for this is that all
   the ready-to-invoke callbacks (that is, those in the ``RCU_DONE_TAIL``
   segment) are extracted all at once at callback-invocation time
   (``rcu_do_batch``), due to which ``->head`` may be set to NULL if there
   are no not-done callbacks remaining in the ``rcu_segcblist``. If
   callback invocation must be postponed, for example, because a
   high-priority process just woke up on this CPU, then the remaining
   callbacks are placed back on the ``RCU_DONE_TAIL`` segment and
   ``->head`` once again points to the start of the segment. In short, the
   head field can briefly be ``NULL`` even though the CPU has callbacks
   present the entire time. Therefore, it is not appropriate to test the
   ``->head`` pointer for ``NULL``.

In contrast, the ``->len`` and ``->len_lazy`` counts are adjusted only
after the corresponding callbacks have been invoked. This means that the
``->len`` count is zero only if the ``rcu_segcblist`` structure really
is devoid of callbacks. Of course, off-CPU sampling of the ``->len``
count requires careful use of appropriate synchronization, for example,
memory barriers. This synchronization can be a bit subtle, particularly
in the case of ``rcu_barrier()``.

rcu_data의 CPU 및 leaf 연결

812-854

`rcu_data`는 RCU subsystem의 per-CPU 상태입니다. 별도 언급이 없으면 해당 CPU와 tracing만 접근합니다. Quiescent-state detection, callback queue, leaf `rcu_node`를 통한 효율적 상향 보고, grace-period local copy, 과거 dyntick-idle 상태와 통계를 담당합니다.

`cpu`는 대응 CPU 번호이고 `mynode`는 대응 leaf `rcu_node` pointer입니다. Quiescent state를 결합 트리 위로 올릴 때 `mynode`를 사용합니다. 두 field는 상수라 동기화가 필요 없습니다.

`grpmask`는 이 `rcu_data`가 `mynode->qsmask`에서 차지하는 bit이며 보고 전파에 사용합니다. `beenonline`은 CPU가 한 번이라도 online이 되면 설정되므로 debugfs tracing은 한 번도 online이 아니었던 CPU의 `rcu_data`를 출력하지 않을 수 있습니다.

Per-CPU 보고 연결
CPU number in rcu_data.cpurcu_data.grpmaskleaf rcu_data.mynode->qsmaskparent rcu_node masksroot

CPU별 상태가 one-bit mask로 leaf에 합쳐지고 parent chain을 따라 root로 올라갑니다.

The ``rcu_data`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``rcu_data`` maintains the per-CPU state for the RCU subsystem. The
fields in this structure may be accessed only from the corresponding CPU
(and from tracing) unless otherwise stated. This structure is the focus
of quiescent-state detection and RCU callback queuing. It also tracks
its relationship to the corresponding leaf ``rcu_node`` structure to
allow more-efficient propagation of quiescent states up the ``rcu_node``
combining tree. Like the ``rcu_node`` structure, it provides a local
copy of the grace-period information to allow for-free synchronized
access to this information from the corresponding CPU. Finally, this
structure records past dyntick-idle state for the corresponding CPU and
also tracks statistics.

The ``rcu_data`` structure's fields are discussed, singly and in groups,
in the following sections.

Connection to Other Data Structures
'''''''''''''''''''''''''''''''''''

This portion of the ``rcu_data`` structure is declared as follows:

::

     1   int cpu;
     2   struct rcu_node *mynode;
     3   unsigned long grpmask;
     4   bool beenonline;

The ``->cpu`` field contains the number of the corresponding CPU and the
``->mynode`` field references the corresponding ``rcu_node`` structure.
The ``->mynode`` is used to propagate quiescent states up the combining
tree. These two fields are constant and therefore do not require
synchronization.

The ``->grpmask`` field indicates the bit in the ``->mynode->qsmask``
corresponding to this ``rcu_data`` structure, and is also used when
propagating quiescent states. The ``->beenonline`` flag is set whenever
the corresponding CPU comes online, which means that the debugfs tracing
need not dump out any ``rcu_data`` structure for which this flag is not
set.

rcu_data의 GP와 quiescent-state 상태

855-904

`rcu_data.gp_seq`는 `rcu_state`와 `rcu_node`의 같은 이름 field에 대응하고 `gp_seq_needed`는 node의 요청 field에 대응합니다. 일반적으로 leaf node보다 최대 한 단계 늦을 수 있습니다. `CONFIG_NO_HZ_IDLE` 또는 `CONFIG_NO_HZ_FULL`에서 dyntick-idle CPU는 임의로 오래 뒤처질 수 있지만 idle을 나올 때 따라잡습니다. 아래 두 bit가 0이면 이 CPU 관점에서 RCU는 idle입니다.

Sequence number를 전역 하나로 합치면 안전한 접근과 update를 위해 전역 lock 하나가 필요해집니다. 전역 lock을 피하려면 node별 번호를 세심하게 관리해야 합니다. 이전 GP에서 sample한 quiescent state를 다른 GP에 적용하면 심각한 lifetime 오류가 생기므로 복제와 전파 규칙이 필요합니다.

`cpu_no_qs`는 CPU가 아직 quiescent state를 지나지 않았음을, `core_needs_qs`는 RCU core가 이 CPU의 보고를 필요로 함을 표시합니다. `gpwrap`은 CPU가 너무 오래 idle해 `gp_seq` overflow 위험이 있음을 뜻하며, 다음 idle exit에서는 자기 counter 값을 신뢰하지 않고 새 상태를 받아들이게 합니다.

rcu_data GP field
field의미
gp_seqCPU가 아는 현재 GP sequence
gp_seq_neededCPU에 필요한 가장 먼 GP
cpu_no_qs아직 QS 미통과
core_needs_qsRCU core가 QS 보고 요구
gpwrap장기 idle로 counter 신뢰 폐기 필요

CPU의 local 관점과 보고 필요 여부를 분리합니다.

Quiescent-State and Grace-Period Tracking
'''''''''''''''''''''''''''''''''''''''''

This portion of the ``rcu_data`` structure is declared as follows:

::

     1   unsigned long gp_seq;
     2   unsigned long gp_seq_needed;
     3   bool cpu_no_qs;
     4   bool core_needs_qs;
     5   bool gpwrap;

The ``->gp_seq`` field is the counterpart of the field of the same name
in the ``rcu_state`` and ``rcu_node`` structures. The
``->gp_seq_needed`` field is the counterpart of the field of the same
name in the rcu_node structure. They may each lag up to one behind their
``rcu_node`` counterparts, but in ``CONFIG_NO_HZ_IDLE`` and
``CONFIG_NO_HZ_FULL`` kernels can lag arbitrarily far behind for CPUs in
dyntick-idle mode (but these counters will catch up upon exit from
dyntick-idle mode). If the lower two bits of a given ``rcu_data``
structure's ``->gp_seq`` are zero, then this ``rcu_data`` structure
believes that RCU is idle.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| All this replication of the grace period numbers can only cause       |
| massive confusion. Why not just keep a global sequence number and be  |
| done with it???                                                       |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Because if there was only a single global sequence numbers, there     |
| would need to be a single global lock to allow safely accessing and   |
| updating it. And if we are not going to have a single global lock, we |
| need to carefully manage the numbers on a per-node basis. Recall from |
| the answer to a previous Quick Quiz that the consequences of applying |
| a previously sampled quiescent state to the wrong grace period are    |
| quite severe.                                                         |
+-----------------------------------------------------------------------+

The ``->cpu_no_qs`` flag indicates that the CPU has not yet passed
through a quiescent state, while the ``->core_needs_qs`` flag indicates
that the RCU core needs a quiescent state from the corresponding CPU.
The ``->gpwrap`` field indicates that the corresponding CPU has remained
idle for so long that the ``gp_seq`` counter is in danger of overflow,
which will cause the CPU to disregard the values of its counters on its
next exit from idle.

rcu_data의 callback 처리와 통계

905-949

CPU-hotplug이 없다면 callback은 등록한 CPU가 호출하지만 이는 cache locality 최적화일 뿐 보장은 아닙니다. 등록 CPU가 callback 호출 전에 offline되면 다른 CPU가 실행해야 합니다.

`cblist`는 앞에서 설명한 segmented callback list입니다. CPU는 자기 `rcu_data.gp_seq`와 leaf `rcu_node.gp_seq`가 다른 것을 보고 GP 완료를 감지하며 callback 구간을 전진시킵니다. Node의 sequence는 각 GP 시작과 종료에 바뀝니다.

`qlen_last_fqs_check`와 `n_force_qs_snap`은 `call_rcu()` 계열 callback list가 지나치게 길 때 forced quiescent state를 요청하는 과정을 조정합니다. `n_cbs_invoked`는 호출 수, `n_cbs_orphaned`는 CPU offline 때 다른 CPU로 보낸 수, `n_cbs_adopted`는 offline된 다른 CPU에서 받은 수를 셉니다. `n_nocbs_invoked`는 callback을 kthread에 offload한 CPU에서 사용합니다. `blimit`은 한 번에 호출할 수 있는 최대 callback 수입니다.

Callback accounting
field역할
n_cbs_invoked직접 호출한 callback
n_nocbs_invokedoffload kthread가 호출
n_cbs_orphanedoffline 때 내보냄
n_cbs_adopted다른 offline CPU에서 받음
blimit한 batch의 호출 상한

Hotplug, offload와 batch 제한을 per-CPU 통계로 관찰합니다.

RCU Callback Handling
'''''''''''''''''''''

In the absence of CPU-hotplug events, RCU callbacks are invoked by the
same CPU that registered them. This is strictly a cache-locality
optimization: callbacks can and do get invoked on CPUs other than the
one that registered them. After all, if the CPU that registered a given
callback has gone offline before the callback can be invoked, there
really is no other choice.

This portion of the ``rcu_data`` structure is declared as follows:

::

    1 struct rcu_segcblist cblist;
    2 long qlen_last_fqs_check;
    3 unsigned long n_cbs_invoked;
    4 unsigned long n_nocbs_invoked;
    5 unsigned long n_cbs_orphaned;
    6 unsigned long n_cbs_adopted;
    7 unsigned long n_force_qs_snap;
    8 long blimit;

The ``->cblist`` structure is the segmented callback list described
earlier. The CPU advances the callbacks in its ``rcu_data`` structure
whenever it notices that another RCU grace period has completed. The CPU
detects the completion of an RCU grace period by noticing that the value
of its ``rcu_data`` structure's ``->gp_seq`` field differs from that of
its leaf ``rcu_node`` structure. Recall that each ``rcu_node``
structure's ``->gp_seq`` field is updated at the beginnings and ends of
each grace period.

The ``->qlen_last_fqs_check`` and ``->n_force_qs_snap`` coordinate the
forcing of quiescent states from ``call_rcu()`` and friends when
callback lists grow excessively long.

The ``->n_cbs_invoked``, ``->n_cbs_orphaned``, and ``->n_cbs_adopted``
fields count the number of callbacks invoked, sent to other CPUs when
this CPU goes offline, and received from other CPUs when those other
CPUs go offline. The ``->n_nocbs_invoked`` is used when the CPU's
callbacks are offloaded to a kthread.

Finally, the ``->blimit`` counter is the maximum number of RCU callbacks
that may be invoked at a given time.

Dyntick-idle 상태와 긴급 QS 요청

950-1041

`watching_snap`은 forced quiescent-state 처리 때 대상 CPU의 dyntick-idle 상태 snapshot을 보관하므로 다른 CPU도 접근합니다. `dynticks_fqs`는 이 CPU가 dyntick-idle이라고 판정된 횟수를 세어 tracing과 debugging에 씁니다.

`nesting`, `nmi_nesting`, atomic `dynticks`, `rcu_need_heavy_qs`, `rcu_urgent_qs`는 CPU별 dyntick-idle 상태를 유지합니다. 별도 언급이 없으면 대응 CPU만 접근합니다. `nesting`은 process execution 중첩 깊이로 보통 0 또는 1입니다. NMI, IRQ와 tracer는 `nmi_nesting`이 셉니다.

NMI는 mask할 수 없어 Andy Lutomirski의 algorithm에 따라 조심스럽게 `nmi_nesting`을 바꿉니다. Idle에서 최초 전환은 1을 더하고 중첩 전환은 2를 더하므로 실제 중첩 5는 값 9로 표현됩니다. Process-level 전환을 제외하고 CPU가 dyntick-idle에 들어갈 수 없는 이유의 수라고 볼 수 있습니다.

Kernel은 끝나지 않는 interrupt handler나 실제 진입 없이 돌아오는 듯한 misnested interrupt도 겪을 수 있습니다. 이를 복구하기 위해 `nesting`이 0에서 증가하면 `nmi_nesting`을 큰 양수로 만들고, `nesting`이 0으로 내려오면 `nmi_nesting`도 0으로 만듭니다. Counter가 overflow할 만큼 misnest가 많지 않다면 process context에서 idle loop로 들어갈 때마다 상태가 교정됩니다. 그래서 두 counter를 단순 합칠 수 없습니다.

Dyntick nesting 보정
nesting rises from 0set nmi_nesting to large positive valueinterrupt/NMI nesting changesnesting falls to 0reset nmi_nesting to 0

Process 경계에서 interrupt 중첩 추적을 보수적인 값으로 재설정합니다.

Atomic `dynticks`는 dyntick-idle 또는 user mode로 들어가고 나오는 전환을 셉니다. 짝수면 CPU가 dyntick-idle/user mode이고 홀수면 그 밖의 kernel 상태입니다. User-mode adaptive ticks를 위해 user mode 전환도 세며 자세한 내용은 `Documentation/timers/no_hz.rst`에 있습니다.

`rcu_need_heavy_qs`는 RCU core가 이 CPU의 quiescent state를 매우 원해 무거운 dyntick-counter operation까지 허용한다는 뜻입니다. Context-switch와 `cond_resched()` code가 이 flag를 보고 잠깐 idle 상태를 만듭니다. `rcu_urgent_qs`도 긴급한 QS 요구를 표시하며 다른 field가 긴급도를 구체화합니다. `rcu_note_context_switch` 경로와 cond_resched code가 검사합니다.

Dyntick 상태 판정
상태표현
dynticks evendyntick-idle 또는 user mode
dynticks oddRCU가 관찰하는 kernel 실행
rcu_need_heavy_qs무거운 QS operation 허용
rcu_urgent_qs긴급 QS 요청

Counter parity와 요청 flag가 CPU 관찰과 강제 진전을 연결합니다.

특수 목적 build에는 추가 field가 있으며 별도 문서에서 설명합니다.

Dyntick-Idle Handling
'''''''''''''''''''''

This portion of the ``rcu_data`` structure is declared as follows:

::

     1   int watching_snap;
     2   unsigned long dynticks_fqs;

The ``->watching_snap`` field is used to take a snapshot of the
corresponding CPU's dyntick-idle state when forcing quiescent states,
and is therefore accessed from other CPUs. Finally, the
``->dynticks_fqs`` field is used to count the number of times this CPU
is determined to be in dyntick-idle state, and is used for tracing and
debugging purposes.

This portion of the rcu_data structure is declared as follows:

::

     1   long nesting;
     2   long nmi_nesting;
     3   atomic_t dynticks;
     4   bool rcu_need_heavy_qs;
     5   bool rcu_urgent_qs;

These fields in the rcu_data structure maintain the per-CPU dyntick-idle
state for the corresponding CPU. The fields may be accessed only from
the corresponding CPU (and from tracing) unless otherwise stated.

The ``->nesting`` field counts the nesting depth of process
execution, so that in normal circumstances this counter has value zero
or one. NMIs, irqs, and tracers are counted by the
``->nmi_nesting`` field. Because NMIs cannot be masked, changes
to this variable have to be undertaken carefully using an algorithm
provided by Andy Lutomirski. The initial transition from idle adds one,
and nested transitions add two, so that a nesting level of five is
represented by a ``->nmi_nesting`` value of nine. This counter
can therefore be thought of as counting the number of reasons why this
CPU cannot be permitted to enter dyntick-idle mode, aside from
process-level transitions.

However, it turns out that when running in non-idle kernel context, the
Linux kernel is fully capable of entering interrupt handlers that never
exit and perhaps also vice versa. Therefore, whenever the
``->nesting`` field is incremented up from zero, the
``->nmi_nesting`` field is set to a large positive number, and
whenever the ``->nesting`` field is decremented down to zero,
the ``->nmi_nesting`` field is set to zero. Assuming that
the number of misnested interrupts is not sufficient to overflow the
counter, this approach corrects the ``->nmi_nesting`` field
every time the corresponding CPU enters the idle loop from process
context.

The ``->dynticks`` field counts the corresponding CPU's transitions to
and from either dyntick-idle or user mode, so that this counter has an
even value when the CPU is in dyntick-idle mode or user mode and an odd
value otherwise. The transitions to/from user mode need to be counted
for user mode adaptive-ticks support (see Documentation/timers/no_hz.rst).

The ``->rcu_need_heavy_qs`` field is used to record the fact that the
RCU core code would really like to see a quiescent state from the
corresponding CPU, so much so that it is willing to call for
heavy-weight dyntick-counter operations. This flag is checked by RCU's
context-switch and ``cond_resched()`` code, which provide a momentary
idle sojourn in response.

Finally, the ``->rcu_urgent_qs`` field is used to record the fact that
the RCU core code would really like to see a quiescent state from the
corresponding CPU, with the various other fields indicating just how
badly RCU wants this quiescent state. This flag is checked by RCU's
context-switch path (``rcu_note_context_switch``) and the cond_resched
code.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Why not simply combine the ``->nesting`` and                          |
| ``->nmi_nesting`` counters into a single counter that just            |
| counts the number of reasons that the corresponding CPU is non-idle?  |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| Because this would fail in the presence of interrupts whose handlers  |
| never return and of handlers that manage to return from a made-up     |
| interrupt.                                                            |
+-----------------------------------------------------------------------+

Additional fields are present for some special-purpose builds, and are
discussed separately.

rcu_head callback cookie

1042-1084

각 `rcu_head`는 RCU callback 하나를 나타내며 asynchronous grace period를 쓰는 algorithm에서는 보통 RCU-protected 자료구조 안에 삽입됩니다. 반대로 grace period를 block하며 직접 기다리는 algorithm은 사용자가 `rcu_head`를 제공하지 않아도 됩니다.

`next`는 `rcu_data` 안의 callback list에서 `rcu_head`끼리 연결합니다. `func`는 callback이 호출 가능해졌을 때 실행할 함수 pointer이며 그 함수에는 해당 `rcu_head` pointer가 전달됩니다. 단, `kfree_rcu()`는 `func` field에 enclosing object 안에서 `rcu_head`가 위치한 offset을 기록합니다.

두 field 모두 RCU 내부용이므로 사용자에게 `rcu_head`는 불투명한 cookie입니다. 일반적으로 RCU-protected 자료구조 type마다 callback 함수가 따로 있고, callback은 Linux의 `container_of()` macro로 전달받은 `rcu_head`에서 enclosing structure의 시작 주소를 찾습니다.

Callback에서 원래 객체 찾기
RCU invokes func(rcu_head *)type-specific callbackcontainer_of(head, type, member)enclosing RCU-protected object

Type별 callback이 embedding 위치를 알고 있어 container_of로 enclosing object를 복원합니다.

The ``rcu_head`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~

Each ``rcu_head`` structure represents an RCU callback. These structures
are normally embedded within RCU-protected data structures whose
algorithms use asynchronous grace periods. In contrast, when using
algorithms that block waiting for RCU grace periods, RCU users need not
provide ``rcu_head`` structures.

The ``rcu_head`` structure has fields as follows:

::

     1   struct rcu_head *next;
     2   void (*func)(struct rcu_head *head);

The ``->next`` field is used to link the ``rcu_head`` structures
together in the lists within the ``rcu_data`` structures. The ``->func``
field is a pointer to the function to be called when the callback is
ready to be invoked, and this function is passed a pointer to the
``rcu_head`` structure. However, ``kfree_rcu()`` uses the ``->func``
field to record the offset of the ``rcu_head`` structure within the
enclosing RCU-protected data structure.

Both of these fields are used internally by RCU. From the viewpoint of
RCU users, this structure is an opaque “cookie”.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| Given that the callback function ``->func`` is passed a pointer to    |
| the ``rcu_head`` structure, how is that function supposed to find the |
| beginning of the enclosing RCU-protected data structure?              |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| In actual practice, there is a separate callback function per type of |
| RCU-protected data structure. The callback function can therefore use |
| the ``container_of()`` macro in the Linux kernel (or other            |
| pointer-manipulation facilities in other software environments) to    |
| find the beginning of the enclosing structure.                        |
+-----------------------------------------------------------------------+

task_struct의 RCU 전용 field

1085-1124

`CONFIG_PREEMPT_RCU`는 `task_struct`에 추가 상태를 둡니다. `rcu_read_lock_nesting`은 RCU read-side critical section 중첩 수준을 기록하고, `rcu_read_unlock_special` bitmask는 `rcu_read_unlock()`이 추가 작업을 해야 하는 특수 조건을 기록합니다.

`rcu_node_entry`는 preemptible-RCU read section에서 block된 task list의 연결 원소입니다. `rcu_blocked_node`는 task가 들어 있는 `rcu_node`를 가리키며, block된 read section에 있지 않으면 `NULL`입니다.

`CONFIG_TASKS_RCU`의 `rcu_tasks_nvcsw`는 현재 Tasks-RCU GP가 시작될 때 이 task의 voluntary context-switch 횟수를 기록합니다. `rcu_tasks_holdout`은 현재 Tasks-RCU GP가 task를 기다리는지, `rcu_tasks_holdout_list`는 holdout list 연결 원소입니다. `rcu_tasks_idle_cpu`는 이 idle task가 현재 실제로 실행 중, 즉 해당 CPU가 idle일 때 어느 CPU에서 도는지 추적합니다.

task_struct RCU 상태
구성field
PREEMPT_RCU nestingrcu_read_lock_nesting, rcu_read_unlock_special
Blocked reader listrcu_node_entry, rcu_blocked_node
Tasks-RCU progressrcu_tasks_nvcsw, rcu_tasks_holdout
Tasks-RCU lists/idlercu_tasks_holdout_list, rcu_tasks_idle_cpu

Preemptible reader 추적과 Tasks-RCU holdout 추적은 서로 다른 field 군을 사용합니다.

RCU-Specific Fields in the ``task_struct`` Structure
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The ``CONFIG_PREEMPT_RCU`` implementation uses some additional fields in
the ``task_struct`` structure:

::

    1 #ifdef CONFIG_PREEMPT_RCU
    2   int rcu_read_lock_nesting;
    3   union rcu_special rcu_read_unlock_special;
    4   struct list_head rcu_node_entry;
    5   struct rcu_node *rcu_blocked_node;
    6 #endif /* #ifdef CONFIG_PREEMPT_RCU */
    7 #ifdef CONFIG_TASKS_RCU
    8   unsigned long rcu_tasks_nvcsw;
    9   bool rcu_tasks_holdout;
   10   struct list_head rcu_tasks_holdout_list;
   11   int rcu_tasks_idle_cpu;
   12 #endif /* #ifdef CONFIG_TASKS_RCU */

The ``->rcu_read_lock_nesting`` field records the nesting level for RCU
read-side critical sections, and the ``->rcu_read_unlock_special`` field
is a bitmask that records special conditions that require
``rcu_read_unlock()`` to do additional work. The ``->rcu_node_entry``
field is used to form lists of tasks that have blocked within
preemptible-RCU read-side critical sections and the
``->rcu_blocked_node`` field references the ``rcu_node`` structure whose
list this task is a member of, or ``NULL`` if it is not blocked within a
preemptible-RCU read-side critical section.

The ``->rcu_tasks_nvcsw`` field tracks the number of voluntary context
switches that this task had undergone at the beginning of the current
tasks-RCU grace period, ``->rcu_tasks_holdout`` is set if the current
tasks-RCU grace period is waiting on this task,
``->rcu_tasks_holdout_list`` is a list element enqueuing this task on
the holdout list, and ``->rcu_tasks_idle_cpu`` tracks which CPU this
idle task is running, but only if the task is currently running, that
is, if the CPU is currently idle.

Root와 node 순회 accessor

1125-1169

`rcu_get_root()`는 지정한 `rcu_state.node[]`의 첫 원소, 즉 root `rcu_node` pointer를 반환합니다.

`rcu_for_each_node_breadth_first()`는 `node[]`가 breadth-first 순서라는 배치를 이용해 `node[0]`부터 `node[NUM_RCU_NODES]` 직전까지 단순 선형 순회합니다. `rcu_for_each_leaf_node()`는 `level[NUM_RCU_LVLS - 1]`에서 배열 끝까지만 순회해 leaf node만 방문합니다.

트리가 node 하나뿐이면 그 node는 root이면서 leaf입니다. 따라서 `rcu_for_each_leaf_node()`는 이 단일 node를 한 번 순회합니다.

Accessor가 보는 배열 범위
rcu_get_root: &node[0]breadth_first: node[0] .. node[NUM_RCU_NODES)leaf_only: level[last] .. node[NUM_RCU_NODES)

같은 node[] 배열에서 시작 위치만 달리해 전체 BFS와 leaf-only 순회를 구현합니다.

Accessor Functions
~~~~~~~~~~~~~~~~~~

The following listing shows the ``rcu_get_root()``,
``rcu_for_each_node_breadth_first`` and ``rcu_for_each_leaf_node()``
function and macros:

::

     1 static struct rcu_node *rcu_get_root(struct rcu_state *rsp)
     2 {
     3   return &rsp->node[0];
     4 }
     5
     6 #define rcu_for_each_node_breadth_first(rsp, rnp) \
     7   for ((rnp) = &(rsp)->node[0]; \
     8        (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)
     9
    10 #define rcu_for_each_leaf_node(rsp, rnp) \
    11   for ((rnp) = (rsp)->level[NUM_RCU_LVLS - 1]; \
    12        (rnp) < &(rsp)->node[NUM_RCU_NODES]; (rnp)++)

The ``rcu_get_root()`` simply returns a pointer to the first element of
the specified ``rcu_state`` structure's ``->node[]`` array, which is the
root ``rcu_node`` structure.

As noted earlier, the ``rcu_for_each_node_breadth_first()`` macro takes
advantage of the layout of the ``rcu_node`` structures in the
``rcu_state`` structure's ``->node[]`` array, performing a breadth-first
traversal by simply traversing the array in order. Similarly, the
``rcu_for_each_leaf_node()`` macro traverses only the last part of the
array, thus traversing only the leaf ``rcu_node`` structures.

+-----------------------------------------------------------------------+
| **Quick Quiz**:                                                       |
+-----------------------------------------------------------------------+
| What does ``rcu_for_each_leaf_node()`` do if the ``rcu_node`` tree    |
| contains only a single node?                                          |
+-----------------------------------------------------------------------+
| **Answer**:                                                           |
+-----------------------------------------------------------------------+
| In the single-node case, ``rcu_for_each_leaf_node()`` traverses the   |
| single node.                                                          |
+-----------------------------------------------------------------------+

요약, 감사와 법적 고지

1170-1196

RCU 상태는 `rcu_state`가 나타내며 그 안에는 `rcu_node` 결합 트리와 per-CPU `rcu_data`가 연결됩니다. `CONFIG_NO_HZ_IDLE`에서는 각 CPU의 dyntick-idle 상태도 `rcu_data`의 dynticks 관련 field가 추적합니다. 여기까지 이해했다면 이 series의 다른 code walkthrough를 읽을 준비가 된 것입니다.

문서를 사람이 읽기 쉬운 형태로 만드는 데 도움을 준 Cyrill Gorcunov, Mathieu Desnoyers, Dhaval Giani, Paul Turner, Abhishek Srivastava, Matt Kowalczyk, Serge Hallyn에게 감사를 표합니다.

이 글은 저자의 견해이며 반드시 IBM의 견해를 나타내지는 않습니다. Linux는 Linus Torvalds의 등록 상표이고, 다른 회사·제품·서비스 이름은 각 소유자의 상표 또는 서비스표일 수 있습니다.

Summary
~~~~~~~

So the state of RCU is represented by an ``rcu_state`` structure, which
contains a combining tree of ``rcu_node`` and ``rcu_data`` structures.
Finally, in ``CONFIG_NO_HZ_IDLE`` kernels, each CPU's dyntick-idle state
is tracked by dynticks-related fields in the ``rcu_data`` structure. If
you made it this far, you are well prepared to read the code
walkthroughs in the other articles in this series.

Acknowledgments
~~~~~~~~~~~~~~~

I owe thanks to Cyrill Gorcunov, Mathieu Desnoyers, Dhaval Giani, Paul
Turner, Abhishek Srivastava, Matt Kowalczyk, and Serge Hallyn for
helping me get this document into a more human-readable state.

Legal Statement
~~~~~~~~~~~~~~~

This work represents the view of the author and does not necessarily
represent the view of IBM.

Linux is a registered trademark of Linus Torvalds.

Other company, product, and service names may be trademarks or service
marks of others.