Try Embedded

Linux drivers and kernel modules

Modules, character devices, platform drivers and probe.

Kernel space and user space

On Linux, applications run in user space, with protected memory and no direct access to hardware. The kernel runs in kernel space, with full privileges. Drivers are kernel code: they own the hardware and expose it to applications through standard interfaces (files in /dev, sysfs, network interfaces, input events). A bug in a driver can crash the whole system, so driver code follows strict rules.

Before writing a driver, check whether one exists: the mainline kernel has thousands, and many devices only need a device-tree node. For simple GPIO, I2C or SPI access from an application, user-space interfaces (libgpiod, /dev/i2c-N, spidev) may be enough.

Modules

Drivers can be built into the kernel image or as loadable modules (.ko files) loaded at run time.

#include <linux/module.h>
#include <linux/init.h>

static int __init hello_init(void)
{
    pr_info("hello: loaded\n");
    return 0;                     /* non-zero aborts the load */
}

static void __exit hello_exit(void)
{
    pr_info("hello: unloaded\n");
}

module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Minimal example module");
make -C /lib/modules/$(uname -r)/build M=$PWD modules   # out-of-tree build
sudo insmod hello.ko        # load (modprobe also loads dependencies)
dmesg | tail                # kernel log
lsmod | grep hello
sudo rmmod hello

MODULE_LICENSE("GPL") matters: many kernel symbols are exported only to GPL-compatible modules.

The driver model: buses, devices, drivers

Linux matches devices to drivers on a bus:

BusDevices come fromMatch by
platformDevice tree nodes for SoC peripheralscompatible
I2C, SPIDevice tree child nodes of the controllercompatible (or ID table)
USB, PCIEnumerationVendor/product IDs

When a match occurs the driver's probe() runs: it acquires resources, initialises the hardware and registers the device with a subsystem. remove() undoes it.

A platform driver skeleton

#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/of.h>

struct acme_dev {
    void __iomem *regs;
    int irq;
};

static int acme_probe(struct platform_device *pdev)
{
    struct acme_dev *ad;

    ad = devm_kzalloc(&pdev->dev, sizeof(*ad), GFP_KERNEL);
    if (!ad)
        return -ENOMEM;

    ad->regs = devm_platform_ioremap_resource(pdev, 0);   /* from the node's reg property */
    if (IS_ERR(ad->regs))
        return PTR_ERR(ad->regs);

    ad->irq = platform_get_irq(pdev, 0);                  /* from the interrupts property */
    if (ad->irq < 0)
        return ad->irq;

    platform_set_drvdata(pdev, ad);
    dev_info(&pdev->dev, "version 0x%08x\n", readl(ad->regs + 0x00));
    return 0;
}

static const struct of_device_id acme_of_match[] = {
    { .compatible = "acme,widget" },
    { }
};
MODULE_DEVICE_TABLE(of, acme_of_match);

static struct platform_driver acme_driver = {
    .probe  = acme_probe,
    .driver = {
        .name = "acme-widget",
        .of_match_table = acme_of_match,
    },
};
module_platform_driver(acme_driver);
MODULE_LICENSE("GPL");

Points to notice:

  • devm_ (managed) functions free their resources automatically when the device is removed or probe fails, removing most clean-up code and leaks.
  • Registers are accessed with readl/writel on an __iomem pointer, never by dereferencing directly; these handle barriers and byte order.
  • Errors are returned as negative errno values (-ENOMEM, -ENODEV). Returning -EPROBE_DEFER asks the kernel to retry probe later, when a dependency (a clock, regulator or GPIO controller) is not ready yet.

Character devices

To give applications a /dev node with open, read, write and ioctl, register a character device. The simplest way is a misc device:

static ssize_t acme_read(struct file *f, char __user *buf, size_t len, loff_t *off)
{
    u32 value = readl(regs + 0x10);
    if (len < sizeof(value))
        return -EINVAL;
    if (copy_to_user(buf, &value, sizeof(value)))     /* never touch user pointers directly */
        return -EFAULT;
    return sizeof(value);
}

static const struct file_operations acme_fops = {
    .owner = THIS_MODULE,
    .read  = acme_read,
};

static struct miscdevice acme_misc = {
    .minor = MISC_DYNAMIC_MINOR,
    .name  = "acme",              /* appears as /dev/acme */
    .fops  = &acme_fops,
};
/* in probe: misc_register(&acme_misc); */

User pointers must go through copy_to_user/copy_from_user, which validate them; dereferencing a user pointer in the kernel is a security hole.

Prefer a subsystem

Before inventing a custom /dev interface, use the subsystem made for the device type: IIO for sensors and ADCs, hwmon for temperatures and fans, input for buttons and touchscreens, LED, GPIO, PWM, regulator, RTC, net for network devices, DRM/fbdev for displays. Standard tools and libraries then work with your device, and the subsystem provides sysfs attributes, buffering and events.

Interrupts and concurrency

ret = devm_request_threaded_irq(&pdev->dev, irq, acme_hardirq, acme_thread_fn,
                                IRQF_ONESHOT, "acme", ad);
  • The hard IRQ handler runs in interrupt context: no sleeping, keep it short (acknowledge, maybe read a status).
  • The threaded handler runs in a kernel thread and may sleep (I2C transfers, mutexes).
  • Other deferral mechanisms: workqueues, tasklets (legacy).
  • Protect shared data: spinlocks (spin_lock_irqsave) where interrupt context is involved, mutexes where sleeping is allowed.

Debugging

  • dev_info, dev_err, dev_dbg (enable with dynamic debug) and dmesg.
  • /sys/bus/platform/drivers/ and /sys/bus/platform/devices/ show what bound.
  • ftrace, trace_printk, kernel config options such as CONFIG_PROVE_LOCKING and CONFIG_DEBUG_ATOMIC_SLEEP catch locking mistakes.

