Your interrupt handler asks an I2C sensor for a reading, and the kernel stops with BUG: scheduling while atomic. Move the read into a threaded handler and it works.
Learn how a Linux driver for a chip that did not exist yesterday is put together: which code may sleep, how the kernel finds your device, and how to debug the crash when you get it wrong.
Switch on Read the sensor over I2C with the plain handler. Read the BUG banner. Then pick the threaded handler and raise the interrupt rate. Then we build, piece by piece, the whole driver.
You need a little C and a picture of an interrupt (a signal that makes the processor stop its work and run a short function). We build the rest from zero.
Built from primary sources: the Linux kernel documentation on interrupts, devres, the DMA API and IIO. The full list is in the Field Guide.
A model, not a kernel. The read is a 2-byte register read of about 48 I2C clock pulses; the 2 µs hard-handler time and the 30 µs thread wake-up are illustrative. Arrival gaps are random (seeded, 600 interrupts) so the histogram is the same on every visit.
Chapter 0
See why the kernel kills a handler that waits on an I2C sensor, and which tool lets the same work run safely
Dana has a new temperature chip on her board. We call it the ACME-T1, an invented part, so no datasheet applies. The chip sits on an I2C bus, a two-wire bus where a controller sends a device address and a register number and the device answers with bytes. When a new reading is ready, the chip pulls a separate wire low. That wire is an interrupt line.
Dana writes the obvious code. When the interrupt fires, a function asks the chip for the reading. She boots the board. The first reading arrives, and the console prints BUG: scheduling while atomic. The board may freeze or carry on in a damaged state.
Her code is correct C. The mistake is about where it runs. This whole lesson is about that question, and the hero at the top of the page is the experiment. Go back and try it once more now that you know what to look for.
The kernel runs your code in one of two main settings. It calls each setting a context. Think of a restaurant. In process context, a waiter is serving one table. If the kitchen is slow, the waiter can step aside and serve another table. The kernel calls this step sleeping: the scheduler parks your code and runs something else until the thing you wait for is ready.
In hard interrupt context (also called atomic context), the doorbell has just rung. The kernel has stopped whatever was running and called your handler on top of it. There is no table of your own to leave. Nobody stored a place to come back to. If the handler goes to sleep, the scheduler has no safe way to resume it, and the interrupted task is stuck underneath.
So there is one rule. Code in hard interrupt context must be short and must never sleep. The docs describe a hard handler as one that checks whether the device raised the interrupt, quiets the device, and returns. The scheduler guards the rule. If code calls schedule() from an atomic section, it prints BUG: scheduling while atomic.
The I2C subsystem is the part of Linux that talks over I2C. Its function i2c_transfer() sends messages and returns when the bus is done. The bus is slow. The controller clocks out one bit per tick, and the CPU has better things to do, so the I2C core waits on a lock and then waits for the controller to report the end. It sleeps for both. SPI transfers work the same way. Any sensor driver on I2C or SPI has this problem.
How long is the wait? Count the clock pulses. I2C sends every byte as 8 data bits plus 1 acknowledge bit, so 9 clock pulses per byte (NXP UM10204). A 2-byte register read sends the device address with the write flag (9), the register number (9), a repeated start, the address with the read flag (9), and two data bytes (18). That is 45 pulses. Add roughly 3 for the start, repeated start and stop conditions. The total is about 48 pulses.
48 pulses ÷ 400,000 pulses per second = 120 µs | 48 ÷ 100,000 = 480 µs
A hard handler should take a few microseconds. The read takes 120 to 480 µs, tens to hundreds of times longer. Try other sizes on the bar below.
Bars on a log scale: each gridline is ten times the last. Warm is the hard handler. Blue is the I2C read of the number of bytes you choose. Drag the bytes and change the bus speed.
Arithmetic: 30 + 9n clock pulses for an n-byte register read (three address bytes at 9 pulses each, n data bytes at 9 each, about 3 for start, repeated start and stop). The 2 µs handler time is illustrative. Real controllers add driver overhead on top.
The kernel gives you a tool for this: request_threaded_irq(). You hand it two functions. The first, the hard handler, runs in interrupt context. It does the minimum and returns the value IRQ_WAKE_THREAD. The second, the thread function, runs in a kernel thread (a kthread, a process-like worker that lives inside the kernel). The thread is allowed to sleep, so it can call i2c_transfer().
The docs state the split plainly: the handler checks that the device raised the interrupt, disables the interrupt on the device, and returns IRQ_WAKE_THREAD. Most sensor drivers pass no hard handler at all. The kernel then uses a default one that only wakes the thread, and it demands the flag IRQF_ONESHOT. The flag keeps the interrupt line masked until the thread finishes, so a level-triggered line does not storm while the thread works.
c/* WRONG: the handler runs in hard IRQ context, but the read sleeps */ static irqreturn_t acme_irq(int irq, void *dev_id) { struct acme_dev *d = dev_id; acme_read_temp(d); /* i2c_transfer() inside: BUG */ return IRQ_HANDLED; } ret = devm_request_irq(dev, irq, acme_irq, 0, "acme", d); /* RIGHT: the read moves to a thread that may sleep */ static irqreturn_t acme_thread(int irq, void *dev_id) { struct acme_dev *d = dev_id; acme_read_temp(d); /* sleeping is fine here */ return IRQ_HANDLED; } ret = devm_request_threaded_irq(dev, irq, NULL, acme_thread, IRQF_ONESHOT, "acme", d);
The cost shows in the hero. The thread adds a wake-up delay and queues reads one after another. The histogram is that delay made visible. When interrupts arrive faster than one read per 120 µs, the queue grows without bound. At 400 kHz that limit is 1 ÷ 120 µs, or about 8,333 interrupts per second. At 100 kHz it is about 2,083.
Symptom. The console prints a stack trace that ends in your handler. The trace names schedule and i2c_transfer above it. The first line reads BUG: scheduling while atomic. Measurement. Build development kernels with CONFIG_DEBUG_ATOMIC_SLEEP. It makes every function that might sleep check its context first, so a bad call is caught even when the call would not actually have slept. The report then reads BUG: sleeping function called from invalid context. Fix. Move the sleeping call into a thread function, or into a workqueue (a queue of jobs run by kernel threads; Chapter 6).
This rule also explains the board you meet in real-time Linux: a real-time kernel runs most handlers as threads for exactly this reason. For the electrical side of I2C, see buses on the wire. For how a firmware interrupt differs, see interrupts and DMA.
/dev.Chapter 1
Find where a driver lives in the source tree, build it as a module, and read the error when the kernel refuses to load it
Dana fixes her handler. She builds the driver on her laptop, copies acme.ko to the board and types insmod acme.ko. The shell answers Invalid module format. Nothing is wrong with her code. The kernel on the board simply does not trust a file built for a different kernel.
To see why, you need two things: a map of the source tree, and a picture of how a module is built. Both are short.
The Linux source is one very large tree, and four folders matter most for driver work. arch/ holds code that is specific to a CPU family, such as arch/arm64. kernel/ holds the core: the scheduler, the interrupt layer, time. mm/ holds memory management. drivers/ holds the rest, and it is by far the biggest folder.
Inside drivers/, each kind of device has a folder. I2C controllers live in drivers/i2c. Sensors that fit the Industrial I/O framework live in drivers/iio, and temperature chips sit in drivers/iio/temperature. GPIO chips live in drivers/gpio. When you write a driver for the ACME-T1, you first find the framework that matches the device, then put your file in that framework's folder. Chapter 3 explains why IIO is the match.
The kernel has thousands of options. Each one is a Kconfig symbol, and it has one of three values. y builds the code into the kernel image. m builds it as a separate module, a file ending in .ko that you load later. n leaves it out. Your choices are stored in a file named .config.
You rarely write .config by hand. You start from a defconfig, a small ready-made set of choices for one board, with make defconfig. Then you run make menuconfig, a text menu where you toggle options. Each driver adds its own entry in a file named Kconfig. A sibling file named Makefile (read by the build system, Kbuild) says which source files belong to the entry.
kconfig + kbuild# drivers/iio/temperature/Kconfig config ACME_T1 tristate "ACME-T1 temperature sensor" # tristate = y, m or n depends on I2C select REGMAP_I2C # drivers/iio/temperature/Makefile obj-$(CONFIG_ACME_T1) += acme_t1.o # becomes obj-m when the value is m # Out-of-tree Makefile, next to acme_t1.c obj-m := acme_t1.o all: $(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
The last two lines are the out-of-tree recipe from the kernel's own documentation. -C tells make to run inside the kernel build directory. M=$(PWD) says that an external module lives in the current folder. The build directory holds the headers and the configuration of one particular kernel, so the module is built for that kernel.
At the end of the build, the tool modpost stamps a string into the module. It is called the vermagic (version magic). It holds the kernel release and a list of the options that change the shape of kernel data, such as SMP, preempt, mod_unload and the CPU architecture. When you run insmod, the kernel compares the stamp with its own. A mismatch ends the load with Invalid module format, and dmesg prints both strings.
The kernel is strict because a module is not an application. It runs inside the kernel with full privilege and reads the kernel's structures directly. A struct with a different layout turns a field read into garbage. A related guard, CONFIG_MODVERSIONS, stores a checksum of every function the module uses in Module.symvers as a simple check of binary compatibility. A kernel can also be set to refuse a module that carries no signature from the build's key.
There is a deeper reason behind this strictness. Linux does not promise a stable interface inside the kernel. Kernel developers change a function or a struct whenever the change makes the whole tree better, and they fix every in-tree user in the same patch. A driver inside the tree is fixed for free. A driver outside the tree is not, and the vermagic check is the first alarm that tells you so. Chapter 9 returns to this cost.
You can check the stamp before you copy the file: modinfo acme_t1.ko | grep vermagic on the laptop, and uname -r on the board. The release must match. Then try the device below, which uses invented strings in the real format.
The board runs the kernel in blue. Choose what you built against. Pink tokens that differ show in red, and the loader decides.
The strings are invented to show the real format (release, then option tokens, then architecture). Real vermagic strings carry more tokens. The check itself is a plain string comparison in the module loader.
The fix is always the same. Build against the exact tree and .config that produced the running kernel. On a board that you cross-compile for, pass the architecture and the cross compiler: make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- -C ~/board-kernel M=$PWD modules. Keep that tree around. It is part of your product.
The failure shows up in three stages. Symptom: insmod prints Invalid module format. Measurement: dmesg | tail names both version strings. Fix: rebuild against the matching tree. Never use a force flag on a product, because it hides the mismatch and keeps the bad struct layout. See embedded Linux for the board side of this story and the device tree and the device model for how the kernel then finds your device.
Chapter 2
Follow one read() call from a program into your driver, and copy the bytes across the user and kernel boundary without lying about it
The IIO framework serves Dana's sensor to tools that know IIO. A teammate has a camera-calibration program that wants a plain stream: open a file, read 64 bytes, repeat. She needs a file in /dev that her driver feeds. That file is a character device: a device that moves a stream of bytes, with no fixed block size and no seeking required.
Everything starts with one idea. A program does not call your driver. It calls the kernel, with a system call such as read. The kernel looks at which file the program holds, finds your driver behind it, and calls your function. This chapter follows that path and shows the one rule that keeps it safe.
Each device file has a pair of numbers, the major and minor. The kernel keeps a table that maps them to a struct cdev, which points to a struct file_operations, a table of function pointers: .open, .read, .write, .unlocked_ioctl, .poll, .mmap, .release. When the program calls read(fd, buf, 64), the kernel's file layer (the VFS, virtual file system) calls your .read(file, buf, 64, &pos).
To set this up you pick a device number, fill a cdev and a file_operations, call cdev_add(), and ask for a node in /dev. If your device needs just one node and nothing special, there is a shortcut: a misc device. You fill a struct miscdevice with a name and the operations table and call misc_register(). The kernel picks the numbers and creates the node. For most single-node drivers, that is enough.
The buf in your .read is an address in the program's memory. Your driver cannot simply write to it. The page might be absent. The program might have passed a wrong address by mistake, or on purpose, such as the address of a kernel structure. A blind write would let any program overwrite the kernel.
So the kernel gives you two copy functions. copy_to_user(to, from, n) copies from kernel memory to the program. copy_from_user(to, from, n) goes the other way. They check the address range. They also survive a page fault part way through, because the fault handler knows the copy is in progress.
The rule that people forget is in the return value. Both functions return the number of bytes they could not copy. Zero means success. A positive number means a partial copy. The type annotation __user on the pointer helps you here: a static checker called sparse (run with make C=1) warns when you dereference a __user pointer directly or pass one where a kernel pointer is expected.
cstatic ssize_t acme_read(struct file *f, char __user *ubuf, size_t n, loff_t *pos) { struct acme_dev *d = f->private_data; size_t avail, copied; if (kfifo_is_empty(&d->fifo)) { if (f->f_flags & O_NONBLOCK) return -EAGAIN; if (wait_event_interruptible(d->wq, !kfifo_is_empty(&d->fifo))) return -ERESTARTSYS; /* a signal arrived */ } avail = min(n, (size_t)kfifo_len(&d->fifo)); return kfifo_to_user(&d->fifo, ubuf, avail, &copied) ? -EFAULT : copied; } static const struct file_operations acme_fops = { .owner = THIS_MODULE, .open = acme_open, .read = acme_read, .poll = acme_poll, .unlocked_ioctl = acme_ioctl, .release = acme_release, };
Now watch what happens when the program gives a buffer that is only partly mapped. The kernel buffer has 64 bytes ready. The program's buffer runs off the end of a mapped page after some number of bytes.
Top row: 64 bytes in the kernel buffer. Bottom row: what reached the program. Drag how many bytes of the program buffer are mapped, then switch the check on and off.
Model of a 64-byte read. The copy stops at the first unmapped byte and returns the count left over, as copy_to_user does. How much of the buffer is mapped is your choice here; in a real program it is whatever the page tables say.
With 40 bytes mapped, copy_to_user returns 24. A driver that ignores this and returns 64 tells the program that all 64 bytes are valid. The last 24 bytes are old data from the program's own stack. Nothing crashes, and no message appears. Calibration numbers are simply wrong. A careful driver returns the 40 that arrived. If nothing was copied at all, it returns -EFAULT (the error code for a bad address).
A real sensor delivers data at its own pace, so a read must be able to wait. The example above sleeps in wait_event_interruptible on a wait queue, a list of sleepers. The interrupt thread from Chapter 0 calls wake_up_interruptible(&d->wq) after it pushes a sample into the FIFO (first in, first out buffer).
Programs that watch many files use poll or select. Your .poll function calls poll_wait(file, &d->wq, wait), which registers the caller on the same wait queue, and returns EPOLLIN | EPOLLRDNORM when data is ready. The same wake-up serves both blocked readers and pollers.
For commands that are not a byte stream, such as "set the sample rate", you implement ioctl. The command number is built with the macros _IOR and _IOW, which pack a type letter, a command number and the size of the argument. For big buffers, mmap maps the driver's memory into the program, so no copy happens at all. That is how camera drivers hand frames to userspace; the device model chapter and the DMA chapter below show where those buffers come from.
The failure to remember: symptom, bad data with no error. Measurement, run a test that gives a buffer ending at a page boundary and compare the returned count with the bytes you know arrived. Fix, always use the return value. The sparse checker catches the other mistake, direct use of a user pointer, at build time.
Chapter 3
Read the chip's registers through one clean layer, then hand the numbers to the kernel's sensor framework in the right units
Dana has the datasheet for the ACME-T1 open next to her terminal. Three registers matter. Register 0x00 and 0x01 hold the temperature as a 16-bit number. Register 0x02 is a status byte whose lowest bit, DRDY, says "a new reading is ready". Register 0x03 is a control byte with an enable bit.
A register here is a numbered byte inside the chip. Your driver reads and writes them over I2C. Almost every sensor driver in Linux does the same few things with them, so the kernel has a standard layer for it and a standard framework above it. This chapter covers both.
The layer is regmap. You describe the chip once in a struct regmap_config: how many bits in a register address (reg_bits), how many in a value (val_bits), the byte order of each (reg_format_endian, val_format_endian), the highest valid address (max_register), and the cache. From then on you call regmap_read(), regmap_write(), regmap_bulk_read() and regmap_update_bits(). You never build an I2C message by hand. The same driver code can sit on I2C, SPI or plain memory-mapped registers, because only the line that creates the regmap changes.
cstatic bool acme_volatile(struct device *dev, unsigned int reg) { return reg == ACME_STATUS || reg == ACME_TEMP; /* the chip changes these itself */ } static const struct regmap_config acme_regmap = { .reg_bits = 8, .val_bits = 8, .max_register = ACME_CTRL, .cache_type = REGCACHE_MAPLE, .volatile_reg = acme_volatile, }; map = devm_regmap_init_i2c(client, &acme_regmap); regmap_update_bits(map, ACME_CTRL, ACME_EN, ACME_EN); /* read, modify, write one bit */ regmap_bulk_read(map, ACME_TEMP, buf, 2); /* buf[0]=high byte, buf[1]=low */ temp = get_unaligned_be16(buf); /* the chip sends the high byte first */
Two settings cause nearly all the trouble: the byte order and the cache. We take each in turn.
A 16-bit value needs two bytes. Big-endian chips send the high byte first, little-endian chips the low byte first. The datasheet says which. Suppose the ACME-T1 sends 0x19 0x00 and counts in steps of 1/256 °C. Read as big-endian, that is 0x1900 = 6,400, and 6,400 ÷ 256 = 25.00 °C. Read as little-endian, it is 0x0019 = 25, and 25 ÷ 256 = 0.098 °C. The two readings differ by exactly 256 times.
The symptom is a sensor that reads about 0.1 °C in a warm room. The measurement is a raw check with the i2cget tool, which shows the bytes on the wire before any driver touches them. The fix is one field in the config.
One call deserves a worked example. regmap_update_bits(map, reg, mask, val) changes only some bits of a register. Say CTRL holds 0b0100_0000 (0x40) and you want to set the enable bit, bit 0. You call it with mask 0x01 and value 0x01. The regmap reads 0x40, clears the bits in the mask (still 0x40), sets the bits of the value inside the mask (0x41), and writes 0x41 back. If the result equals the old value, it skips the write. You never touch bit 6 by accident, and you do it in one call instead of three lines of read, modify and write.
Bus traffic is slow, so regmap can keep a copy of register values. With a cache, a read of a register it has already seen returns the stored value and skips the bus. The default is no cache; you opt in with cache_type. This is perfect for a control register that only your driver writes.
It is a disaster for a register that the chip changes. A status register is the classic case. If the cache holds "DRDY = 0", every later poll sees 0 and never goes to the chip. Mark such registers volatile with the volatile_reg callback. Volatile reads always go to the hardware. Try it.
The chip sets DRDY after your third bus read of STATUS. Press Poll STATUS up to five times with the volatile switch off and on. Change the byte order and read the temperature.
The ACME-T1 is an invented chip. Its temperature unit (1/256 °C per step) and the three-read delay are chosen to make the two bugs visible. The cache behaviour is regmap's: a non-volatile register is read from the bus once, then served from the cache.
Once your driver can read the chip, it needs to show the number to the rest of the system. The IIO subsystem (Industrial I/O) is the standard for sensors that produce samples: temperature, light, acceleration, ADCs. You allocate an iio_dev with devm_iio_device_alloc(), describe each measurement as a struct iio_chan_spec (its type, such as IIO_TEMP, and the info it exports), implement read_raw(), and register with devm_iio_device_register().
IIO then creates files under /sys/bus/iio/devices/iio:deviceN/, such as in_temp_raw and in_temp_scale. The ABI rule is: input = (raw + offset) × scale, and for temperature the result is in milli degrees Celsius. Your driver returns the raw count and the scale and lets user space multiply. Here the scale is 1000 ÷ 256 = 3.90625 milli °C per step. With raw = 6,400 that gives 25,000 milli °C, or 25 °C. In read_raw() you return val = 3, val2 = 906250 with IIO_VAL_INT_PLUS_MICRO.
For streaming data IIO adds buffers (a queue of samples that user space reads from /dev/iio:deviceN) and triggers (an event that says "capture now", such as the data-ready interrupt). The trigger fires, a handler reads the registers, and the sample enters the buffer. That handler runs in a thread, for the reason you met in Chapter 0, because it reads over I2C. Sensor fusion code such as a Kalman filter then consumes the stream.
Chapter 4
Register a handler with the right flags, say honestly whether the interrupt was yours, and free it before the memory it uses
Dana's driver works. She tests it by loading and unloading the module in a loop, with the sensor still sending data-ready pulses. On the ninth unload the kernel prints a long report that starts with BUG: KASAN and the words use-after-free. An interrupt arrived after her code had thrown the driver's memory away.
An interrupt is an event that arrives on its own schedule. Your driver does not control when it comes. That fact shapes three things: how you ask for the interrupt, how you answer it, and how you stop listening.
Where does the interrupt number come from? On an ARM board, the device tree node of your sensor lists an interrupts property, and the I2C core hands your driver a ready number in client->irq. If the line goes to a GPIO pin (general-purpose input/output pin), the GPIO chip acts as a small interrupt controller of its own. It feeds the main controller of the SoC, so the kernel models a chain of controllers. You see only the final number, which the kernel calls a virq (virtual interrupt number).
You then call devm_request_threaded_irq(dev, irq, hard, thread, flags, name, dev_id). The flags matter:
IRQF_TRIGGER_RISING, IRQF_TRIGGER_FALLING, IRQF_TRIGGER_HIGH, IRQF_TRIGGER_LOW: the signal shape that counts as an interrupt. Usually the device tree supplies this, so pass none.IRQF_ONESHOT: keep the line masked until the thread finishes (the kernel docs: "Run thread_fn with interrupt line masked"). Required when you have no hard handler.IRQF_SHARED: several devices use the same line. Then every handler is called for every interrupt.On a shared line your handler cannot assume the interrupt was for its chip. It reads a status register in the chip, and returns IRQ_NONE if the chip did not raise it, or IRQ_HANDLED if it did (IRQ_WAKE_THREAD when the thread must finish the job). The dev_id pointer must be unique and not NULL on a shared line, since it tells the kernel which handler to remove later.
The return value is not decoration. The kernel counts it. In kernel/irq/spurious.c, the comment reads: if 99,900 of the previous 100,000 interrupts have not been handled, assume the IRQ is stuck in some manner, drop a diagnostic and try to turn it off. The code counts every interrupt on the line. When the count reaches 100,000 it checks whether more than 99,900 returned IRQ_NONE. If so, it prints irq N: nobody cared, then Disabling IRQ #N, and masks the line. Your sensor goes silent, with only that message as a clue.
A shared line adds a twist. With three chips on one line, the kernel calls all three handlers for every interrupt. Two of them correctly return IRQ_NONE, and that is fine. The kernel treats the interrupt as unhandled only when no handler claimed it. So the line's unhandled count rises only when every handler on it says no. A driver that always says no, or a chip that fires with no cause the driver can see, pushes the count up.
The bar is the last 100,000 interrupts on one line. The pink part is interrupts your handler answered with IRQ_NONE. Drag the unhandled share past the mark, and pick how fast the line fires.
The threshold is from kernel/irq/spurious.c: the check runs when 100,000 interrupts have been counted, and the line is disabled if more than 99,900 were unhandled. The times are 100,000 divided by the rate.
A stuck level-triggered line is the usual cause. The chip holds the line low, your handler returns IRQ_NONE because it read the wrong register, and the interrupt fires again at once. At 50,000 per second, the kernel reaches 100,000 in two seconds.
Now Dana's use-after-free. Her remove() function freed the driver state with kfree(d), and the IRQ was released later. In the gap, the chip fired and the thread ran with d pointing at freed memory. The order of teardown must be the reverse of setup. Setup: allocate state, initialise it, then request the interrupt (the handler may run at once). Teardown: stop the chip generating interrupts, free the interrupt (free_irq waits for a running handler to finish), then free the state.
A timeline of remove(). The red zone is the time when the IRQ is still live but the state is gone. Pick an order and slide the moment a late interrupt arrives.
Illustrative times: the first step of remove() ends at 10 µs and the second at 40 µs. The real gap depends on the code between the two calls.
The easy fix is devres (Chapter 6). Managed resources are released in the reverse order of acquisition, so if you request the IRQ after allocating the state, the IRQ goes first. Symptom: an oops or a KASAN report in the thread function after unload. Measurement: unload and reload in a loop on a kernel built with KASAN, which poisons freed memory. Fix: free the IRQ first. For the firmware view of the same events, see interrupts and DMA.
Chapter 5
Let a device move data into memory by itself, and keep the CPU from reading a stale copy
Dana's team adds a second device: a camera that sends 1,920 by 1,080 frames. One frame at 2 bytes per pixel is 4,147,200 bytes. If the CPU copied that much data a byte at a time, or took an interrupt for every few bytes, it would do nothing else. The camera needs to write the frame into memory itself.
That is DMA, direct memory access. The device becomes a second writer to RAM. The driver's job is to give the device a place to write, tell the kernel who owns that place at each moment, and wake the CPU when a block is done. The ownership step is where drivers go wrong.
The CPU does not read RAM directly. It reads through a cache, a small fast memory that keeps copies of recent lines of RAM. On many embedded chips the camera writes to RAM and the cache does not notice. The next time the CPU reads that address it gets the old copy from its cache. The data in RAM is new, and the CPU sees the previous frame.
Chips that keep the cache and the device in step are called coherent. Many embedded SoCs are not, at least for some devices. How caches and memory ordering work in detail belongs to the virtual memory and DMA topic in the microcontroller track. Here you need only the rule it leads to: tell the kernel when the CPU is about to read and when the device is about to write.
The kernel's DMA API gives you two tools. dma_alloc_coherent(dev, size, &handle, GFP_KERNEL) allocates a region that both sides always see consistently. It returns a CPU pointer and a DMA handle, the address you give to the device as the base of the region. Use it for long-lived structures such as descriptor rings.
The other tool is the streaming mapping: dma_map_single(dev, ptr, size, dir) hands an existing buffer to the device and returns its DMA address. The dir says which way the data flows: DMA_TO_DEVICE (memory to device), DMA_FROM_DEVICE (device to memory), or DMA_BIDIRECTIONAL. While mapped, the device owns the buffer. Before the CPU reads, you call dma_sync_single_for_cpu(). Before the device uses it again, you call dma_sync_single_for_device(). When you finish, dma_unmap_single() must repeat the same address, size and direction as the map.
The direction is not a hint. It decides what the sync does. A device-to-memory buffer needs the CPU's old cache lines thrown away before the CPU reads. If you say DMA_TO_DEVICE by mistake, the sync assumes the CPU wrote the data and the device will read it, so it does the wrong maintenance. The kernel docs add that bidirectional memory must be synced twice, once each way.
Streaming data needs many buffers. A descriptor ring is a loop of small records, each saying "write the next block to this address". The device walks the ring and wraps at the end. The CPU follows behind, reading finished slots and giving them back.
A shared DMA controller on the SoC does this for many peripherals. Linux calls it the dmaengine framework. A driver asks for a channel with dma_request_chan(dev, "rx"), describes the peripheral with dmaengine_slave_config() (its FIFO address, word width, burst size), prepares a transfer with dmaengine_prep_slave_single() or, for streams, dmaengine_prep_dma_cyclic() (a ring of equal periods that repeats until stopped), sets a callback, submits, and calls dma_async_issue_pending(). The callback fires after each period. It usually runs in a tasklet (a deferred handler that runs in atomic context), so it cannot sleep, by the Chapter 0 rule.
The camera writes frame 0, 1, 2 and so on into eight slots, in order. After each frame the CPU reads the slot. Press Next frame or Run 24 frames. Then change the sync settings and run again.
A model of a non-coherent system. It assumes the CPU's cache keeps the line it loaded on the previous lap of the ring. A real cache may evict it sooner, which makes the bug rarer and harder to find. The sync is modelled as throwing the old line away.
Look at the run. For the first eight frames the CPU reads each slot for the first time, so its cache is empty and it fetches fresh data. Everything looks fine. From frame 8 on, the CPU still holds the old line for each slot. Without a correct sync it reads frame 0 where frame 8 should be. The system passed its first test and failed in the field.
The failure in three stages. Symptom: corrupted frames after a short, clean start, often random and rare. Measurement: build with CONFIG_DMA_API_DEBUG, which checks mapping rules and warns about wrong directions and missing unmaps, and use the ftrace function tracer filtered on dma_sync* to see whether the sync runs before each read. Fix: sync for the CPU before every read, with the direction that matches the data flow, and sync back to the device afterwards. For the field story of a stale frame every few hundred, see the virtual memory and DMA lesson in the microcontroller track (named in the road, not yet linked).
Chapter 6
Pick the lock, the wait and the allocation that are legal in each context, and let devres clean up the rest
Dana's thread function pushes samples into a ring buffer. A read call takes them out. Two paths touch the same pointers, so she needs a lock. She wraps the push in a mutex and, to be safe, the interrupt handler too. The board prints BUG: scheduling while atomic again. She has met the same rule from a new side.
Chapter 0 gave one rule: hard interrupt context must not sleep. The rule spreads. Every primitive in the kernel either may sleep or may not, and every context either allows sleeping or does not. A driver is mostly the work of matching the two.
Process context is a system call or a kernel thread. Sleeping is allowed. Your probe(), .read, .ioctl and threaded IRQ function run here. Hard interrupt context is your hard handler. It cannot sleep. Atomic context is the wider name for any place where sleeping is banned: hard handlers, softirqs and tasklets (deferred work that runs right after an interrupt), and any code between spin_lock() and spin_unlock(). A spinlock holder cannot sleep, because another CPU spins waiting for it and the lock owner must finish fast.
A spinlock protects data that an interrupt handler also touches. A waiting CPU spins in a tight loop until the lock is free. Hold it for a few lines only. If the same lock is also taken in a handler, take it with spin_lock_irqsave(), which turns interrupts off on this CPU. Otherwise an interrupt could arrive while your code holds the lock, the handler would wait for the lock, and the CPU would wait forever for itself.
A mutex protects data between process-context paths. A waiting task sleeps. So it is illegal in a hard handler and illegal under a spinlock. A completion is a one-shot signal: wait_for_completion() sleeps until some other code calls complete(). The waiting half may sleep; the signalling half is safe anywhere. A wait queue (Chapter 2) works the same way. A workqueue runs a function later in a kernel worker thread. schedule_work() is safe in a handler, and the job itself may sleep. It is the other way to do what a threaded IRQ does.
Here is the deadlock that spin_lock_irqsave() prevents, step by step. First, a thread on CPU 0 takes the lock with plain spin_lock(). Second, the sensor interrupt arrives on CPU 0 and the kernel runs the handler on top of the thread. Third, the handler asks for the same lock and spins. The thread cannot run until the handler returns, and the handler cannot return until the thread releases the lock. Both wait forever. Turning interrupts off on this CPU while the thread holds the lock breaks the cycle.
Choose where your code runs, then tap a primitive. The matrix shows all three contexts. Green is legal. Red is a BUG.
The verdicts follow each primitive's contract: it may sleep, or it may not. A copy to user memory may fault and sleep. GFP_KERNEL may sleep to reclaim memory, so the kernel docs allow it only where the caller may sleep.
Allocating memory is a call that can sleep, because the kernel may have to free other memory first. You tell it what is allowed with a GFP flag (get free pages). The kernel docs say GFP_KERNEL is what you need most of the time, and that "the calling context must be allowed to sleep". GFP_ATOMIC never sleeps and may use memory reserves, so it suits interrupt-side code, with a fallback for failure. The docs also point to GFP_NOWAIT for atomic callers that can cope with failure. So kmalloc(GFP_KERNEL) under a spinlock is the same bug as mutex_lock in a handler.
Device registers need ioremap(), which maps the physical addresses of the chip's registers into kernel address space. You then use readl() and writel(), not plain pointer reads, so the compiler and CPU keep the order. Mapping happens in probe(), in process context, where sleeping is fine. Reading a register in a handler is legal.
Every resource a probe function acquires must be released if a later step fails, and again on remove. Manual error paths with goto labels are easy to get wrong. The kernel's answer is devres: resources tied to a struct device, released automatically when the driver detaches or when probe fails. The kernel doc calls it a linked list of memory areas associated with the device, each with a release function. You use the devm_ versions: devm_kzalloc, devm_ioremap_resource, devm_request_threaded_irq, devm_iio_device_register. Resources release in reverse order of acquisition, which also gives the right teardown order from Chapter 4.
Probe takes five steps. Slide the step where it fails. With manual unwinding the author forgot one label (the mapping). Turn devres on and compare.
An invented probe with five resources. The forgotten label is a deliberate mistake, typical of hand-written unwinding. One leak per failed probe; the count after 50 unbind and rebind cycles is the number of failures times one.
Symptom: memory use creeps up each time you bind and unbind the driver. Measurement: build with kmemleak and loop echo dev > unbind then bind in sysfs a few hundred times, then read the leak report. Fix: move to devm_. See kernel internals for platform engineers for the allocator and scheduler under these rules, and advanced C for the pointer habits.
Chapter 7
Turn a screen of hexadecimal into one line of source code, and pick the instrument that does not disturb the bug
Dana's board prints a wall of text and stops answering. The first line says BUG: kernel NULL pointer dereference, address: 0000000000000010. Under it are register values, a call trace and a code dump. To a newcomer it looks like noise. To an experienced kernel developer it is a map to one line of code.
This kind of report is called an oops: the kernel hit an illegal action in its own code, wrote what it knew and, in the usual case, killed the task that caused it. This chapter teaches you to read one, and covers the tools you use before and after it.
The oldest tool is printk(), which writes a line into the kernel log ring buffer. You read the buffer with dmesg. Each message has a level from 0 to 7. The kernel docs list them: KERN_EMERG 0, KERN_ALERT 1, KERN_CRIT 2, KERN_ERR 3, KERN_WARNING 4, KERN_NOTICE 5, KERN_INFO 6, KERN_DEBUG 7. In practice you call the short forms pr_err(), pr_info(), or, in drivers, dev_err(dev, ...) and dev_dbg(dev, ...), which add the device name.
The file /proc/sys/kernel/printk holds four numbers, the current, default, minimum and boot-time-default levels. A typical value is 4 4 1 7. Only messages whose level is below the console level reach the console. Everything still lands in dmesg. With dynamic debug (CONFIG_DYNAMIC_DEBUG) the dev_dbg lines cost nothing until you switch them on for one file at runtime through /sys/kernel/debug/dynamic_debug/control.
Printing is slow. A printk of a 60-character line on a 115,200 baud serial console takes about 5 ms, because each character needs about 87 µs. That changes the timing, and a timing bug disappears when you add the print. People call this a heisenbug. The cure is a tool that writes to memory, not to a console.
ftrace is the kernel's built-in tracer, controlled through files in /sys/kernel/tracing. Set current_tracer to function_graph, restrict it with set_ftrace_filter to acme_*, and you get every call into and out of your driver with its duration. Tracepoints are fixed event hooks in the source (such as scheduler switches and IRQ entry) that you can enable per event. For your own debug output on a hot path, use trace_printk(), which writes to the same ring buffer in memory, far faster than any console. Two memory tools complete the set. KASAN marks memory as valid or poisoned and reports use-after-free and out-of-bounds accesses at the access. kmemleak finds blocks that nothing points to any more.
Three parts of an oops matter most. First, the fault line: what went wrong and at which address. Second, the RIP line (on arm64, pc): the instruction that faulted, written as function+offset/size, such as acme_irq_thread+0x2c/0x90 [acme]. It means 0x2c bytes into the function, which is 0x90 bytes long. Third, the call trace: who called whom.
To turn function+offset into a source line, build with debug info and run scripts/decode_stacktrace.sh on the oops text. The kernel's bug-hunting guide shows the manual way too: in gdb, l *acme_irq_thread+0x2c prints the line.
The fault address carries a clue most people skip. If a pointer d is NULL and the code reads d->irq, the CPU reads address 0 + offset of irq. So an address like 0x10 is not random: it is a field offset. Find the field at offset 0x10 in your struct (the tool pahole prints layouts) and you know which pointer was NULL before you read any code.
Pick a sample oops. The report is on top, the struct layout of the driver state below. Read the address, find the field, and tap Reveal the cause.
Invented reports for an invented driver. The struct offsets are illustrative. The 0x6b pattern is what the slab allocator writes into freed memory when poisoning is on.
The third sample is a different species. An address made of repeated 0x6b bytes is not an offset. It is the pattern the allocator writes into freed memory when poisoning is on, so your code read a pointer out of a block that was already freed. That is the use-after-free of Chapter 4, and KASAN would have named the free site and the access site.
The workflow, as three stages. Symptom: the wall of text and a dead task. Measurement: note the fault address, decode function+offset to a line, and match the address to a field. Fix: find why that pointer was NULL or freed (for instance, an IRQ requested before the regmap existed, a Chapter 4 ordering mistake). For firmware-side debugging with a scope, see bench and root cause.
Chapter 8
Choose between a kernel driver and a user-space route, and see where Rust has reached in the kernel
Priya has a prototype on her desk. It has an I2C chip she wants to read once a second and a GPIO pin she wants to toggle. Dana's chapters make her think she needs a kernel driver. She does not. A kernel driver is the most expensive way to reach a chip: it ties her code to one kernel version (Chapter 1), a bug in it can stop the whole machine (Chapter 7), and it needs a review before anyone else can use it (Chapter 9).
The kernel offers several ways to reach hardware from a normal program. Knowing them is part of writing drivers well, because the best driver is often the one you did not write.
i2c-dev exposes each I2C bus as /dev/i2c-N. A program opens it, calls ioctl(fd, I2C_SLAVE, addr) to pick the chip, then reads and writes with read, write, SMBus helper calls or an I2C_RDWR ioctl for combined transactions. The bus driver needs no change. spidev does the same for SPI, with /dev/spidevB.C. libgpiod is a library over the GPIO character device /dev/gpiochipN: you request lines, set or read values and wait for edge events. Together they cover a large share of prototypes and slow sensors.
UIO, user-space I/O, handles a device with memory-mapped registers and an interrupt. A very small kernel module registers the device. The program maps the registers, and a blocking read() on /dev/uioX returns when an interrupt occurs. The kernel docs add a warning: you cannot rely on the user-space half, since it can exit at any time, so any hardware work needed after each interrupt must stay in the kernel stub. Docs also say UIO "simplifies development and reduces the risk of serious bugs within a kernel module".
VFIO is the safer cousin for devices that do DMA. It gives a program direct access to a device inside an IOMMU-protected environment. The IOMMU (input-output memory management unit) limits which memory the device can touch, so a buggy program cannot make the device scribble on the kernel. The docs describe the aim as safe, non-privileged, user-space drivers, and say UIO has no notion of IOMMU protection.
How small is the cheap route? This is the complete read of two bytes from register 0 of an I2C chip at address 0x48 (an example address), from a normal program:
cint fd = open("/dev/i2c-1", O_RDWR); ioctl(fd, I2C_SLAVE, 0x48); /* pick the chip on the bus */ uint8_t reg = 0x00, buf[2]; write(fd, ®, 1); /* send the register number */ read(fd, buf, 2); /* read two bytes back */
That is five lines, with no module, no vermagic, no oops risk. The cost is that every program must know the chip, and no other kernel code can use the reading. The next device sorts the cases.
Switch on the statements that are true for your device. The highlighted card is the cheapest route that still works.
The order of the questions is a rule of thumb, not a kernel rule: another kernel user wins first, then DMA safety, then slow bus chips, then register-and-interrupt devices. Anything else gets a kernel driver.
A kernel driver is the right answer when the device must join a kernel framework (an IIO sensor, an input device, a network interface, a camera for V4L2), when many programs and containers must share it, or when nothing else fits. The failure mode of the opposite choice: symptom, a driver that only wraps a few register reads, breaks on each kernel update, and has one user. Measurement, ask who calls it and whether i2c-dev gives the same result. Fix, move the logic to user space.
Many driver bugs in this lesson are bugs of ownership: a pointer used after its memory was freed, a resource not released, a lock not taken. The Rust language checks ownership when the code is compiled. A value that has been moved or dropped cannot be used again:
rust (plain Rust, not a kernel API)let state = Box::new(AcmeState::new()); drop(state); // freed here // let irq = state.irq; // compile error: borrow of moved value
That is the Chapter 4 bug turned into a compile error. Rust in Linux wraps the C kernel API in safe abstractions. Drivers use them and keep unsafe code small. Not every subsystem has the abstractions yet, so Rust drivers land first where they exist. Where does this stand? Move along the timeline.
Drag along five milestones. Each is dated from a source named in the read-out.
Sources: Phoronix on Linux 6.1 (initial Rust infrastructure, about 12.5k lines, no drivers yet) and on 6.18 (Rust Binder); kernel.org (6.18 released 2025-11-30); LWN and a patch titled "rust: conclude the Rust experiment" (December 2025); Phoronix on Linux 7.1 Rust DRM changes. Airlie's remark is a second-hand report of a Maintainers Summit comment, not a quote from a primary transcript.
Chapter 9
Get the driver into mainline so you stop carrying it, then keep the numbers, the checklist and the core code in one place
Dana's driver works, and her company ships a board with it. Two kernel updates later, a teammate spends a week making it build again. A year later, someone else does the same. The driver is a patch pile that follows the product from one kernel version to the next. The cure is to get the driver into the official Linux tree, the mainline, so that the people who change kernel APIs also fix her driver.
You send your work as a series of patches (small changes in text form) to a mailing list. Three tools make that routine. scripts/checkpatch.pl checks style and common mistakes. scripts/get_maintainer.pl tells you which maintainers and lists must see each patch. b4 is a command-line helper that collects a patch series from the list archive, applies it, and helps you send your own series with the right headers.
If your driver needs a device tree node, the properties must be documented in a binding, a YAML file under Documentation/devicetree/bindings that the device tree maintainers review. Review is the real work. Expect comments on naming, on the ordering problems from Chapter 4, on the contexts from Chapter 6, and requests to use the existing IIO and regmap helpers. Each round takes days. That is normal.
A new mainline kernel appears every 9 to 10 weeks, says the kernel.org releases page. The development process opens a merge window of about two weeks after each release, when new features go in. Then Linus Torvalds releases a candidate (-rc1) about once a week until the release is stable. Your patch must be ready, reviewed and in a maintainer's tree before a merge window opens, or it waits for the next one.
One kernel a year is marked long-term and gets fixes for years. Kernel.org lists 6.12 (released 17 November 2024) and 6.18 (released 30 November 2025), both projected to end in December 2028. From 6.12 to 6.18 is six releases in 54 weeks: nine weeks each on average. A product that stays on 6.12 for years carries its patches across, or moves from one long-term kernel to the next and rebases at each jump.
Seven kernel releases from 6.12 to 6.18. Choose how many out-of-tree patches you carry, then switch on upstreaming and see what remains.
Dates from kernel.org: 6.12 released 2024-11-17, 6.18 released 2025-11-30, which is 378 days or 54 weeks for six releases. A patch rebase is counted as one unit of work per patch per release, an illustrative measure; real cost depends on how much each release changes your code.
The failure here is a slow one. Symptom: every kernel update costs days. Measurement: count the patches you carry and the releases you cross, as above. Fix: upstream the driver, and keep only what cannot be shared.
A Linux driver chooses the right context for each primitive. A hard IRQ handler cannot sleep, and an I2C or SPI transfer does, so request_threaded_irq moves the transfer into a kernel thread. The build ties a module to one kernel by its vermagic. A character driver copies across the user boundary and reports the copy honestly.
regmap and IIO give sensors a standard shape, where byte order and the cache decide what you believe. Interrupts need the right flags, the right return value and the right teardown order. DMA needs ownership calls around every CPU read. Locks, waits and allocations follow the context. Oops reports, ftrace and KASAN find the rest. Often a user-space route beats a driver. Upstream what remains.
| What | Number | Why it matters |
|---|---|---|
| 2-byte I2C register read | about 48 clock pulses: 120 µs at 400 kHz, 480 µs at 100 kHz | Far too long for a hard handler, so use a thread |
| Reads per second the bus allows | about 8,333 at 400 kHz, about 2,083 at 100 kHz | The thread falls behind past this rate |
| Spurious interrupt limit | more than 99,900 of 100,000 unhandled | The kernel disables the line (nobody cared) |
| Byte order bug | 0x19 0x00: 25.00 °C big-endian, 0.10 °C little-endian | A wrong endian setting is a 256 times error |
| IIO temperature scale | 1000/256 = 3.90625 milli °C per step; 6,400 gives 25,000 | Drivers return raw plus scale in milli degrees |
| printk levels | 0 (EMERG) to 7 (DEBUG); typical /proc/sys/kernel/printk is 4 4 1 7 | Choose what reaches the console |
| NULL dereference address | 0x10 means field offset 0x10 | The address names the field that was read |
| Rust in the kernel | 6.1 (Dec 2022) infrastructure; 6.18 (Nov 2025) Rust Binder | A second language for new drivers, growing |
| Mainline cadence | 9 to 10 weeks per release; merge window about 2 weeks | When your patch can land |
| Long-term kernels | 6.12 (2024-11-17), 6.18 (2025-11-30), projected end Dec 2028 | Pick a base that gets fixes |
cstatic const struct iio_chan_spec acme_chan[] = {{ .type = IIO_TEMP, .info_mask_separate = BIT(IIO_CHAN_INFO_RAW) | BIT(IIO_CHAN_INFO_SCALE), }}; static int acme_read_raw(struct iio_dev *indio, struct iio_chan_spec const *ch, int *val, int *val2, long mask) { struct acme_dev *d = iio_priv(indio); __be16 raw; int ret; switch (mask) { case IIO_CHAN_INFO_RAW: /* process context: may sleep (Ch 0) */ ret = regmap_bulk_read(d->map, ACME_TEMP, &raw, 2); /* Ch 3 */ if (ret) return ret; *val = (s16)be16_to_cpu(raw); /* the chip sends the high byte first */ return IIO_VAL_INT; case IIO_CHAN_INFO_SCALE: *val = 3; *val2 = 906250; /* 1000/256 milli degC per step */ return IIO_VAL_INT_PLUS_MICRO; } return -EINVAL; } static const struct iio_info acme_info = { .read_raw = acme_read_raw }; static irqreturn_t acme_thread(int irq, void *p) /* kthread, may sleep (Ch 0) */ { /* read the sample with regmap, push it into the IIO buffer */ return IRQ_HANDLED; } static int acme_probe(struct i2c_client *client) { struct iio_dev *indio; struct acme_dev *d; indio = devm_iio_device_alloc(&client->dev, sizeof(*d)); /* Ch 6: devres */ if (!indio) return -ENOMEM; d = iio_priv(indio); d->map = devm_regmap_init_i2c(client, &acme_regmap); if (IS_ERR(d->map)) return PTR_ERR(d->map); indio->name = "acme_t1"; indio->info = &acme_info; indio->channels = acme_chan; indio->num_channels = 1; indio->modes = INDIO_DIRECT_MODE; /* the IRQ comes last: everything its thread uses exists (Ch 4) */ ret = devm_request_threaded_irq(&client->dev, client->irq, NULL, acme_thread, IRQF_ONESHOT, "acme", indio); if (ret) return ret; return devm_iio_device_register(&client->dev, indio); } static const struct of_device_id acme_of[] = { { .compatible = "acme,t1" }, { } }; MODULE_DEVICE_TABLE(of, acme_of); static struct i2c_driver acme_driver = { .driver = { .name = "acme_t1", .of_match_table = acme_of }, .probe = acme_probe, }; module_i2c_driver(acme_driver); MODULE_LICENSE("GPL");
The listing is a sketch built from the APIs in this lesson. The ACME-T1 is invented, so the register names and the compatible string are placeholders. Variable ret is declared in the full file.
Take a Raspberry Pi or another Linux board with an I2C temperature sensor that has a Linux IIO driver in the kernel tree. Read in_temp_raw and in_temp_scale in /sys/bus/iio/devices/ and compute raw times scale. Compare with i2cget. Then enable function_graph on the driver's functions and measure how long one read takes at 100 kHz and at 400 kHz. Does it match 480 µs and 120 µs, plus driver overhead?
This lesson stands on the device tree and device model, which explains how the kernel finds a node and calls your probe, and on buses on the wire. The kernel side continues in kernel internals for platform engineers and real-time Linux. The memory ordering behind Chapter 5 belongs to the virtual memory and DMA lesson in the microcontroller track, which is planned and not yet written.
Opened and checked for this lesson: the Linux kernel documentation pages on generic IRQs, devres, the DMA API, IIO, printk, memory allocation, bug hunting, kbuild modules, the UIO, VFIO and i2c-dev guides, and the process howto; kernel/irq/spurious.c, include/linux/regmap.h and the IIO sysfs ABI file in the kernel source; the kernel.org releases page; the NXP I2C specification UM10204 (speeds and byte format); the Linux Kernel Module Programming Guide (vermagic); Phoronix and LWN reports on Rust in Linux 6.1, 6.18, the December 2025 Maintainers Summit and Linux 7.1. Chip, register names and offsets are invented for teaching. Planned further reading, not used for any number here: Bootlin's embedded Linux kernel and driver course, Madieu's Linux Device Drivers Development, and Linux Device Drivers 3rd edition (its API is from Linux 2.6, though the mechanisms hold).
Open Teach and explain the threaded IRQ to a friend on the whiteboard. Then go back to the handler at the top and break it on purpose.