Kernel Synchronization – Part 1
local graph
Chapter 12 — Kernel Synchronization – Part 1
Section titled “Chapter 12 — Kernel Synchronization – Part 1”With the previous chapter and the one preceding it (Chapters 11 and 10, respectively), you learned a good deal about CPU (or task) scheduling on the Linux OS. In this chapter and the following one, we shall dive into the – at times necessarily complex – topic of kernel synchronization.
As any developer familiar with programming in a multithreaded environment is well aware, there is a need for synchronization whenever two or more threads (code paths in general) may work upon a shared writable data item. Without synchronization (or mutual exclusion) in accessing the shared data, they can race; that is, the outcome cannot be predicted. This is called a data race. (In fact, data races can even occur when multiple single-threaded processes work on any kind of shared memory object, or where interrupts are a possibility.) Pure code itself is never an issue as its permissions are read+execute (r-x); reading and executing code simultaneously on multiple CPU cores is not only perfectly fine and safe but actively encouraged (as it results in better throughput, and that is why multithreading is a good idea). However, the moment you’re working on shared writable data is the moment you need to start being very careful (it’s why multithreading and concurrency tend to be complex topics!).
The discussions around concurrency and its control via synchronization are varied, especially with as rich and complex a piece of software as the Linux kernel (and related drivers/modules), which is what we’re dealing with in this book. Thus, for convenience, we will split this large topic into two chapters, this one and the next.
In this chapter, we will cover the following topics:
- Critical sections, exclusive execution, and atomicity
- Concurrency concerns within the Linux kernel
- Mutex or spinlock? Which to use when
- Using the mutex lock
- Using the spinlock
- Locking and interrupts
- Locking – common mistakes and guidelines
Technical requirements
Section titled “Technical requirements”I assume you have gone through Online Chapter, Kernel Workspace Setup, and have appropriately prepared a guest Virtual Machine (VM) running Ubuntu 22.04 LTS (or a later stable release, or a recent Fedora distro) and installed all the required packages. If not, I highly recommend you do this first.
To get the most out of this book, I strongly recommend you first set up the workspace environment, including cloning this book’s GitHub repository for the code, and work on it in a hands-on fashion. The repository can be found here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E.
In this and the following chapter, we refer to small (and simple) device driver examples now and then. If you’re not familiar with the basic Linux driver concepts, though not a required prerequisite, may I again suggest the Linux Kernel Programming – Part 2 – Char Device Drivers and Kernel Synchronization book; this is explained in the first chapter itself: Chapter 1, Writing a Simple misc Character Device Driver (this Part 2 book is in fact considered the companion volume to this book; also, the e-book is freely downloadable).
With this done, fasten your seatbelts, and let’s get started on this important and interesting topic area!
Critical sections, exclusive execution, and atomicity
Section titled “Critical sections, exclusive execution, and atomicity”Imagine you’re writing software for a multicore system (well, nowadays, it’s typical that you will work on multicore systems, even on most embedded projects). As we mentioned in the introduction, running multiple code paths in parallel is not only safe but also desirable (why spend those dollars otherwise, right?). On the other hand, concurrent (parallel and simultaneous) code paths within which shared writable data (also known as shared state) is accessed in any manner is where you are required to guarantee that, at any given point in time, only one thread can work on that data at a time! This is key. Why? Think about it: if you allow multiple concurrent code paths to work in parallel on shared writable data, you’re asking for trouble: data corruption (a “data race”) can occur as a result. The following section, after covering some key points, will clearly illustrate the data race concept with a few pseudocode examples (also, you could peek at Figure 12.6 if you’d like).
What is a critical section?
Section titled “What is a critical section?”The points that follow are very important; please read them carefully.
A critical section is a code path that must fulfill these two conditions:
- Condition one: The code path is possibly concurrent, that is, there exists a possibility that it can run in parallel.
AND
- Condition two: That it works upon (reads and/or writes) shared writable data (aka shared state).
Thus, critical sections, by definition, require protection from parallelism.
In other words, a critical section is a piece of code that must run exclusively, even, at times, atomically.
- By exclusively, we’re implying that at any given point in time, exactly one thread is running the code of the critical section; that is, it runs alone (serialized, as opposed to parallelized). This is required for data safety reasons.
- The word atomic implies something indivisible; in this context, it means the ability to run to completion without interruption.
If two or more threads can execute a critical section’s code concurrently, it is a bug or a defect; this is often referred to as a race condition or data race.
Identifying and protecting critical sections from simultaneous execution (from data races) is an implicit requirement for correct software that you – the designer/architect/developer – must ensure. Learning how to protect critical sections is (relatively) easy; correctly identifying every critical section is a skill you must master. We’ll try and help with that via the “exercises” that follow.
Exercise 1. In the following user-mode Pthreads (pseudo) code snippet, where you can assume the function code can be run in parallel (by multiple threads), does the code region between time t1 and t2 (shown in comments) constitute a critical section?
void qux(int factor){ int nok; [ … ] //------------------------ t1 nok += 10*PI; //------------------------ t2 printf("..."); [ … ]}Solution 1. Okay, I’ll help you with this first exercise! Ask yourself, what exactly constitutes a critical section? It’s when these two conditions are fulfilled: the code path can possibly execute in parallel and works upon shared writable data. So, now, does the code in question (the line between t1 and t2) fulfill these two pre-conditions? Well, it can run in parallel (as explicitly stated), but it does not work on shared writable data (the variable nok isn’t shared; it’s a local variable, thus each thread that executes this code path will get a copy of the variable on its stack). So, the answer here is clearly no, it isn’t a critical section. In other words, it can run in parallel – any number of instances – without any kind of explicit protection.
Onto another couple of small exercises.
Exercises 2 and 3. In the following kernel module (pseudo) code snippets, where you can assume the code can run in parallel (by multiple user-mode threads switching into kernel space to these code paths, running them in process context), do the code regions between time t1 and t2 (shown in comments) constitute critical sections? | ||
| | |
(Solutions can be found at the end of this chapter in the Solutions(s) section; please try solving them for yourself before you check the solution.)
Let’s now revisit the key notion of atomicity: an atomic operation is one that is indivisible. On any modern processor, two operations are generally considered to always be atomic; that is, they will run to completion without interruption:
- The execution of a single machine language instruction.
- Reads or writes to an aligned primitive data type that is within the processor’s word size (typically 32 or 64 bits); so, reading or writing a 32-bit or 64-bit integer on a 64-bit system is guaranteed to be atomic. Threads reading that variable will never see an in-between, torn, or dirty result; they will either see the old or the new value. On the other hand, a 32-bit processor operating on a 64-bit item is not guaranteed to be atomic and could result in a torn or dirty read (or write).
A word to the wise: it pays to tread very carefully here! It’s been shown that with modern highly optimizing compilers on modern hardware processors, even this “truth” – that loads/stores (meaning reads/writes) to aligned primitive data types within the processor’s word size are always atomic – may not hold true! Compilers can now employ load-/store-tearing techniques, and more; read more in this excellent article: Who’s afraid of a big bad optimizing compiler? LWN, July 2019: https://lwn.net/Articles/793253/ (plus more in the Further reading section of this chapter).
So, if you have some lines of code that work upon shared (global or static) writable data, they cannot – in the absence of an explicit synchronization mechanism – be guaranteed to run exclusively. Note that at times, running the critical section’s code atomically, as well as exclusively, is required, but not all the time; let’s delve further into this aspect.
When the code of the critical section is running in a safe-to-sleep possibly blocking process context (such as typical file operations on a driver via a user app (open, read, write, ioctl, mmap, and so on), or the execution path of a kernel thread or workqueue), it might well be acceptable to not have the critical section being truly atomic, but it does need to be exclusive. However, when its code is running in a non-blocking atomic context (such as within a hardware interrupt: a hardirq, tasklet, or softirq), it must run atomically as well as exclusively (we shall cover these points in more detail in the Mutex or spinlock? Which to use when section).
A conceptual example will help clarify things. Let’s say that three threads (from user-space app(s)) issue the open() and read() system calls, thus working on your driver (implemented as a kernel module or within the kernel) more or less simultaneously on a multicore system. (Recall, Linux is a monolithic kernel; when a process or thread issues a system call, it switches to kernel mode and runs the appropriate kernel/driver code paths in process context.)
Without any intervention, they may well end up running the critical section’s code in parallel, thus working on the shared writable data in parallel (a data race!) and very likely corrupting it! For now, let’s look at a conceptual diagram to see how non-exclusive execution within a critical section’s code path is wrong (we won’t even talk about atomicity here):

Diagram Description automatically generated
Figure 12.1: A conceptual diagram showing how a critical section code path is violated by having more than one thread running within it simultaneously, a data race
As shown in the preceding diagram, in your device driver, within its (say) read method, you’re having it run some code to perform its job (reading some data from the hardware). Let’s take a more in-depth look at this diagram in terms of data accesses being made at different points in time:
- From time
t0tot1: None or only local variable data is accessed. This is concurrent-safe, with no protection required, and can run in parallel (since each thread has its own private stack). - From time
t1tot2: Global/static shared writable data is accessed. This is not automatically concurrent-safe; it’s a critical section (as Figure 12.1 shows that it definitely fulfills the two conditions for it). Thus, it must be protected from concurrent access. It must run exclusively (alone, exactly one thread at a time, and serialized) and, perhaps, atomically. - From time
t2tot3: None or only local variable data is accessed. This is concurrent-safe, with no protection required, and can run in parallel (since each thread has its own private stack).
In this book, with the material covered so far and your own knowledge, we assume that you are by now aware of the need to synchronize critical sections; we will not discuss this particular point any further. Those of you who are interested in learning more may refer to my earlier book, Hands-On System Programming with Linux (Packt, October 2018), which covers these points in detail (especially Chapter 15, Multithreading with Pthreads Part II – Synchronization).
So, knowing this, we can now restate the notion of a critical section while also mentioning when the situation arises. A critical section is code that must run as follows:
- (Always) Exclusively: Alone (serialized)
- (When in an atomic context) Atomically: Indivisibly, to completion, without interruption
In the next section, we’ll look at a classic scenario – the increment of a global integer.
A classic case – the global i ++
Section titled “A classic case – the global i ++”Think of this classic example: a global integer i is being incremented within a concurrent code path, one within which multiple threads of execution can simultaneously execute. A naive understanding of computer hardware and software will lead you to believe that this operation is obviously atomic. However, the reality is that modern hardware and software (the compiler and OS) are much more sophisticated than you may imagine, thus causing all kinds of invisible (to the app developer) performance-driven optimizations.
We won’t attempt to delve into too much detail here, but the reality is that modern processors are extremely complex: among the many technologies they employ toward better performance, a few are superscalar and super-pipelined execution in order to execute multiple independent instructions and several parts of various instructions in parallel (respectively), performing on-the-fly instruction and/or memory reordering, caching memory in complex hierarchical on-CPU caches, load/store tearing, and so on! We will delve into some of these details in Chapter 13, Kernel Synchronization – Part 2, in the Understanding CPU caching basics, cache effects and false sharing and Introducing memory barriers sections. Several papers (and books) worth delving into on these fascinating topics can be found in the Further reading section.
All of this makes for a situation that’s more complex than it appears to be at first glance. Let’s continue with the classic i ++ in a possibly concurrent code path:
static int i = 5;[ ... ]foo(){ [ ... ] i ++; /* Is this safe? Yes, if this code path is truly exclusive or atomic... * Alternately, if this code path's not exclusive, is the i ++ truly atomic?? */}So, is this increment safe? The short answer is no, you must protect it. Why? It’s a critical section – we’re accessing (reading/writing) shared writable data in a possibly concurrent code path! The longer answer is that it really depends on:
- Whether the code of function foo() is guaranteed to run exclusively.
- Whether the increment operation here is truly atomic (indivisible); if it is, then
i ++poses no danger in the presence of parallelism – if not, it does!
So, assuming the execution of the code path surrounding the i ++ is non-exclusive – that is, other threads can execute this code path foo() in parallel – to have it work correctly, we then require the i ++ operation to be truly atomic. Being a simple high-level language operation, it may “appear” at first glance to be atomic, but is it really? How do we know whether this is the case or not? Two things determine this:
- The processor’s Instruction Set Architecture (ISA), which determines (among several things related to the processor at a low level) the machine instructions that execute at runtime when this operation runs
- The compiler, which of course converts the high-level language source to assembly (and then the assembler generates the machine code that ultimately executes on the processor)
If the ISA has within it the facility to employ a single machine instruction to perform an integer increment, and the compiler has the intelligence and occasion to use it, then it’s truly atomic – it’s safe and doesn’t require explicit protection, typically, locking. Otherwise, it’s not safe and requires locking! So, on your machine and with your current compiler, how do we know?
Try this out: Navigate your browser to this wonderful compiler explorer website: https://godbolt.org/. Select C as the programming language and then, in the left pane, declare the global i integer and increment it within a function. Compile in the right pane with an appropriate compiler and compiler options. You’ll see the actual machine code generated for the C high-level i ++; statement. If it’s indeed a single machine instruction, then it will be safe and atomic; if not, it will require locking. Typically, on CISC-based machines like the x86[_64], compiler optimization levels of 2 and above do make the code atomic, but this isn’t always the case with RISC machines (like ARM-based ones).
By and large, you will find that you can’t really tell; in effect, you cannot afford to assume things – you will have to assume that the i ++ operation is unsafe, that is, non-atomic, by default and protect it! This can be seen in the following screenshot:

Figure 12.2: Even with the latest stable gcc version but no optimization, the x86_64 gcc produces multiple machine instructions for the i ++
The preceding screenshot clearly shows this: the light/yellow background regions in the left- and right-hand panes are the C source for our famous i ++; statement and the corresponding assembly generated by the compiler, respectively (based on the x86_64 ISA and the particular compiler’s optimization level). (FYI, in Figure 12.2, I changed the assembly syntax from Intel to the more generalized AT&T one by deselecting Intel asm syntax from the Setting gear wheel in the right pane). Typically, with no optimization, i ++ becomes three machine instructions. This is exactly what we expect: it corresponds to the fetch or load of i (memory to register), the increment, and the store (register to memory)! Now (in this case at least, without optimization) this is not atomic; thus it’s entirely possible that, after one of the machine instructions executes, the control unit interferes and switches the instruction stream to a different point. This could even result in another process or thread being context-switched in (unless you used locking around it)!
The good news is that with a quick -O2 in the Compiler options… window, i ++ becomes just one machine instruction – truly atomic! (It doesn’t always show though.) However, we can’t predict these things in advance; one day, your code may execute on a fairly low-end ARM (RISC) system, increasing the chance that multiple machine instructions are required for i ++. You might by now be wondering – to fix this, using something like a mutex (or even a spinlock) lock for an i ++ seems pretty sub-optimal; you’d be right. We shall cover an optimized locking technology specifically for integer operations in Chapter 13, Kernel Synchronization – Part 2, in the Using the atomic_t and refcount_t interfaces section.
Modern languages provide native atomic operators; for C/C++, it’s fairly recent (from 2011); the ISO C++11 and ISO C11 standards provide ready-made and built-in atomic variables for this. A little googling will quickly reveal them to you. Modern glibc also makes use of them. As an example, if you’ve worked with signaling in user space, you will know to use the volatile sig_atomic_t data type to safely access and/or update an integer atomically within a signal handler. What about in the kernel? In the next chapter, you’ll learn about the Linux kernel’s solution to this key issue.
Do realize early: the Linux kernel is, of course, a concurrent environment; multiple threads of execution run in parallel on multiple CPU cores. Not only that, but even on uni-processor (UP/single CPU) systems, the presence of hardware interrupts, traps, faults, exceptions, and software signals can cause data integrity issues (data races). Needless to say, protecting against concurrency at required points in the code path, at critical sections, is easier said than done; identifying and protecting critical sections using technologies such as locking – as well as other synchronization primitives and technologies – is absolutely essential, which is why this is the core subject matter of this chapter and the next.
Concepts – the lock
Section titled “Concepts – the lock”We require synchronization because of the fact that, without any intervention, threads can concurrently execute critical sections where shared writable data (shared state) is being worked upon. To defeat concurrency in these critical sections, we need to get rid of parallelism; we need to serialize the flow of code in the critical section.
To force a code path to become serialized, a common technique is to use a lock. Essentially, a lock works by guaranteeing that precisely one thread of execution can “take” or own the lock at any given point in time; once taken, only this thread can move forward – we term it the “winner.” These notions are expanded on shortly. Thus, using a lock to protect a critical section in your code will give you what we’re after – running the critical section’s code exclusively (and also perhaps atomically; more on this to come). Check out this diagram (Figure 12.3):

Diagram Description automatically generated
Figure 12.3: A conceptual diagram showing how a critical section code path is honored, given exclusivity, by using a lock
Figure 12.3 shows one way to fix the situation mentioned previously (Figure 12.1): using a lock to protect the critical section! How does the lock (and unlock) work, conceptually?
The basic premise of a lock is that whenever there is contention for it – that is, when multiple competing threads (say, n threads) attempt to acquire the lock (via the conceptual LOCK operation) – exactly one thread will succeed. This thread is deemed the “winner,” the “owner,” of the lock. It sees the lock API as a non-blocking call and thus continues to run happily – and exclusively! – while executing the code of the critical section (the critical section is effectively the code between the lock and the unlock operations!).
What happens to the n-1 “loser” threads? They (perhaps) see the lock API as a blocking call; they, to all practical effect, wait. Wait for what? The UNLOCK operation, of course, which is (must be) performed by the owner of the lock (the “winner” thread) when it’s done with the work of the critical section! Once unlocked, the remaining n-1 threads now compete for the next “winner” slot; of course, exactly one of them will win and proceed forward. In the interim, the n-2 losers will now wait upon the (new) winner’s unlock. This repeats until all n threads (finally and sequentially) acquire the lock.
Now, locking works of course, but – and this should be quite intuitive – it results in (pretty steep!) overhead, as it defeats parallelism and serializes the execution flow! To help you visualize this situation, think of a funnel, with the narrow stem being the critical section where only one thread can fit at a time. All other threads get choked, waiting on the unlock; locking creates bottlenecks. The following figure is meant to show this analogy:

Diagram Description automatically generated
Figure 12.4: A lock creates a bottleneck, analogous to a physical funnel
Another oft-mentioned physical analog to locking is a highway with several lanes merging into one very busy – and choked with traffic – lane, a poorly designed toll booth, perhaps. Again, parallelism – cars (threads) driving in parallel with other cars in different lanes (CPUs) – is lost, and serialized behavior is required; cars are forced to queue one behind the other.
Thus, it is imperative that we, as software architects, try and design our products/projects with minimal locking. While completely eliminating global variables is not practically possible in most real-world projects, optimizing and minimizing their usage is required. We shall cover more regarding this, including some very interesting lockless programming techniques, later.
Another really key point: a newbie programmer might naively assume that performing reads on a shared writable data object is perfectly safe and thus requires no explicit protection; (with the exception of an aligned primitive data type that is within the size of the processor’s bus) this is untrue. This situation can lead to what’s called dirty or torn reads, a situation where possibly stale and/or inconsistent data is being read even as another writer thread is simultaneously writing.
The moral’s clear: you need to protect all accesses, read and write, to shared writable data in possibly concurrent code paths, in effect, in all critical sections.
Since we’re on the topic of atomicity, as we just learned, on a typical modern microprocessor, the only things guaranteed to be atomic are a single machine language instruction or (as we learned, possibly) a read/write to an aligned primitive data type within the processor bus’s width. So, how can we mark a few lines of C code so that they’re truly atomic? In user space, this isn’t even possible (we can come close, but cannot guarantee atomicity).
How do you “come close” to atomicity in user-space apps? You can always construct a user thread to employ the SCHED_FIFO task scheduling policy and a real-time (RT) priority of 99. This way, when it wants to run, pretty much nothing besides hardware interrupts/exceptions can preempt it. (The old audio subsystem implementation heavily relied on this semantic.)
In kernel space, we can write code that’s truly atomic. How, exactly? The short answer is that we use spinlocks to do so! We’ll learn about spinlocks in more detail shortly.
Critical sections – a summary of key points
Section titled “Critical sections – a summary of key points”Let’s summarize some key points regarding critical sections. It’s really important to go over these carefully, keep these handy, and ensure you use them in practice:
- A critical section is a possibly concurrent code path, one that can execute in parallel, and that works upon (reads and/or writes) shared writable data (aka shared state).
- Because it works on shared writable data, the critical section:
- Requires protection from parallelism and concurrency (that is, it must run alone/serialized/in a mutually exclusive fashion).
- When running in an atomic non-blocking context (which includes any kind of interrupt context), you must guarantee it runs atomically: indivisibly, to completion, without interruption.
- Requires protection from parallelism and concurrency (that is, it must run alone/serialized/in a mutually exclusive fashion).
Once protected, you can safely access your shared state until you “unlock.”
- Every critical section in the codebase must be identified and protected:
- Identifying critical sections is critical! Carefully review your code and make sure you don’t miss them. (Any global or static variable is a typical red flag; but it’s not only these, any kind of shared state – hardware registers, mailboxes, and so on – in a possibly concurrent code path can be a critical section.)
- Protecting them can be achieved via various technologies; one very common technique is locking (which we’ll shortly get into in detail). There are also atomic operators and lock-free programming techniques, which we’ll look at in the next chapter.
- A common mistake is only protecting critical sections that write to shared writable data; you must also protect critical sections that read shared writable data. Otherwise, you risk a torn or dirty read! To help make this key point clear, visualize an unsigned 64-bit data item being read and written on a 32-bit system; in such a case, the operation can’t be atomic (two load/store operations are required per read/write). Thus, what if, while one thread’s reading the value of the data item, it’s being simultaneously written to by another thread!? The writer thread would have taken a “lock” of some sort on the access but because you thought reading is safe, the lock isn’t taken by the reader thread; due to an unfortunate timing coincidence, you can end up performing a partial/torn/dirty read. We will learn how to overcome these issues by using various locking techniques in the coming sections now and in the next chapter.
- Another deadly mistake is not using the same (correct) lock to protect a given data item. For example, if you’re using lock A to protect a global data structure X, then you must always use lock A whenever it’s accessed; using lock B doesn’t help. This can be more difficult than it seems at first, as large projects (like the Linux kernel) can have tens of thousands of locks!
- Failing to protect critical sections leads to a data race, a situation where the outcome – the actual value of the shared data being read/written – is “racy,” which means it varies, depending on runtime circumstances and timing. This is a defect, a bug (a bug that, once in “the field,” is extremely difficult to see, reproduce, determine its root cause, and fix. We will cover some very powerful stuff to help you with this in the next chapter, in the Lock debugging within the kernel section; be sure to read it then!).
- Identifying critical sections is critical! Carefully review your code and make sure you don’t miss them. (Any global or static variable is a typical red flag; but it’s not only these, any kind of shared state – hardware registers, mailboxes, and so on – in a possibly concurrent code path can be a critical section.)
- Exceptions: You are safe (implicitly, without explicit protection) in the following situations:
- When you are working on local variables. They’re allocated on the private stack of the thread (or, in interrupt context, on the local IRQ stack) and are thus, by definition, safe.
- When you are working on shared writable data in code that cannot possibly run in another context; that is, it’s serialized by nature. In our context, the init and cleanup methods of a kernel module qualify (they run exactly once, serially, on
insmod(ormodprobe) andrmmodonly). - When you are working on shared data that is truly constant and read-only (don’t let C’s
constkeyword fool you, though!).
- When you are working on shared writable data in code that cannot possibly run in another context; that is, it’s serialized by nature. In our context, the init and cleanup methods of a kernel module qualify (they run exactly once, serially, on
- When you are working on local variables. They’re allocated on the private stack of the thread (or, in interrupt context, on the local IRQ stack) and are thus, by definition, safe.
- Locking is inherently complex; you must carefully think, design, and implement your locking schema while avoiding deadlocks. We’ll cover this in more detail in the Locking – common mistakes and guidelines section.
Data races – a more formal definition
Section titled “Data races – a more formal definition”A more formal approach to the important notions of memory consistency in the presence of multiple concurrent load/store operations is provided by a memory (consistency) model; it “models” the system memory behavior predicting what values may result via load (read from memory) operations when code executes on that system. The Linux kernel has just such a model; it’s called the Linux-Kernel Memory Model (LKMM).
Delving into its details isn’t really required here, but does make for some fascinating reading; do look up the explanation.txt document in the official kernel documentation here: https://elixir.bootlin.com/linux/v6.1.25/source/tools/memory-model/Documentation/explanation.txt.
(I’d definitely recommend you read at least the first three sections: INTRODUCTION, BACKGROUND, and A SIMPLE EXAMPLE. The notion of memory ordering is also covered in the LKMM.)
The LKMM provides two kinds of access to memory:
- Plain access: These are the typical accesses made to memory via C language statements, for example,
i ++ory = 42 - x;. - Marked access: These are “special” accesses; they’re designed and implemented to implicitly guarantee atomicity:
- Loads (reads) via the
READ_ONCE()macro (e.g..,READ_ONCE(x);)- Stores (writes) via the
WRITE_ONCE()macro (e.g.,WRITE_ONCE(y, 42-x);) - (In fact, it’s not just these macros that guarantee atomicity; the
atomic_*(),refcount_*(),smp_load_acquire(), and similar macros fall into the class of marked access.)
- Stores (writes) via the
- Loads (reads) via the
Okay, now to the key point here: what exactly, in the view of the LKMM, constitutes a data race?
From the same explanation.txt document, the section PLAIN ACCESSES AND DATA RACES (here: https://elixir.bootlin.com/linux/v6.1.25/source/tools/memory-model/Documentation/explanation.txt#L1977) goes into the details. It’s best to quote directly a bit from this document:
A "data race" occurs when there are two memory accesses such that:1. they access the same location,2. at least one of them is a store,3. at least one of them is plain,4. they occur on different CPUs (or in different threads on the same CPU), and5. they execute concurrently.In the literature, two accesses are said to "conflict" if they satisfy 1 and 2 above. We'll go a little farther and say that two accesses are "race candidates" if they satisfy 1 - 4. Thus, whether or not two race candidates actually do race in a given execution depends onwhether they are concurrent. [ … ]This is wonderful! A clear and formal definition, via the LKMM, of precisely what constitutes a data race.
You’d think this knowledge should be leveraged to write a tool to detect data races, right? This is precisely what the Kernel Concurrency Sanitizer (KCSAN) does! (Marco Elver is the current maintainer of KCSAN.) In fact, the Linux Kernel Debugging book in Chapter 8, Lock Debugging, covers using KCSAN in some detail (with examples). I’d definitely recommend you learn how to use KCSAN.
Marco Elver, in a presentation at the Linux Plumbers Conference, August 2020, entitled Data-race detection in the Linux kernel (link: https://lpc.events/event/7/contributions/647/attachments/549/972/LPC2020-KCSAN.pdf), explains data races as defined by the LKMM with this slide:

Figure 12.5: The “What are data races?” slide. Credit: Marco Elver
As you can see, on the right of Figure 12.5 are examples of two threads running concurrently (on different CPU cores) working on the same memory object (same location, shared writable data). The red cross to the left indicates a data race, the green tick mark implies it’s fine (the in-betweens – rows 3 and 5 – are a “maybe”; they race when interpreted “strictly”).
This might well have you thinking: “ Why not always use marked accesses and never have data races?” Please do NOT do this. Marked accesses are meant to be used internally by the kernel code and/or when you know there’s a potential data race but don’t care too much about it (a typical example is network driver statistics code that increments a counter without explicit locking primitives; a data race here is deemed to not matter too much). The key point here though, especially for module/driver authors, is this: using marked accesses actually prevents tools like KCSAN from catching data races. It’s important to continue to use plain C accesses for most of the cases.
Also, careful – though marked accesses guarantee atomic loads and stores, they do not guarantee memory ordering; this must be done via memory barriers (the following chapter throws some light on this). Now, we will move on to another key area – identifying concurrency and critical sections when working with the Linux OS.
Concurrency concerns within the Linux kernel
Section titled “Concurrency concerns within the Linux kernel”Recognizing critical sections within a piece of kernel code is of critical importance; how can you protect it if you can’t even see it? The following are a few guidelines to help you, as a budding kernel/driver developer, recognize where concurrency concerns – and thus critical sections – may arise:
- The presence of Symmetric Multi-Processor (SMP) systems (
CONFIG_SMP=y) - The presence of a preemptible kernel (
CONFIG_PREEMPTION=y) - Blocking I/O
- Hardware interrupts (on both SMP and/or UP systems)
These are critical points to understand, and we will discuss each in this section.
Multicore SMP systems and data races
Section titled “Multicore SMP systems and data races”This first point is pretty obvious; take a look at the pseudocode shown in Figure 12.6:

Graphical user interface, application Description automatically generated
Figure 12.6: Pseudocode – a critical section (time t2 to t3) within a (fictional) driver’s read method; it’s potentially buggy as there’s no locking
It’s a similar situation to what we showed in Figure 12.1 and Figure 12.3. As shown, from time t2 to time t3, the function can run in parallel and it’s working on some global shared writable data, thus making this a critical section.
Now, visualize a system with, say, four CPU cores (an SMP/multicore system); two user-space processes, P1 (running on, say, CPU 0) and P2 (running on, say, CPU 2), can concurrently open the device file and simultaneously issue a read() system call. Now, both processes will be concurrently executing the driver’s read “method,” thus simultaneously working on shared writable data! As we know, the code between t2 and t3 is a critical section, and since we violate the fundamental exclusivity rule – critical sections must be executed by only a single thread at any point in time – we can very well end up corrupting the data, the application, or worse.
In other words, this approach can lead to a data race; depending on delicate timing coincidences, we may or may not generate an error (a bug). This very uncertainty – the delicate timing coincidence – is what makes finding and fixing errors like this extremely difficult (it can escape your testing effort).
This aphorism is all too true, unfortunately: Testing can detect the presence of errors, not their absence. Adding to this, you’re worse off if your testing fails to catch data races (and bugs), allowing them free rein in the field.
You might argue that since your product is a small embedded system running on one CPU core (UP), this discussion regarding controlling concurrency (often, via locking) does not apply to you. We beg to differ: pretty much all modern products, if they haven’t already, will move to multicore (in their next-generation phases, perhaps). More importantly, even UP systems have concurrency concerns, as we shall soon explore.
Preemptible kernels, blocking I/O, and data races
Section titled “Preemptible kernels, blocking I/O, and data races”Imagine you’re running your kernel module or driver on a Linux kernel that’s been configured to be preemptible (that is, CONFIG_PREEMPT is on; we covered this topic in Chapter 10, The CPU Scheduler – Part 1). Again, referring to Figure 12.6, consider that a process, P1, is running the driver’s read method code in process context, working on the global array. Now, while it’s within the critical section (between time t2 and t3), what if the kernel preempts process P1 and context switches to another process, P2, which is just waiting to execute this very code path? It’s dangerous; it can lead to a data race. This could well happen on even a single CPU (UP) system! (Note that though we use the term “process” here, it’s interchangeable with “thread.”)
Another scenario that’s somewhat similar (and again, could occur on either a single-core (UP) or multicore system): process P1 is running through the critical section of the driver method (between time t2 and t3; again, see Figure 12.6). This time, what if, within the critical section, it hits a blocking call?
A blocking call is a function that causes the calling process context to be put to sleep, waiting upon an event; when that event occurs, the kernel (or the underlying driver) will “wake up” the task, and it will resume execution from where it left off.
This is also known as blocking on I/O and is very common; many APIs (including several user-space library and system calls, as well as several kernel APIs) are blocking by nature). In such a case, process P1 is effectively context-switched off the CPU and goes to sleep, which means that the code of schedule() runs and enqueues it onto a wait queue. In the interim, before P1 gets switched back, what if another process, P2, is scheduled to run? What if that process is also running this particular code path? Think about it – firstly, P2 now works on data that’s in an in-between state perhaps, not fully updated. Furthermore, by the time P1 is back, the shared data could have changed “underneath it,” causing all kinds of errors; again, a data race, a bug!
Hardware interrupts and data races
Section titled “Hardware interrupts and data races”Finally, envision this scenario: process P1 is innocently running the driver’s read method code; thus, it enters the critical section (between time t2 and t3; again, see Figure 12.6). It makes some progress but then, alas, a hardware interrupt triggers on the same CPU core! (You can learn about hardware interrupts and their handling in detail in the Linux Kernel Programming – Part 2 companion volume). On the Linux OS, hardware interrupts have the highest priority; they preempt all code (including kernel code) by default. Thus, process (or thread) P1 will be at least temporarily shelved, losing the processor, as the interrupt-handling code paths will certainly preempt it and run.
Well, you might be wondering, so what? Indeed, this is a completely commonplace occurrence! Hardware interrupts fire very frequently on modern systems, effectively (and literally) interrupting all kinds of task contexts (do a quick vmstat 3 on your shell; the column under system labeled in shows the number of hardware interrupts that fired on your system in the last 1 second!).
Here, the key question to ask is this: is the interrupt-handling code (either the hardirq, ISR, or “top half,” or the so-called tasklet or softirq “bottom half,” whichever occurred), sharing and working upon the same shared writable data as the process context that it just interrupted?
If this is true, then Houston, we have a problem – a data race! If not, then your interrupted code is not a critical section with respect to the interrupt code path, and that’s fine. The fact is that most device drivers do handle interrupts; thus, it is the driver author’s (your!) responsibility to ensure that no global or static data – in effect, no critical sections – are shared between the process context and interrupt context code paths. If they are (which does happen at times), you must somehow protect that data from data races and possible corruption (this is typically effected by employing a spinlock; worry not, we shall get to it).
These scenarios might leave you feeling that protecting against these concurrency concerns is a really tall order; how exactly can you accomplish data safety in the face of critical sections existing, along with the various possible concurrency concerns just discussed: multicore (or SMP), kernel preemption, blocking I/O, and hardware interrupts? The good news is that it’s really quite easy; the actual (locking) APIs that protect your critical sections are not hard to learn to use. Again, we emphasize that recognizing – and then being able to protect – critical sections is the key thing.
Without further ado, let’s now begin our dive into the primary synchronization technology that will serve to protect our critical sections – locking.
Locking guidelines and deadlock
Section titled “Locking guidelines and deadlock”Locking, by its very nature, is a complex beast; it tends to give rise to complex interlocking scenarios. Not understanding it well enough can lead to both performance headaches and bugs – deadlocks, circular dependencies, interrupt-unsafe locking, and more. The following locking guidelines are key to ensuring correctly written code when using locking:
- Locking granularity
- The “distance” between the lock and the unlock – in effect, the length of the critical section – should not be coarse (too long a critical section); it should be “fine enough.” The points below expand on this.
- You need to be careful here. When you’re working on large projects, keeping too few locks is a problem, as is keeping too many! Too few locks can lead to performance issues (as the same locks are repeatedly used and thus tend to be highly contended).
- Having a lot of locks is actually good for performance, but not good for complexity control. This also leads to another key point for you, the developer, to understand: with many locks in the codebase, you should be very clear on precisely which lock protects which shared data object. It’s completely meaningless if you use, say,
lockAto protectmystructX, but in a code path far away (perhaps an interrupt handler) you forget this and use some other lock,lockB, for protection when working on the same structure! Right now, these things might sound obvious, but (as experienced developers know), under sufficient pressure and complexity, even the obvious isn’t always so! - Try and balance things out. In large projects, using one lock to protect one global (shared) data structure is typical. Now, naming the lock variable well can become a big problem in itself! This is why we often place the lock that protects a data structure within it, as a member.
- Long critical sections that are atomic can cause high latency and become performance bottlenecks, especially in time-critical real-time systems. Several tools exist (in various states of stability) to help you understand where (and for how long) these sections occur. One from the eBPF stable is the tool named criticalstat [-bpfcc]. It can detect and report long critical sections (it also helpfully displays the kernel stack trace thus showing their origin) for long durations, in terms of when preemption and/or IRQs are disabled for long-ish durations. The criticalstat utility’s man page can be found here: https://manpages.ubuntu.com/manpages/focal/man8/criticalstat-bpfcc.8.html; here’s its “examples” page: https://github.com/iovisor/bcc/blob/master/tools/criticalstat_example.txt. (Ftrace too has tracers that can catch long bouts of preemption/IRQ off times.)
- The “distance” between the lock and the unlock – in effect, the length of the critical section – should not be coarse (too long a critical section); it should be “fine enough.” The points below expand on this.
- Only the “owner,” the current holder, of a lock can release (unlock) it; attempts to release a lock you don’t hold or to re-acquire it while held are considered bugs (the latter can be side-stepped by using recursive locking; see the next point though).
- Avoid recursive locking as much as possible; the kernel community in general frowns upon it.
- Lock ordering is critical, greatly mitigating deadlock. You must ensure that locks are taken in the same order throughout; these “lock-ordering rules” should be documented and followed by all the developers working on the project (annotating locks is useful too; more on this in the section on lockdep in the next chapter). Incorrect lock ordering often leads to deadlock.
- On the other hand, the order in which locks are released doesn’t matter (of course, you must at some point release all held locks to not cause starvation).
- Take care to prevent starvation; verify that a lock, once taken, is indeed released “quickly enough.”
- Simplicity is key: Try to avoid complexity or over-design, especially concerning complex scenarios involving locks.
On the topic of locking, the (dangerous) issue of deadlock arises. A deadlock is the inability to make any progress; in other words, the application processes/threads and/or kernel component(s) appear to hang indefinitely. While we don’t intend to delve into the gory details of deadlocks here, I will quickly mention some of the more common types of deadlock scenarios that can occur:
- Simple case, single lock, process context:
- Attempting to acquire the same lock twice is considered a defect and results in self-deadlock. Think about it; while holding a lock, you attempt to re-acquire it. Now, as the lock is locked, you have to wait until it’s unlocked. But you are holding the lock and waiting (and only you can unlock it) and thus cannot unlock it; the result is (self) deadlock! Recursive locking could solve this, but it’s generally disabled and using it is frowned upon.
- Simple case, multiple (two or more) locks, process context – let’s study this with an example:
- On CPU
0, thread A acquires lock A and then wants to acquire lock B.- Concurrently, on CPU
1, thread B acquires lock B and then wants to acquire lock A. - Thus, each waits on the other, forever… The result is a classic case of circular deadlock, often called the AB-BA deadlock. An illustration of this is as follows (the timeline is vertically downward):
CPU 0 : Thread A CPU 1 : Thread B... ...acquire lock A acquire lock B... ...try to acquire lock B try to acquire lock Awaits for lock B … … ... waits for lock A … … …… forever … … … ... … forever … … … …- This can be indefinitely extended; for example, the AB-BC-CA circular dependency (A-B-C lock chain) results in a deadlock.
- Concurrently, on CPU
- On CPU
- Complex case, single lock, process and interrupt contexts – let’s again study this via an example (this case is actually meant for the spinlock one; we’ll get to the details soon):
- Process P1, running, say, the read method of your driver (module), acquires lock A on, say, CPU core 0.
- A millisecond later, your driver’s hardware interrupt occurs on the same core and thus your driver’s interrupt handler immediately preempts P1. Now, what if the interrupt context attempts to take this same lock, lock A? As lock A is currently locked (by process context P1), the interrupt context is forced to wait on the unlock; but P1 is holding the lock and waiting to get back the CPU, which won’t happen as long as the interrupt’s running… thus, it cannot perform the unlock and the interrupt context too ends up waiting forever… again, the result is (self) deadlock!
- Process P1, running, say, the read method of your driver (module), acquires lock A on, say, CPU core 0.
The prescribed solution to this case, of course, is to disable (mask) all hardware interrupts on the local core when acquiring the lock; then the process context cannot be interrupted and it runs the critical section to completion. In other words, it’s now truly atomic. When it performs the unlock, this operation reenables all interrupts on the local core and all is well! Thus, locks acquired in an interrupt (or more generally, an atomic) context must always be used with interrupts disabled. (How exactly do we do this? With the spinlock; we shall of course look at these aspects in more detail when we cover spinlocks.)
- More complex cases, multiple locks, and process and interrupt (hardirq and softirq) contexts. (We don’t take this further here; you’ll find details in the upcoming Locking and interrupts section.)
In simpler cases, always following the lock-ordering guideline is sufficient: always obtain locks in a well-documented order (we will provide an example of this in kernel code in the Using the mutex lock section). However, as you are perhaps starting to realize, things can get very complex, and complex deadlock scenarios can trip up even experienced developers. Luckily for us, lockdep – the Linux kernel’s runtime lock dependency validator – can catch (almost) every single deadlock case! (Don’t worry – we shall get there, we’ll cover lockdep in detail in the next chapter; just proceed step by step). When we cover spinlocks (in the Using the spinlock section), we’ll come across process and/or interrupt context scenarios like the ones mentioned previously; the precise spinlock APIs to use (to avoid deadlock, among other things) are made clear there.
The reality is that even livelock situations can be just as deadly as deadlocks! Livelock is essentially a situation conceptually similar to deadlock; it’s just that the state of the participating tasks is running and not waiting. As an example, an interrupt “storm” (hundreds or even thousands of hardware interrupts – and their associated softirqs – occur in bursts and need to be processed very rapidly, stressing the system) can cause a livelock; modern network drivers mitigate this effect by switching off interrupts (under interrupt load) and resorting to a polling technique called New API (NAPI), switching interrupts back on when appropriate. (Well, it’s more complex than that, but we’ll leave it at that here.)
For those of you who’ve not been living under a rock, you will know that the Linux kernel has two primary types of locks: the mutex lock and the spinlock. Actually, there are several more types, including other synchronization (and “lockless” programming) technology, all of which will be covered in the course of this chapter and the next.
The kernel documentation refers to three lock categories implemented within the kernel: sleeping, CPU-local, and spinning locks. Sleeping locks include the (RT) mutex, the semaphore, and variations. Spinning locks include the spinlock, the reader-writer spinlock, and variations. The “local lock” is usually meant for RT usage, though the non-RT usage includes using it for lock debugging.
So now, let’s delve into what exactly the mutex lock and spinlock really mean and which you should use in what circumstance!
Mutex or spinlock? Which to use when
Section titled “Mutex or spinlock? Which to use when”The exact semantics of learning to use the mutex lock and the spinlock are quite simple (with appropriate abstraction within the kernel API set making it even easier for the typical driver developer or module author). The critical question in this situation is a conceptual one: what really is the difference between these two lock types? More to the point, under which circumstances should you use which lock? You will learn the answers to these questions in this section.
Taking our previous driver read method’s pseudocode (Figure 12.6) as a base example, let’s say that three threads – tA, tB, and tC – are running in parallel (on an SMP system) through this code. We shall solve this concurrency issue, while avoiding any data races, by taking (acquiring) a lock prior to the start of the critical section (time t2), and releasing the lock (unlock) just after the end of the critical section code path (time t3). Let’s take a look at the pseudocode once more via a diagram (Figure 12.7), this time with locking to ensure it’s correct:

Graphical user interface Description automatically generated with medium confidence
Figure 12.7: Pseudocode: a critical section within a (fictional) driver’s read method; here it’s done correctly, with locking
When the three threads attempt to simultaneously acquire the lock, the lock API semantics guarantee that exactly one of them will get it. Let’s say that tB (thread B) gets the lock: it’s now the “winner” or “owner” thread. This means that threads tA and tC are the “losers”; what do they do? They wait upon the unlock!
The moment the “winner” (tB) completes the critical section and unlocks the lock, the battle resumes between the previous losers; one of them will be the next winner and the process repeats. (Do understand that the “APIs” we show in Figure 12.7 are merely pseudocode and not the actual (un)lock APIs; we cover those in the two main sections that follow this one.)
The key difference between the two lock types – the mutex and the spinlock – is based on how the losers wait upon the unlock event. With the mutex lock, the loser threads are put to sleep; that is, they wait by sleeping (in effect, when they attempt to lock the mutex and it’s already locked, they see it as a blocking call; they are scheduled or context-switched off the CPU – they are now “sleeping”). The moment the winner performs the unlock, the kernel awakens the loser threads (all of them) and they run, again competing for the lock. (In fact, mutexes and semaphores are sometimes referred to as sleeplocks.)
With the spinlock, however, there is no question of sleeping; the loser threads wait by “spinning” upon the lock until it is unlocked. Conceptually, this looks as follows:
while (locked) ;Note that this is only conceptual. Think about it a moment – this is actually polling. However, as a good programmer, you will understand that polling is usually considered a bad idea. Why, then, does the spinlock work this way? Well, it doesn’t; it has only been presented in this manner for conceptual purposes. As you will soon understand, spinlocks only really have meaning on multicore (SMP) systems. On such systems, while the winner thread is away and running the critical section code, the losers wait by spinning on other CPU cores! In reality, at the implementation level, the code that’s used to implement the modern spinlock is highly optimized (and arch-specific) and does not work by trivially “spinning” via a while (locked); type of semantic (for example, many spinlock implementations for ARM use the wait for event (WFE) machine language instruction, which has the CPU optimally wait in a low-power state. Do see the Further reading section for several resources on the internal implementation of the mutex and spinlock within the kernel).
Determining which lock to use – in theory
Section titled “Determining which lock to use – in theory”How the spinlock is implemented is really not our concern here; the fact that the spinlock has a lower overhead than the mutex lock is of interest to us. How so? It’s simple, really: for the mutex lock to work, the loser thread has to go to sleep (and then be awoken on the unlock). To do so, internally, the schedule() function gets called, which means the loser sees the mutex lock API as a blocking call! A call to the scheduler will ultimately result in the thread being context-switched off the CPU. Conversely, when the owner thread eventually unlocks the lock, the loser thread(s) must be woken up; again, one of them, the next “winner,” will be context-switched back onto the processor.
Thus, the minimal “cost” of the mutex lock/unlock operation is the time it takes to perform two context switches on the given machine. (See the Information Box designated as [1] in the next section.) By relooking at Figure 12.7, we can determine the time spent in the critical section (the “locked” code path); that is, t_locked = t3 - t2.
Let’s say that t_ctxsw represents the time to context switch. As we’ve learned, the minimal cost of the mutex lock/unlock operation is two context switches (the first to “go to sleep” and the second when it’s “awoken”): 2 * t_ctxsw.
Now, let’s say that the following expression is true:
t_locked < 2 * t_ctxswIn other words, what if the time spent within the critical section is less than the time taken for two context switches? In this case, using the mutex lock is just wrong as this is far too much overhead; more time is being spent performing metawork than actual work – a phenomenon known as thrashing. It’s this precise use case – the presence of very short critical sections – that’s often the case on modern OSes such as Linux, that has us employ the spinlock in preference to the mutex. So, in conclusion, select the spinlock when you have short, non-blocking critical sections, and select the mutex when the critical section is long-ish and (possibly) blocking. Why the emphasis on “blocking”? The following section – the practical stuff – makes this clear; read on!
Determining which lock to use – in practice
Section titled “Determining which lock to use – in practice”So, while operating under the t_locked < 2 * t_ctxsw “rule” might be great in theory, hang on: are you really expected to precisely measure the context switch time and the time spent in the critical section of each and every case where one (a critical section) exists? No, of course not – that’s unrealistic and pedantic.
Practically speaking, think about it this way: the mutex lock works by having the loser threads sleep (until the unlock occurs); the spinlock does not (the losers “spin”). Let’s recall one of our “golden rules” of the Linux kernel: the kernel cannot sleep (call schedule()) in any kind of atomic context. Thus, we can never use the mutex lock in an interrupt context, or indeed in any context where it isn’t safe to sleep; using the spinlock, however, would be fine. (Recall, a blocking API is one that puts the calling context to sleep by calling schedule().) Let’s summarize this:
- Is the critical section running in an atomic (for example, interrupt) context, or in process context where it cannot sleep? Use the spinlock.
- Is the critical section running in process context and is sleep or blocking I/O in the critical section possible? Use the mutex lock.
Of course, using the spinlock is considered lower overhead than using the mutex; thus, you can even use the spinlock in process context (such as our fictional driver’s read method), as long as the critical section does not block (sleep).
[1] The time taken for a context switch is varied; it largely depends on the hardware and the OS quality. Some previous (September 2018) measurements show that context-switching time is in the region of 1.2 to 1.5 us (microseconds) on a pinned-down CPU, and around 2.2 us without pinning (https://eli.thegreenplace.net/2018/measuring-context-switching-and-memory-overheads-for-linux-threads/).
Both hardware and the Linux OS have improved tremendously, and because of that, so has the average context-switching time. An old (December 1998) Linux Journal article determined that on an x86 class system, the average context switch time was 19 microseconds (us), and that the worst-case time was 30 us; those numbers are now outdated.
This brings up the next question: how do we know if the code is currently running in process or interrupt context? That’s easy – use the in_task() macro to determine it (as our PRINT_CTX() macro within our convenient.h header does):
if (in_task()) /* we're in process context (usually safe to sleep / block) */else /* we're in an atomic or interrupt context (cannot sleep / block) */Now that you understand which one – mutex or spinlock – to use and when, let’s get into the actual usage. We’ll begin with how to use the mutex lock!
Using the mutex lock
Section titled “Using the mutex lock”Mutexes are also called sleepable or blocking mutual exclusion (mutex) locks. As you have learned, they are used in process context if the critical section can sleep (block). They must not be used within any kind of atomic or interrupt context (top halves, bottom halves such as tasklets or softirqs, and so on), kernel timers, or in process context where blocking is not allowed.
Initializing the mutex lock
Section titled “Initializing the mutex lock”Prior to usage, every lock must be initialized to the “unlocked” state. A mutex lock “object” is represented in the kernel as a struct mutex data structure. Consider the following code:
#include <linux/mutex.h>struct mutex mymtx;To use this mutex lock, it must be explicitly initialized to the unlocked state. Initialization can be performed statically (declare and initialize the object) with the DEFINE_MUTEX() macro, or dynamically via the mutex_init() function (this is actually a macro wrapper over the __mutex_init() function).
For example, to declare and initialize the mutex object mymtx, we can use DEFINE_MUTEX(mymtx);.
We can also do this dynamically. Why dynamically? Often, the mutex lock is a member of the (global) data structure that it protects.
Keeping the lock variable as a member of the (parent) data structure it protects is a common (and clever) pattern that’s used within Linux; this approach has the added benefit of avoiding namespace pollution and is unambiguous about which mutex protects which shared data item (a bigger problem than it might appear to be at first, especially in enormous projects such as the Linux kernel!).
For example, let’s say we have the following global context data structure in our driver code (note that this code is fictional):
struct mydrv_priv { <member 1>; <member 2>; [...] struct mutex mymtx; /* protects access to mydrv_priv */ [...]} *drvctx;/* Then, in your driver module's init method, do the following: */static int __init init_mydrv(struct mydrv_priv *drvctx){ [...] mutex_init(drvctx->mymtx); [...]}Correctly using the mutex lock
Section titled “Correctly using the mutex lock”One quite often finds very insightful comments within the kernel source tree. Here’s a great one that neatly summarizes the rules you must follow to correctly use a mutex lock (https://elixir.bootlin.com/linux/v6.1.25/source/include/linux/mutex.h#L35); please read this carefully:
/* * Simple, straightforward mutexes with strict semantics: * * - only one task can hold the mutex at a time * - only the owner can unlock the mutex * - multiple unlocks are not permitted * - recursive locking is not permitted * - a mutex object must be initialized via the API * - a mutex object must not be initialized via memset or copying * - task may not exit with mutex held * - memory areas where held locks reside must not be freed * - held mutexes must not be reinitialized * - mutexes may not be used in hardware or software interrupt * contexts such as tasklets and timers * * These semantics are fully enforced when DEBUG_MUTEXES is * enabled. Furthermore, besides enforcing the above rules, the mutex * [ ... ]As a kernel (or driver) developer, you must understand the following (we have covered most of these points in the Locking guidelines and deadlock section):
- A critical section causes the code path to be serialized, defeating parallelism. Due to this, it’s imperative that you keep the critical section as short as possible. A corollary to this is lock data, not code.
- Attempting to reacquire an already acquired (locked) mutex lock – which is effectively recursive locking – is not supported and will lead to a self-deadlock.
- Lock ordering: This is a very important rule of thumb for preventing dangerous deadlock situations. In the presence of multiple threads and multiple locks, the order in which locks are taken must be documented and strictly followed by all the developers working on the project. The actual lock ordering itself isn’t sacrosanct, but the fact that once it’s been decided on it must be followed, is. While browsing through the kernel source tree, you will come across many places where the kernel developers ensure this is done, and they (usually) write a comment regarding this for other developers to see and follow. Here’s a sample comment from the slab allocator code (
mm/slub.c):/** Lock order:* 1. slab_mutex (Global Mutex)* 2. node->list_lock (Spinlock)* 3. kmem_cache->cpu_slab->lock (Local lock)* 4. slab_lock(slab) (Only on some arches)* 5. object_map_lock (Only for debugging)...
Now that we understand how mutexes work from a conceptual standpoint (and their initialization), let’s learn how to make use of their business end, the actual lock/unlock APIs.
Mutex lock and unlock APIs and their usage
Section titled “Mutex lock and unlock APIs and their usage”In the Linux kernel, the mutex lock and unlock APIs, respectively, are as follows:
void __sched mutex_lock(struct mutex *lock);void __sched mutex_unlock(struct mutex *lock);(Ignore the __sched here; it’s just a compiler attribute that has this function disappear in the WCHAN output, which shows up in procfs and with certain option switches to ps (such as -l).)
Again, the comments within the source code in kernel/locking/mutex.c are very detailed and descriptive; I encourage you to take a look at this file in more detail. We’ve only shown some of its code here, which has been taken directly from the 6.1.25 Linux kernel source tree, https://elixir.bootlin.com/linux/v6.1.25/source/kernel/locking/mutex.c#L260:
[ ... ]/** * mutex_lock - acquire the mutex * @lock: the mutex to be acquired * * Lock the mutex exclusively for this task. If the mutex is not * available right now, it will sleep until it can get it. * * The mutex must later on be released by the same task that * acquired it. Recursive locking is not allowed. The task * may not exit without first unlocking the mutex. Also, kernel * memory where the mutex resides must not be freed with * the mutex still locked. The mutex must first be initialized * (or statically defined) before it can be locked. memset()-ing * the mutex to 0 is not allowed. * * (The CONFIG_DEBUG_MUTEXES .config option turns on debugging * checks that will enforce the restrictions and will also do * deadlock debugging) * * This function is similar to (but not equivalent to) down(). */void __sched mutex_lock(struct mutex *lock){ might_sleep(); if (!__mutex_trylock_fast(lock)) __mutex_lock_slowpath(lock);}EXPORT_SYMBOL(mutex_lock);might_sleep() is a macro with an interesting debug property: its presence catches code that’s supposed to execute in an atomic context but doesn’t! (More explanation for might_sleep() can be found in the Linux Kernel Programming – Part 2 companion volume.)
So, think about it: might_sleep(), which is the first line of code in mutex_lock(), is literally telling you that the code that follows “might sleep”! This further implies that this code path should not be executed by anything that’s in an atomic context since it might sleep. This of course means that you should only use the mutex in the process context when it’s safe to sleep!
A quick and important reminder: The Linux kernel can be configured with a large number of debug options; in this context, the CONFIG_DEBUG_MUTEXES=y config option will help you catch possible mutex-related bugs, including deadlocks. Similarly, when you configure via the usual make menuconfig UI, under the Kernel Hacking menu, you will find a large number of debug-related kernel config options; we discussed this in Chapter 5, Writing Your First Kernel Module – Part 2. There are several very useful kernel configs with regard to lock debugging; we shall cover these in the next chapter, in the Lock debugging within the kernel section.
Mutex lock – via [un]interruptible sleep?
Section titled “Mutex lock – via [un]interruptible sleep?”As usual, there’s more to the mutex than what we’ve seen so far. You already know that a Linux process (or thread) cycles through various states of a state machine. On Linux, sleeping has two discrete states – an interruptible sleep and an uninterruptible sleep. A process (or thread) in an interruptible sleep is sensitive – which means it will respond – to user-space signals, whereas a task in an uninterruptible sleep is not sensitive to user signals.
In a human-interactive application with an underlying driver, as a general rule of thumb, you should typically put a process into an interruptible sleep (while it’s blocking upon the lock), thus leaving it up to the end user as to whether to abort the application by pressing Ctrl + C (or some such mechanism involving signals).
There is a design rule that’s often followed on Unix-like systems: provide mechanism, not policy.
Having said this, on non-interactive code paths, it’s often the case that you must wait on the lock indefinitely, with the semantic that a signal that’s been delivered to the task should not abort the blocking wait (it should instead be kept pending). On Linux, the uninterruptible case turns out to be the most common one.
So, here’s the thing: the mutex_lock() API, in the “loser” thread’s code path, always puts this loser task into an uninterruptible sleep. If this is not what you want, use the mutex_lock_interruptible() API, to put the (loser) calling task into an interruptible sleep. There is one difference syntax-wise: the latter returns an integer value of 0 on success and -EINTR (remember the 0/-E return convention) on signal interruption (by the way, EINTR's English error message is Interrupted system call).
In general, using mutex_lock() is faster than using mutex_lock_interruptible(); use it when the critical section is short (thus pretty much guaranteeing that the lock is held for a short while, which is a very desirable characteristic).
The 6.1.25 kernel codebase contains over 22,000 and just over 800 instances of calling the mutex_lock() and mutex_lock_interruptible() APIs, respectively; you can check things like this out by leveraging the powerful cscope utility on the kernel source tree.
In theory, the kernel provides a mutex_destroy() API as well. This is the opposite of mutex_init(); its job is to mark the mutex as being unusable. It must only be invoked once the mutex is in the unlocked state, and once invoked, that mutex cannot be used. This is a bit theoretical because, on regular systems, it just reduces to an empty function; only on a kernel with CONFIG_DEBUG_MUTEXES enabled does it become actual (simple) code.
Thus, we should use this pattern when working with the mutex, as shown in the following pseudocode:
DEFINE_MUTEX(...); /* init: initialize the mutex object statically *//* or dynamically, via */mutex_init(); /* don't use both, use one of them... */[ ... ] /* critical section: perform the (mutex) locking, unlocking */ mutex_lock[_interruptible](); << ... critical section code ... >> mutex_unlock(); [ ... ] mutex_destroy(); // cleanup: destroy the mutex objectNow that you have learned how to use the mutex lock APIs, let’s put this knowledge to use. In the next section, we will build on top of a poorly written – no protection! – simple “misc” driver by employing the mutex object to lock critical sections as required.
Mutex locking – an example driver
Section titled “Mutex locking – an example driver”We have created a simple device driver code example in the Linux Kernel Programming – Part 2 companion volume in its first chapter, Writing a Simple misc Character Device Driver.
As stated, you can obtain a free download of the Linux Kernel Programming - Part 2 companion volume. The PDF version is available here: https://github.com/PacktPublishing/Linux-Kernel-Programming/tree/master/Linux-Kernel-Programming-(Part-2). (You can also download the Kindle edition from Amazon.)
There, we wrote a simple misc (miscellaneous) class character device driver named miscdrv_rdwr (the code can be found here, within its GitHub repository: https://github.com/PacktPublishing/Linux-Kernel-Programming-Part-2/tree/main/ch1/miscdrv_rdwr). We also wrote a small user-space utility program (https://github.com/PacktPublishing/Linux-Kernel-Programming-Part-2/blob/main/ch1/miscdrv_rdwr/rdwr_test_secret.c) to read and write a (so-called) “secret” from and to the device driver’s memory. The Linux Kernel Programming – Part 2 book’s first chapter will show you in detail how to write and then try out this device driver.
What we glaringly (egregiously is the right word here!) failed to do in that project is protect shared (global) writable data from concurrent invocation! In other words, we blithely ignored critical sections. This will cost us dearly in the real world. I urge you to take some time to think about this: isn’t it viable that two (or more) user-mode processes open the device file of this driver, and then concurrently issue various I/O: reads and writes? Here, the global shared writable data (in this particular case, two global integers and the members of the driver’s context data structure) could easily get corrupted.
So, let’s learn from and correct our mistakes by making a copy of this driver (we will now call it ch12/1_miscdrv_rdwr_mutexlock/1_miscdrv_rdwr_mutexlock.c) and rewrite some portions of it.
The key point is that we use mutex locks to protect all critical sections. Instead of displaying all the code here (it’s in this book’s GitHub repository of course), let’s do something interesting: let’s look at a “diff” (the differences – the delta generated by diff) between the older unprotected and the newer protected driver code versions (output truncated for readability):
$ cd <lkp2e-book-repo>/ch12/1_miscdrv_rdwr_mutexlock$ diff -u <lkp-p2...>/ch12/miscdrv_rdwr/miscdrv_rdwr.c \miscdrv_rdwr_mutexlock.c > miscdrv_rdwr.patch$ cat miscdrv_rdwr.patch[ ... ]+#include <linux/mutex.h> // mutex lock, unlock, etc #include "../../convenient.h"[ ... ]+DEFINE_MUTEX(lock1); /* this mutex lock is meant to protect the integers ga and gb */[ ... ]+ struct mutex lock; // this mutex protects this data structure };[ ... ]In the output of diff, lines prefixed with a “+” symbol have been added in the new version whereas lines prefixed with a “-” symbol were deleted (in the new version).
Here, we can see that in the newer safe version of the driver, we have protected all shared writable data (aka shared state) from concurrent access, which is the whole point. To do so, we first declared and initialized a mutex lock variable called lock1; we shall use it to protect the (just for demonstration purposes) two global integers, ga and gb, within our driver. Next, importantly, we declared a mutex lock named lock within the global “driver context” data structure; that is, drv_ctx. This will be used to protect all access to members of that data structure. It is initialized within the module’s init code path:
+ mutex_init(&ctx->lock);+ /* Retrieve the device pointer for this device */+ ctx->dev = llkd_miscdev.this_device;++ /* Initialize the "secret" value :-) */- strlcpy(ctx->oursecret, "initmsg", 8);- dev_dbg(ctx->dev, "A sample print via the dev_dbg(): driver initialized\n");+ strscpy(ctx->oursecret, "initmsg", 8);+ /* Why don't we protect the above strscpy() with the mutex lock?+ * It's working on shared writable data, yes?+ * Yes, BUT this is the init code; it's guaranteed to run in exactly+ * one context (typically the insmod(8) process), thus there is+ * no concurrency possible here. The same goes for the cleanup+ * code path.+ */Next, the detailed comment clearly explains why we don’t need to lock/unlock around the strscpy() in this particular case (as it’s the module init code that can run only once in a single context). Similarly, and this should be obvious to you, local variables are implicitly private to each process context (as they reside in that process or thread’s kernel mode stack) and therefore require no protection (each thread/process has a separate instance of the variable, so no one steps on anyone else’s toes!). Before we forget, the cleanup code path (which is invoked via the rmmod(8) process context) must destroy the mutexes:
-static void __exit miscdrv_rdwr_exit(void)+static void __exit miscdrv_exit_mutexlock(void) {+ mutex_destroy(&lock1);+ mutex_destroy(&ctx->lock); misc_deregister(&llkd_miscdev);- pr_info("LLKD misc (rdwr) driver deregistered, bye\n");+ pr_info("LKP2E misc driver %s deregistered, bye\n", llkd_miscdev.name); }Now, let’s look at the relevant portion of the patch (diff) with regard to the driver open method. Here, in the old unsafe version, we simply operated upon our global integers ga and gb willy-nilly, with no protection; now, we do so correctly, under the aegis of the mutex:
++ mutex_lock(&lock1);+ ga++; gb--;+ mutex_unlock(&lock1);++ dev_info(dev, " filename: \"%s\"\n" [ ... ]But (there’s always a but, isn’t there?), all is not well! Take a look at the printk function (via the dev_info() wrapper) following the mutex_unlock() line of code here:
+ dev_info(dev, " filename: \"%s\"\n"+ " wrt open file: f_flags = 0x%x\n"+ " ga = %d, gb = %d\n",+ filp->f_path.dentry->d_iname, filp->f_flags, ga, gb);Does this look okay to you? No, look carefully: we are reading the value of the global integers, ga and gb. Recall the fundamentals: in the presence of concurrency (which is certainly a possibility here in this driver’s open method), even reading shared writable data without making it an exclusive access (via locking, typically) is potentially unsafe. If this doesn’t make sense to you, please think: what if, while one thread is reading the integers, another is simultaneously updating (writing) them; what then? This kind of situation can result in what’s called a dirty or torn read; we might end up reading stale/incorrect/partially correct data that must be protected.
Well, to be honest, the fact is that this isn’t really a great example of a dirty read as, on most modern processors, reading and writing single integer items does tend to be an atomic operation. However, we must not assume such things – we must simply do our job and protect shared writable data accesses – both reads and writes – from concurrent access.
In fact, there’s another similar bug-in-waiting: in the code snippet just seen, did you notice that we read data from the open file structure (the filp pointer) without bothering to protect it? (Indeed, the open file structure has a lock; we’re supposed to use it! We shall do so later.)
The precise semantics of how and when things such as dirty reads occur do tend to be very arch (machine)-dependent; nevertheless, our job as kernel or driver authors is clear: we must ensure that we protect all critical sections. This includes reads upon shared writable data.
For now, we shall just flag these as potential defects (bugs, on the to-do list). We will take care of them in the following chapter, in the Using the atomic_t and refcount_t interfaces section, in a more performance-friendly manner.
Moving along, look at the patch (the diff) of the driver’s read method; it reveals something interesting, how we now use the driver context structure’s mutex lock to protect the critical sections that turn up in the code path:

Figure 12.8: The diff of the driver’s read() method; notice the usage of the mutex lock in the newer version (lines prefixed with “+” have been added in the newer version)
Figure 12.8 is a (partial) screenshot of the diff, focused on our driver’s read method. Study it; you will notice how we’ve now used the mutex lock to protect every access to shared writable data, in other words, to protect every critical section. (Some of it’s a bit pedantic, no doubt. Also, why not use the get_task_comm() helper to get the thread name (as we learned in Chapter 6, Kernel Internals Essentials – Processes and Threads)? This will become clear in the coming chapter. Patience, please!) The same protection-via-mutex goes for the open, write and close (release) methods of the device driver (why not generate the patch for yourself and take a look?).
Note that the user-mode app remains unchanged, which means for us to test the new safer version, we must continue using the original user-mode app at ch12/miscdrv_rdwr/rdwr_drv_secret.c. (For your convenience, I’ve copied its code across to this book’s GitHub repo here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/ch12/rdwr_test_secret.c.) Do try it out along with the misc driver!
Running and testing code such as this driver code on a debug kernel, which contains various locking errors and deadlock detection capabilities, is crucial (we’ll return to these “debug” capabilities in the next chapter, in the Lock debugging within the kernel section).
In the preceding code diff (Figure 12.8), we took the mutex lock just before the copy_to_user() routine; the copy_to_user() helper macro is a blocking one (and might sleep!). This is fine; using mutex locks for a possibly blocking critical section is one of its key use cases, after all.
However, we only release the mutex after the dev_info() call. Why not release it before this routine, thus shortening the critical section? A closer look at dev_info() reveals why it’s within the critical section. We are printing the values of three variables here: the number of bytes read - by secret_len - and the number of bytes that are “transmitted” and “received” by ctx->tx and ctx->rx, respectively. Now secret_len is a local variable and does not require protection, but the other two variables are within the global driver context structure and thus (pedantically) do require protection, even when “only reading” them, thus protecting against possibly dirty or torn reads!
The mutex lock – a few remaining points
Section titled “The mutex lock – a few remaining points”In this section, we will cover a few additional points regarding mutexes.
Mutex lock API variants
Section titled “Mutex lock API variants”First, let’s take a look at a few variants of the mutex lock API; besides the interruptible variant (described in the Mutex lock – via [un]interruptible sleep? section), we have the trylock, killable, and io variants.
The mutex trylock variant
Section titled “The mutex trylock variant”What if you would like to implement a busy-wait semantic; that is, test for the availability of the (mutex) lock and, if available (meaning it’s currently unlocked), acquire it and continue with the critical section code path. However, if it’s not available (meaning it’s currently in the locked state), don’t wait for the lock; instead, perform some other work and retry.
In effect, this is a non-blocking mutex lock variant and is thus called the trylock; the following flowchart approximates how it works:

Figure 12.9: The “busy wait” semantic, a non-blocking trylock variant of the mutex lock
The dotted box in Figure 12.9 signifies that the internal implementation – checking if the lock is unlocked and then locking it – is atomic. The API for this trylock variant of the mutex lock is as follows:
int __sched mutex_trylock(struct mutex *lock);This API’s return value signifies what transpired at runtime:
- A return value of
1indicates that the lock has been successfully acquired. - A return value of
0indicates that the lock is currently contended (locked).
Though it might be tempting to, do not attempt to use the mutex_trylock() API to figure out if a mutex lock is in a locked or unlocked state; this is inherently “racy.” Next, note that using this trylock variant in a highly contended lock path may well reduce your chances of acquiring the lock. The trylock variant has been traditionally used in deadlock prevention code that might need to back out of a certain lock order sequence and be retried via another sequence (ordering).
Also, with respect to the trylock variant, even though the literature uses the wording try and acquire the mutex atomically, it does not work in an atomic or interrupt context – it only works in process context (as with any type of mutex lock). As usual, the lock must be released by mutex_unlock() being invoked by the owner context.
I suggest that you now try working on the trylock mutex variant as an exercise. See the Questions section at the end of this chapter for an assignment!
The mutex interruptible and killable variants
Section titled “The mutex interruptible and killable variants”As you have already learned, the mutex_lock_interruptible() API is used when the driver (or module) is willing to acknowledge any (user-space) signal interrupting it (and, if that happens, it returns -ERESTARTSYS to tell the kernel VFS layer to perform signal handling; the user-space system call will fail with errno set to EINTR). An example can be found in the module-handling code in the kernel, within the delete_module(2) system call (which rmmod invokes):
[ ... ]SYSCALL_DEFINE2(delete_module, const char __user *, name_user, unsigned int, flags){ struct module *mod; [ ... ] if (!capable(CAP_SYS_MODULE) || modules_disabled) return -EPERM; [ ... ] if (mutex_lock_interruptible(&module_mutex) != 0) return -EINTR; mod = find_module(name); [ ... ]out: mutex_unlock(&module_mutex); return ret;}Notice how the API returns -EINTR on failure. (By the way, the SYSCALL_DEFINEn() macro becomes a system call signature; n signifies the number of parameters this particular system call accepts. Also, notice the capability check – unless you are running as root or have the CAP_SYS_MODULE capability (or module loading is completely disabled), the system call just returns failure (-EPERM).)
If, however, your driver is only willing to be interrupted by fatal signals (those that will kill the user-space context), then use the mutex_lock_killable() API (the signature is identical to that of the interruptible variant).
The mutex I/O variant
Section titled “The mutex I/O variant”The mutex_lock_io() API is identical in syntax to the mutex_lock() API; the only difference is that the kernel thinks that the wait time of the loser thread(s) is the same as waiting for I/O (the code comment in kernel/locking/mutex.c:mutex_lock_io() clearly documents this; take a look: https://elixir.bootlin.com/linux/v6.1.25/source/kernel/locking/mutex.c#L1016). This can matter accounting-wise.
You can find fairly exotic APIs such as mutex_lock[_interruptible]_nested() within the kernel, with the emphasis here being on the nested suffix. However, note that the Linux kernel does not prefer developers to use nested (or recursive) locking (as mentioned in the Locking guidelines and deadlock and Correctly using the mutex lock sections). Also, these APIs only get compiled in the presence of the CONFIG_DEBUG_LOCK_ALLOC config option; in effect, the nested APIs were added to support the kernel lock validator mechanism. They should only be used in special circumstances (where a nesting level must be incorporated between instances of the same lock type).
In the next section, we will answer a typical FAQ: what’s the difference between the mutex and semaphore objects? Wait, does Linux even have a semaphore object? Read on to find out!
The semaphore and the mutex
Section titled “The semaphore and the mutex”The Linux kernel does provide a semaphore object, along with the usual operations you can perform on a (binary) semaphore:
- A semaphore lock acquire via the
down[_interruptible]()(and variations) APIs - A semaphore unlock via the
up()API
In general, the semaphore is an older implementation, so it’s advised that you use the mutex lock in place of it.
An FAQ worth exploring, though, is this: what is the difference between a mutex and a semaphore? They appear to be conceptually similar, but are actually quite different; one answer is summarized by the following points (of course, these are primarily wrt the Linux kernel):
- A semaphore is a more generalized form of a mutex; a mutex lock can be acquired (and subsequently released or unlocked) exactly once, while a semaphore can be acquired (and subsequently released) multiple times.
- A mutex is used to protect a critical section from simultaneous access, while a semaphore should be used as a mechanism to signal another waiting task that a certain milestone has been reached (typically, a producer task posts a signal via the semaphore object, which a consumer task is waiting to receive, in order to continue with further work).
- A mutex has the notion of ownership of the lock and only the owner context can perform the unlock; there is no ownership for a binary semaphore.
Priority inversion and the RT-mutex
Section titled “Priority inversion and the RT-mutex”A word of caution when using any kind of locking is that you should carefully design and code to prevent the dreaded deadlock scenarios that could arise (again, more on catching this is in the next chapter in the The lock validator lockdep – catch locking issues early section).
Aside from deadlocks, there is another risky scenario that arises when using the mutex: that of priority inversion (again, we will not delve into the details in this book). Suffice it to say that the unbounded priority inversion case can be a deadly one; the end result is that the product’s high(est) priority thread is kept off the CPU for too long.
As I covered in some detail in my earlier book, Hands-on System Programming with Linux, it’s precisely this priority inversion issue that struck NASA’s Mars Pathfinder robot, on the Martian surface no less, back in July 1997! The usage of a hardware watchdog had the system reboot whenever the project’s high-priority thread waited on the mutex for too long, past the deadline; the trouble is that this occurred often! Due to debug telemetry being enabled (yay!), the underlying issue was diagnosed from Earth and fixed (by using the priority inheritance (PI) mutex attribute to prevent lower-priority threads holding the mutex from being preempted before they released it). The firmware was then uploaded to the robot on Mars (!), and it all worked! See the Further reading section of this chapter for interesting resources about this, something that every software developer should be aware of!
The user-space Pthreads mutex implementation certainly has priority inheritance (PI) semantics available. But what about within the Linux kernel? For this, Ingo Molnar provided the PI-futex-based RT-mutex (a real-time mutex; in effect, a mutex extended to have PI capabilities. FYI, the futex(2) API is a sophisticated system call that provides a fast user-space mutex). It becomes available when the CONFIG_RT_MUTEXES config option is enabled. Quite similar to the “regular” mutex semantics, RT-mutex APIs are provided to initialize, (un)lock, and destroy the RT-mutex object. (This code has been merged into the mainline kernel from Ingo Molnar’s -rt tree.) As far as actual usage is concerned, the RT-mutex is used for internally implementing the PI futex (did you know that on Linux, the futex(2) system call itself internally implements the user-space Pthreads mutex?). Besides this, the kernel-locking self-test code and the I2C subsystem use the RT-mutex directly.
Thus, for a typical module (or driver) author, these APIs are not going to be used very frequently. The kernel provides some documentation on the internal design of the RT-mutex at https://docs.kernel.org/locking/rt-mutex-design.html (covering priority inversion, priority inheritance, and more).
Internal design
Section titled “Internal design”A word on the reality of the internal implementation of the mutex lock deep within the kernel fabric: Linux tries to implement a fast-path approach whenever possible.
A fast path is the most optimized high-performance code path, typically, one with no locks and no blocking. The intent is to have code follow this fast path as far as possible. Only when it really isn’t possible does the kernel fall back to a (possible) “mid path,” and then a “slow path,” approach; it still works but is slow(er).
This fast path is taken in the absence of contention for the lock (that is, the lock is in an unlocked state to begin with). So, the lock is locked with no fuss, pretty much immediately. If, however, the mutex is already locked, then the kernel typically uses a “mid path” optimistic spinning implementation, making it more of a hybrid (mutex/spinlock) lock type. If even this isn’t possible, the “slow path” is followed – the process context attempting to get the lock may well enter the sleep state. If you’re interested in the mutex’s internal implementation, more details can be found within the official kernel documentation here: https://docs.kernel.org/locking/mutex-design.html.
The LDV (Linux Driver Verification) project: back in Online Chapter, Kernel Workspace Setup, in the section The LDV – Linux Driver Verification – project, we mentioned that this project has useful “rules” with respect to various programming aspects of Linux modules (drivers, mostly) as well as the core kernel.
With regard to our current topic, here’s one of the rules: Locking a mutex twice or unlocking without prior locking (http://linuxtesting.org/ldv/online?action=show_rule&rule_id=0032). It mentions the kind of things you cannot do with the mutex lock (we have already covered this in the Correctly using the mutex lock section). The interesting thing here is that you can see an actual example of a bug – a mutex lock double-acquire attempt, leading to (self) deadlock – in a kernel driver (as well as the subsequent fix).
Another type of mutex that we will just mention is the so-called w/w – wait/wound (or simply the WW-mutex) – one (where wound rhymes with “doomed”). The term originates with RDBMS literature and is a way to handle deadlock (the documentation goes as far as to use the term “deadlock-proof”). With w/w in the Linux kernel, the usage is primarily within the graphics subsystem and, to some extent, DMA. Here, the task acquiring the mutex lock receives a unique reservation or ticket identifier. Now, the “age” of the task acquiring the WW-mutex is taken into account. In the case where deadlock is detected, the “oldest” task – the one that holds the reservation the longest – is given precedence. How? It’s done by having the “younger” task(s) back off, by having (forcing) them to release the WW lock(s) they hold; hence, the younger task is “wounded” (poor fellow). Usage of the WW- mutex within the kernel is pretty low, especially when compared with the regular mutex. See the Further reading section for more on it.
Now that you’ve understood how to use the mutex lock, let’s move on and look at the other very common lock within the kernel – the spinlock!
Using the spinlock
Section titled “Using the spinlock”In the Determining which lock to use – in practice section, you learned – practically speaking – when to use the spinlock instead of the mutex lock and vice versa. For convenience, we have reproduced the key statements we provided previously here:
- Is the critical section running in an atomic (for example, interrupt) context, or in process context where it cannot sleep? Use the spinlock.
- Is the critical section running in process context and is sleep or blocking I/O in the critical section possible? Use the mutex lock.
In this section, we shall consider that you’ve now decided to use the spinlock.
Spinlock – simple usage
Section titled “Spinlock – simple usage”For all the spinlock APIs, you must include the relevant header file, that is, #include <linux/spinlock.h>.
Similar to the mutex lock, you must declare and initialize the spinlock to the unlocked state before use. The spinlock is an “object” that’s declared via the typedef data type named spinlock_t (internally, it’s a structure defined in include/linux/spinlock_types.h). It can be initialized dynamically via the spin_lock_init() macro:
spinlock_t lock;spin_lock_init(&lock);Alternatively, this can be performed statically (declared and initialized) via the DEFINE_SPINLOCK(lock); macro.
As with the mutex, declaring a spinlock within the (global/static) data structure it’s meant to protect (against concurrent access) is typically a very good idea. As we mentioned earlier, this very idea is made use of within the Linux kernel often; as an example, the data structure representing an open file in the kernel is called the struct file:
struct file { [...] struct path f_path; struct inode *f_inode; /* cached value */ const struct file_operations *f_op; /* * Protects f_ep_links, f_flags. * Must not be taken from IRQ context. */ spinlock_t f_lock; [...] struct mutex f_pos_lock; loff_t f_pos; [...]Check it out: for the file structure, the spinlock variable named f_lock is the spinlock that protects (as the comment says) the f_ep_links and f_flags members of the file data structure; also, it has a mutex lock to protect another member, that is, the file’s current seek position f_pos.
How do you actually perform the lock and unlock operations with the spinlock? There are quite a few variations on the API that are exposed by the kernel to us module/driver authors; the simplest form of the spin(un)lock APIs are as follows:
void spin_lock(spinlock_t *lock);<< ... critical section ... >>void spin_unlock(spinlock_t *lock);Note that there is no spinlock equivalent of the mutex_destroy() API. Now, let’s see the spinlock APIs in action!
Spinlock – an example driver
Section titled “Spinlock – an example driver”Similar to what we did with our mutex locking sample driver (refer to the Mutex locking – an example driver section if you need to), to illustrate the simple usage of a spinlock, we shall (again) make a copy of our – poorly written, deliberately-with-no-locking – simple “misc” character device driver from the Linux Kernel Programming – Part 2 companion volume, from its first chapter, Writing a Simple misc Character Device Driver (ch1/1_miscdrv_rdwr) as a starting template and then place it in a new module driver location for this book; that is, here: ch12/2_miscdrv_rdwr_spinlock (of course, we expect you to clone the book’s GitHub repo).
Again, here, for readability, we’ll only show small, relevant portions of the diff (the differences, the delta generated by diff) between the original program and this one:
+#include <linux/spinlock.h>[ ... ]-/*- * The driver 'context' (or private) data structure;- * all relevant 'state info' regarding the driver is here.+static int ga, gb = 1;+DEFINE_SPINLOCK(lock1); /* this spinlock protects the global integers ga and gb */++/* The driver 'context' data structure;+ * all relevant 'state info' reg the driver is here. */ struct drv_ctx { struct device *dev; int tx, rx, err, myword; u32 config1, config2; u64 config3; [ … ]+#define MAXBYTES 128 char oursecret[MAXBYTES];+ struct mutex mutex; /* this mutex protects these members of this data+ * structure: oursecret+ * in the (possibly) blocking critical section+ */+ spinlock_t spinlock; /* this spinlock protects these members of this data+ * structure: oursecret, tx, rx+ * in the non-blocking / atomic critical sections+ */ }; static struct drv_ctx *ctx;This time, to protect the members of our drv_ctx global data structure, we have both the mutex lock (from the previous version) and a new spinlock. It’s quite common to have more than one lock within a data structure; typically, the mutex lock protects member usage in critical sections where blocking can occur, while the spinlock is used to protect members in critical sections where blocking (sleeping) cannot occur (you could use a spinlock to protect data members in process context as well, as long as the critical section’s non-blocking).
Of course, we must ensure that we initialize all the locks so that they’re in the unlocked state. We do this in the driver’s init code path (so, continuing with the patch output):
+ mutex_init(&ctx->mutex);+ spin_lock_init(&ctx->spinlock);In this version, in the driver’s open method, we replace the mutex lock with the spinlock to protect the increments and decrements of the global integers; a partial screenshot of the patch serves to show it with color highlighting:

Figure 12.10: Partial screenshot of the patch showing the code of the driver’s open method (and the spinlock usage therein)
Again, it’s worth repeating: wherever we use the spinlock(s), it implies that the critical section that it protects – the code path between the spinlock and the unlock – is definitely non-blocking code.
Next, in this version, within the driver’s read method, we use the spinlock instead of the mutex to protect some critical sections:
static ssize_t read_miscdrv_rdwr(struct file *filp, char __user *ubuf,- size_t count, loff_t *off)+ size_t count, loff_t *off) {- int ret = count, secret_len = strnlen(ctx->oursecret, MAXBYTES);+ int ret = count, secret_len, err_path = 0; struct device *dev = ctx->dev;- char tasknm[TASK_COMM_LEN];++ spin_lock(&ctx->spinlock);+ secret_len = strlen(ctx->oursecret);+ spin_unlock(&ctx->spinlock);However, that’s not all! Continuing with the driver’s read method, carefully take a look at the following code snippet taking the mutex lock and the comment that follows:
ret = -EFAULT;+ mutex_lock(&ctx->mutex);+ /* Why don't we just use the spinlock??+ * Because - VERY IMP! - remember that the spinlock can only be used when+ * the critical section will not sleep or block in any manner; here,+ * the critical section invokes the copy_to_user(); it very much can+ * cause a 'sleep' (a schedule()) to occur.+ */ if (copy_to_user(ubuf, ctx->oursecret, secret_len)) { [ … ]When protecting data where the critical section has possibly blocking APIs – such as copy_to_user() – we must only use a mutex lock! (Due to space constraints, we haven’t displayed more of the patch here; we expect you to read through the spinlock sample driver code and try it out for yourself.)
Test – sleep in an atomic context
Section titled “Test – sleep in an atomic context”You have already learned that the one thing we should not do is sleep (block) in any kind of atomic or interrupt context. Let’s put this to the test. As always, the empirical approach – where you test things for yourself rather than relying on other’s experiences – is key!
How exactly can we test this? Easy: we shall use a simple integer module parameter, buggy, which, when set to 1 (the default value being 0), executes a code path within our driver’s spinlock-protected critical section that violates this rule. There, we shall invoke the schedule_timeout() API, which internally invokes schedule(); it’s how we put the process context – current – to sleep in kernel space. (FYI, using this API, and a lot more, is covered in the Linux Kernel Programming – Part 2 companion volume in Chapter 5, Working with Kernel Timers, Threads, and Workqueues.) Here’s the relevant code:
[ ... ]static int buggy;module_param(buggy, int, 0600);MODULE_PARM_DESC(buggy,"If 1, cause an error by issuing a blocking call within a spinlock critical section");[ ... ]static ssize_t write_miscdrv_rdwr(struct file *filp, const char __user *ubuf, size_t count, loff_t *off){ int ret, err_path = 0; [ ... ] spin_lock(&ctx->spinlock); strscpy(ctx->oursecret, kbuf, (count > MAXBYTES ? MAXBYTES : count)); [ ... ] if ( == buggy) { /* We're still holding the spinlock! */ set_current_state(TASK_INTERRUPTIBLE); schedule_timeout(1*HZ); /* ... and this is a blocking call! * Congratulations! you've just engineered a bug */ } spin_unlock(&ctx->spinlock); [ ... ]}Now for the interesting part: let’s test this (buggy) code path within our custom 6.1.25 “debug” kernel (the kernel where we have enabled several kernel debug configuration options (mostly from within the Kernel Hacking menu in the make menuconfig UI)).
Testing the buggy module on a 6.1 debug kernel
Section titled “Testing the buggy module on a 6.1 debug kernel”First of all, ensure you’ve built the custom 6.1 kernel (we’re using version 6.1.25) and that all the required kernel debug config options are enabled (refer back to Chapter 5, Writing Your First Kernel Module – Part 2, the Configuring a “debug” kernel section, if you need to). Then, boot off your debug kernel (here, it’s named 6.1.25-dbg). Now, build the misc driver (in ch12/2_miscdrv_rdwr_spinlock/) against this debug kernel (the usual make within the driver’s directory should do this; you might find that, on the debug kernel, the build is a bit slower and the binary module is bigger):
$ lsb_release -a 2>/dev/null | grep "^Description" ; uname -rDescription: Ubuntu 23.106.1.25-dbg# Before running make, ensure that the Makefile has the variable MYDEBUG set to # y (I have kept it this way).$ cd <lkp2e_book_src>/ch12/2_miscdrv_rdwr_spinlock$ make--- Building : KDIR=/lib/modules/6.1.25-dbg/build ARCH= CROSS_COMPILE= ccflags-y="-DDEBUG -g -ggdb -gdwarf-4 -Wall -fno-omit-frame-pointer -fvar-tracking-assignments -DDYNAMIC_DEBUG_MODULE" MYDEBUG=y DBG_STRIP=n ---gcc (Ubuntu 13.2.0-4ubuntu3) 13.2.0[ … ]$ modinfo ./miscdrv_rdwr_spinlock.kofilename: /home/c2kp/lkp2e/ch12/2_miscdrv_rdwr_spinlock/./miscdrv_rdwr_spinlock.ko[ … ]vermagic: 6.1.25-dbg SMP preempt mod_unload modversionsparm: buggy:If 1, cause an error by issuing a blocking call within a spinlock critical section (int)$ sudo virt-whatvirtualboxkvm$As you can see, we’re running our custom 6.1.25 “debug” kernel on an x86_64 Ubuntu 23.10 guest VM here.
How do you know whether you’re running on a virtual machine (VM) or on the “bare metal” (native) system? virt-what(1) is a useful little script that shows this (you can install it on Ubuntu with sudo apt install virt-what).
To run our test case, insert the driver into the kernel and set the buggy module parameter to 1. Invoking the driver’s read method (via our user-space app; that is, ch12/rdwr_test_secret) isn’t an issue, as the buggy code path isn’t there, as shown here:
$ sudo dmesg -C$ sudo insmod ./miscdrv_rdwr_spinlock.ko buggy=1$ lsmod |grep miscdrvmiscdrv_rdwr_spinlock 20480 0$ ../rdwr_test_secretUsage: ../rdwr_test_secret opt=read/write device_file ["secret-msg"] opt = 'r' => we shall issue the read(2), retrieving the 'secret' form the driver opt = 'w' => we shall issue the write(2), writing the secret message <secret-msg> (max 128 bytes)$ ../rdwr_test_secret r /dev/llkd_miscdrv_rdwr_spinlockDevice file /dev/llkd_miscdrv_rdwr_spinlock opened (in read-only mode): fd=3../rdwr_test_secret: read 7 bytes from /dev/llkd_miscdrv_rdwr_spinlockThe 'secret' is: "initmsg"$Next, we issue a write(2) system call to the driver via the user-mode app; this time, the write method of the driver runs (in the context of our user-space rdwr_test_secret process of course), and thus the buggy code path gets executed!
Right, let’s run our user-space app, writing the new “secret” to the device (triggering our kernel module bug):
$ ../rdwr_test_secret w /dev/llkd_miscdrv_rdwr_spinlock "When you have exhausted all possibilities, remember this: you haven't"Device file /dev/llkd_miscdrv_rdwr_spinlock opened (in write-only mode): fd=3../rdwr_test_secret: wrote 70 bytes to /dev/llkd_miscdrv_rdwr_spinlock$As you saw in the code snippet shown earlier in this section, we issued a schedule_timeout() within a spinlock critical section (that is, between the lock and unlock). The debug kernel detects this as a bug and spawns (impressively large) debug diagnostics into the kernel log (note that bugs like this can quite possibly hang your system, so it’s always recommended to test stuff like this on a test VM). We check it out via sudo dmesg:

Figure 12.11: Kernel diagnostics being triggered by the “scheduling while atomic” bug we’ve deliberately hit here
The preceding (partial) screenshot (Figure 12.11) shows what transpired; let’s follow along while viewing the driver code in ch12/2_miscdrv_rdwr_spinlock/miscdrv_rdwr_spinlock.c:
- Firstly, see the second line, our useful
PRINT_CTX()macro’s output (we’ve reproduced this line here):miscdrv_rdwr_spinlock:write_miscdrv_rdwr(): 005) rdwr_test_secre :3066 | ...0 /* write_miscdrv_rdwr() */
Clearly, the driver’s write method code, write_miscdrv_rdwr(), is running in the context of our user-space process (rdwr_test_secre; notice how the name is truncated to the first 16 characters, including the NULL byte).
- It copies in the new “secret” from the user-space writer process and writes it, for 70 bytes.
- It then “takes” the spinlock, thus entering the critical section, and copies this data to the
oursecretmember of our driver’s context structure. - After this, the
if (1 == buggy) {condition evaluates to true. - So, it calls
schedule_timeout(), which is a blocking API (as it internally callsschedule()), triggering the bug, which is helpfully highlighted in red:BUG: scheduling while atomic: rdwr_test_secre/3066/0x00000002 - The kernel now dumps a good deal of the diagnostic output. Among the first things to be dumped is the call stack.
The call trace or stack backtrace of the kernel-mode stack of the process – here, it’s our user-space app, rdwr_drv_secret, which is running our (buggy) driver’s code in process context – can be clearly seen in Figure 12.11. Each line after the Call Trace: header is essentially a call frame on the kernel stack.
A couple of tips:
- Always read the call stack (or call trace) bottom-up (so, we can see we entered via a system call, quite clearly,
write(2), as it becomesksys_write(), thenvfs_write(), and so on). - Ignore all stack frames that begin with the
?symbol; they are questionable call frames, in all likelihood “leftovers” from previous stack usage in the same memory region. It’s worth taking a small memory-related diversion here: this is how stack allocation really works; stack memory isn’t allocated and freed on a per-call frame basis as that would be frightfully expensive. Only when a stack memory page is exhausted is a new one automatically faulted in! (Recall our discussions in Chapter 9, Kernel Memory Allocation for Module Authors – Part 2, in the A brief note on memory allocations and demand paging section). So, the reality is that as code calls and returns from functions, the same stack memory page(s) tend to keep getting reused.
Not only that, but for performance reasons, the call frame’s memory isn’t wiped each time, leading to leftovers from previous frames often appearing. (They can literally “spoil” the picture. However, fortunately, the modern stack call frame tracing algorithms are usually able to do a superb job at figuring out the correct stack trace.)
The vfs_write() calls __vfs_write(), which ends up invoking our driver’s write method; that is, write_miscdrv_rdwr()! (That, of course, is how the character driver framework is designed to work. Also, notice the [module name] in square brackets on the right of any module function call frame – another useful clue.) This code, as we well know, invokes the buggy code path where we call schedule_timeout(), which, in turn, invokes schedule() (which calls the actual worker routine __schedule()), causing the whole BUG: scheduling while atomic kernel bug to trigger.
The format of the scheduling while atomic code path is retrieved from the following line of code, which can be found in kernel/sched/core.c:
printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", prev->comm, prev->pid, preempt_count());Interesting! Here, you can see that it printed the following string:
BUG: scheduling while atomic: rdwr_test_secre/3066/0x00000002After atomic:, it prints the (possibly truncated) process name, the PID, and then invokes the preempt_count() inline function, which prints the preempt depth; essentially, the preempt depth is a counter that’s incremented every time a spinlock is taken and decremented on every unlock. So, if it’s positive, this implies that the code is within a critical or atomic section; here, it shows as the value 2, proving we’re in an atomic, non-preemptible code path!
We don’t interpret the rest of the useful kernel diagnostics here; do check out the Linux Kernel Debugging book for a deep dive into all these aspects.
It’s key to note that this bug gets neatly served up by the kernel during this test run as the CONFIG_DEBUG_ATOMIC_SLEEP debug kernel config option is turned on (it’s on because we’re running a custom “debug kernel”!) This config option’s details (you can interactively find and set this option in make menuconfig, under the Kernel Hacking menu) are as follows:
[ ... ]config DEBUG_ATOMIC_SLEEP bool "Sleep inside atomic section checking" select PREEMPT_COUNT depends on DEBUG_KERNEL depends on !ARCH_NO_PREEMPT help If you say Y here, various routines which may sleep will become very noisy if they are called inside atomic sections: when a spinlock is held, inside an rcu read side critical section, inside preempt disabled sections, inside an interrupt, etc...What happens if we also perform the very same test on a standard “distro” system and kernel (like our Ubuntu 22.04 LTS VM), which, importantly, is typically not configured as a “debug” kernel (hence the CONFIG_DEBUG_ATOMIC_SLEEP kernel config option hasn’t been set)? We’d perhaps expect that the kernel then doesn’t catch this particular bug; well, being empirical, this is how it worked out:
- In this book’s first edition, running the test on a standard Ubuntu 20.04 VM with the standard distro (5.4) kernel, it indeed didn’t catch this bug.
- However, I find that on more recent distros, and hence the kernels they run, even though the
CONFIG_DEBUG_ATOMIC_SLEEPkernel config option hasn’t been explicitly set, it still does catch the scheduling while atomic bug! Kernel enhancements over the years seem to have ensured this forward progress… (I tested on both Ubuntu 22.04 with the 5.19.0-45-generic kernel as well as on a Fedora 38 distro with the more recent 6.5.6-200.fc38.x86_64 kernel.)
It typically helps to keep the CONFIG_DEBUG_ATOMIC_SLEEP kernel config option enabled even in production.
Again, the LDV project has this as one of its rules:”It’s not allowed to acquire spin_lock twice. It’s not allowed to release not acquired spin_lock. At the end all spin_lock should be released. It’s not allowed to re-release a lock by spin_unlock/spin_unlock_irqrestore functions” (http://linuxtesting.org/ldv/online?action=show_rule&rule_id=0039). (We have of course covered these points in the Locking guidelines and deadlock section.) It mentions key points with regard to the correct usage of spinlocks; interestingly, here, it shows an actual bug instance in a driver where a spinlock was attempted to be released twice – a clear violation of the locking rules, leading to an unstable system.
Great, done with the spinlock? No, not by a long shot! The next section has us delve into a deeper understanding of the spinlock and its usage in the kernel and modules, where we work with the spinlock in interrupt contexts as well.
Locking and interrupts
Section titled “Locking and interrupts”So far, we have learned how to use the mutex lock and, for the spinlock, the basic spin_[un]lock() APIs. A few other API variations on the spinlock exist, and we shall examine the more common ones here.
In this section, there’s a bit more advanced coverage, and it will definitely help if you understand at least the basics of writing a (char) device driver and hardware interrupt handling on Linux (typically in the device driver context). These topics are covered in depth in this book’s companion volume Linux Kernel Programming - Part 2, in Chapter 1, Writing a Simple misc Character Device Driver and Chapter 4, Handling Hardware Interrupts (the LKP-2 e-book is freely downloadable). Also, as a quick guide/refresher, we have provided a sub section titled: Interrupt handling on Linux - a summary of key points, that comes later in this section. (If you’re unfamiliar with interrupt handling concepts on Linux, we suggest you first take a look at the LKP - Part 2 book and/or this section and then continue from here.)
To understand exactly why you may need other APIs for spinlocks, let’s go over a scenario: as a driver author, you find that the device you’re working on asserts a hardware interrupt; accordingly, you write the interrupt handler for it.
Now, while implementing, say, a read method for your driver, you find that you have a non-blocking critical section within it. This is easy to deal with: as you’ve learned, you should use a spinlock to protect it. Great! But, think, what if, while in the read method’s critical section, the device’s hardware interrupt fires? As you’re aware, hardware interrupts preempt anything and everything; thus, control will go to the interrupt handler code, preempting the driver’s read method.
The key question here: is this an issue? That answer depends on what both your driver’s interrupt handler and your read method were doing and how they were implemented. Let’s visualize a few scenarios:
- The driver’s interrupt handler (ideally) uses only local variables, so even if the
readmethod were in a critical section, it really wouldn’t matter; the interrupt handling will complete very quickly (typically and broadly speaking, within a range of 10 to 100 microseconds) and control will be handed back to whatever was interrupted (again, there’s more to it than this; any existing bottom-half mechanism, such as a softirq or tasklet, may also need to execute before your driver’sreadmethod is handed back the processor). So, as such, there is really no race in this case. - The driver’s interrupt handler is working on (global) shared writable data but not on the shared data items that your driver’s
readmethod is using. Thus, again, there is no conflict and no race with thereadmethod’s code. (What you should also realize, of course, is that as your interrupt handler’s working on shared state, it does have a critical section that must be protected (typically via another spinlock).) - The driver’s interrupt handler is working on the same (or a portion of the same) shared writable data that your driver’s
readmethod is working upon. In this case, we can see that the potential for a data race definitely exists, so we need locking! (Recall our definition of a data race in the Data races – a more formal definition section.)
Let’s of course focus on the third case, the one that has the potential for data races. Obviously, we must use a spinlock to protect the critical section within the interrupt-handling code (recall that using a mutex is disallowed when we’re in any kind of atomic or interrupt context). Also, unless we use the very same spinlock in both the driver’s read method and the interrupt handler code path, they won’t really be protected at all!
As this discussion shows, be extra careful when working with locks; take the time to think through your design and code in detail.
Let’s try and make this discussion a bit more hands-on (with pseudocode): let’s say we have a (global) shared data structure named gctx; we’re operating on it in both the read method as well as the interrupt handler (a top half and/or tasklet) within our driver. With regard to our read method, since this code path can run concurrently and it contains shared state, it is a critical section and therefore requires protection. Now, since we are running in process context, it might seem like using a mutex here would be fine.
No! Think… to be effective, we obviously need to protect the same shared state by using the very same lock in both our driver’s read method and the interrupt handler. Now, the interrupt handler’s critical section also requires protection, and as we’ve learned, we really don’t have much of a choice here: we must use the spinlock. So, we find that both the driver’s read method and the driver’s interrupt handler must thus use the same spinlock! (Here, we call the spinlock variable slock; read it as “s lock”).
The following pseudocode shows some timestamps (t1, t2, ...) for this situation; but first, let’s do it the wrong way:
/* Driver read method ; WRONG ! */driver_read(...) << time t0 >>{ [ ... ] spin_lock(&slock); <<--- time t1 : start of read method critical section >>... << critical section: operating on global data object gctx >> ... spin_unlock(&slock); <<--- time t2 : end of read method critical section >> [ ... ]} << time t3 >>(Why do we mark this driver read method as being “wrong”? You’ll soon find out!)
Now, to make this discussion interesting, we consider three scenarios (going from less to more complex):
- Scenario 1 – wherein the driver’s
readmethod and interrupt run sequentially, one after the other (in other words, in a serialized fashion, no race) - Scenario 2 – (more interesting) where they run in an interleaved fashion (potential for data race exists)
- Scenario 3 – where they run interleaved and some interrupts are masked (and some not; potential for data race exists)
We begin with the first scenario.
Scenario 1 – driver method and hardware interrupt handler run serialized, sequentially
Section titled “Scenario 1 – driver method and hardware interrupt handler run serialized, sequentially”The following pseudocode is for the device driver’s interrupt handler. As we “know” they run serialized, sequentially here, we have the timeline continue from earlier (from the code snippet of our fictional driver’s read method that was seen just before this section); hence, the first timestamp is shown as time t4 following the earlier time t3 one at the end of the read method):
handle_interrupt(...) << time t4; hardware interrupt fires! >>{ [ ... ] spin_lock(&slock); <<--- time t5: start of interrupt critical section >> ... << critical section: operating on global data object gctx >> ... spin_unlock(&slock); <<--- time t6 : end of interrupt critical section >> [ ... ]} << time t7 >>This can be summed up with the following diagram; study it carefully:

Diagram Description automatically generated
Figure 12.12: Timeline, scenario 1: the driver’s read method and hardware interrupt handler run sequentially when working on global data; there are no issues here (diagram not to scale)
In Figure 12.12, sL and sU imply the spin_lock() and spin_unlock() APIs being used. Luckily, everything has gone well – “luckily” because, here, the hardware interrupt fired after (it could have fired before as well) the read function’s critical section completed and not in between (as we shall consider in the following scenario!). Surely we can’t count on luck as the exclusive safety stamp of our product!?
Scenario 2 – driver method and hardware interrupt handler run interleaved
Section titled “Scenario 2 – driver method and hardware interrupt handler run interleaved”Whether your code’s running on a UP (uniprocessor, with only one CPU core) or SMP (multicore) system matters as well. Let’s first consider this scenario on a UP system.
Scenario 2 on a single-core (UP) system
Section titled “Scenario 2 on a single-core (UP) system”Hardware interrupts are, of course, asynchronous (they can arrive at any time). What if your peripheral chip’s (that your driver is purpose-built to “drive”) interrupt fired, on the same CPU core that the read method is running upon, at a less opportune time (for us) – say, while the read method’s critical section is running, that is, between time t1 and t2 (see Figure 12.12)? Well, shouldn’t the spinlock (taken at t1) simply do its job and protect our data?
No, think carefully: at this point, the interrupt handler will preempt your read method’s critical section and it will soon enter its critical section; doing so, it will obviously attempt to acquire the same spinlock (&slock). But wait a minute – it cannot acquire (lock) it as it’s currently locked (by the process context running the read method)! Thus, it “spins,” in effect waiting on the unlock. But how can it ever be unlocked? The driver’s read process context will have to unlock it (as it owns it) but can’t as it’s preempted by the hardware interrupt! Thus, it cannot be unlocked, and so the interrupt-side spinlock “spins” forever; so there we have it, a (self) deadlock.
So what’s the solution? We’ll reach it in a moment, so do read on…
Scenario 2 on a multicore (SMP) system
Section titled “Scenario 2 on a multicore (SMP) system”Interestingly, the spinlock is more intuitive and makes complete sense on an SMP (or multicore) system. So, here, let’s now consider a slightly different scenario from the previous one – running on multicore. Assume that the read method is running on CPU core 1; the interrupt can be delivered on another CPU core, say core 2. Given that the read method’s in its critical section, it implies the spinlock is locked (of course); thus, the interrupt code path, attempting to acquire the same spinlock, will “spin” on the lock on CPU core 2. Once the read method, on core 1, completes its critical section, it will unlock the spinlock, thus unblocking the interrupt handler, which can now “take” the spinlock and proceed forward; great!
But what about on UP? How will it work then? One can’t, after all, be running logic in one (say, process) context and “spinning” simultaneously in another (say, interrupt) context on one CPU core. And what if, on a multicore (SMP) box, the driver’s read method and the hardware interrupt handler happen to execute on the same core?
Worry not, there is indeed a solution!
Solving the issue on UP and SMP with the spin_[un]lock_irq() API variant
Section titled “Solving the issue on UP and SMP with the spin_[un]lock_irq() API variant”Ah, so finally, here’s the solution to this conundrum: when “racing” with interrupts, regardless of it being on uniprocessor or SMP systems, simply use the _irq variant of the spinlock API:
#include <linux/spinlock.h>void spin_lock_irq(spinlock_t *lock);The spin_lock_irq() API internally masks hardware interrupts (except for non-maskable ones, like the (Non Maskable Interrupt (NMI)) on the processor core that it’s running upon, that is, on the local core.
So, by using this API in our driver’s read method, interrupts will be effectively disabled on the local core during the length of the critical section, thus making any possible “race” impossible via hardware interrupts. (If the interrupt does fire on another CPU core, the spinlock technology will simply work as advertised, as discussed previously!)
The spin_lock_irq() implementation is pretty nested (as with most of the spinlock functionality), yet fast; down the line, it ends up invoking the local_irq_disable() and preempt_disable() macros, thus disabling both interrupts and kernel preemption on the local processor core that it’s running on. In other words, with this spinlock API variant, disabling hardware interrupts has the (desirable) side effect of disabling kernel preemption as well!
The spin_lock_irq() API pairs off with the corresponding spin_unlock_irq() API. So, the correct usage of the spinlock for this scenario (as opposed to the naive approach we saw previously, which could in fact result in self-deadlock) is as follows:
/* Driver read method ; CORRECT ! */driver_read(...) << time t0 >>{ [ ... ] spin_lock_irq(&slock); // Note: we're using the _irq version of the spinlock! <<--- time t1 : start of critical section >>[now all interrupts + kernel preemption on local CPU core are masked (disabled)]... << critical section: operating on global data object gctx >> ... spin_unlock_irq(&slock); <<--- time t2 : end of critical section >>[now all interrupts + kernel preemption on local CPU core are unmasked (enabled)] [ ... ]} << time t3 >>Now, it should work as, of course, with the _irq variant of the spinlock API, it’s impossible for hardware interrupts to preempt the driver read method’s critical section!
A sneaky problem still lurks, though (eye roll); the following scenario describes it and provides a solution.
Scenario 3 – some interrupts masked, driver method and hardware interrupt handler run interleaved
Section titled “Scenario 3 – some interrupts masked, driver method and hardware interrupt handler run interleaved”Before patting ourselves solidly on the back and taking the rest of the day off, let’s consider yet another scenario. In this scenario, on a more complex product (or project), it’s quite possible that, among the several developers working on the codebase, one has deliberately set the hardware interrupt (bit)mask to a certain value, thus blocking some hardware interrupts while allowing others (the disable_irq() / enable_irq() APIs allow you to selectively disable/enable individual IRQ lines).
For the sake of our example, let’s say that this had occurred earlier, at some point in time t0. Now, as we described previously, another developer (you!) comes along, and in order to protect a critical section within the driver’s read method uses the spin_lock_irq() API (as we just learned in the Solving the issue on UP and SMP with the spin_[un]lock_irq() API variant section). Sounds correct, yes? Well, yes, but this API has the power to turn off (mask) all hardware interrupts (and kernel preemption, which we’ll ignore for now) on the local CPU core. It does so by manipulating, at a low level, the (very arch-specific) hardware CPU state register(s).
FYI, on the x86[_64], the spin_lock_irq() API saves the EFLAGS (32-bit)/RFLAGS (64-bit) register content (more correctly, it saves the LSB 16 bits, the content that’s called ‘FLAGS’). On the AArch32, it saves the EFLAGS register content, and on the AArch64 it saves the DAIF (Debug, Asynchronous (serror), Interrupts, and FIQ exceptions) register content. The spin_unlock_irqrestore() API, of course, restores it.
Well, so what, you ask? Consider this scenario unfolding:
- time
t0: The interrupt mask is set to some value, say,0x8e (10001110b), enabling some and disabling some interrupts (via, say, careful usage of thedisable_irq()API). This setting is important to the project (here, for simplicity, we’re assuming it’s an 8-bit mask register):[... time elapses ... ]. - time
t1: Just before entering the driverreadmethod’s critical section, callspin_lock_irq(&slock);. As we now understand, this API will internally save some CPU state register and have the internal effect of clearing all bits in the interrupt mask register to0, thus effectively masking all interrupts. - time
t2: Now, hardware interrupts cannot be handled on this CPU core, so we go ahead and complete the critical section. That’s fine. Once we’re done with the critical section, we callspin_unlock_irq(&slock);. This API will have the internal effect of restoring certain (arch-specific) CPU state registers, which will also have the internal side effect of setting all bits in the interrupt mask register to1, thus reenabling all interrupts.
However, the interrupt mask register has now been wrongly “restored” to a value of 0xff (11111111b), not the value 0x8e as the original developer(s) wants, requires, and assumes! This can (and probably will) break something in the project. Sounds difficult.
The solution, though, is quite straightforward: when saving the CPU state, don’t assume anything; simply save and restore the existing CPU state, and thus, the interrupt mask state. This way, if the interrupt mask initially was the value 0x8e (10001110b), this is what gets saved, and later, restored; perfect. This save-and-restore-cpu-state (with the spinlock) can be achieved with the following spinlock API pair:
#include <linux/spinlock.h>unsigned long spin_lock_irqsave(spinlock_t *lock, unsigned long flags);void spin_unlock_irqrestore(spinlock_t *lock, unsigned long flags);The first parameter to both of these lock and unlock functions is the pointer to spinlock variable to use. The second parameter, flags, must be a local variable of the unsigned long data type. This will be used to save and restore the arch-specific CPU register (and thus the interrupt mask state as well). So, finally, for this scenario, the correct (pseudo)code is this:
spinlock_t slock;spin_lock_init(&slock);[ ... ]driver_read(...){ [ ... ] spin_lock_irqsave(&slock, flags); <<--- time t1 : start of critical section >>[now the CPU state is saved; as a side effect, all interrupts + kernel preemption on the local CPU core are masked (disabled) ] << ... critical section ... >> spin_unlock_irqrestore(&slock, flags);<<--- time t2 : end of critical section >>[now the CPU state is restored; as a side effect, only the previously masked interrupts + kernel preemption on the local CPU core are unmasked (enabled) ] [ ... ]}To be pedantic, spin_lock_irqsave() is not an API, but a macro; we’ve shown it as an API for readability. Also, although the return value of this macro is not void, it’s an internal detail (the flags parameter variable is updated here).
Great, now let’s round off this discussion by using spinlocks with regard to interrupt bottom halves.
Interrupt handling, bottom halves, and locking
Section titled “Interrupt handling, bottom halves, and locking”Before embarking on the points regarding locking and bottom halves, a quick overview (summary, really) of some key points with regard to interrupt handling on Linux will help.
Interrupt handling on Linux – a summary of key points
Section titled “Interrupt handling on Linux – a summary of key points”Interrupt handlers must be non-blocking and complete their work quickly. How quickly? A rule of thumb is, within 100 microseconds. However, what if there is quite a bit of work to perform while in the handler? It might take longer… which can introduce latencies. A solution (which most modern OSes go with) is to “split” the interrupt handling into two halves – top and bottom. The “top half” (or hardirq) handler is the one invoked almost instantly when the hardware interrupt fires; you – the driver author – are to do the bare minimum required work here, keeping it as short as possible. If more work is required to be carried out, you (earlier) register and invoke the “bottom half,” a deferred function that runs “later.”
In reality, bottom halves are implemented as “tasklets,” which in turn are built on the kernel’s low-level softirq technology. The tasklet or softirq runs pretty much immediately after the top half completes.
But then where’s the benefit in this “splitting” approach? Ah, here’s the key thing, with important side effects with regard to locking: the top half (hardirq) always runs with all interrupts disabled (masked) on the current CPU and the IRQ it’s handling disabled (masked) across all CPUs; the bottom-half handler runs with all interrupts enabled.
It’s important to realize that even the bottom-half mechanisms – the softirq and tasklet – run in interrupt (and not process) context. Thus, as with the top-half or hardirq handler, you musn’t do anything that could possibly block within them.
A hardirq handler will never run in parallel with itself (thus, it’s not reentrant). A tasklet (which is built on the softirq mechanism under the hood) will also never run in parallel with itself; this property makes using the tasklet easier. A softirq, though, can run in parallel with itself (on other cores).
Next, using threaded handlers for interrupt processing is now quite popular with many types of drivers (especially for devices that are a bit slower, that don’t have extremely high performance demands unlike many block, network, graphics devices, and is in fact the default when registering an interrupt handler). In this case, as the interrupt handler entity is really nothing but a kernel thread (at SCHED_FIFO scheduling policy and real-time priority 50), issuing blocking calls within it is allowed. Moreover, this removes the ‘top-bottom half’ dichotomy as well.
Bottom halves and locking
Section titled “Bottom halves and locking”Now, having understood these points, let’s move on to locking.
What if your driver’s softirq or tasklet has a critical section that “races” with your top-half (hardirq) interrupt handler (by executing on a core different from the one where the top half executes)? Easy: use a regular spinlock in both to protect the critical section(s).
Next, what if your driver’s softirq or tasklet has a critical section that “races” with your process-context code paths?
In such situations, using the spin_lock_bh() routine in your driver’s methods is likely what’s required as it first disables bottom halves on the local processor and then takes the spinlock, thus safeguarding the critical section (similar to the way that spin_lock_irq[save]() protects the critical section in process context by disabling hardware interrupts on the local core):
void spin_lock_bh(spinlock_t *lock);The corresponding unlock API is the spin_unlock_bh().
Of course, overhead does matter in highly performance-sensitive code paths (the kernel code implementing the network stack being a great example). Thus, using the simplest form of spinlocks will help in performance terms, than with the more complex variants.
Having said that, though, there are certainly going to be occasions that demand the use of the stronger forms of the spinlock API.
For example, with regard to the 6.1.25 LTS Linux kernel codebase, here’s an approximation of the number of usage instances of different forms of the spinlock APIs we have seen:
spin_lock(): Over 10,200 usage instancesspin_lock_irq(): Over 3,800 usage instancesspin_lock_irqsave(): Over 15,500 usage instancesspin_lock_bh(): Over 4,400 usage instances
(Just for contrast, the numbers for the book’s first edition with the 5.4.0 LTS kernel were 9,400, over 3,600, over 15,000, and over 3,700 usage instances, respectively.) We aren’t drawing any major inference from these numbers and the different forms of spinlock API usage; we just wish to point out that using the stronger form of spinlock APIs is quite widespread in the Linux kernel.
Finally, a very brief note on the internal implementation of the spinlock: in terms of under-the-hood internals, the implementation tends to be very arch-specific code, often comprised of atomic machine language instructions that execute very fast on the microprocessor. On the popular x86[_64] architecture, for example, the spinlock ultimately boils down to an atomic test-and-set machine instruction on a member of the spinlock structure (typically implemented via the cmpxchg machine language instruction). On many ARM machines, as we mentioned earlier, it’s often the wfe (Wait For Event, as well as the SetEvent (SEV)) machine instruction at the heart of the implementation. (You will find resources regarding its internal implementation in the Further reading section.) Regardless, as a kernel or driver author, you should only use the exposed APIs (and macros) when using spinlocks.
Using spinlocks – a quick summary
Section titled “Using spinlocks – a quick summary”Let’s quickly summarize spinlocks, API-wise:
- Simplest, lowest overhead: Use the non-irq spinlock primitives,
spin_lock()/spin_unlock(), when protecting critical sections in process context (there are either no hardware interrupts to deal with or there are interrupts but we do not race with them at all; in effect, use this when interrupts don’t come into play or don’t matter).- Also, this form can be used when protecting critical sections between a top-half and bottom-half handler.
- Medium overhead: Use the irq-disabling (as well as kernel preemption disabling) versions,
spin_lock_irq()/spin_unlock_irq(), when hardware interrupts are in play and do matter (here, process and interrupt contexts can “race”; that is, they share global writable data).- Also, you can use the
spin_[un]lock_bh()API pair when protecting critical sections between the process context and bottom half (it internally disables/enables bottom halves on the local core).
- Also, you can use the
- Strongest form, (relatively) high overhead: This is the safest way to use a spinlock. It does the same as the one with medium overhead, except it performs a save-and-restore on the CPU state via the
spin_lock_irqsave()/spin_unlock_irqrestore()API pair, so as to guarantee that, in effect, the previous interrupt mask settings aren’t inadvertently overwritten, which could happen with the previous case.
As we saw earlier, the spinlock – in the sense of “spinning” on the processor it’s running on when awaiting the lock – is impossible on UP (how can you spin on the one CPU that’s available while another thread runs simultaneously on the very same CPU?). Indeed, on UP systems, spinlock APIs become a no-op (unless spinlock debug configs are on); the only real effect of the spinlock APIs here is that they disable (mask) hardware interrupts and kernel preemption on the processor! On SMP (multicore) systems, however, the spinning logic actually comes into play, and thus the locking semantics work as expected.
Hang on – these details should not stress you, budding kernel/driver developer; in fact, the whole point is that you should simply use the spinlock APIs as described and you will never have to worry about UP versus SMP, about kernel preemption and what-not; the details of what is internally done and what isn’t are all hidden by the implementation.
A new feature was added to the 5.8 kernel from the Real-Time Linux (RTL, previously called PREEMPT_RT) project, which deserves a quick mention here: “ local locks.” While the main use case for local locks is for (hard) real-time kernels, they help with non-real-time kernels too, mainly for lock debugging via static analysis, as well as runtime debugging via lockdep (we cover lockdep in the next chapter). Here’s the LWN article on the subject: https://lwn.net/Articles/828477/.
Next, when a thread’s holding an irq-off/preempt-off spinlock, it cannot, by definition, be preempted. This is a thorn in the side for the Linux real-time kernel (RTL); obviously, it needs to be able to guarantee that a lower priority thread is preempted when a higher priority real-time thread becomes runnable, no matter what. With the traditional spinlock, this design is defeated; hence, when RTL is enabled, the spinlock is actually re- implemented as a “ sleeping spinlock ”! This is achieved by substituting the spinlock with an rt-mutex lock, in effect making the critical section sleep-able and thus preemptable. Just something to be aware of.
With this, we complete the section on spinlocks, an extremely common and key lock used within the Linux kernel by virtually all its subsystems, including drivers.
Locking – common mistakes and guidelines
Section titled “Locking – common mistakes and guidelines”To wrap up, a quick reference or summary, if you will, covering the typical common mistakes made when locking, and (with some repetition), locking guidelines. (Note that some of the techniques mentioned here – like lock-free programming – are covered in the following chapter).
Common mistakes
Section titled “Common mistakes”- Not recognizing critical sections:
- “Simple” increments/decrements (of the
i ++ori --type): As we learned in the A classic case – the global i ++ section, these too can be critical sections. In the following chapter, we show optimized and atomic ways to work with them.- “Hey, I’m only reading the shared data”: It’s still a critical section if the two conditions for one are met; not protecting it can result in a dirty or torn read, inconsistent or corrupted data.
- Deadlock: A situation where forward progress is impossible; carefully design your locking schema and follow the well-understood locking rules or guidelines that follow to avoid deadlock. It essentially comes down to these key points:
- Document and always follow the lock-ordering rule. - Don’t attempt to re-acquire a lock you already hold. - Only release a lock that you currently hold.
- Prevent starvation.
- “Simple” increments/decrements (of the
Locking guidelines
Section titled “Locking guidelines”An overall summary on locking guidelines follows:
- In the first place, try your best to avoid locks:
- Now, this does not simply mean: “use no globals.” Instead, you have to figure an overall architecture where, as far as is possible, no writer thread (to shared writable data) can run concurrently with any other read/write access to that data.
- Next, if you are using shared writable data, say within a global structure, try to keep all, or as many (of the integer) members as possible as
refcount_toratomic_t(covered later). - Take into account memory barriers (when required).
- Use lock-free technologies!
- Next, if you are using shared writable data, say within a global structure, try to keep all, or as many (of the integer) members as possible as
- Now, this does not simply mean: “use no globals.” Instead, you have to figure an overall architecture where, as far as is possible, no writer thread (to shared writable data) can run concurrently with any other read/write access to that data.
- If you must use locking, proceed in this order:
- Try to use lock-free technologies:
- Per-CPU variables - RCU
- Where you cannot, use normal locking:
- Mutex: In process context, when the critical section is long-ish, and/or blocking I/O (sleeping) in the critical section is required or can occur
- Spinlock: When working in any atomic context (like interrupt handling), when the critical section is short; must be non-blocking (no sleep allowed) in the critical section. Or, can use it even in process context where there’s no blocking in the critical section.
- If either the mutex or spinlock is fine to use, prefer the spinlock (it not only gets you typically better performance, it also enforces stricter rules within the critical section that must be followed).
-
refcount_tfor integer operations (theatomic_tatomic operators are the older interface for this). - Use the kernel’s RMW bitwise operators when manipulating bits (covered in the following chapter). - reader-writer (spin)locks (going out in favor of RCU).
- Try to use lock-free technologies:
- Always keep in mind lock ordering: Always take locks in the same order; document the order and follow it strictly; this helps with deadlock prevention (the order of releasing the locks doesn’t really matter).
- Lock data, not code:
- Move toward fine(r) granularity locking, where possible.
- There’s (much) more to this point; at a deeper level, it means to design your locking schema by carefully looking at the data structure (or even the member(s) within) you’re protecting, specifying exactly how it will be protected against concurrent access – in effect, using a data-centric approach rather than a code-centric one where you more or less randomly sprinkle around some mutex or spinlocks in the code until it seems to “work.” These ideas, and more, are delved into in this article by Daniel Vetter: Locking Engineering Principles, July 2022: https://blog.ffwll.ch/2022/07/locking-engineering.html).
- Move toward fine(r) granularity locking, where possible.
- Performance is affected by the length of the critical section (the code path between the lock and the unlock); keep it short! (Recall the criticalstat eBPF utility we mentioned earlier; you can use it to check for and report long atomic critical sections as they’re encountered.)
- Prevent starvation.
- Keep cache effects and memory barriers in mind (false sharing and cache line bouncing; covered in the following chapter).
- Use a debug kernel to run all your test cases; with regard to locking, the debug kernel must have “lockdep” enabled; also, locking statistics being enabled can also help pinpoint hotspots (covered in the following chapter).
- Keep your locking schema as simple as possible.
Done.
Solutions
Section titled “Solutions”These small exercises were mentioned in the What is a critical section? section.
Solution to Exercise 2. Again, ask yourself, what exactly constitutes a critical section? It’s when the code path in question both can possibly execute in parallel and works upon shared writable data. So, now, does the code in question (the lines between t1 and t2) fulfill these two pre-conditions? Well, it can run in parallel (as explicitly stated), and it does work on shared writable data (the mydrv variable is shared, as it’s a global variable, thus each and every thread within this code path will work upon that very same memory item in parallel).
So, the answer here is clearly yes, it is indeed a critical section. In other words, it should not be allowed to run without some kind of explicit protection.
Solution to Exercise 3. This one’s interesting; the second condition – does it work upon shared writable data? – is true, but the first condition – can it possibly execute in parallel? – is false. This is because the init and cleanup “methods” (functions) of a kernel module will only ever execute once (thus there are no more possible instances to execute in parallel with). So, this does not constitute a critical section and thus requires no special protection.
Summary
Section titled “Summary”Congratulations on completing this chapter!
Understanding concurrency and its related concerns is absolutely critical for any software professional. In this chapter, you learned key concepts regarding critical sections, the need for exclusive execution within them, and what atomicity and data races really mean. You then learned why we need to be concerned with concurrency while writing code for the Linux OS. After that, we delved into two very common locking technologies that are heavily used in the kernel – mutex locks and spinlocks – in detail. You also learned how to decide which lock to use when. Finally, and again, importantly, learning how to handle concurrency concerns when hardware interrupts (and their possible bottom halves) are in play was covered.
But we aren’t done with kernel concurrency yet! There are many more concepts and technologies we need to learn about, which is just what we will do in the next, and final, chapter of this book. I suggest that you first digest the content of this chapter well by browsing through it, as well as the resources in the Further reading section, and work on the exercises provided, before diving into the last chapter!
Questions
Section titled “Questions”As we conclude, here is a list of questions for you to test your knowledge regarding this chapter’s material: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/questions/ch12_qs_assignments.txt. You will find some of the questions answered in the book’s GitHub repo: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/tree/main/solutions_to_assgn.
Further reading
Section titled “Further reading”To help you delve deeper into the subject with useful materials, we provide a rather detailed list of online references and links (and, at times, even books) in a Further reading document in this book’s GitHub repository. The Further reading document is available here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/Further_Reading.md.