Kernel Synchronization – Part 2
local graph
Chapter 13 — Kernel Synchronization – Part 2
Section titled “Chapter 13 — Kernel Synchronization – Part 2”This chapter continues the discussion on the fairly complex topics of kernel synchronization and dealing with concurrency within the kernel in general, from the previous chapter. I suggest that, if you haven’t already, you first read the previous chapter and then continue with this one.
Here, we shall continue our learning with respect to the vast topic of kernel synchronization and handling concurrency when in kernel space. As before, the material is targeted at kernel and/or device driver/module developers. In this chapter, we shall cover the following:
- Using the
atomic_tandrefcount_tinterfaces - Using the RMW atomic operators
- Using the reader-writer spinlock
- Understanding CPU caching basics, cache effects, and false sharing
- Lock-free programming with per-CPU and RCU
- Lock debugging within the kernel
- Introducing memory barriers
Technical requirements
Section titled “Technical requirements”The technical requirements remain identical to those for the previous chapter, Chapter 12, Kernel Synchronization – Part 1.
Using the atomic_t and refcount_t interfaces
Section titled “Using the atomic_t and refcount_t interfaces”You’ll recall that in our original simple misc character device driver program’s (available in the Linux Kernel Programming – Part 2 companion volume, in the code here: https://github.com/PacktPublishing/Linux-Kernel-Programming-Part-2/blob/main/ch1/miscdrv_rdwr/miscdrv_rdwr.c) open method (and elsewhere), we defined and manipulated two static global integers, ga and gb:
static int ga, gb = 1;[...]ga++; gb--;By now, it should be obvious to you that the place where we operate on these integers is a potential bug if left as it is: it’s shared writable data (aka shared state) being accessed in a possibly concurrent code path and, therefore, qualifies as a critical section, thus requiring protection against concurrent access. (If this isn’t clear to you, please first read the Critical sections, exclusive execution, and atomicity section in the previous chapter carefully.)
In the previous chapter, Kernel Synchronization – Part 1, to fix the issue, in our ch12/1_miscdrv_rdwr_mutexlock/1_miscdrv_rdwr_mutexlock.c program, we first used a mutex lock to protect the critical section. Later, you learned that using a spinlock to protect non-blocking critical sections such as this one would be (far) superior to using a mutex in terms of performance; so in our next driver, ch12/2_miscdrv_rdwr_spinlock/2_miscdrv_rdwr_spinlock.c, we used a spinlock to protect the critical section instead (here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/05c6b2853ef053ad22621983f17d4f326c4de97f/ch12/2_miscdrv_rdwr_spinlock/miscdrv_rdwr_spinlock.c#L111):
spin_lock(&lock1);ga++; gb--;spin_unlock(&lock1);That’s good, but we can do better still! Operating upon global integers turns out to be such a common occurrence within the kernel (think of reference or resource counters getting incremented and decremented, and so on) that it provides a class of operators, called the refcount and atomic integer operators or interfaces; these are very specifically designed to atomically – safely and indivisibly – operate on only integers.
The newer refcount_t versus older atomic_t interfaces
Section titled “The newer refcount_t versus older atomic_t interfaces”Before we start this topic, it’s important to mention this: until version 4.10 (inclusive), a set of interfaces to operate atomically upon integers existed; they were called the atomic_t interfaces. Since the 4.11 kernel, there has been a newer and better set of interfaces christened the refcount_t APIs, designed for manipulating a kernel-space object’s reference counters. This newer set greatly improves the security posture of the kernel – via much-improved Integer Overflow (IoF) and Use After Free (UAF) protection as well as memory ordering guarantees, which the older atomic_t APIs lack. The refcount_t interfaces, like several other security technologies used on Linux, have their origins in work done by the PaX Team – https://pax.grsecurity.net/ (also called PAX_REFCOUNT).
Having said that, the reality is that (at the time of writing) the older atomic_t interfaces are still very much in use within the kernel core and drivers (they are slowly being converted, with the older atomic_t interfaces being moved to the newer refcount_t model and the API set). Thus, in this topic, we cover both, pointing out differences and mentioning which refcount_t API supersedes an atomic_t API wherever applicable. Think of the refcount_t interfaces as a variant of the (older) atomic_t interfaces, which are specialized toward reference counting.
A key difference between the older atomic_t operators and the newer refcount_t ones is that the former works upon signed integers and can be used for any type of counting, whereas the latter is designed to work for object reference counting only and has a strict valid range.
More details on the newer refcount_t follow:
- It works only within a strictly specified range:
1toINT_MAX-1, that is, [1.. 2,147,483,646].
From include/linux/refcount.h:
[ ... ] * INT_MAX REFCOUNT_SATURATED UINT_MAX * 0 (0x7fff_ffff) (0xc000_0000) (0xffff_ffff) * +--------------+----------------+----------------+ * <---------- bad value! -----------> * * (in a signed view of the world, the "bad value" range corresponds to * a negative counter value). [ ... ]- To quote the official kernel documentation: “The counter saturates at REFCOUNT_SATURATED and will not move once there. This avoids wrapping the counter and causing ‘spurious’ use-after-free bugs. [ … ]”
Attempting to set a refcount_t variable to 0 or negative, or to INT_MAX or above, is impossible; this is just what the doctor ordered to help prevent and/or catch integer underflow/overflow issues and thus prevent the UAF class bug in many cases! (This is because an object must only be freed when its reference count hits zero; so the last holder will have it at reference count 1 and will free it. If the reference count is ever out of the valid range, it’s a likely use-after-free case, and the noisy warning emitted to the kernel log alerts us to this possibility.) Well, it’s not impossible to under/overflow a reference counter; it’s just that it now results in a (noisy) warning being fired via a REFCOUNT_WARN() – which translates to the WARN_ONCE() macro – and the developer is expected to notice and thus fix (or at least report) the issue. (Of course, the naming WARN_ONCE() supplies a hint: the particular warning will be emitted exactly once during the system’s lifetime).
Again, refcount_t variables are meant to be used only for kernel object reference counting, and nothing else. Thus, this is indeed the required behavior; the reference counter must start at a positive value (typically 1 when the object is newly instantiated), is incremented (or added to) whenever code “gets” or takes a reference to it, and is decremented (or subtracted from) whenever code “puts” or drops a reference on the object in question. You are expected to carefully manipulate the reference counter (matching your “gets” and “puts”), always keeping its value within the legal range.
But you’re perhaps wondering, how do I use these exotic interfaces? The following sections cover just this.
The simpler atomic_t and refcount_t interfaces
Section titled “The simpler atomic_t and refcount_t interfaces”Regarding the atomic_t interfaces, firstly, understand that all the following atomic_t constructs are for 32-bit integers only; of course, with 64-bit integers now being commonplace, 64-bit atomic integer operators are available as well (we cover them in the upcoming 64-bit atomic integer operators section).
Typically, they are semantically identical to their 32-bit counterparts, with the difference being in the name (atomic_foo() becomes atomic64_foo()). So the primary data type for 64-bit atomic integers is called atomic64_t (AKA atomic_long_t). The newer refcount_t interfaces, on the other hand, cater to both 32- and 64-bit integers.
Next, it’s key to realize that all accesses to the atomic_t or refcount_t variable in question must be made only via these accessor “methods” or helpers. For example, to even read the content of an atomic_t variable, you must use the atomic_read() helper method and not simply read it in the usual way. Similarly, to set an atomic integer v to the value i, you must use (something like) atomic_set(&v, i); and not simply v = i (likewise for all refcount_t operations).
The complete set of all the atomic_t and refcount_t interfaces available within the kernel is large; to help keep things simple and clear in this section, we list only some of the more commonly used atomic (32-bit) and refcount_t interfaces in the following table (they operate upon generic atomic_t v and refcount_t v variables, respectively):
| Operation | Older (<= 4.10 kernel) 32-bit atomic_t interface | Newer (>= 4.11; 32- and 64-bit) refcount_t interface Range: [1.. INT_MAX-1] |
|---|---|---|
| Header file to include | <linux/atomic.h> | <linux/refcount.h> |
Declare and initialize a variable v to 1 | static atomic_t v = ATOMIC_INIT(1); | static refcount_t v = REFCOUNT_INIT(1); |
Atomically read the current value of v | int atomic_read(atomic_t *v) | unsigned int refcount_read(const refcount_t *v) |
Atomically set v to the value i | void atomic_set(atomic_t *v, int i) | void refcount_set(refcount_t *v, int i) |
Atomically increment the v value by 1 | void atomic_inc(atomic_t *v) | void refcount_inc(refcount_t *v) |
Atomically decrement the v value by 1 | void atomic_dec(atomic_t *v) | void refcount_dec(refcount_t *v) |
Atomically add the value of i to v | void atomic_add(int i, atomic_t *v) | void refcount_add(int i, refcount_t *v) |
Atomically subtract the value of i from v | void atomic_sub(int i, atomic_t *v) | void refcount_sub(int i, refcount_t *v) |
Atomically add the value of i to v and return the result | int atomic_add_return(int i, atomic_t *v) | bool refcount_add_not_zero(int i, refcount_t *v) (Not a precise match; adds i to v unless it’s 0) |
Atomically subtract the value of i from v and return the result | int atomic_sub_return(int i, atomic_t *v) | bool refcount_sub_and_test(int i, refcount_t *r) (Not a precise match; subtracts i from v and tests; returns true if resulting refcount is 0, else false) |
Table 13.1: The older atomic_t (the second column) versus the newer refcount_t (the third column) interfaces for common reference counting operations
You’ve now seen several atomic_t and refcount_t functions; let’s quickly check out a few examples of their usage in the kernel.
Examples of using refcount_t within the kernel codebase
Section titled “Examples of using refcount_t within the kernel codebase”Again, in the Linux Kernel Programming – Part 2 companion volume, within one of our demo kernel modules regarding kernel threads (the code’s here: https://github.com/PacktPublishing/Linux-Kernel-Programming-Part-2/blob/main/ch5/kthread_simple/kthread_simple.c), we created a kernel thread and then employed the get_task_struct() inline function to mark the kernel thread’s task structure as in use. As you can now guess, the get_task_struct() routine works internally by incrementing the task structure’s reference counter – a refcount_t variable named usage – via the refcount_inc() function:
static inline struct task_struct *get_task_struct(struct task_struct *t){ refcount_inc(&t->usage); return t;}The converse routine, put_task_struct(), performs the subsequent decrement on the task structure’s reference counter. The actual routine employed by it internally, refcount_dec_and_test(), tests whether the new refcount value has dropped to 0; if so, it returns true, and if this is the case, it implies that the task structure isn’t being referenced by anyone. Then, the call to [__]put_task_struct() frees it up:
static inline void put_task_struct(struct task_struct *t){ if (refcount_dec_and_test(&t->usage)) __put_task_struct(t);}Another example of the refcounting methods in use within the kernel is found in kernel/user.c (which helps track the number of processes, files, and so on that a user has claimed via a per-user structure).
The following screenshot (Figure 13.1) shows us grepping this source file for lines containing the (case-insensitive) string refcount; thus, here, we can see how the code performs the initialization, increment/decrement, and setting of some refcount_t variables:

Figure 13.1: Screenshot showing the usage of the refcount_t interfaces in kernel/user.c
Look up the refcount_t API interface official kernel documentation here: https://www.kernel.org/doc/html/latest/driver-api/basics.html#reference-counting. FYI, the refcount_dec_and_lock_irqsave() function seen (in Figure 13.1), has a spinlock as it’s second parameter. If able to decrement the reference counter to 0, it returns true while holding the spinlock (with interrupts disabled), or false otherwise.
Exercise
Modify our earlier ch12/2_miscdrv_rdwr_spinlock/miscdrv_rdwr_spinlock.c driver code; it has the integers ga and gb, which, when being read or written, are protected via a spinlock. Now, make them refcount variables (initializing them to some value – say, 42), and use the appropriate refcount_t methods when working on them. Include a test case where you deliberately make them go outside the valid allowed range ([1..INT_MAX-1]).
You’ll find a reference solution in the GitHub repo within solutions_to_assgn/ch13
Careful! Don’t allow their values to go out of the (default) allowed range, [1..INT_MAX-1]! If you do, that is, you underflow or overflow it, this will typically trigger a kernel-level warning (via a REFCOUNT_WARN(), which translates to the WARN_ONCE() macro).
Deliberately causing an underflow or overflow with refcount variables
Section titled “Deliberately causing an underflow or overflow with refcount variables”It’s useful at times to play devil’s advocate; what if a module (or the kernel) does cause a refcount_t variable to go out of range? As mentioned, this will have the kernel generate a noisy one-time warning to the kernel log. But, of course, let’s be empirical and try it out!
So here’s a code snippet (from a solution to the aforementioned exercise):
…static refcount_t ga = REFCOUNT_INIT(42); /* ga will be init to 42 */static refcount_t gb = REFCOUNT_INIT(42); /* gb will be init to 42 */…static int open_miscdrv_rdwr(struct inode *inode, struct file *filp){… /* Tweaked the code here to _deliberately_ cause overflow/underflow * refcount bugs (resp) if the #if 1 is changed to #if 0 */#if 1 refcount_inc(&ga);#else //refcount_add((int i, atomic_t *v); // adds i to v // Here we deliberately overflow it, leading to a warning (once)! pr_debug("*** Bad case! About to overflow refcount var! ***\n"); refcount_add(INT_MAX, &ga);#endif...If we change the #if 1 to #if 0, then the deliberate bug will surface; clearly, we overflow the reference counter by adding INT_MAX to whatever value’s already within it! Imagine we do so, and then build (in debug mode), load, and test this module.
Here’s a partial screenshot showing the one-time warning that the kernel’s reference counting code emits:

Figure 13.2: Partial screenshot showing the one-time warning emitted by the kernel reference counting code when we overflow the counter
You can see the WARNING: … line highlighted in Figure 13.2; lower in the kernel log we then see the following (not seen in the figure):
…[ 142.155685] ---[ end trace 0000000000000000 ]---[ 142.155687] misc llkd_miscdrv_rdwr_refcount: filename: "llkd_miscdrv_rdwr_refcount" wrt open file: f_flags = 0x8241 ga = -1073741824(0xc0000000), gb = 41(0x29)[ 142.155690] misc llkd_miscdrv_rdwr_refcount: stats: tx=0, rx=0(The code for this demo seen in Figure 13.2 isn’t included in our GitHub repository.) Look at the value of the refcount variable ga now; it’s 0xc0000000, which is the value REFCOUNT_SATURATED, as expected.
The modern kernel has several useful test infrastructures; one is called the Linux Kernel Dump Test Module (LKDTM); see drivers/misc/lkdtm/refcount.c for many test cases being run on the refcount interfaces, which you can learn from. FYI, you can also use LKDTM via the kernel’s fault injection framework to test and evaluate the kernel’s reaction to faulty scenarios (see the documentation here: Provoking crashes with Linux Kernel Dump Test Module (LKDTM) – https://www.kernel.org/doc/html/latest/fault-injection/provoke-crashes.html#provoking-crashes-with-linux-kernel-dump-test-module-lkdtm.
Right, let’s move on. The atomic interfaces we’ve mentioned so far (Table 13.1) all operate on 32-bit integers; what about on 64-bit? That’s what follows.
64-bit atomic integer operators
Section titled “64-bit atomic integer operators”As mentioned at the start of this topic, the set of atomic_t integer operators we have seen so far all operate on traditional 32-bit integers (note: this discussion doesn’t apply to the newer refcount_t interfaces; they transparently operate upon both 32- and 64-bit quantities). Obviously, with 64-bit systems becoming the norm rather than the exception nowadays, the kernel community provides an identical set of atomic integer operators for 64-bit integers. The difference is as follows:
- Declare the 64-bit atomic integer as a variable of type
atomic64_t(that is,atomic_long_t). - For all operators, in place of the
atomic_prefix, use theatomic64_prefix.
So, take the following examples:
- In place of
ATOMIC_INIT(), useATOMIC64_INIT(). - In place of
atomic_read(), useatomic64_read(). - In place of
atomic_dec_if_positive(), useatomic64_dec_if_positive().
Recent C and C++ language standards – C11 and C++11 – provide an atomic operations library that helps developers implement atomicity more easily due to the implicit language support; we won’t delve into this aspect here. A reference can be found here (C11 also has pretty much the same equivalents): https://en.cppreference.com/w/c/atomic.
Note that all these routines – both the 32- and 64-bit atomic[64]_* operators – are arch-independent. A key point worth repeating is that any operations performed upon an atomic integer must be done by declaring the variable as atomic[64]_t and only via the methods provided (including initialization and even an (integer) read operation).
A note on internal implementation
Section titled “A note on internal implementation”In terms of internal implementation, a foo() atomic integer operator is typically a macro that becomes an inline function, which in turn invokes the arch-specific arch_foo() function. (For example, the x86 employs the well-known LOCK assembly prefix as part of the internal implementation, while ARM families tend to use a more generic approach with memory ordering semantics.)
The x86 LOCK prefix isn’t an instruction; it’s a prefix to an instruction (for example, lock orb %b1,%0). It guarantees that the core the instruction following LOCK is running on, has exclusive ownership of the cache line being operated upon; also, the control unit won’t allow hardware interrupts – as it’s a single machine-level instruction executing – plus there are memory ordering guarantees.
As usual, glancing through the official kernel documentation on atomic operators is always a good idea (within the kernel source tree, which can be found here: Documentation/atomic_t.txt, or here: https://www.kernel.org/doc/Documentation/atomic_t.txt). It neatly categorizes the numerous atomic integer APIs into distinct sets. FYI, arch-specific memory ordering issues do affect the internal implementation (a quick note on this follows). If interested, refer to this page on the official kernel documentation site at https://www.kernel.org/doc/html/latest/core-api/refcount-vs-atomic.html#refcount-t-api-compared-to-atomic-t.
Quite non-intuitively, at least for the generic arch-independent refcount implementation, the refcount_t APIs are internally implemented over the (older) atomic_t API set. For example, the refcount_set() API – which atomically sets a refcount variable’s value to the parameter passed – is implemented like this within the kernel:
/** * refcount_set - set a refcount's value * @r: the refcount * @n: value to which the refcount will be set */static inline void refcount_set(refcount_t *r, unsigned int n){ atomic_set(&r->refs, n);}We can see that it’s simply a thin wrapper over atomic_set(). The obvious FAQ here is: then why use the refcount API at all? There are a few reasons:
- Unlike the atomic operators, the counter saturates at the
REFCOUNT_SATURATEDvalue (which is set toINT_MIN/2by default, which is0xc0000000) and will not budge once there. This is critical: it avoids wrapping the counter, which could cause weird and spurious UAF bugs; this is even considered as a key security fix (https://kernsec.org/wiki/index.php/Kernel_Protections/refcount_t). - Several of the newer APIs do provide memory ordering guarantees; in particular, the
refcount_tAPIs – as compared to their olderatomic_tcousins – and the memory ordering guarantees they provide are documented at https://www.kernel.org/doc/html/latest/core-api/refcount-vs-atomic.html#refcount-t-api-compared-to-atomic-t (do have a look if you’re interested in the low-level details). - Also, realize that arch-dependent
refcountimplementations (when they exist – for example, x86 does have them, while ARM doesn’t) can differ from the previously mentioned generic one.
What exactly is memory ordering and how does it affect us? The fact is, it’s a complex topic, and unfortunately, the intricate details of this are beyond the scope of this book. It’s worth knowing the basics: I suggest you read up on the Linux-Kernel Memory Model (LKMM), which includes coverage on processor memory ordering and more. We refer you to good documentation on this here: Explanation of the Linux-Kernel Memory Model (https://github.com/torvalds/linux/blob/master/tools/memory-model/Documentation/explanation.txt).
We haven’t attempted to show all the atomic and refcount APIs here (it’s not necessary). The following are references from the official kernel documentation on atomic_t and refcount_t; browse through if interested:
atomic_tinterfaces:- Semantics and Behavior of Atomic and Bitmask Operations (https://www.kernel.org/doc/html/v6.1/core-api/local_ops.html)
- API ref: Atomics (https://www.kernel.org/doc/html/latest/driver-api/basics.html#atomics)
- Semantics and Behavior of Atomic and Bitmask Operations (https://www.kernel.org/doc/html/v6.1/core-api/local_ops.html)
- (Newer 4.11+)
refcount_tinterfaces for kernel object reference counting:- refcount_t API compared to atomic_t (https://www.kernel.org/doc/html/latest/core-api/refcount-vs-atomic.html#refcount-t-api-compared-to-atomic-t)
- API reference: Reference counting (https://www.kernel.org/doc/html/latest/driver-api/basics.html#reference-counting)
- refcount_t API compared to atomic_t (https://www.kernel.org/doc/html/latest/core-api/refcount-vs-atomic.html#refcount-t-api-compared-to-atomic-t)
Let’s move on to the usage of a typical construct when working on device drivers – Read-Modify-Write (RMW). Read on!
Using the RMW atomic operators
Section titled “Using the RMW atomic operators”A more advanced set of atomic operators called the RMW APIs is available as well. (Why exactly it’s called RMW and more is explained in the following section.) Among its many uses (we show a list in the upcoming section) is that of performing atomic RMW bitwise operations (safely and indivisibly). As a device driver author operating upon device or peripheral registers, this is indeed something you will very likely find yourself using.
The material in this section assumes you have at least a basic understanding of accessing peripheral device (chip) memory and registers; we have covered this topic in detail in the Linux Kernel Programming – Part 2 companion volume in Chapter 3, Working with Hardware I/O Memory. It’s recommended you first understand this before moving further.
When working with drivers, you’ll typically need to perform bit operations (with the bitwise AND & and bitwise OR | being the most commonplace operators) on registers; this is done to modify its value, setting and/or clearing some bits within it. The thing is, merely performing some C manipulation to query or set device registers isn’t quite enough. No, sir: don’t forget about concurrency issues! Read on for the full story.
RMW atomic operations – operating on device registers
Section titled “RMW atomic operations – operating on device registers”Let’s quickly go over some basics first (please control your eye rolling): a byte consists of 8 bits, numbered from bit 0, the Least Significant Bit (LSB), to bit 7, the Most Significant Bit (MSB). (This is formally defined as the BITS_PER_BYTE macro in include/linux/bits.h, along with a few other interesting definitions.)
Here, by the term register, we refer to a small piece of memory within a peripheral device (or chip); typically, its size, the register bit width, is one of 8, 16, or 32 bits. (Here, as is the case for driver authors, we refer to peripheral chip – not CPU – registers. These discussions, though, equally apply to CPU registers with even a 64-bit width, as we’ll point out.) These device registers provide control, status, and other information and are often programmable. This, in fact, is largely what you as a driver author will do – program the device registers appropriately to make the device do something, and query it.
To flesh out this discussion, let’s consider a hypothetical device that has two registers: a status register and a control register, each 8 bits wide. (In the real world, every device or chip has (at least it should have) a datasheet that will provide a detailed specification of the chip and register-level hardware; this becomes an essential document for the driver author.) Hardware folks usually design devices in such a way that several registers are sequentially clubbed together in a larger piece of memory; this is sometimes called register banking. By having the base address of the first register and the offset to each following one, it becomes easy to address any given register (here, we won’t delve into how exactly registers are “mapped” into the virtual address space on an OS such as Linux; this is part of the coverage in the Linux kernel Programming – Part 2 book). For example, the (purely hypothetical) registers for our purely hypothetical device may be described like this within a header file:
#define REG_BASE 0x5a00#define STATUS_REG (REG_BASE+0x0)#define CTRL_REG (REG_BASE+0x1)Now, say that in order to turn on some feature in our fictional device, the datasheet informs us we can do so by setting bit 7 (the MSB) of the control register to 1. As every driver author quickly learns, there is a hallowed sequence for modifying registers, as shown below:
- Read the register’s current value into a temporary variable.
- Modify the temporary variable to the desired value.
- Write back the temporary variable to the register.
This is often called the RMW – Read-Modify-Write – sequence. So great, we write the (pseudo) code like this:
turn_on_feature_x_dev(){ u8 tmp; tmp = ioread8(CTRL_REG); /* read: the current register value into tmp */ tmp |= 0x80; /* modify: set bit 7 (MSB) of tmp */ iowrite8(tmp, CTRL_REG); /* write: the new tmp value into the register */}(FYI, the actual routines used on Linux MMIO – memory-mapped I/O – to perform I/O are ioread[8|16|32]() and iowrite[8|16|32]().)
A key point here: this isn’t good enough; the reason is concurrency and data races! Think about it: a register (both CPU and device registers) is in fact a global shared writable memory location; if the code path where it’s accessed can run concurrently – and this is usually the case – then it constitutes a critical section, which you have to take care to protect from concurrent access! The how is easy; we could just use a spinlock (for now at least). It’s trivial to modify the preceding pseudocode to insert the spin_[un]lock() APIs in the critical section – the RMW sequence.
However, there is an even better way to achieve data safety when dealing with small quantities such as integers; we have already covered it: atomic operators! Linux, however, goes further, providing a set of atomic APIs for both of the following:
- Atomic non-RMW operations (the ones we saw earlier, in the Using the atomic_t and refcount_t interfaces section).
- Atomic RMW operations: These include several types of operators that can be categorized into a few distinct classes: arithmetic, bitwise, swap (exchange), reference counting, miscellaneous, and barriers.
Let’s not reinvent the wheel; the kernel documentation (https://www.kernel.org/doc/html/v6.1/core-api/wrappers/atomic_t.html) has all the information required. We’ll show just a relevant portion of this document as follows, quoting directly from there:
[ ... ]Non-RMW ops: atomic_read(), atomic_set() atomic_read_acquire(), atomic_set_release()RMW atomic operations:Arithmetic: atomic_{add,sub,inc,dec}() atomic_{add,sub,inc,dec}_return{,_relaxed,_acquire,_release}() atomic_fetch_{add,sub,inc,dec}{,_relaxed,_acquire,_release}()Bitwise: atomic_{and,or,xor,andnot}() atomic_fetch_{and,or,xor,andnot}{,_relaxed,_acquire,_release}()Swap: atomic_xchg{,_relaxed,_acquire,_release}() atomic_cmpxchg{,_relaxed,_acquire,_release}() atomic_try_cmpxchg{,_relaxed,_acquire,_release}()Reference count (but please see refcount_t): atomic_add_unless(), atomic_inc_not_zero() atomic_sub_and_test(), atomic_dec_and_test() Misc: atomic_inc_and_test(), atomic_add_negative() atomic_dec_unless_positive(), atomic_inc_unless_negative()[ ... ]Good; now that you’re aware of these RMW (and non-RMW) operators, let’s get practical and check out how to use RMW operators to safely perform bit operations.
Using the RMW bitwise operators
Section titled “Using the RMW bitwise operators”Here, we’ll focus on employing the RMW bitwise operators; we’ll leave it to you to explore the others (refer to the kernel docs mentioned). So let’s think again about how to code our pseudocode example more efficiently. We can set (to 1) any given bit in any register or memory item using the set_bit() API:
void set_bit(unsigned int nr, volatile unsigned long *p);This API, atomically, meaning safely and indivisibly, sets the nr th bit (nr is simply short for number) of p to 1. (The reality is that the device registers (and possibly device memory) are mapped into kernel virtual address space and, thus, appear to be visible as though they are RAM locations – such as the address p here. This is called MMIO and is the common way in which driver authors map in and work with device memory. Again, we cover this (and more) in the Linux Kernel Programming – Part 2 book.)
Thus, with the RMW atomic operators, we can safely and correctly achieve what we’ve (incorrectly) attempted previously – turning on our (fictional) device feature – with a single line of code:
set_bit(7, CTRL_REG);The following table summarizes common RMW bitwise atomic APIs: