270 lines · 12.3 KB · Text
RawDownload
This document provides options for those wishing to keep theirmemory-ordering lives simple, as is necessary for those whose domainis complex.  After all, there are bugs other than memory-ordering bugs,and the time spent gaining memory-ordering knowledge is not availablefor gaining domain knowledge.  Furthermore Linux-kernel memory model(LKMM) is quite complex, with subtle differences in code often havingdramatic effects on correctness. The options near the beginning of this list are quite simple.  The ideais not that kernel hackers don't already know about them, but ratherthat they might need the occasional reminder. Please note that this is a generic guide, and that specific subsystemswill often have special requirements or idioms.  For example, developersof MMIO-based device drivers will often need to use mb(), rmb(), andwmb(), and therefore might find smp_mb(), smp_rmb(), and smp_wmb()to be more natural than smp_load_acquire() and smp_store_release().On the other hand, those coming in from other environments will likelybe more familiar with these last two.  Single-threaded code==================== In single-threaded code, there is no reordering, at least assumingthat your toolchain and hardware are working correctly.  In addition,it is generally a mistake to assume your code will only run in a singlethreaded context as the kernel can enter the same code path on multipleCPUs at the same time.  One important exception is a function that makesno external data references. In the general case, you will need to take explicit steps to ensure thatyour code really is executed within a single thread that does not accessshared variables.  A simple way to achieve this is to define a global lockthat you acquire at the beginning of your code and release at the end,taking care to ensure that all references to your code's shared data arealso carried out under that same lock.  Because only one thread can holdthis lock at a given time, your code will be executed single-threaded.This approach is called "code locking". Code locking can severely limit both performance and scalability, so itshould be used with caution, and only on code paths that execute rarely.After all, a huge amount of effort was required to remove the Linuxkernel's old "Big Kernel Lock", so let's please be very careful aboutadding new "little kernel locks". One of the advantages of locking is that, in happy contrast with theyear 1981, almost all kernel developers are very familiar with locking.The Linux kernel's lockdep (CONFIG_PROVE_LOCKING=y) is very helpful withthe formerly feared deadlock scenarios. Please use the standard locking primitives provided by the kernel ratherthan rolling your own.  For one thing, the standard primitives interactproperly with lockdep.  For another thing, these primitives have beentuned to deal better with high contention.  And for one final thing, it issurprisingly hard to correctly code production-quality lock acquisitionand release functions.  After all, even simple non-production-qualitylocking functions must carefully prevent both the CPU and the compilerfrom moving code in either direction across the locking function. Despite the scalability limitations of single-threaded code, RCUtakes this approach for much of its grace-period processing and alsofor early-boot operation.  The reason RCU is able to scale despitesingle-threaded grace-period processing is use of batching, where allupdates that accumulated during one grace period are handled by thenext one.  In other words, slowing down grace-period processing makesit more efficient.  Nor is RCU unique:  Similar batching optimizationsare used in many I/O operations.  Packaged code============= Even if performance and scalability concerns prevent your code frombeing completely single-threaded, it is often possible to use libraryfunctions that handle the concurrency nearly or entirely on their own.This approach delegates any LKMM worries to the library maintainer. In the kernel, what is the "library"?  Quite a bit.  It includes thecontents of the lib/ directory, much of the include/linux/ directory alongwith a lot of other heavily used APIs.  But heavily used examples includethe list macros (for example, include/linux/{,rcu}list.h), workqueues,smp_call_function(), and the various hash tables and search trees.  Data locking============ With code locking, we use single-threaded code execution to guaranteeserialized access to the data that the code is accessing.  However,we can also achieve this by instead associating the lock with specificinstances of the data structures.  This creates a "critical section"in the code execution that will execute as though it is single threaded.By placing all the accesses and modifications to a shared data structureinside a critical section, we ensure that the execution context thatholds the lock has exclusive access to the shared data. The poster boy for this approach is the hash table, where placing a lockin each hash bucket allows operations on different buckets to proceedconcurrently.  This works because the buckets do not overlap with eachother, so that an operation on one bucket does not interfere with anyother bucket. As the number of buckets increases, data locking scales naturally.In particular, if the amount of data increases with the number of CPUs,increasing the number of buckets as the number of CPUs increase resultsin a naturally scalable data structure.  Per-CPU processing================== Partitioning processing and data over CPUs allows each CPU to takea single-threaded approach while providing excellent performance andscalability.  Of course, there is no free lunch:  The dark side of thisexcellence is substantially increased memory footprint. In addition, it is sometimes necessary to occasionally update some globalview of this processing and data, in which case something like lockingmust be used to protect this global view.  This is the approach takenby the percpu_counter infrastructure. In many cases, there are alreadygeneric/library variants of commonly used per-cpu constructs available.Please use them rather than rolling your own. RCU uses DEFINE_PER_CPU*() declaration to create a number of per-CPUdata sets.  For example, each CPU does private quiescent-state processingwithin its instance of the per-CPU rcu_data structure, and then uses datalocking to report quiescent states up the grace-period combining tree.  Packaged primitives: Sequence locking===================================== Lockless programming is considered by many to be more difficult thanlock-based programming, but there are a few lockless design patterns thathave been built out into an API.  One of these APIs is sequence locking.Although this API can be used in extremely complex ways, there are simpleand effective ways of using it that avoid the need to pay attention tomemory ordering. The basic keep-things-simple rule for sequence locking is "do not writein read-side code".  Yes, you can do writes from within sequence-lockingreaders, but it won't be so simple.  For example, such writes will belockless and should be idempotent. For more sophisticated use cases, LKMM can guide you, including usecases involving combining sequence locking with other synchronizationprimitives.  (LKMM does not yet know about sequence locking, so it iscurrently necessary to open-code it in your litmus tests.) Additional information may be found in include/linux/seqlock.h. Packaged primitives: RCU======================== Another lockless design pattern that has been baked into an APIis RCU.  The Linux kernel makes sophisticated use of RCU, but thekeep-things-simple rules for RCU are "do not write in read-side code"and "do not update anything that is visible to and accessed by readers",and "protect updates with locking". These rules are illustrated by the functions foo_update_a() andfoo_get_a() shown in Documentation/RCU/whatisRCU.rst.  AdditionalRCU usage patterns maybe found in Documentation/RCU and in thesource code.  Packaged primitives: Atomic operations====================================== Back in the day, the Linux kernel had three types of atomic operations: 1.	Initialization and read-out, such as atomic_set() and atomic_read(). 2.	Operations that did not return a value and provided no ordering,	such as atomic_inc() and atomic_dec(). 3.	Operations that returned a value and provided full ordering, such as	atomic_add_return() and atomic_dec_and_test().  Note that some	value-returning operations provide full ordering only conditionally.	For example, cmpxchg() provides ordering only upon success. More recent kernels have operations that return a value but do notprovide full ordering.  These are flagged with either a _relaxed()suffix (providing no ordering), or an _acquire() or _release() suffix(providing limited ordering). Additional information may be found in these files: Documentation/atomic_t.txtDocumentation/atomic_bitops.txtDocumentation/core-api/refcount-vs-atomic.rst Reading code using these primitives is often also quite helpful.  Lockless, fully ordered======================= When using locking, there often comes a time when it is necessaryto access some variable or another without holding the data lockthat serializes access to that variable. If you want to keep things simple, use the initialization and read-outoperations from the previous section only when there are no racingaccesses.  Otherwise, use only fully ordered operations when accessingor modifying the variable.  This approach guarantees that code priorto a given access to that variable will be seen by all CPUs as havinghappened before any code following any later access to that same variable. Please note that per-CPU functions are not atomic operations andhence they do not provide any ordering guarantees at all. If the lockless accesses are frequently executed reads that are usedonly for heuristics, or if they are frequently executed writes thatare used only for statistics, please see the next section.  Lockless statistics and heuristics================================== Unordered primitives such as atomic_read(), atomic_set(), READ_ONCE(), andWRITE_ONCE() can safely be used in some cases.  These primitives provideno ordering, but they do prevent the compiler from carrying out a numberof destructive optimizations (for which please see the next section).One example use for these primitives is statistics, such as per-CPUcounters exemplified by the rt_cache_stat structure's routing-cachestatistics counters.  Another example use case is heuristics, such asthe jiffies_till_first_fqs and jiffies_till_next_fqs kernel parameterscontrolling how often RCU scans for idle CPUs. But be careful.  "Unordered" really does mean "unordered".  It is alltoo easy to assume ordering, and this assumption must be avoided whenusing these primitives.  Don't let the compiler trip you up================================== It can be quite tempting to use plain C-language accesses for locklessloads from and stores to shared variables.  Although this is bothpossible and quite common in the Linux kernel, it does require asurprising amount of analysis, care, and knowledge about the compiler.Yes, some decades ago it was not unfair to consider a C compiler to bean assembler with added syntax and better portability, but the advent ofsophisticated optimizing compilers mean that those days are long gone.Today's optimizing compilers can profoundly rewrite your code during thetranslation process, and have long been ready, willing, and able to do so. Therefore, if you really need to use C-language assignments instead ofREAD_ONCE(), WRITE_ONCE(), and so on, you will need to have a very goodunderstanding of both the C standard and your compiler.  Here are someintroductory references and some tooling to start you on this noble quest: Who's afraid of a big bad optimizing compiler?	https://lwn.net/Articles/793253/Calibrating your fear of big bad optimizing compilers	https://lwn.net/Articles/799218/Concurrency bugs should fear the big bad data-race detector (part 1)	https://lwn.net/Articles/816850/Concurrency bugs should fear the big bad data-race detector (part 2)	https://lwn.net/Articles/816854/  More complex use cases====================== If the alternatives above do not do what you need, please look at therecipes.txt file to peel off the next layer of the memory-orderingonion.