The interpreter cannot run kernel code, but the ERR_PTR convention the kernel uses (an error code encoded in a pointer's top 4095 values) is plain C:

#include <stdio.h>
#include <stdint.h>

#define MAX_ERRNO 4095
#define ENOMEM 12
static void *ERR_PTR(long err)        { return (void *)(intptr_t)err; }
static long  PTR_ERR(const void *p)   { return (long)(intptr_t)p; }
static int   IS_ERR(const void *p)    { return (uintptr_t)p >= (uintptr_t)-MAX_ERRNO; }

static int real_object = 42;
static void *get_resource(int fail) { return fail ? ERR_PTR(-ENOMEM) : &real_object; }

int main(void) {
  for (int fail = 0; fail <= 1; fail++) {
    void *p = get_resource(fail);
    if (IS_ERR(p)) printf("error %ld\n", PTR_ERR(p));
    else printf("got object %d\n", *(int *)p);
  }
  return 0;
}

Pitfall: Calling a function that may sleep (mutex_lock, kmalloc(GFP_KERNEL), an I2C transfer) from an interrupt handler or while holding a spinlock causes "BUG: scheduling while atomic". Use threaded IRQs and the right lock type.

Interview question: Walk through how a platform driver binds to hardware described in the device tree.

Answer: At boot the kernel creates platform devices from device-tree nodes with status "okay". The driver registers a platform_driver with an of_match_table listing compatible strings. When a node's compatible matches, the platform bus calls the driver's probe with the device. Probe allocates driver data with devm_kzalloc, maps registers from the reg property with devm_platform_ioremap_resource, gets the IRQ, clocks, GPIOs and regulators, initialises the hardware, and registers with a subsystem or as a character device. Resources obtained with devm_ helpers are released automatically on remove or failure.

Interview question: Why use copy_to_user rather than writing directly to a user-supplied pointer in a driver?

Answer: The pointer comes from an untrusted application: it may be invalid, point into kernel memory, or refer to a page that is not currently mapped. copy_to_user checks that the destination is a valid user-space address range and handles page faults safely, returning the number of bytes not copied, so the driver can return -EFAULT. Dereferencing it directly could crash the kernel or let an application make the kernel overwrite kernel memory, a serious security vulnerability.

Build it: a /dev node for the Zigbee radio

This is step 4 of the module project, the smart-home gateway. The Zigbee radio sends its frames over a serial link, and the gateway's driver exposes them as /dev/zbradio for the Zigbee daemon to read. Bytes arrive in the interrupt handler, which puts them in a ring buffer; the daemon's read() calls take them out. A read() that returns 0 tells the daemon the device has gone away, and one that touches a user pointer directly is a security hole: the details matter.

Lab: The ring buffer and read() of a character driver

The ring holds RING_SIZE bytes, with free-running counters: head counts bytes ever written, tail bytes ever read, the ring holds head - tail bytes, and a counter's position in buf is counter & (RING_SIZE - 1).

  • zb_irq_rx(d, byte) runs in the interrupt handler for each received byte. If the ring is full, count the byte in overruns and drop it; never overwrite unread data.
  • zb_read(d, ubuf, count, nonblock) is the driver's read():
  • count 0: return 0.
  • Ring empty: with nonblock set (the daemon opened the device with O_NONBLOCK), return -EAGAIN. Otherwise call wait_for_data(d), which sleeps until the interrupt handler adds data, and return its result if it is not 0 (-ERESTARTSYS: a signal woke the reader). Check the ring again after waking.
  • Otherwise copy up to count of the waiting bytes to user space, in two pieces when they wrap round the end of buf. User memory may only be written with copy_to_user(to, from, n), which returns the number of bytes it could not copy: if that is not 0, return -EFAULT and leave the data in the ring.
  • Return the number of bytes copied. Never return 0 for "nothing yet": to a reader, 0 means end of file.

Going deeper

Interview question: How would you expose a custom sensor board to applications on an embedded Linux device?

Answer: Write a kernel driver that binds from the device tree, talks to the sensor over its bus, and exposes readings through a standard subsystem (IIO for sensors, hwmon for temperatures) rather than a custom character device, so standard tools and libraries work. Handle power management and errors, and upstream it if it is general.

Interview question: What is the difference between a spinlock and a mutex in the kernel?

Answer: A spinlock busy-waits and never sleeps, so it can be used in interrupt context and protects very short critical sections; the variants with _irqsave also disable local interrupts to prevent deadlock with handlers. A mutex puts the waiting task to sleep, so it suits longer sections in process context but must never be taken in interrupt context or while holding a spinlock.

Interview question: Why prefer the IIO subsystem over a custom character device for a sensor?

Answer: IIO gives a standard interface: sysfs attributes for raw values, scale and offset, buffered capture with triggers, events, and existing user-space tools and libraries (libiio) that work with any IIO device. A custom character device requires a custom protocol and tools, and duplicates buffering and configuration logic. Using the right subsystem also eases upstreaming.

Explain it: In your own words, explain what happens when a platform driver is probed.

Answer: When the kernel creates a device from a device-tree node and finds a driver whose compatible string matches, it calls the driver's probe function with that device. Probe allocates its private data, maps the register region given in the node, obtains the interrupt, clocks, resets, GPIOs and regulators, enables and initialises the hardware, and registers the device with the appropriate subsystem or creates a device node so user space can use it. If a dependency is not ready yet it returns a defer code and is retried later; resources taken with the managed helpers are released automatically on removal or failure.