Acknowledge a level-triggered interrupt and a storm that pins one CPU stops. Leave it unacknowledged and the kernel disables the line after 99,900 unhandled out of 100,000.
Learn which context your code runs in: interrupt, softirq, thread or process. That one question tells you what you may call, what can starve you, and where to look when a Linux board misbehaves.
Switch Acknowledge off and watch the counter climb. Then switch to a threaded handler and raise the RT task priority. Then we build everything underneath, one context at a time.
You need a little C and a feel for what an interrupt is (a device tapping the CPU on the shoulder). We build the rest from zero.
Built from primary sources: the Linux kernel source and documentation (docs.kernel.org), the man7.org man pages, OSTEP, Robert Love’s Linux Kernel Development (3rd ed., the CFS era, so read it as history for the scheduler) and Paul McKenney’s perfbook. Full list in the Field Guide.
A model, not a measurement. Illustrative costs: 3 µs per hard interrupt, 20 µs of softirq work per event, 1 µs for a threaded stub plus 15 µs in the thread. The rules are real: the 99,900 of 100,000 test is in kernel/irq/spurious.c, softirqs may run inline for 2 ms at most (kernel/softirq.c), and IRQ threads run as SCHED_FIFO priority 50 (kernel/sched/syscalls.c). Time runs at 0.15 × so you can watch it.
Chapter 0
Read the kernel’s own storm alarm, learn why no scheduler setting can stop it, and see which one line of driver code does
You boot a small Linux board with a new camera attached. Within seconds the fan spins up and your SSH session crawls. You run top and press 1 to see each CPU. One CPU shows 100.0 hi. The other three sit idle. Then dmesg prints two lines:
dmesgirq 47: nobody cared (try booting with the "irqpoll" option)
Disabling IRQ #47
The board calms down at once, and the camera is dead. Something went badly wrong in the first second. To see what, we need three ideas: the interrupt line, the way a level signal behaves, and the kernel’s rule for giving up.
A device such as a camera cannot call a function. It owns one wire into the CPU’s interrupt controller. When it wants attention, it changes that wire. The CPU stops what it is doing and runs a function the driver registered. That function is the interrupt handler. The pause and jump is an interrupt. This lesson says hard interrupt when it needs to be exact, because later chapters meet softer kinds.
A wire can signal in two ways. Think of a doorbell and a porch light. A doorbell gives one ring per press. That is edge-triggered: the signal is the change, from low to high. A porch light stays on until someone switches it off. That is level-triggered: the signal is the state, and it lasts as long as the device wants attention.
To acknowledge (ack) a level interrupt, the handler tells the device to switch the light off. It usually writes to a status register on the device. If the handler skips this, the light stays on.
Follow one unacknowledged interrupt. The line goes high. The CPU enters the handler. The handler returns without touching the device. The kernel tells the interrupt controller the work is finished. The controller looks at the line. It is still high. The CPU enters the handler again, and so on, forever. This is an interrupt storm.
Here is the part that surprises people. The scheduler cannot help. The scheduler picks which task runs next, and it runs between tasks. A hard interrupt arrives on top of whatever runs, even a real-time task at priority 99. The CPU never gets back to the scheduler. Nice values, priorities and time slices all sit above this problem. Only the device’s own wire matters, and the handler is the only code that can fix the wire.
Try it. In the instrument at the top, switch Acknowledge off with a hard handler. Then try the threaded handler. Come back when you have watched the counter.
Every handler returns a value. IRQ_HANDLED means “this device was mine and I served it”. IRQ_NONE means “not mine”. This matters on shared lines, where several drivers listen to one wire and each must say whether it was the cause.
The function note_interrupt() in kernel/irq/spurious.c keeps score. It counts how many interrupts in a row returned IRQ_NONE. After 100,000 interrupts it checks the score. The source comment says it plainly: if 99,900 of the previous 100,000 interrupts have not been handled, the kernel declares the line stuck. It prints irq N: nobody cared, then Disabling IRQ #N, and masks the line. It starts a timer that polls the handlers every HZ/10 jiffies (100 ms at any tick rate) so a slow device is not lost forever.
100,000 interrupts × 3 µs each = 0.30 s (333,333 interrupts per second; illustrative 3 µs)
So a hard storm lasts about a third of a second on this model before the kernel steps in. That is already enough to drop camera frames and stall every task on that CPU.
The grid shows the last 100,000 interrupts, 100 per square. Red squares went unhandled. Drag the unhandled count past 99,900, then stretch the gap between unhandled interrupts past 100 ms.
The thresholds are the kernel’s (kernel/irq/spurious.c): window of 100,000, trip above 99,900, and the unhandled run restarts at 1 when more than HZ/10 passes between unhandled interrupts. The gap slider is a log scale from 1 µs to 1 s; HZ/10 jiffies is always 100 ms.
Look at the gap slider. If unhandled interrupts come slower than one every 100 ms, the count restarts at 1 each time. The detector never trips. The kernel built the rule to catch a stuck wire, and a slow trickle is not a stuck wire.
There is a second kind. A sloppy handler reads a status bit it recognises, does its work, and returns IRQ_HANDLED, but it never clears the source. The kernel sees a handled interrupt every time, so the counter stays at zero. The storm never ends and nothing is printed. Only your measurements show it.
The symptom is a system that crawls with one CPU near 100% in interrupt time. The measurements take one minute. In top, press 1 and read %hi (hardware interrupts) and %si (software interrupts) per CPU. Run watch -d -n1 cat /proc/interrupts and see which row climbs by hundreds of thousands per second. Compare that row with the line number in dmesg.
The fix is in the driver or the wiring, never in the scheduler. Clear the source in the handler with the device’s own register. Check that the trigger type in the device tree matches the hardware: a level signal declared as edge gives one interrupt and then silence, while an edge declared as level can loop (the device tree and device model lesson covers the trigger flags). When the device sits behind a slow bus such as I2C, you cannot clear it from a hard handler, because the bus access sleeps. Use a threaded handler (Chapter 3).
cstatic irqreturn_t cam_irq(int irq, void *dev_id) { struct cam *c = dev_id; u32 st = readl(c->base + CAM_STATUS); /* read why the line is high */ if (!(st & CAM_IRQ_MASK)) return IRQ_NONE; /* shared line: not mine */ writel(st & CAM_IRQ_MASK, c->base + CAM_STATUS); /* ack: switch the light off */ schedule_work(&c->frame_work); /* defer the slow part */ return IRQ_HANDLED; }
CAM_STATUS and CAM_IRQ_MASK name a made-up write-1-to-clear register. Real parts name theirs in the reference manual.
On real hardware. Use any Linux board, for example a Raspberry Pi 5. Run watch -d -n1 'grep -v " 0 " /proc/interrupts | head -20' while you load the system. Note the row with the biggest change per second. That row is your busiest line.
The rest of the lesson answers one question again and again: which context am I in, and what is legal here?
Chapter 1
Follow one request across the line between your program and the kernel, price each step, and learn three ways to cross less often
A robot controller reads a distance sensor through a file. Your code calls read() on /dev/sensor0 ten thousand times per second. Each call asks the kernel for four bytes. Does that waste a lot of CPU? To answer, we need to look at what a call into the kernel really does.
The CPU runs your program in user mode. In this mode the CPU refuses to touch devices or other programs’ memory. The kernel runs in kernel mode, where everything is allowed. This split keeps one buggy program from crashing the machine (see pipeline and privilege for how the hardware enforces it).
A system call (syscall) is the one door between the rooms. Your program cannot jump into kernel code at will. It asks, and the CPU opens the door at one fixed place.
rax on x86-64, x8 on arm64) and the arguments in others. It runs one instruction: syscall on x86-64, svc #0 on arm64.read.Steps 1, 2, 3 and 5 are pure overhead: the price of the door. Step 4 is the work you asked for. For a trivial call such as getpid(), step 4 is almost nothing, so measuring getpid() measures the door itself.
Alexandre Chartre measured it on a 5.10-rc4 kernel and posted the numbers to the kernel mailing list. getpid() took about 0.080 µs (80 ns) with page table isolation off, and 0.20 µs (200 ns) with it on. That is 120 ns more per call, a rise of 150%.
Page table isolation (KPTI) is one of the mitigations against the Meltdown CPU flaw. It switches the page tables at every crossing so user mode cannot even see most kernel memory. Each extra defence lengthens the path. Your numbers will differ with the CPU and the kernel flags. Measure on your board.
10,000 calls per second × 200 ns = 2 ms per second = 0.2% of one CPU
So the sensor loop from the start costs 0.2% of a CPU in door fees. It is fine. The door only hurts when you cross it millions of times per second, or when each crossing also does a slow thing, such as waking a sleeping thread.
The path boxes are sized by cost. Pick how your program asks for N things, switch the Meltdown mitigation on or off, and drag N. The bars compare the three ways.
The 80 ns and 200 ns door costs are Chartre’s getpid() figures (LKML, Nov 2020, kernel 5.10-rc4). The split of the door into steps, the 20 ns vDSO call and the 10 ns to queue one io_uring entry are illustrative.
Skip the door. Some calls need no kernel privilege, only data. The kernel maps a small library, the vDSO, into every process. Calls such as clock_gettime() read a page the kernel keeps updated, and return without crossing. That is why reading the time is cheap.
Batch the crossing. io_uring gives your program two rings of memory shared with the kernel. You write requests into the submission queue (SQ). Each request is a 64 byte entry, the SQE. The kernel writes results into the completion queue (CQ). Each result is a 16 byte CQE (32 bytes if you ask for the big form). One call to io_uring_enter() can submit many requests.
32 syscalls × 200 ns = 6.4 µs against 1 enter × 200 ns + 32 × 10 ns = 0.52 µs
The same 32 requests need 32 × 64 = 2,048 bytes of SQEs and, when they finish, 32 × 16 = 512 bytes of CQEs. The kernel can even poll the queue so no crossing happens at all (the SQPOLL mode, which spends a core).
Do more per call. Read 4 KiB once instead of a byte 4,096 times. This is the oldest trick and still the best one.
Thread-per-connection servers cross the door gently but wake a thread for every packet. With 10,000 threads, the CPU spends its time switching between them. The symptom is high load with little useful work. Measure with vmstat 1 (read the cs column: context switches per second) or perf stat -e context-switches -p PID. The fix is fewer threads and an event loop: epoll, or io_uring. Chapter 8 compares them.
On real hardware. On a Linux board run perf bench syscall basic with the default boot flags and again after rebooting with mitigations=off. Write both numbers on a sticky note. Never ship a product with mitigations off without reading what you give up.
Chapter 2
Learn how Linux picks the next task, why the slice sets latency while the weight sets share, and which class wins when classes disagree
Your board runs a vision job that wants every CPU it can get, and a small control task that wakes ten times per second to nudge a motor. Both are ordinary tasks. The control task sometimes answers 3 ms late. Nothing is overloaded. Who decides that 3 ms, and which knob moves it?
A CPU runs one task at a time, so the kernel must take turns. The part that picks the next task is the scheduler. The simplest fair rule is: whoever has had the least CPU goes next. To apply that rule, the kernel keeps a running total for each task called its virtual runtime (vruntime).
The word “virtual” matters. Time is scaled by importance. A task gets a weight from its nice value. Nice 0 has weight 1024. Nice +5 has 335. Nice +19 has 15. Nice −20 has 88,761. These come from the table sched_prio_to_weight in kernel/sched/core.c. A heavy task’s vruntime grows slowly: it grows by real time × 1024 / weight. So a heavy task can run longer before it looks “used up”.
share(A) = 1024 / (1024 + 335) = 75.3% for nice 0 against nice +5, both always busy
Linux used the Completely Fair Scheduler (CFS) for many years. Kernel 6.6 replaced its pick rule with EEVDF, Earliest Eligible Virtual Deadline First. Kernel 6.12 completed the transition. The name holds the rule. Two questions decide each pick.
Read that again. The weight sets how much CPU a task gets over time. The slice sets how soon it gets a turn. A short slice means an early deadline. So a task with a short slice jumps the queue without taking more CPU in total. The kernel doc says tasks can ask for their own slice with sched_setattr().
Three tasks start with vruntime 0: hog A and hog B with 3 ms slices, and L with a 0.5 ms slice. All weigh 1024. The average vruntime V is 0, so all three are eligible. Deadlines: A is 3, B is 3, L is 0.5. L wins.
L runs 0.5 ms. Its vruntime is now 0.5 and its new deadline is 1.0. The average is (0.5 + 0 + 0) / 3 = 0.17. L’s vruntime is above the average, so L has negative lag and is not eligible. Only A and B qualify. Both have deadline 3. The kernel runs A. L gets its next turn when it wakes again, and the others have caught up.
Two hogs run all the time. Task L wakes every 10 ms for 0.4 ms of work. Set L’s slice and nice, then read how long L waits after each wake. Start with the slice at 3 ms.
A simplified EEVDF: the average is weighted by task weight, a waking task is placed with zero lag, and L preempts at wake only if it would be picked. The weights are the kernel’s table; the three tasks and the 10 ms rhythm are illustrative. Real kernels also track per-CPU run queues, groups and sleeper lag.
Slide L’s slice down to 0.3 ms. Its wait collapses from a few milliseconds to almost nothing, and its share barely moves. Now change only the nice. The wait stays about the same but the shares shift. That is the whole rule: slice for latency, weight for share.
The base slice in kernels 6.6 and 6.12 is 0.75 ms (sysctl_sched_base_slice = 750000 ns in kernel/sched/fair.c). The current development tree lists 0.70 ms. The kernel scales it by 1 + ilog2(ncpus), with the CPU count capped at 8:
0.75 ms × (1 + log2 8) = 0.75 × 4 = 3 ms on 8 or more CPUs
That is the 3 ms in the device. You can read the live value in /sys/kernel/debug/sched/base_slice_ns. The old CFS knobs (sched_latency_ns, min_granularity_ns) are gone, so tuning guides from before 6.6 mislead you. The timer tick rate (CONFIG_HZ of 100, 250 or 1000, with 250 as the default choice in kernel/Kconfig.hz) sets how often the kernel checks whether a slice has ended. A coarse tick makes a slice end late.
Ordinary tasks are only one scheduling class. The kernel keeps a strict order, written in include/asm-generic/vmlinux.lds.h:
stop > deadline > rt > fair > ext > idle
The stop class serves the kernel’s own urgent jobs. Deadline is SCHED_DEADLINE. rt holds SCHED_FIFO and SCHED_RR. fair is EEVDF, for SCHED_OTHER. ext is sched_ext, where a BPF program writes the policy; it arrived in 6.12. idle runs when nothing else can. A higher class always beats a lower one. A runaway SCHED_FIFO task starves every fair task on its CPU, and that is why the RT lesson in this series spends so long on limits (real-time Linux).
The symptom of a latency slip is a control task that answers late at random. Measure with perf sched record then perf sched latency, which lists max wake-up delay per task. The fix, in order: shorten the slice of that task, move it to SCHED_FIFO if it truly needs a bound, or give it its own isolated CPU (Chapter 6).
On real hardware. On any multicore Linux board, start two stress-ng --cpu 1 hogs on one CPU (use taskset -c 2) and a small task that sleeps 10 ms and works 0.4 ms in a loop on the same CPU. Run perf sched record then perf sched latency and read its max delay.
Chapter 3
Split an interrupt into a tiny urgent part and a patient deferred part, and learn which deferred kind may sleep
A network card receives 40,000 packets per second. Each packet needs a checksum, a table lookup and a hand-off to a socket. If the interrupt handler did all of that, the CPU would sit inside the handler for most of every second, and nothing else could run. Linux solves this by cutting the work in two.
A hard interrupt handler runs with its own line masked and arrives on top of whatever was running. While it runs, nothing it interrupted makes progress. So the rule is: do only what cannot wait. Read the status, acknowledge the device, grab the data, and leave. This is the top half.
The slow remainder is the bottom half. The kernel runs it a moment later, with interrupts open again. There are four main ways to defer work. They differ in one question: may it sleep? To sleep means to give up the CPU and wait, as a task does when it blocks on a lock or a disk read.
Code that cannot sleep is in atomic context. The reason is simple. A hard interrupt has no task of its own. If the code tried to sleep, the scheduler would have nothing to put to sleep and nothing to wake later. Code that may sleep is in process context: it belongs to a task.
HI, TIMER, NET_TX, NET_RX, BLOCK, IRQ_POLL, TASKLET, SCHED, HRTIMER, RCU (the enum in include/linux/interrupt.h). Runs in atomic context, fast, and can run on several CPUs at once. Drivers cannot add new kinds.TASKLET softirq. One instance never runs on two CPUs at once, which makes it easy to write. Also atomic.kworker). It runs in process context, so it may sleep, take mutexes and talk to slow buses.request_threaded_irq(). The quick one returns IRQ_WAKE_THREAD. The thread does the rest, in process context. By default the kernel runs it as SCHED_FIFO at priority 50.For a level interrupt, a threaded handler has a trap. The quick function returns before the thread has touched the device. The line is still high. If the kernel unmasked the line, the interrupt would fire again at once. So the flag IRQF_ONESHOT tells the kernel to keep the line masked until the thread finishes. Chapter 0’s storm then becomes slower, and visible as a busy thread in top, but it does not end until the thread acknowledges the device.
When a hard interrupt ends, the kernel checks for pending softirqs and runs them right there, on the way out. That is cheap and keeps latency low. But a busy network could keep the CPU in softirqs forever. So kernel/softirq.c limits the loop: at most 2 ms (MAX_SOFTIRQ_TIME) or 10 restarts (MAX_SOFTIRQ_RESTART). If work is left over, the kernel wakes ksoftirqd/N, one thread per CPU, to finish it as an ordinary task.
That thread is in the fair class. It competes like any process. A busy SCHED_FIFO task on the same CPU starves it, and the queue behind it grows until packets are dropped. This is the trap in mixed real-time and network systems.
1 event × (3 µs hard + 20 µs softirq) = 23 µs → 1 s / 23 µs = 43,478 events per second per CPU
That is the most one CPU can serve if every cycle goes to the device, using the illustrative costs. Above that rate, userspace gets nothing. The device below shows how the load splits.
Left: where one CPU’s time goes. Right: the queue of unserved events over 100 ms. Raise the rate past 25,000, then add the RT hog and switch to the threaded handler.
Illustrative costs, the same as the hero: 3 µs hard, 20 µs softirq work, 1 µs stub plus 15 µs in the thread. Softirq may run inline for at most 40% of the CPU in this model, standing in for the 2 ms rule. The queue limit of 1,000 events is made up.
Look for two lessons in the plot. With the softirq path, ksoftirqd only helps when no RT hog sits on the core. With the threaded path, a hog at priority 60 outranks the IRQ thread at 50, so the thread starves and nothing is served at all. Priorities are a tool you must set on purpose.
You can steer interrupts. Each IRQ has an affinity mask in /proc/irq/N/smp_affinity (or smp_affinity_list). Write a CPU list there to move the top half away from your control core. Read /proc/interrupts to see which CPU takes each line, and /proc/softirqs to see how many NET_RX or TIMER softirqs each CPU ran. In top, the si column and the ksoftirqd row show the pressure. The file /proc/net/softnet_stat counts packets dropped per CPU in its second column.
Calling something that sleeps from atomic context is the classic bug. A mutex lock, a kmalloc(GFP_KERNEL) or an I2C transfer in a hard handler all end in the same message: BUG: scheduling while atomic. With CONFIG_DEBUG_ATOMIC_SLEEP you get the friendlier BUG: sleeping function called from invalid context, printed at the first offence. The fix is to move the work to a workqueue or a threaded handler (see writing the driver).
On real hardware. On any Linux board, run an iperf3 test over Ethernet while you watch watch -d -n1 cat /proc/softirqs. Note which CPU the NET_RX row grows on, then move the NIC’s IRQ with smp_affinity_list and watch it follow.
Chapter 4
Pick the lock that is legal in your context, and see how RCU lets readers run without ever waiting
Two CPUs both want to add a camera frame to a shared list. CPU 1 reads the list head. CPU 2 reads the same head. Each links its frame in front of that head and writes back. One frame vanishes. Nothing crashed, and nothing complained. You need a rule that lets only one of them change the list at a time.
A spinlock is a flag. To take it, a CPU loops (“spins”) until the flag is free, then sets it. It never sleeps. That is exactly why it works in atomic context, such as a hard interrupt handler, where sleeping is illegal. The price is that every waiting CPU burns time, so you hold a spinlock for a few lines only, never across a sleep, an allocation that can block, or a slow device access.
One more trap. If a hard interrupt on the same CPU wants the lock the code already holds, the CPU waits for itself forever. That is a deadlock. So code that shares data with an interrupt handler uses spin_lock_irqsave(), which also turns off local interrupts while the lock is held.
A mutex is a lock whose waiters sleep. A task that fails to take it gives up the CPU and is woken on release. That is kind to the machine when the wait is long. But a sleeping lock can only be taken in process context. A reader-writer lock lets many readers in together but one writer alone. A seqlock goes further: the writer bumps a counter before and after its change, and a reader copies the data, checks that the counter did not move, and retries if it did. Seqlocks fit small values that are read far more often than written, like the system time.
| Primitive | Waiters | Legal in hard IRQ | Best for |
|---|---|---|---|
| spinlock | spin | yes (irqsave form) | short critical sections |
| mutex | sleep | no | long sections in process context |
| seqlock | readers retry | readers yes | small data, many readers |
| RCU | readers never wait | readers yes | read-mostly pointers and lists |
| per-CPU data | none | yes, if preemption is off | counters, scratch buffers |
RCU (read-copy-update) fits a common shape: a pointer to a configuration that many CPUs read all the time and one CPU rarely changes. The trick has three steps.
rcu_read_lock(), follows the pointer, uses the data, and calls rcu_read_unlock(). On many kernels these calls cost almost nothing. The reader never takes a lock and never waits for a writer.rcu_assign_pointer(). New readers see the new copy. Old readers keep using the old one, which stays intact.synchronize_rcu(), which returns after a grace period: every CPU has passed a quiescent state, a moment such as a context switch where it cannot hold an old reference. Only then is kfree(old) safe.c/* reader: any context where sleeping is not needed */ rcu_read_lock(); cfg = rcu_dereference(gcfg); gain = cfg->gain; rcu_read_unlock(); /* writer: rare, process context */ new = kmemdup(old, sizeof(*new), GFP_KERNEL); new->gain = 3; rcu_assign_pointer(gcfg, new); /* publish */ synchronize_rcu(); /* wait for old readers */ kfree(old); /* now safe */
Each lane is a CPU. Teal blocks are readers inside rcu_read_lock. The writer swaps the pointer at the dashed line. The purple bar is the grace period. Make CPU 2’s long section longer and watch the wait grow.
Illustrative reader lengths (a few ms on CPUs 0 and 1). The default stall timeout of 21 s is the kernel’s (CONFIG_RCU_CPU_STALL_TIMEOUT in kernel/rcu/Kconfig.debug). The slider is a log scale from 1 ms to 60 s.
Readers on CPUs 0 and 1 never stop. Only the writer waits. This is why RCU suits hot paths such as routing tables: the common case costs the reader nothing.
Suppose a driver loops in the kernel for 30 s without a context switch, on a kernel built without full preemption. That CPU never reaches a quiescent state. The grace period cannot end. After 21 seconds by default, the kernel prints rcu: INFO: rcu_sched self-detected stall on CPU (the name in the message shows the flavour, such as rcu_preempt). The symptoms: memory that is waiting to be freed piles up, and everything that waits on RCU hangs. Find it with the stall message, which names the stuck CPU and prints its stack. Fix it by adding cond_resched() inside the long loop so it offers the CPU back.
The cheapest lock is none. Give each CPU its own copy of a counter with DEFINE_PER_CPU and bump it with this_cpu_inc(). No two CPUs touch the same memory. A reader sums all copies when it needs a total. One catch: if two CPUs’ counters share a 64 byte cache line, the line bounces between their caches on every write. That is false sharing; the planned caches and coherence lesson in this series covers the cost. Align hot per-CPU data to a cache line.
Take a priority 90 real-time task that waits on a mutex held by a priority 10 task. A priority 50 task keeps preempting the holder. The urgent task is stuck behind the middle one. That is priority inversion. Linux fixes it with priority inheritance: the holder temporarily runs at the waiter’s priority. The kernel’s rt_mutex does this, user programs reach it through priority-inheriting futexes (PTHREAD_PRIO_INHERIT), and the PREEMPT_RT kernel turns most spinlocks into such sleeping locks. A newer idea, proxy execution, lets a blocked task lend its whole scheduling identity to the owner; Phoronix lists optimised donor migration for it among the scheduler changes merged for Linux 7.2.
On real hardware. On a Linux board, build a kernel module or use the kernel’s rcutorture or lockdep options to see messages first hand: with CONFIG_PROVE_LOCKING a wrong lock order prints a dependency chain before it ever deadlocks.
Chapter 5
Choose the right clock, sleep until an absolute time, and find the 50 microseconds the kernel adds on purpose
A helper thread polls a sensor every 1 ms. It calls clock_nanosleep() for 1 ms in a loop. You log how late each wake-up is. Most are 5 µs late. A few are 45 µs late. The pattern looks random. No other task is running. Is the hardware broken?
It is not. The kernel is late on purpose. To see why, we need two things: what a kernel timer is, and what a clock is.
The old way is the tick. The kernel sets a hardware timer to fire at a fixed rate, HZ times per second, and counts the ticks in a variable called jiffies. A timer built on this can only be as exact as one tick: 4 ms at HZ=250.
The modern way is the high resolution timer (hrtimer). The kernel stores timers in a sorted tree by expiry time in nanoseconds. It programs the CPU’s timer hardware for the nearest one only. When that fires, the kernel runs everything due, and programs the next. nanosleep() and clock_nanosleep() sit on hrtimers.
A clock id says what the time means. The four you meet most:
Different clocks tick at slightly different rates, and sensors may have their own. The series treats clock domains in a separate lesson, so here we keep to the kernel side: pick MONOTONIC for anything that measures a duration.
A loop that sleeps for 10 ms after each 0.3 ms of work runs every 10.3 ms. After 1,000 iterations it is 300 ms behind its plan. The error adds up. The fix is to sleep until an absolute time and add the period each round.
cstruct timespec next; clock_gettime(CLOCK_MONOTONIC, &next); for (;;) { next.tv_nsec += 10000000; /* + 10 ms */ if (next.tv_nsec >= 1000000000) { next.tv_nsec -= 1000000000; next.tv_sec++; } clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &next, NULL); do_work(); /* 0.3 ms: the next wake-up does not move */ }
Waking the CPU costs power. If ten timers expire a few microseconds apart, ten wake-ups waste energy. So the kernel lets each ordinary timer fire a little late, so it can ride along with another event. Each hrtimer has a soft expiry (the time you asked for) and a hard expiry (soft plus timer slack). The timer may fire anywhere in between, whenever the hardware fires for some other reason. If nothing else fires, it goes off at the hard expiry.
The default slack is 50 µs for ordinary threads. The man page for prctl(PR_SET_TIMERSLACK) says the init process starts with 50,000 ns, and new threads inherit their creator’s value. Threads under a real-time policy get no slack at all: the man page says it is not applied to them.
You can see the mechanism in the source. In kernel/time/hrtimer.c, the sleep path calls hrtimer_set_expires_range_ns(&t.timer, rqtp, current->timer_slack_ns). The range is the time you asked for, plus the calling thread’s slack. So every nanosleep() a thread makes carries its slack with it. A tick-based timer at HZ=250 would round a 1 ms request up to the next 4 ms tick. An hrtimer keeps the 1 ms and adds at most the slack.
The histogram shows how late 600 wake-ups of a 1 ms timer are, in 5 microsecond bins. Other timers in the system fire about every 125 microseconds. Set the slack to 50, then to 1, then switch to an RT thread.
A model. The 50 µs default and the exemption for real-time threads come from the prctl(2) man page. The 125 µs mean gap between other timer events, and the 2 to 8 µs of interrupt and wake-up cost, are illustrative. Each wake-up lands at the first other event inside the slack window, or at the end of the window.
With slack 50, wake-ups spread between 4 and 50 µs late, and none after 50 plus the wake-up cost. With slack 1 they bunch near the wake-up cost. The lateness never exceeded the slack. That is the guarantee.
The symptom is a normal thread that wakes up to 50 µs late “at random”. Measure it: read CLOCK_MONOTONIC before and after each sleep, subtract the target, and print a histogram. If the maximum sits near 50 µs plus a few, slack is the cause. Fix it per thread with prctl(PR_SET_TIMERSLACK, 1). Passing 0 does not mean zero: it resets to the default, so use 1 ns as the smallest value. Do not turn it down on every thread of a battery device; you pay in wake-ups.
On real hardware. On any Linux board, write the loop above with a histogram of lateness, run it with the default slack and again after the prctl call. Then set the thread to SCHED_FIFO with chrt -f 50 and compare.
Chapter 6
Separate what a process can see from what it can use, then clear every source of noise off the one core that must stay quiet
Your robot runs a vision container and a control loop on the same four-core board. The vision job works in bursts. Every few seconds the camera pipeline drops a frame for no reason you can find, even though the average CPU use looks low. Meanwhile the control loop, pinned to core 3, still shows 80 µs hiccups. Two problems with two different causes, both about isolation.
Linux splits “isolation” into two questions. Namespaces decide what a process can see. A process in its own PID namespace sees only its own processes. In its own network namespace, only its own interfaces. There are namespaces for mounts, hostnames, users, IPC and more. Control groups (cgroups) decide what a process can use: CPU, memory, I/O. A container is a process with both. Neither one makes a process faster or more predictable; they only fence it.
You can try the fence by hand. The command unshare --pid --fork --mount-proc bash starts a shell in new PID and mount namespaces, and ps there shows only that shell and its children. Notice what did not change. The shell still runs on the same kernel, the same scheduler and the same timer tick as everything else. That shared kernel is the reason this chapter does not stop at containers. A fence tells a process what exists. It does not clear noise away from a core.
In cgroup v2 the file cpu.max holds two numbers, $MAX $PERIOD, both in microseconds. The group may use up to MAX of CPU time in each PERIOD. The kernel doc gives the default as max 100000: no limit, and a period of 100,000 µs, which is 100 ms.
The quota works like a bucket that refills at the start of every period. When the bucket empties, the group stops until the next refill. That stop is throttling. Counters in cpu.stat record it: nr_periods, nr_throttled and throttled_usec.
Now the sharp edge. Set 50000 100000: half a CPU. A task that averages 40% sounds safe. But if it needs 80 ms of CPU at the start of a period, it runs 50 ms, empties the bucket, and sits frozen for 50 ms. Four busy threads empty it in 12.5 ms. The averages look fine. The stall is real.
80 ms of work, quota 50 ms per 100 ms: 50 ms run + 50 ms frozen + 30 ms run = 130 ms against 80 ms with no limit
The teal blocks run, the red blocks are throttled. A burst of CPU work starts at time zero. Change the number of busy threads and the period. Watch nr_throttled.
The bucket rule is the cgroup v2 cpu.max rule (the quota is half a CPU in both periods). The thread counts and the burst size are illustrative. Real throttling hands out quota in small slices per CPU, which adds more noise than this model shows.
The shorter period still allows 50% of a CPU, but it cuts each freeze from up to 50 ms to under 10 ms. The fixes, in order of effort: a larger quota, a shorter period, cpu.max.burst to bank unused quota, or a cpuset that gives the group whole cores instead of a quota. Writing isolated to cpuset.cpus.partition makes a partition root without load balancing, and unlike the boot option you can change it at run time.
Now the control loop on core 3. The boot option isolcpus=3 sounds like the answer. By default it applies the domain flag: the scheduler stops balancing ordinary tasks onto that core. That removes other tasks. But the core still takes the periodic scheduler tick (a timer interrupt, 1,000 per second at HZ=1000), runs RCU callbacks, serves any device IRQ routed to it, and hosts per-CPU kernel threads and work items.
Each leftover source needs its own switch:
nohz_full=3 stops the tick whenever one task runs there. The kernel doc notes that a residual 1 Hz tick stays and is handed to workqueues, so point those at the housekeeping cores.rcu_nocbs=3 moves them to threads on other cores. nohz_full already implies it.irqaffinity=0-2 at boot, or write each line’s smp_affinity from Chapter 3./sys/devices/virtual/workqueue/cpumask, and keep kernel threads off the core.Each bar is one noise source on core 3, in events per second. Switch the options on one at a time and watch the total. The read-out names what is left.
Illustrative rates for a busy four-core board at HZ=1000: tick 1,000 per second, foreign tasks 40, RCU callbacks 300, device IRQs 1,200, kernel work 60. What each option removes follows the kernel docs (kernel-parameters.txt, no_hz.rst). Real numbers depend on your load.
Prove it with measurement, not hope. Watch the timer row of /proc/interrupts for core 3, or use the kernel’s osnoise tracer, which runs a loop and reports every interruption it suffers. Remember: the tracer is the judge, not the boot line.
On real hardware. On a four-core Linux board, add the boot options one by one, reboot, and read the timer-interrupt row for core 3 in /proc/interrupts over ten seconds each time.
Chapter 7
Learn why Linux says yes to memory it does not have, who it kills when the bill arrives, and why a feature meant to speed memory up can stall a real-time loop
A 4 GB board runs a vision app and a model server. At some point the log says Out of memory: Killed process 812 (inference). The kill was not a crash. The kernel chose a victim on purpose. Later, a different symptom: the control loop stalls 3 ms, once in a while, and no other task is running. Both come from how Linux hands out memory.
When a program asks for memory with malloc(), Linux usually agrees without finding any RAM. It gives the program a range of virtual addresses and a promise. Real memory is attached on the first touch. The CPU raises a page fault, and the kernel picks a free page (a 4 KiB block) and maps it. The lesson on virtual memory and DMA (planned for this series) shows the table behind this.
This is overcommit. It is useful because most programs ask for more than they use. It is dangerous because the bill comes late. Several programs may each touch their pages at a time when RAM is already full.
The kernel first reclaims what it can: it drops clean file cache, writes back dirty pages, and swaps out cold pages if swap exists. If that does not free enough, it runs the OOM killer. It scores each process, mostly by how much memory it uses, adjusted by /proc/PID/oom_score_adj (a number from −1000 to +1000), and kills the highest score. You can protect a critical process with a low adjustment, or put a group in a cgroup with memory.max so the kill stays inside the group.
Small boards often have no disk swap. zram makes a block device that lives in RAM and stores its pages compressed. Using it as swap trades CPU time for capacity. zswap is a compressed cache in front of a real swap device.
The bar is a 4 GB board. The kernel and its caches need part of it. Drag the apps’ demand upward and switch zram on.
Illustrative: 4 GB of RAM, 0.5 GB for the kernel and unreclaimable data, a compression ratio of 2:1 (real ratios depend on the data). The OOM killer rule and the oom_score_adj range are the kernel’s.
The CPU translates every address through a table, and a small cache called the TLB holds recent answers. With 4 KiB pages, a big working set misses the TLB often. Transparent huge pages (THP) let the kernel use 2 MiB pages without the program asking. One 2 MiB page covers 512 normal pages, so the TLB misses less. That sounds like a pure win.
The catch: a huge page needs 2 MiB of contiguous physical memory, and after a long uptime memory is chopped into pieces. When the kernel cannot find a block, it may run compaction: it copies pages around to make room, while your thread waits in the page fault. The kernel doc says it plainly: compact_stall in /proc/vmstat is incremented every time a process stalls to run memory compaction so a huge page is free. Moving up to 512 pages is millisecond work.
2 MiB / 4 KiB = 512 pages to move · 2 MiB at 2 GB/s ≈ 1 ms of copying alone (illustrative speed)
The setting lives in /sys/kernel/mm/transparent_hugepage/enabled: always, madvise (only regions the program marks with madvise(MADV_HUGEPAGE)) or never. A second file, defrag, decides how hard the kernel works to find a block: with always the faulting thread stalls and compacts directly.
Each tick is the stall one thread sees when it first touches a fresh 2 MiB region. Raise the fragmentation, then switch the setting from never to always.
A model with seeded random stalls. Stall time between 0.5 and 4 ms per compaction, a huge-page fault of about 0.1 ms and a normal fault of 0.002 ms are illustrative. The counters compact_stall and thp_fault_fallback are real /proc/vmstat fields.
The symptom is a rare, millisecond-sized stall in a thread that only touches memory. Measure by sampling /proc/vmstat before and after the stall and checking whether compact_stall moved. The fix is not “THP is bad”. Use madvise mode and mark only the big buffers that benefit, or never on a real-time system. Real-time programs also call mlockall(MCL_CURRENT | MCL_FUTURE) and touch their memory at start-up, so page faults happen before the loop begins.
Some devices need physically contiguous buffers, such as a camera that writes a whole frame by DMA. After a few days of uptime, finding such a block by chance fails. The contiguous memory allocator (CMA) sets a region aside at boot. Ordinary movable pages may live there meanwhile, and the kernel moves them out when a device asks. If a page there is pinned, the move waits or fails. The DMA lesson (PCIe, DMA and the accelerator driver) uses this.
On real hardware. On a Linux board, run grep -E 'compact_stall|thp_fault_fallback' /proc/vmstat, run your workload for a minute, and run it again. If compact_stall grew, find the process with perf trace -F all or by testing with THP set to never.
Chapter 8
Follow a write() down through the cache, the block layer and the drive, and learn the three calls that make it survive a power cut
A robot saves its calibration file. The code calls write(), checks that it returned the right byte count, and moves on. Then a battery pull cuts the power. On the next boot the file exists, and it is empty. The call succeeded. Where did the data go?
Follow the bytes down. Each layer has one job.
write() works on ext4, a network share or a RAM disk.write() returns. This is the step that makes it fast. It is also the step that lies about safety: nothing has reached the drive.blk-mq (multi-queue). It keeps a request queue per CPU, merges neighbours and feeds the drive’s hardware queues.Dirty pages are written out by kernel flusher threads. The usual defaults are tunable in /proc/sys/vm: a flusher wakes every 5 s (dirty_writeback_centisecs = 500), and data older than 30 s (dirty_expire_centisecs = 3000) is written. So a plain write() may sit in RAM for tens of seconds. Filesystems are the topic of building the image; here we only need the shape of the path.
fsync(). fsync(fd) does not return until the kernel has pushed the file’s data and metadata to the device and asked the device to flush its own cache. After it returns, the bytes survive a power cut. It is slow on purpose: it is a trip to the flash.
The block layer has a policy too. Each drive offers a small set of I/O schedulers, which you can list in /sys/block/<device>/queue/scheduler; fast drives often use none and let the hardware queues do the work, while slower ones may use mq-deadline to bound how long a request waits. For a robot with a microSD card this choice matters less than the habit of calling fsync only where durability needs it, because each call waits for the card’s slowest operation.
Write a new file, then rename. If you open an existing file with truncate and then write, there is a window where the old content is gone and the new content is not on disk yet. That window produced the empty file above. The safe pattern is four steps:
cfd = open("calib.tmp", O_WRONLY | O_CREAT | O_TRUNC, 0644); write(fd, buf, len); fsync(fd); /* 1. the bytes are on the device */ close(fd); rename("calib.tmp", "calib.json"); /* 2. atomic: old or new, never half */ dfd = open(".", O_RDONLY | O_DIRECTORY); fsync(dfd); /* 3. the rename itself is durable */
Skip the cache on purpose. O_DIRECT sends data around the page cache. It needs aligned buffers and sizes, and it does not by itself promise the drive flushed its cache. Databases use it because they run their own cache.
Pick how the program saves, then drag the time of the power cut. Each layer lights when it holds the new data. The read-out says what the file looks like after reboot.
The time axis is logarithmic, from 1 ms to 40 s. The 5 s and 30 s writeback defaults are the usual Linux values; the 3 ms fsync cost and the drive’s behaviour are illustrative, and real filesystems differ in what they promise after a crash.
Slide the cut to 100 ms with plain write(). The truncate can already be in the journal while the new bytes are still in RAM. The file comes back empty. Switch to the rename pattern: at any cut time you see either the old file or the complete new one.
How does a server wait for many sockets? epoll tells you which descriptors are ready. Then you call read() or recv() on each, one syscall per operation. io_uring (Chapter 1) reverses it: you submit the operation, and the kernel reports the finished result. That removes one crossing per operation and lets many run at once.
It also enabled zero-copy network paths. IORING_OP_SEND_ZC sends from your buffer without a copy and arrived with Linux 6.0. Zero-copy receive, IORING_OP_RECV_ZC, was merged for Linux 6.15; the kernel doc stresses that the NIC must be set up separately, because the kernel API does not configure the hardware.
The symptom of mixing these up is a latency spike every few seconds under load: the flusher threads finally write a lot of dirty data at once, and a slow fsync waits behind them. Measure with vmstat 1 (columns bo, wa), and grep Dirty /proc/meminfo. Fix by calling fsync at the right moments, not by tuning the flusher alone.
On real hardware. On a Linux board with a microSD card, time write() of 1 MiB against write() plus fsync() with strace -T. Expect the second to take far longer. Record both numbers.
Chapter 9
Keep the context rule, the numbers and the checklist, then take the scheduler home as thirty lines of code
You can now answer, for any Linux symptom, the question this lesson kept asking: which context am I in, and what is legal here? A stuck interrupt line is a wire the handler never switched off. A syscall is a door with a price. A task’s turn comes from its weight, its slice and its class. An interrupt splits into a tiny top half and a deferred bottom half. Locks must match the context. Clocks and timers carry slack. Isolation needs every noise source moved. Memory is a promise. A write() is a request to the cache.
Choose the context you are in. Then read which primitives it allows and why the others fail.
Pick a context. Its column lights up. Tap any cell to hear why it is legal or not.
The matrix follows the kernel rules for sleeping in atomic context (BUG: scheduling while atomic, CONFIG_DEBUG_ATOMIC_SLEEP) and classic RCU read-side sections. With PREEMPT_RT, spinlocks become sleeping locks and some rows change.
| What | Number | Where it comes from |
|---|---|---|
| Storm detector | over 99,900 unhandled of 100,000; run restarts if the gap exceeds HZ/10 (100 ms) | kernel/irq/spurious.c |
| getpid() | about 80 ns without KPTI, about 200 ns with it | LKML, Nov 2020, kernel 5.10-rc4, one machine |
| io_uring entries | SQE 64 B, CQE 16 B (32 B with CQE32) | include/uapi/linux/io_uring.h |
| Zero-copy io_uring | send since 6.0, receive since 6.15 | io_uring pulls; Phoronix |
| EEVDF | introduced 6.6, completed 6.12; base slice 0.75 ms (6.6, 6.12), 0.70 ms in the 7.4-rc1 tree; times 1 + log2(CPUs up to 8), so 3 ms at 8 CPUs | kernel/sched/fair.c; KernelNewbies |
| Nice weights | nice 0 = 1024, +5 = 335, +19 = 15, −20 = 88,761 | kernel/sched/core.c |
| Class order | stop > deadline > rt > fair > ext > idle | include/asm-generic/vmlinux.lds.h |
| Softirq limits | 10 kinds; inline for at most 2 ms or 10 restarts, then ksoftirqd | interrupt.h; softirq.c |
| IRQ thread | SCHED_FIFO priority 50 | kernel/sched/syscalls.c |
| RCU stall warning | 21 s by default (range 3 to 300) | kernel/rcu/Kconfig.debug |
| Timer slack | 50 µs default; not applied to real-time threads; 0 resets to default | prctl(2) man page |
| cgroup CPU quota | default “max 100000”, a 100 ms period | cgroup-v2.rst |
| Huge page | 2 MiB = 512 normal pages; compact_stall counts stalls | transhuge.rst |
| Writeback defaults | flusher every 5 s, data older than 30 s written | vm sysctl defaults |
| Mainline milestones | 6.12: sched_ext and PREEMPT_RT. 7.0 (2026-04-12): Clang capability analysis, io_uring filters. 7.2 (2026-08-16): cache-aware scheduling, proxy-execution donor migration | KernelNewbies; Linux Journal; Phoronix |
This is the whole pick rule of Chapter 2 as a small program. It ignores groups, sleeper lag and many details. Run it on paper with three tasks.
cstruct task { double w, slice, v, d; int runnable; }; /* weight, slice (ms), vruntime, deadline */ static double avg_v(struct task *t, int n) { /* V: weighted mean of vruntime */ double sw = 0, sv = 0; for (int i = 0; i < n; i++) if (t[i].runnable) { sw += t[i].w; sv += t[i].w * t[i].v; } return sw ? sv / sw : 0; } static int pick(struct task *t, int n) { /* earliest deadline among the eligible */ double V = avg_v(t, n); int best = -1; for (int i = 0; i < n; i++) { if (!t[i].runnable || t[i].v > V) continue; /* lag < 0: not eligible */ if (best < 0 || t[i].d < t[best].d) best = i; } return best; } static void run(struct task *x, double dt_ms) { /* charge virtual time by weight */ x->v += dt_ms * 1024.0 / x->w; if (x->v >= x->d) x->d = x->v + x->slice * 1024.0 / x->w; /* slice used: new deadline */ }
/proc/interrupts, find the climbing row, fix the acknowledge or the trigger type.perf bench syscall basic.perf sched latency. Do not assume CFS knobs after 6.6.CONFIG_DEBUG_ATOMIC_SLEEP in development.cond_resched(). Watch for RCU stall messages.CLOCK_MONOTONIC.nr_throttled in cpu.stat; widen the quota or shorten the period.compact_stall; use madvise or never, and lock memory.This lesson is the kernel side of the platform story. The firmware side (reset, vectors, interrupts and DMA on a microcontroller) starts at reset to main and interrupts and DMA. The same ideas, minus the operating system, appear in RTOS basics and real-time systems. For the Linux platform, continue with embedded Linux, writing the driver, the accelerator driver and building the image. Bounds and guarantees come next in real-time Linux, with robot-side views in real-time performance and sensor and actuator integration. Systems C in the kernel style is in advanced C, and a first overview of the field is embedded systems. Filtering sensor streams that these timings feed is the Kalman filter lesson.
No course slides were used. Every number above comes from a source opened for this lesson: the Linux kernel source tree (torvalds/linux: kernel/irq/spurious.c, kernel/sched/fair.c, kernel/sched/core.c, kernel/softirq.c, include/linux/interrupt.h, include/uapi/linux/io_uring.h, include/asm-generic/vmlinux.lds.h), the EEVDF doc, cgroup v2, transparent hugepages, the kernel-parameters file for isolcpus and nohz_full, the PR_SET_TIMERSLACK man page, Alexandre Chartre’s page table isolation measurements, KernelNewbies 6.12, 7.0, Phoronix on io_uring zero-copy receive, Phoronix on the 7.2 scheduler and Linux Journal on 7.2. Background reading: OSTEP (scheduling and concurrency chapters), Robert Love, Linux Kernel Development 3rd ed. (the CFS era, so use it for structure and read its scheduler chapter as history), and Paul McKenney, Is Parallel Programming Hard. The devices are models, and each says which numbers are illustrative.
Now press Present or Teach and explain, from memory, why an unacknowledged level interrupt beats every scheduler setting. Then go back to the interrupt line at the top and break it again.