
Recall first from Provable answers and the why questions
- Removing a character-device registration stops future opens through that registration while existing files can still call its operations.
- User-copy helpers can sleep and return the number of bytes left uncopied.
- Lock choice depends on which contexts access the data and whether those contexts may sleep.
Whiteboard a platform probe
4 min readThe last lesson answered interview questions. This lesson answers the hands-on formats, whiteboarding a platform driver probe and ioremap, and live-coding a module and file_operations table.
The kernel's generic IRQ documentation describes a real setup hazard. Once an IRQ request enables the interrupt, your handler may run. If your drawing initializes the handler's state after requesting the IRQ, the interviewer can point to exactly where the driver could use uninitialized state. Put the ordering on the board so you can reason about it without relying on a particular boot sequence.
Start by asking what the device exposes and what the interviewer wants you to implement. State the assumptions you will use. For this sketch, the device already exists as a platform device and supplies a memory resource. Its first register is a readable 32-bit little-endian register and the hardware is already accessible. Any interrupt extension needs the device's documented status, mask and acknowledgement rules. A real board's resource and register definitions determine those details.
Draw driver registration and device matching before probe(). The driver core calls the probe for a matching device. For a Device Tree match, point to where the driver's .of_match_table would go and say that its compatible string comes from the binding. The skeleton below uses platform name matching and assumes a platform device of the same name exists. Registering this module alone supplies the driver.
#include <linux/err.h>
#include <linux/io.h>
#include <linux/module.h>
#include <linux/platform_device.h>
static int wb_probe(struct platform_device *pdev)
{
void __iomem *regs;
u32 value;
regs = devm_platform_ioremap_resource(pdev, 0);
if (IS_ERR(regs))
return PTR_ERR(regs);
value = readl(regs);
dev_info(&pdev->dev, "register value: %#x\n", value);
return 0;
}
static struct platform_driver wb_driver = {
.probe = wb_probe,
.driver = {
.name = "wb-demo",
},
};
module_platform_driver(wb_driver);
MODULE_LICENSE("GPL");
Point at 0 and identify it as the index of the first memory resource. If asked to expand the mapping step, name platform_get_resource() with IORESOURCE_MEM, then explain that the resource describes an address range. Bare ioremap() maps an I/O range and returns NULL on failure. A driver managing that mapping itself must also handle resource ownership and call iounmap() when finished. The managed platform helper obtains the resource, reserves it and maps it. It reports failure as an error pointer, so the skeleton checks IS_ERR() and returns PTR_ERR().
From the mapped void __iomem * address, use readl() to read a 32-bit register. For registers beyond the first, add the documented byte offset to the mapped base. Explain what makes the access valid: the offset is within the resource, the width and byte order match the register, and any required power, clock and reset setup has happened. If a dependency lookup returns -EPROBE_DEFER, preserve it so the core can retry. A register value is data, so the return from readl() does not use the error-pointer convention.
When the interviewer adds an IRQ and a userspace interface, place both on the same drawing. Allocate per-device state, save it with platform_set_drvdata() if other driver callbacks need to retrieve it, and initialize the queue and event state. Keep device interrupt generation masked while setting up the handler, obtain the IRQ with platform_get_irq(), and propagate a negative result. Request the handler with its state pointer, then enable the source according to the device's register rules. Publish the userspace interface once its callbacks can run safely.
Rehearse one failure after each acquisition. Managed resources are released on failed probe and on unbind. If a later step fails after the driver enables the device's interrupt source, the driver must quiesce the hardware before releasing the resources its handler uses. For an interface that allows open files or blocked readers across unbind, describe how removal prevents new opens, signals shutdown to existing readers, and keeps their state alive until the last reference goes away. The register-only skeleton has no such interface and needs no remove callback.
Live-code the module and file operations
3 min readStart with an empty file and write the entry point and exit point before adding device behavior. Say what successful initialization means and what exit has to undo. A minimal module succeeds after logging its load message. The exit message gives you a second event to verify when you remove it.
#include <linux/init.h>
#include <linux/module.h>
static int __init timed_init(void)
{
pr_info("timed: loaded\n");
return 0;
}
static void __exit timed_exit(void)
{
pr_info("timed: unloaded\n");
}
module_init(timed_init);
module_exit(timed_exit);
MODULE_LICENSE("GPL");
Save this as timed.c and put obj-m := timed.o in a Makefile in the same directory. Use Kbuild on the Ubuntu VM with headers for the running kernel. The source uses kernel headers and is built as a module through Kbuild, which supplies the target kernel's compiler options. Diagnose the first build error before working through messages that may be consequences of it.
make -C "/lib/modules/$(uname -r)/build" M="$PWD" modules &&
sudo insmod ./timed.ko &&
sudo rmmod timed &&
sudo dmesg | tail
For the character device prompt, agree on observable behavior before typing. Here a fresh open can read a fixed line. Reads advance the file position by the bytes returned and reach end of file when the line is exhausted. There is no write callback. A misc device keeps the exercise focused on the read callback and operation table while still registering a character device. Replace the minimal module source with the following version after unloading it.
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
static ssize_t timed_read(struct file *file, char __user *buf,
size_t count, loff_t *pos)
{
static const char message[] = "ready\n";
(void)file;
return simple_read_from_buffer(buf, count, pos,
message, sizeof(message) - 1);
}
static const struct file_operations timed_fops = {
.owner = THIS_MODULE,
.read = timed_read,
.llseek = no_llseek,
};
static struct miscdevice timed_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "timed-demo",
.fops = &timed_fops,
};
static int __init timed_init(void)
{
return misc_register(&timed_dev);
}
static void __exit timed_exit(void)
{
misc_deregister(&timed_dev);
}
module_init(timed_init);
module_exit(timed_exit);
MODULE_LICENSE("GPL");
Explain the callback while you write it. buf is a userspace pointer. simple_read_from_buffer() handles the copy, limits it to the requested length and the remaining data, advances the position for the bytes copied and passes an error back if the copy fails entirely. Excluding the trailing C string terminator makes the readable bytes exactly the text and newline. With .owner = THIS_MODULE, an open file using the operations holds a module reference. That answers the module unload question for this standalone example. A platform device can be unbound separately, so module ownership alone does not protect a platform device's state.
Propagate misc_register()'s result. A registration failure makes module initialization fail, and the exit callback is for unloading a successfully initialized module. After a successful build and insertion, use sudo cat /dev/timed-demo. For an extra behavioral check, use sudo dd if=/dev/timed-demo bs=1 to make small reads through a single open. A read callback that kept returning bytes after the line ended would make a program that reads to EOF keep reading. Close your test programs before unloading. This gives you concrete checks to describe even when the interviewer provides an editor without a running kernel.
Live-code an IRQ handler and explain the wait
3 min readStart the IRQ prompt by defining one interrupt source and what a reader should observe. Assume a shared IRQ, a status bit that identifies this device's event, and a documented acknowledgement register that clears the event when that bit is written. The register offsets and event mask below come from the device specification and are supplied by probe. This sketch delivers a pending notification to a single reader. Events can coalesce into a single notification, so this design is suitable when the reader only needs to know that work is pending.
#include <linux/atomic.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/sched.h>
#include <linux/wait.h>
struct timed_irq {
void __iomem *regs;
unsigned int status_offset;
unsigned int ack_offset;
u32 event_mask;
atomic_t pending;
wait_queue_head_t waitq;
};
static irqreturn_t __maybe_unused timed_irq_handler(int irq, void *data)
{
struct timed_irq *state = data;
u32 status;
(void)irq;
status = readl(state->regs + state->status_offset);
if (!(status & state->event_mask))
return IRQ_NONE;
writel(state->event_mask, state->regs + state->ack_offset);
atomic_set(&state->pending, 1);
wake_up(&state->waitq);
return IRQ_HANDLED;
}
Before requesting the IRQ, fill in the register fields, set pending to zero with atomic_set() and call init_waitqueue_head(). In the platform extension, pass the state pointer as the handler's device cookie and use IRQF_SHARED if the IRQ is shared. Check the request result before unmasking the source. If the hardware requires a readback to complete the acknowledgement before returning, identify which read is safe from its documentation. In the handler, explain both return paths out loud. With the status bit clear, this device claims no interrupt and the handler leaves its registers alone after the status read. With the bit set, acknowledge this source, publish the notification and wake the waiter. The hard handler does not sleep or copy to userspace.
On the reader side, write down wait_event(state->waitq, atomic_read(&state->pending)). In sleepable process context, this tests the condition and sleeps in the uninterruptible state while it is false. It checks again when woken. If the IRQ has already set pending, the reader can proceed immediately because the condition is already true. A wakeup by itself does not make the condition true, which is why the handler stores the flag before waking the queue.
For a blocking userspace read, say you would use wait_event_interruptible() with the same predicate and return its error if interrupted, before consuming the notification. After a successful wait, the single consumer can clear the pending flag using atomic_xchg(&state->pending, 0). This intentionally coalesces events through the exchange. An event published after the exchange can satisfy the next wait. If every event must be delivered, state that you would need a counter or a queue with an explicit overflow policy. If readers can wait through unbind, include shutdown in their wait predicate and wake them on shutdown as well.
Use the final seconds to trace the status-clear branch and the case where the IRQ arrives before the reader calls the wait macro. Both traces should follow directly from the code you wrote. A compile-only handler check on the VM verifies types and headers. It supplies no evidence about real register behavior. The next lesson, “Designing a sensor driver end to end,” applies these explanations to choosing and assembling the pieces of a complete sensor driver.
Key takeaways
- A platform driver's probe runs for a matching device, and the mapping helper returns an error pointer on failure
- A file_operations table connects file operations to callbacks, while registration makes the device available
- A hard IRQ handler checks the device's interrupt status, acknowledges its source and publishes the event before waking waiters
- A wait queue coordinates sleep and wakeup around a condition that the reader checks
Reflect
- Explain to a colleague, in two sentences: draw a platform probe with resource acquisition, failure paths and teardown
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Kernel documentationPlatform devices and drivers
- Kernel documentationBus-independent device accesses
- Kernel documentationDriver basics and wait queues
- Kernel documentationGeneric IRQ handling
- Kernel documentationBuilding external modules
Official documentation first. Links checked when the lesson was published.