Review Checklist for RCU Patches¶
This document contains a checklist for producing and reviewing patchesthat make use of RCU. Violating any of the rules listed below willresult in the same sorts of problems that leaving out a locking primitivewould cause. This list is based on experiences reviewing such patchesover a rather long period of time, but improvements are always welcome!
Is RCU being applied to a read-mostly situation? If the datastructure is updated more than about 10% of the time, then youshould strongly consider some other approach, unless detailedperformance measurements show that RCU is nonetheless the righttool for the job. Yes, RCU does reduce read-side overhead byincreasing write-side overhead, which is exactly why normal usesof RCU will do much more reading than updating.
Another exception is where performance is not an issue, and RCUprovides a simpler implementation. An example of this situationis the dynamic NMI code in the Linux 2.6 kernel, at least onarchitectures where NMIs are rare.
Yet another exception is where the low real-time latency of RCU’sread-side primitives is critically important.
One final exception is where RCU readers are used to preventthe ABA problem (https://en.wikipedia.org/wiki/ABA_problem)for lockless updates. This does result in the mildlycounter-intuitive situation where
rcu_read_lock()andrcu_read_unlock()are used to protect updates, however, thisapproach can provide the same simplifications to certain typesof lockless algorithms that garbage collectors do.Does the update code have proper mutual exclusion?
RCU does allowreaders to run (almost) naked, butwriters muststill use some sort of mutual exclusion, such as:
locking,
atomic operations, or
restricting updates to a single task.
If you choose #b, be prepared to describe how you have handledmemory barriers on weakly ordered machines (pretty much all ofthem -- even x86 allows later loads to be reordered to precedeearlier stores), and be prepared to explain why this addedcomplexity is worthwhile. If you choose #c, be prepared toexplain how this single task does not become a major bottleneckon large systems (for example, if the task is updating informationrelating to itself that other tasks can read, there by definitioncan be no bottleneck). Note that the definition of “large” haschanged significantly: Eight CPUs was “large” in the year 2000,but a hundred CPUs was unremarkable in 2017.
Do the RCU read-side critical sections make proper use of
rcu_read_lock()and friends? These primitives are neededto prevent grace periods from ending prematurely, whichcould result in data being unceremoniously freed out fromunder your read-side code, which can greatly increase theactuarial risk of your kernel.As a rough rule of thumb, any dereference of an RCU-protectedpointer must be covered by
rcu_read_lock(),rcu_read_lock_bh(),rcu_read_lock_sched(), or by the appropriate update-side lock.Explicit disabling of preemption (preempt_disable(), for example)can serve asrcu_read_lock_sched(), but is less readable andprevents lockdep from detecting locking issues. Acquiring araw spinlock also enters an RCU read-side critical section.The guard(rcu)() and scoped_guard(rcu) primitives designatethe remainder of the current scope or the next statement,respectively, as the RCU read-side critical section. Use ofthese guards can be less error-prone than
rcu_read_lock(),rcu_read_unlock(), and friends.Please note that youcannot rely on code known to be builtonly in non-preemptible kernels. Such code can and will break,especially in kernels built with CONFIG_PREEMPT_COUNT=y.
Letting RCU-protected pointers “leak” out of an RCU read-sidecritical section is every bit as bad as letting them leak outfrom under a lock. Unless, of course, you have arranged someother means of protection, such as a lock or a reference countbefore letting them out of the RCU read-side critical section.
Does the update code tolerate concurrent accesses?
The whole point of RCU is to permit readers to run withoutany locks or atomic operations. This means that readers willbe running while updates are in progress. There are a numberof ways to handle this concurrency, depending on the situation:
Use the RCU variants of the list and hlist updateprimitives to add, remove, and replace elements onan RCU-protected list. Alternatively, use the otherRCU-protected data structures that have been added tothe Linux kernel.
This is almost always the best approach.
Proceed as in (a) above, but also maintain per-elementlocks (that are acquired by both readers and writers)that guard per-element state. Fields that the readersrefrain from accessing can be guarded by some other lockacquired only by updaters, if desired.
This also works quite well.
Make updates appear atomic to readers. For example,pointer updates to properly aligned fields willappear atomic, as will individual atomic primitives.Sequences of operations performed under a lock willnotappear to be atomic to RCU readers, nor will sequencesof multiple atomic primitives. One alternative is tomove multiple individual fields to a separate structure,thus solving the multiple-field problem by imposing anadditional level of indirection.
This can work, but is starting to get a bit tricky.
Carefully order the updates and the reads so that readerssee valid data at all phases of the update. This is oftenmore difficult than it sounds, especially given modernCPUs’ tendency to reorder memory references. One mustusually liberally sprinkle memory-ordering operationsthrough the code, making it difficult to understand andto test. Where it works, it is better to use thingslike
smp_store_release()andsmp_load_acquire(), but insome cases thesmp_mb()full memory barrier is required.As noted earlier, it is usually better to group thechanging data into a separate structure, so that thechange may be made to appear atomic by updating a pointerto reference a new structure containing updated values.
Weakly ordered CPUs pose special challenges. Almost all CPUsare weakly ordered -- even x86 CPUs allow later loads to bereordered to precede earlier stores. RCU code must take all ofthe following measures to prevent memory-corruption problems:
Readers must maintain proper ordering of their memoryaccesses. The
rcu_dereference()primitive ensures thatthe CPU picks up the pointer before it picks up the datathat the pointer points to. This really is necessaryon Alpha CPUs.The
rcu_dereference()primitive is also an excellentdocumentation aid, letting the person reading thecode know exactly which pointers are protected by RCU.Please note that compilers can also reorder code, andthey are becoming increasingly aggressive about doingjust that. Thercu_dereference()primitive therefore alsoprevents destructive compiler optimizations. However,with a bit of devious creativity, it is possible tomishandle the return value fromrcu_dereference().Please seePROPER CARE AND FEEDING OF RETURN VALUES FROM rcu_dereference() for more information.The
rcu_dereference()primitive is used by thevarious “_rcu()” list-traversal primitives, suchas thelist_for_each_entry_rcu(). Note that it isperfectly legal (if redundant) for update-side code tousercu_dereference()and the “_rcu()” list-traversalprimitives. This is particularly useful in code thatis common to readers and updaters. However, lockdepwill complain if you accessrcu_dereference()outsideof an RCU read-side critical section. SeeRCU and lockdep checkingto learn what to do about this.Of course, neither
rcu_dereference()nor the “_rcu()”list-traversal primitives can substitute for a goodconcurrency design coordinating among multiple updaters.If the list macros are being used, the
list_add_tail_rcu()andlist_add_rcu()primitives must be used in orderto prevent weakly ordered machines from misorderingstructure initialization and pointer planting.Similarly, if the hlist macros are being used, thehlist_add_head_rcu()primitive is required.If the list macros are being used, the
list_del_rcu()primitive must be used to keeplist_del()’s pointerpoisoning from inflicting toxic effects on concurrentreaders. Similarly, if the hlist macros are being used,thehlist_del_rcu()primitive is required.The
list_replace_rcu()andhlist_replace_rcu()primitivesmay be used to replace an old structure with a new onein their respective types of RCU-protected lists.Rules similar to (4b) and (4c) apply to the “hlist_nulls”type of RCU-protected linked lists.
Updates must ensure that initialization of a givenstructure happens before pointers to that structure arepublicized. Use the
rcu_assign_pointer()primitivewhen publicizing a pointer to a structure that canbe traversed by an RCU read-side critical section.
If any of
call_rcu(),call_srcu(),call_rcu_tasks(), orcall_rcu_tasks_trace()is used, the callback function may beinvoked from softirq context, and in any case with bottom halvesdisabled. In particular, this callback function cannot block.If you need the callback to block, run that code in a workqueuehandler scheduled from the callback. Thequeue_rcu_work()function does this for you in the case ofcall_rcu().Since
synchronize_rcu()can block, it cannot be calledfrom any sort of irq context. The same rule appliesforsynchronize_srcu(),synchronize_rcu_expedited(),synchronize_srcu_expedited(),synchronize_rcu_tasks(),synchronize_rcu_tasks_rude(), andsynchronize_rcu_tasks_trace().The expedited forms of these primitives have the same semanticsas the non-expedited forms, but expediting is more CPU intensive.Use of the expedited primitives should be restricted to rareconfiguration-change operations that would not normally beundertaken while a real-time workload is running. Note thatIPI-sensitive real-time workloads can use the rcupdate.rcu_normalkernel boot parameter to completely disable expedited graceperiods, though this might have performance implications.
In particular, if you find yourself invoking one of the expeditedprimitives repeatedly in a loop, please do everyone a favor:Restructure your code so that it batches the updates, allowinga single non-expedited primitive to cover the entire batch.This will very likely be faster than the loop containing theexpedited primitive, and will be much much easier on the restof the system, especially to real-time workloads running on therest of the system. Alternatively, instead use asynchronousprimitives such as
call_rcu().As of v4.20, a given kernel implements only one RCU flavor, whichis RCU-sched for PREEMPTION=n and RCU-preempt for PREEMPTION=y.If the updater uses
call_rcu()orsynchronize_rcu(), thenthe corresponding readers may use: (1)rcu_read_lock()andrcu_read_unlock(), (2) any pair of primitives that disablesand re-enables softirq, for example,rcu_read_lock_bh()andrcu_read_unlock_bh(), or (3) any pair of primitives that disablesand re-enables preemption, for example,rcu_read_lock_sched()andrcu_read_unlock_sched(). If the updater usessynchronize_srcu()orcall_srcu(), then the corresponding readers must usesrcu_read_lock()andsrcu_read_unlock(), and with the samesrcu_struct. The rules for the expedited RCU grace-period-waitprimitives are the same as for their non-expedited counterparts.Similarly, it is necessary to correctly use the RCU Tasks flavors:
If the updater uses
synchronize_rcu_tasks()orcall_rcu_tasks(), then the readers must refrain fromexecuting voluntary context switches, that is, fromblocking.If the updater uses
call_rcu_tasks_trace()orsynchronize_rcu_tasks_trace(), then thecorresponding readers must usercu_read_lock_trace()andrcu_read_unlock_trace().If an updater uses
synchronize_rcu_tasks_rude(),then the corresponding readers must use anything thatdisables preemption, for example,preempt_disable()andpreempt_enable().
Mixing things up will result in confusion and broken kernels, andhas even resulted in an exploitable security issue. Therefore,when using non-obvious pairs of primitives, commenting isof course a must. One example of non-obvious pairing isthe XDP feature in networking, which calls BPF programs fromnetwork-driver NAPI (softirq) context. BPF relies heavily on RCUprotection for its data structures, but because the BPF programinvocation happens entirely within a single
local_bh_disable()section in a NAPI poll cycle, this usage is safe. The reasonthat this usage is safe is that readers can use anything thatdisables BH when updaters usecall_rcu()orsynchronize_rcu().Although
synchronize_rcu()is slower than iscall_rcu(),it usually results in simpler code. So, unless updateperformance is critically important, the updaters cannot block,or the latency ofsynchronize_rcu()is visible from userspace,synchronize_rcu()should be used in preference tocall_rcu().Furthermore,kfree_rcu()andkvfree_rcu()usually resultin even simpler code than doessynchronize_rcu()withoutsynchronize_rcu()’s multi-millisecond latency. So please takeadvantage ofkfree_rcu()’s andkvfree_rcu()’s “fire and forget”memory-freeing capabilities where it applies.An especially important property of the
synchronize_rcu()primitive is that it automatically self-limits: if grace periodsare delayed for whatever reason, then thesynchronize_rcu()primitive will correspondingly delay updates. In contrast,code usingcall_rcu()should explicitly limit update rate incases where grace periods are delayed, as failing to do so canresult in excessive realtime latencies or even OOM conditions.Ways of gaining this self-limiting property when using
call_rcu(),kfree_rcu(), orkvfree_rcu()include:Keeping a count of the number of data-structure elementsused by the RCU-protected data structure, includingthose waiting for a grace period to elapse. Enforce alimit on this number, stalling updates as needed to allowpreviously deferred frees to complete. Alternatively,limit only the number awaiting deferred free rather thanthe total number of elements.
One way to stall the updates is to acquire the update-sidemutex. (Don’t try this with a spinlock -- other CPUsspinning on the lock could prevent the grace periodfrom ever ending.) Another way to stall the updatesis for the updates to use a wrapper function aroundthe memory allocator, so that this wrapper functionsimulates OOM when there is too much memory awaiting anRCU grace period. There are of course many othervariations on this theme.
Limiting update rate. For example, if updates occur onlyonce per hour, then no explicit rate limiting isrequired, unless your system is already badly broken.Older versions of the dcache subsystem take this approach,guarding updates with a global lock, limiting their rate.
Trusted update -- if updates can only be done manually bysuperuser or some other trusted user, then it might notbe necessary to automatically limit them. The theoryhere is that superuser already has lots of ways to crashthe machine.
Periodically invoke
rcu_barrier(), permitting a limitednumber of updates per grace period.
The same cautions apply to
call_srcu(),call_rcu_tasks(), andcall_rcu_tasks_trace(). This is why there is ansrcu_barrier(),rcu_barrier_tasks(), andrcu_barrier_tasks_trace(), respectively.Note that although these primitives do take action to avoidmemory exhaustion when any given CPU has too many callbacks,a determined user or administrator can still exhaust memory.This is especially the case if a system with a large number ofCPUs has been configured to offload all of its RCU callbacks ontoa single CPU, or if the system has relatively little free memory.
All RCU list-traversal primitives, which include
rcu_dereference(),list_for_each_entry_rcu(), andlist_for_each_safe_rcu(), must be either within an RCU read-sidecritical section or must be protected by appropriate update-sidelocks. RCU read-side critical sections are delimited byrcu_read_lock()andrcu_read_unlock(), or by similar primitivessuch asrcu_read_lock_bh()andrcu_read_unlock_bh(), in whichcase the matchingrcu_dereference()primitive must be used inorder to keep lockdep happy, in this case,rcu_dereference_bh().The reason that it is permissible to use RCU list-traversalprimitives when the update-side lock is held is that doing socan be quite helpful in reducing code bloat when common code isshared between readers and updaters. Additional primitivesare provided for this case, as discussed inRCU and lockdep checking.
One exception to this rule is when data is only ever added tothe linked data structure, and is never removed during anytime that readers might be accessing that structure. In suchcases,
READ_ONCE()may be used in place ofrcu_dereference()and the read-side markers (rcu_read_lock()andrcu_read_unlock(),for example) may be omitted.Conversely, if you are in an RCU read-side critical section,and you don’t hold the appropriate update-side lock, youmustuse the “
_rcu()” variants of the list macros. Failing to do sowill break Alpha, cause aggressive compilers to generate bad code,and confuse people trying to understand your code.Any lock acquired by an RCU callback must be acquired elsewherewith softirq disabled, e.g., via
spin_lock_bh(). Failing todisable softirq on a given acquisition of that lock will resultin deadlock as soon as the RCU softirq handler happens to runyour RCU callback while interrupting that acquisition’s criticalsection.RCU callbacks can be and are executed in parallel. In many cases,the callback code simply wrappers around
kfree(), so that thisis not an issue (or, more accurately, to the extent that it isan issue, the memory-allocator locking handles it). However,if the callbacks do manipulate a shared data structure, theymust use whatever locking or other synchronization is requiredto safely access and/or modify that data structure.Do not assume that RCU callbacks will be executed on the sameCPU that executed the corresponding
call_rcu(),call_srcu(),call_rcu_tasks(), orcall_rcu_tasks_trace(). For example, ifa given CPU goes offline while having an RCU callback pending,then that RCU callback will execute on some surviving CPU.(If this was not the case, a self-spawning RCU callback wouldprevent the victim CPU from ever going offline.) Furthermore,CPUs designated by rcu_nocbs= might wellalways have theirRCU callbacks executed on some other CPUs, in fact, for somereal-time workloads, this is the whole point of using thercu_nocbs= kernel boot parameter.In addition, do not assume that callbacks queued in a given orderwill be invoked in that order, even if they all are queued on thesame CPU. Furthermore, do not assume that same-CPU callbacks willbe invoked serially. For example, in recent kernels, CPUs can beswitched between offloaded and de-offloaded callback invocation,and while a given CPU is undergoing such a switch, its callbacksmight be concurrently invoked by that CPU’s softirq handler andthat CPU’s rcuo kthread. At such times, that CPU’s callbacksmight be executed both concurrently and out of order.
Unlike most flavors of RCU, itis permissible to block in anSRCU read-side critical section (demarked by
srcu_read_lock()andsrcu_read_unlock()), hence the “SRCU”: “sleepable RCU”.As with RCU, guard(srcu)() and scoped_guard(srcu) forms areavailable, and often provide greater ease of use. Please notethat if you don’t need to sleep in read-side critical sections,you should be using RCU rather than SRCU, because RCU is almostalways faster and easier to use than is SRCU.Also unlike other forms of RCU, explicit initializationand cleanup is required either at build time via
DEFINE_SRCU(),DEFINE_STATIC_SRCU(),DEFINE_SRCU_FAST(),orDEFINE_STATIC_SRCU_FAST()or at runtime via eitherinit_srcu_struct()orinit_srcu_struct_fast()andcleanup_srcu_struct(). These last three are passed astructsrcu_structthat defines the scope of a givenSRCU domain. Once initialized, the srcu_struct is passedtosrcu_read_lock(),srcu_read_unlock()synchronize_srcu(),synchronize_srcu_expedited(), andcall_srcu(). A givensynchronize_srcu()waits only for SRCU read-side criticalsections governed bysrcu_read_lock()andsrcu_read_unlock()calls that have been passed the same srcu_struct. This propertyis what makes sleeping read-side critical sections tolerable --a given subsystem delays only its own updates, not those of othersubsystems using SRCU. Therefore, SRCU is less prone to OOM thesystem than RCU would be if RCU’s read-side critical sectionswere permitted to sleep.The ability to sleep in read-side critical sections does notcome for free. First, corresponding
srcu_read_lock()andsrcu_read_unlock()calls must be passed the same srcu_struct.Second, grace-period-detection overhead is amortized onlyover those updates sharing a given srcu_struct, rather thanbeing globally amortized as they are for other forms of RCU.Therefore, SRCU should be used in preference to rw_semaphoreonly in extremely read-intensive situations, or in situationsrequiring SRCU’s read-side deadlock immunity or low read-siderealtime latency. You should also consider percpu_rw_semaphorewhen you need lightweight readers.SRCU’s expedited primitive (
synchronize_srcu_expedited())never sends IPIs to other CPUs, so it is easier onreal-time workloads than issynchronize_rcu_expedited().It is also permissible to sleep in RCU Tasks Trace read-sidecritical section, which are delimited by
rcu_read_lock_trace()andrcu_read_unlock_trace(). However, this is a specializedflavor of RCU, and you should not use it without first checkingwith its current users. In most cases, you should insteaduse SRCU. As with RCU and SRCU, guard(rcu_tasks_trace)() andscoped_guard(rcu_tasks_trace) are available, and often providegreater ease of use.Note that
rcu_assign_pointer()relates to SRCU just as it does toother forms of RCU, but instead ofrcu_dereference()you shouldusesrcu_dereference()in order to avoid lockdep splats.The whole point of
call_rcu(),synchronize_rcu(), and friendsis to wait until all pre-existing readers have finished beforecarrying out some otherwise-destructive operation. It istherefore critically important tofirst remove any paththat readers can follow that could be affected by thedestructive operation, andonly then invokecall_rcu(),synchronize_rcu(), or friends.Because these primitives only wait for pre-existing readers, itis the caller’s responsibility to guarantee that any subsequentreaders will execute safely.
The various RCU read-side primitives donot necessarily containmemory barriers. You should therefore plan for the CPUand the compiler to freely reorder code into and out of RCUread-side critical sections. It is the responsibility of theRCU update-side primitives to deal with this.
For SRCU readers, you can use
smp_mb__after_srcu_read_unlock()immediately after ansrcu_read_unlock()to get a full barrier.Use CONFIG_PROVE_LOCKING, CONFIG_DEBUG_OBJECTS_RCU_HEAD, and the__rcu sparse checks to validate your RCU code. These can helpfind problems as follows:
- CONFIG_PROVE_LOCKING:
check that accesses to RCU-protected data structuresare carried out under the proper RCU read-side criticalsection, while holding the right combination of locks,or whatever other conditions are appropriate.
- CONFIG_DEBUG_OBJECTS_RCU_HEAD:
check that you don’t pass the same object to
call_rcu()(or friends) before an RCU grace period has elapsedsince the last time that you passed that same object tocall_rcu()(or friends).- CONFIG_RCU_STRICT_GRACE_PERIOD:
combine with KASAN to check for pointers leaked outof RCU read-side critical sections. This Kconfigoption is tough on both performance and scalability,and so is limited to four-CPU systems.
- __rcu sparse checks:
tag the pointer to the RCU-protected data structurewith __rcu, and sparse will warn you if you access thatpointer without the services of one of the variantsof
rcu_dereference().
These debugging aids can help you find problems that areotherwise extremely difficult to spot.
If you pass a callback function defined within a moduleto one of
call_rcu(),call_srcu(),call_rcu_tasks(), orcall_rcu_tasks_trace(), then it is necessary to wait for allpending callbacks to be invoked before unloading that module.Note that it is absolutelynot sufficient to wait for a graceperiod! For example,synchronize_rcu()implementation isnotguaranteed to wait for callbacks registered on other CPUs viacall_rcu(). Or even on the current CPU if that CPU recentlywent offline and came back online.You instead need to use one of the barrier functions:
However, these barrier functions are absolutelynot guaranteedto wait for a grace period. For example, if there are no
call_rcu()callbacks queued anywhere in the system,rcu_barrier()can and will return immediately.So if you need to wait for both a grace period and for allpre-existing callbacks, you will need to invoke both functions,with the pair depending on the flavor of RCU:
Either
synchronize_rcu()orsynchronize_rcu_expedited(),together withrcu_barrier()Either
synchronize_srcu()orsynchronize_srcu_expedited(),together with andsrcu_barrier()synchronize_tasks_trace()andrcu_barrier_tasks_trace()
If necessary, you can use something like workqueues to executethe requisite pair of functions concurrently.
SeeRCU and Unloadable Modules for more information.