Tag: linux driver tutorial

  • Linux Platform Driver Tutorial: Probe, Device Tree & Resources

    Updated October 8, 2026. This tutorial explains the Linux platform-driver model and shows a minimal driver that can bind to a matching firmware-described device. It is a learning example, not a driver for real hardware: the compatible string and binding must be supplied by a board or device-tree binding that actually describes the device.

    A platform driver does not create or discover arbitrary hardware by itself. The kernel enumerates a platform device—commonly from Device Tree, ACPI, or board setup—and the driver core matches it to a registered platform_driver. Only then does the core call probe().

    When to use a platform driver

    The platform bus is commonly used for SoC-integrated peripherals and some legacy devices with directly addressable resources. Devices on buses with their own discovery and driver models, such as PCI, USB, I2C, or SPI, should normally use that bus’s driver model instead. See the current Linux platform-device documentation before choosing the bus.

    1. Prepare a safe development environment

    Build against the headers and configuration for the target kernel. A virtual machine or QEMU test system is preferable while learning: an incorrect kernel module can crash or corrupt the running system. Do not load experimental modules on a production device.

    sudo apt update
    sudo apt install build-essential linux-headers-$(uname -r)
    ls /lib/modules/$(uname -r)/build

    On a cross-compiled embedded target, use that target’s kernel source, configuration, and toolchain rather than the headers for your development PC. Kernel APIs change over time, so the target kernel tree is the final authority.

    2. Write a minimal matching platform driver

    This example only logs when the driver binds and unbinds; it does not access registers or control hardware. The placeholder compatible value must be replaced with a real binding string already used by the target device tree. Without a matching enumerated device, the module can load successfully and probe() will not run.

    #include <linux/module.h>
    #include <linux/of.h>
    #include <linux/platform_device.h>
    
    static int example_probe(struct platform_device *pdev)
    {
        dev_info(&pdev->dev, "matched example platform device\n");
        return 0;
    }
    
    static void example_remove(struct platform_device *pdev)
    {
        dev_info(&pdev->dev, "example platform device removed\n");
    }
    
    static const struct of_device_id example_of_match[] = {
        { .compatible = "example,platform-device" },
        { }
    };
    MODULE_DEVICE_TABLE(of, example_of_match);
    
    static struct platform_driver example_driver = {
        .probe = example_probe,
        .remove = example_remove,
        .driver = {
            .name = "example-platform",
            .of_match_table = example_of_match,
        },
    };
    module_platform_driver(example_driver);
    
    MODULE_LICENSE("GPL");
    MODULE_DESCRIPTION("Minimal platform driver example");

    The empty final entry in the match table is required. MODULE_DEVICE_TABLE() makes the match information available to module tooling. Current upstream kernels use a void remove() callback; older kernel branches may use a different signature, so compile against the exact target headers and follow that tree’s platform_driver definition.

    3. Build the external module

    Save the source as example_platform.c and create a Makefile in the same directory:

    obj-m += example_platform.o
    KDIR ?= /lib/modules/$(shell uname -r)/build
    PWD := $(shell pwd)
    
    all:
    	$(MAKE) -C $(KDIR) M=$(PWD) modules
    
    clean:
    	$(MAKE) -C $(KDIR) M=$(PWD) clean

    Run make using the matching build tree. A successful build produces example_platform.ko. A module may still be rejected at load time if its vermagic, signing requirements, architecture, or kernel configuration do not match the running target.

    4. Describe real hardware with a binding

    For a Device Tree system, the device node is part of the board description and must follow the device’s documented binding. A node may describe resources such as registers, interrupts, clocks, resets, and power domains, but their addresses and specifiers are specific to the SoC and board. Do not copy fabricated addresses or interrupt numbers from a generic tutorial.

    For upstreamable drivers, add or update a YAML schema under Documentation/devicetree/bindings/ and validate it with the kernel’s Device Tree checks. Read the Device Tree usage model and the binding documentation for the target subsystem.

    Platform devices may also be enumerated through ACPI or board setup. An OF match table alone only matches Device Tree devices; add ACPI or platform-ID matching only when the hardware and target kernel require it.

    5. Acquire resources in probe()

    A real probe function should validate the device and acquire each resource through the device-managed APIs where appropriate. Common helpers include platform_get_resource() with devm_ioremap_resource() for a memory resource, platform_get_irq() for an IRQ, and the clock, reset, regulator, GPIO, and DMA frameworks for their respective resources. Check every return value, propagate errors, and use -EPROBE_DEFER when a required supplier is not ready yet.

    Do not dereference a missing resource, invent register layouts, or access MMIO before the resource has been reserved and mapped. Use the subsystem’s established helpers rather than raw addresses. Keep interrupt handlers short and move work that may sleep into a threaded handler or workqueue.

    6. Build, bind, and debug

    • Confirm that the device exists in the target’s firmware description and that its compatible string matches the driver table.
    • Check /sys/bus/platform/devices/ and /sys/bus/platform/drivers/ to inspect enumerated devices and registered drivers.
    • Read the exact kernel log message with dmesg or the system journal; distinguish a module-load failure from a device-match or probe failure.
    • Check the probe return value and resource errors. A deferred probe is different from a failed match.
    • Use a VM, QEMU, or a dedicated development board for module-load tests; remove the module and restore the test system if it becomes unstable.

    The official external-module build guide and platform bus documentation describe the supported build and driver-model interfaces.

    Common mistakes

    • Expecting probe() to run without an enumerated device that matches the driver.
    • Registering a fake platform device from the same driver module as a shortcut; device enumeration normally belongs to firmware or board setup.
    • Copying Device Tree register addresses, interrupt cells, or clock names from another board.
    • Ignoring errors from resource helpers or suppressing deferred-probe errors.
    • Using a remove() signature from a different kernel version or adding manual cleanup for resources already managed by devm APIs.
    • Treating a character device and a platform driver as alternatives: a platform driver binds hardware to a bus; a character-device interface is a separate userspace API that may be added when the hardware requires one.

    Further reading

    Start with the Linux platform driver model, the Device Tree usage model, and the Kbuild external-module documentation. For register-level work, continue with the documentation for the specific subsystem and board; a generic example cannot safely define hardware resources for you.

    For broader interview preparation, see our Linux device-driver interview roadmap.

  • How to Write a Network Driver in Linux: A Beginner’s Complete Guide

    Learn how to write a network driver in Linux from scratch. This beginner-friendly guide covers kernel modules, net_device, sk_buff, ndo operations, and everything you need to build your first Linux network driver.

    If you’ve ever wondered what happens between the moment your application sends data and the moment it actually leaves your NIC (network interface card), you’re asking the right question. The answer lives inside the Linux kernel, specifically inside a network driver in Linux.

    Writing one from scratch sounds scary. It’s not. It’s actually one of the most satisfying things you can do as a Linux developer once you understand the moving parts. So let’s walk through it together, step by step, the way a senior kernel developer would explain it to you over coffee.

    What Is a Network Driver in Linux, Really?

    A Linux network driver is a piece of kernel code that acts as the translator between the Linux networking stack and your actual hardware (or virtual hardware). Think of it as a contract: the kernel says “I need you to send this data,” and your driver figures out how to talk to the hardware to make that happen.

    Unlike a userspace program, a Linux driver lives inside the kernel. That means it runs with full hardware access, no memory protection between itself and the kernel, and absolutely zero tolerance for bugs. One NULL pointer dereference and the whole system panics.

    That’s part of what makes Linux kernel module programming exciting, and also why understanding the fundamentals before writing a single line is worth your time.

    Types of Devices in the Linux Kernel

    Before writing anything, you should understand where network drivers sit in the kernel hierarchy.

    The Linux kernel organizes drivers into three main categories:

    Character devices handle data as a stream of bytes, like a serial port or a keyboard. Block devices deal with fixed-size blocks of data, like hard drives. Network devices are completely different from both.

    Network devices don’t have a corresponding file in /dev. You don’t open() or read() them like character devices. Instead, the Linux networking subsystem talks to them through a well-defined set of operations registered via a structure called net_device. That’s the core abstraction you need to understand for Linux network interface driver development.

    The Big Picture: How Linux Network Driver Development Works

    Here’s the high-level flow before we write a single line of code:

    1. You write a kernel module that registers itself with the networking subsystem.
    2. That module allocates and configures a net_device structure.
    3. You fill in the network device operations (the net_device_ops struct) that tell the kernel how to use your driver.
    4. The kernel’s networking stack calls those operations whenever it needs to send or receive data.
    5. On receive, your driver hands a packet up to the kernel using an sk_buff (socket buffer).
    6. On transmit, the kernel hands your driver an sk_buff and says “send this.”

    That’s the whole model. Everything else is implementation details.

    Setting Up Your Linux Driver Development Environment

    You’ll need the right tools before you start writing your Linux network driver example. Here’s what to set up on a typical Ubuntu or Debian system:

    sudo apt update
    sudo apt install build-essential linux-headers-$(uname -r) git
    

    The linux-headers package gives you the kernel header files you need to compile kernel modules. Always match them to your running kernel version using uname -r.

    Create a working directory:

    mkdir ~/mynetdrv && cd ~/mynetdrv
    

    You’ll need two files to get started: your driver source file (let’s call it mynetdrv.c) and a Makefile.

    Writing Your First Linux Kernel Module

    Every kernel module starts with two functions: module_init() and module_exit(). These are the entry and exit points, similar to main() in a regular C program but for kernel space.

    Here’s the skeleton:

    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/init.h>
    #include <linux/netdevice.h>
    #include <linux/etherdevice.h>
    #include <linux/skbuff.h>
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Your Name");
    MODULE_DESCRIPTION("A simple virtual network driver");
    
    static int __init mynetdrv_init(void)
    {
        printk(KERN_INFO "mynetdrv: loaded\n");
        return 0;
    }
    
    static void __exit mynetdrv_exit(void)
    {
        printk(KERN_INFO "mynetdrv: unloaded\n");
    }
    
    module_init(mynetdrv_init);
    module_exit(mynetdrv_exit);
    

    This compiles and loads cleanly but does nothing useful yet. Let’s add the actual network device.

    Understanding the net_device Structure

    The net_device structure is the heart of Linux network driver development. It’s a massive struct defined in <linux/netdevice.h> that holds everything the kernel needs to know about your network interface: its name, its MAC address, its MTU, its statistics, and most importantly, a pointer to your net_device_ops.

    You don’t allocate net_device directly with kmalloc. You use alloc_netdev() or, for Ethernet specifically, alloc_etherdev(). These functions allocate the structure properly and set up sensible defaults.

    static struct net_device *mydev;
    
    mydev = alloc_etherdev(sizeof(struct mynetdrv_priv));
    if (!mydev) {
        printk(KERN_ERR "mynetdrv: alloc_etherdev failed\n");
        return -ENOMEM;
    }
    

    The sizeof(struct mynetdrv_priv) argument lets you piggyback your own private data right after the net_device in memory. You retrieve it later using netdev_priv(dev).

    Defining Your Private Driver Data

    Almost every real-world driver needs to track its own state, things like hardware registers, spin locks, statistics counters, or DMA buffers. This is where your private structure comes in:

    struct mynetdrv_priv {
        struct net_device_stats stats;
        spinlock_t lock;
        /* Add hardware-specific fields here */
    };
    

    You initialize this after alloc_etherdev():

    struct mynetdrv_priv *priv = netdev_priv(mydev);
    memset(priv, 0, sizeof(struct mynetdrv_priv));
    spin_lock_init(&priv->lock);
    

    Filling in the net_device_ops

    This is where you define what your driver can actually do. The net_device_ops structure contains function pointers for every operation the kernel might call on your device. For a minimal network driver in Linux, you need at least these:

    static const struct net_device_ops mynetdrv_ops = {
        .ndo_open        = mynetdrv_open,
        .ndo_stop        = mynetdrv_stop,
        .ndo_start_xmit  = mynetdrv_tx,
        .ndo_get_stats   = mynetdrv_stats,
    };
    

    Let’s implement each one.

    Implementing ndo_open and ndo_stop

    ndo_open is called when someone runs ifconfig mydev0 up or ip link set mydev0 up. This is where you allocate hardware resources, enable interrupts, and tell the kernel the device is ready to transmit.

    static int mynetdrv_open(struct net_device *dev)
    {
        /* In a real driver: enable hardware, request IRQ, start DMA */
        netif_start_queue(dev);
        printk(KERN_INFO "mynetdrv: interface opened\n");
        return 0;
    }
    

    netif_start_queue() tells the networking subsystem that this device is ready to accept outgoing packets. Without this call, the kernel won’t pass anything to your ndo_start_xmit.

    ndo_stop is the reverse. It’s called when the interface goes down:

    static int mynetdrv_stop(struct net_device *dev)
    {
        netif_stop_queue(dev);
        /* In a real driver: disable hardware, free IRQ, stop DMA */
        printk(KERN_INFO "mynetdrv: interface stopped\n");
        return 0;
    }
    

    The Most Important Function: ndo_start_xmit

    If there’s one function in Linux network driver development you need to truly understand, it’s ndo_start_xmit. This is what the kernel calls every time it wants to send a packet through your interface.

    The function receives a pointer to an sk_buff (socket buffer) and the net_device. Your job is to take that packet, do whatever hardware-specific magic is needed to transmit it, and return a status code.

    static netdev_tx_t mynetdrv_tx(struct sk_buff *skb, struct net_device *dev)
    {
        struct mynetdrv_priv *priv = netdev_priv(dev);
        int len = skb->len;
    
        /* For a loopback/virtual driver: just receive the packet back */
        /* In a real driver: write to hardware TX ring, trigger DMA */
    
        priv->stats.tx_packets++;
        priv->stats.tx_bytes += len;
    
        /* Free the socket buffer when done */
        dev_kfree_skb(skb);
    
        return NETDEV_TX_OK;
    }
    

    For a virtual or loopback driver, you can simulate reception by calling netif_rx() with a copy of the packet. For a real hardware driver, this is where you’d write to your hardware’s transmit ring buffer and fire off the DMA engine.

    Understanding sk_buff: The Linux Socket Buffer

    The sk_buff structure (socket buffer) is how the Linux networking stack passes packets between layers. It’s one of the most important data structures in the entire Linux networking subsystem. Understanding it is non-negotiable for serious Linux kernel networking work.

    Key fields you’ll use:

    • skb->data — pointer to the start of the packet data
    • skb->len — total length of the packet
    • skb->head and skb->end — boundaries of the buffer
    • skb->next / skb->prev — for when packets are queued

    When receiving a packet from hardware, you allocate a new sk_buff using dev_alloc_skb(), copy your packet data in, and hand it to the kernel with netif_rx() or napi_gro_receive().

    /* Simulated receive path */
    static void mynetdrv_rx(struct net_device *dev, int len, unsigned char *buf)
    {
        struct sk_buff *skb;
        struct mynetdrv_priv *priv = netdev_priv(dev);
    
        skb = dev_alloc_skb(len + 2);
        if (!skb) {
            priv->stats.rx_dropped++;
            return;
        }
    
        skb_reserve(skb, 2); /* align IP header on 16-byte boundary */
        memcpy(skb_put(skb, len), buf, len);
    
        skb->dev = dev;
        skb->protocol = eth_type_trans(skb, dev);
        skb->ip_summed = CHECKSUM_UNNECESSARY;
    
        priv->stats.rx_packets++;
        priv->stats.rx_bytes += len;
    
        netif_rx(skb);
    }
    

    Getting Statistics Back to the Kernel

    The ndo_get_stats function is simple but important. This is what populates the output when you run ifconfig or ip -s link:

    static struct net_device_stats *mynetdrv_stats(struct net_device *dev)
    {
        struct mynetdrv_priv *priv = netdev_priv(dev);
        return &priv->stats;
    }
    

    Always keep your TX/RX packet and byte counters accurate. Tools like ethtool, iftop, and monitoring systems like Prometheus depend on these numbers being right.

    Registering and Unregistering the Device

    Once all your operations are set up, you wire everything together in module_init and register the device with the kernel using register_netdev():

    static int __init mynetdrv_init(void)
    {
        int ret;
    
        mydev = alloc_etherdev(sizeof(struct mynetdrv_priv));
        if (!mydev)
            return -ENOMEM;
    
        /* Set a fake MAC address */
        eth_hw_addr_random(mydev);
    
        mydev->netdev_ops = &mynetdrv_ops;
        strncpy(mydev->name, "mydev%d", IFNAMSIZ);
    
        ret = register_netdev(mydev);
        if (ret) {
            printk(KERN_ERR "mynetdrv: register_netdev failed: %d\n", ret);
            free_netdev(mydev);
            return ret;
        }
    
        printk(KERN_INFO "mynetdrv: registered as %s\n", mydev->name);
        return 0;
    }
    
    static void __exit mynetdrv_exit(void)
    {
        unregister_netdev(mydev);
        free_netdev(mydev);
        printk(KERN_INFO "mynetdrv: unregistered\n");
    }
    

    register_netdev() is what makes your driver visible to the system. After this call succeeds, you’ll see the interface when you run ip link show.

    Writing the Makefile

    Compiling a Linux kernel module requires a specific Makefile format that hands control off to the kernel build system (kbuild):

    obj-m += mynetdrv.o
    
    all:
    	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
    
    clean:
    	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
    

    Build and load it:

    make
    sudo insmod mynetdrv.ko
    dmesg | tail -10
    ip link show
    

    You should see your new interface mydev0 appear in the output of ip link show. To remove it:

    sudo rmmod mynetdrv
    

    Interrupt Handling in Real Hardware Drivers

    A virtual driver gets away without interrupts, but a real Linux device driver development project requires an interrupt handler. When hardware finishes sending or receives a new packet, it fires an interrupt to tell the CPU.

    You request an IRQ line in ndo_open:

    ret = request_irq(dev->irq, mynetdrv_interrupt, IRQF_SHARED, dev->name, dev);
    

    And release it in ndo_stop:

    free_irq(dev->irq, dev);
    

    Your interrupt handler processes the event and schedules NAPI polling (more on that below) or directly calls netif_rx() if you’re on a simple non-NAPI design.

    NAPI: The Modern Way to Handle Receive in Linux Drivers

    If you’re writing a high-performance Linux network interface driver, you’ll want to use NAPI (New API). NAPI is a hybrid interrupt/polling mechanism that dramatically reduces interrupt overhead under high network load.

    Here’s how it works: when a packet arrives, your interrupt handler disables further RX interrupts and schedules a NAPI poll. The kernel then calls your poll function in a softirq context to drain as many packets as possible from the hardware ring buffer. When the ring is empty, you re-enable interrupts.

    /* In your private struct */
    struct napi_struct napi;
    
    /* During init */
    netif_napi_add(dev, &priv->napi, mynetdrv_poll, 64);
    
    /* In interrupt handler */
    napi_schedule(&priv->napi);
    
    /* Your poll function */
    static int mynetdrv_poll(struct napi_struct *napi, int budget)
    {
        struct mynetdrv_priv *priv = container_of(napi, struct mynetdrv_priv, napi);
        int work_done = 0;
    
        while (work_done < budget && /* packets available */) {
            /* process one packet */
            work_done++;
        }
    
        if (work_done < budget) {
            napi_complete_done(napi, work_done);
            /* re-enable hardware RX interrupts */
        }
    
        return work_done;
    }
    

    NAPI is used by virtually every production-quality Linux network driver today, from Intel’s igb to Broadcom’s bnxt_en.

    Debugging Your Linux Network Driver

    Debugging kernel code is different from debugging userspace apps. You can’t attach GDB directly (well, you can with KGDB but it’s complex). Your main tools are:

    printk / pr_info / netdev_info — Use these liberally during development. netdev_info(dev, "message\n") is preferred because it automatically prefixes your message with the interface name.

    dmesg — This is where your printk messages land. Use dmesg -w to watch in real time.

    dynamic debug — The kernel has a powerful mechanism to enable/disable debug messages at runtime without recompiling. Add pr_debug() calls and enable them with:

    echo "module mynetdrv +p" > /sys/kernel/debug/dynamic_debug/control
    

    QEMU + KVM — Seriously, do all your early development inside a VM. Crashing a virtual machine is painless. Crashing your workstation mid-session is not.

    addr2line — When you get an Oops in dmesg, the stack trace contains hex addresses. addr2line turns those back into file names and line numbers in your source.

    Common Mistakes Beginners Make

    Forgetting to free the sk_buff. If your transmit path doesn’t call dev_kfree_skb(skb), you leak memory on every sent packet. The system will eventually OOM.

    Not calling netif_start_queue. Your ndo_start_xmit will never be called if you forget this in ndo_open.

    Sleeping in interrupt context. You cannot call any function that might sleep (like kmalloc with GFP_KERNEL, mutex_lock, etc.) from an interrupt handler or softirq. Use GFP_ATOMIC for allocations in those contexts.

    Incorrect locking. The networking subsystem makes calls to your driver from multiple contexts. Use spin locks (not mutexes) for protecting shared state in paths that can run in interrupt context.

    Not handling errors. alloc_etherdev, register_netdev, request_irq — all of these can fail. Always check return values and unwind cleanly on failure.

    Real-World Linux Network Driver Examples to Study

    Once you have the basics down, the best way to level up is reading production drivers in the kernel source. Start with these:

    drivers/net/loopback.c — The Linux loopback driver. Tiny, clean, and a perfect reference for virtual devices.

    drivers/net/virtio_net.c — The VirtIO network driver used in QEMU/KVM virtual machines. Great for understanding the full NAPI receive path.

    drivers/net/ethernet/intel/e1000/ — Intel’s classic Gigabit Ethernet driver. Older but very well documented and readable.

    drivers/net/tun.c — The TUN/TAP driver used by VPNs and virtual networks. Shows how to bridge kernel and userspace cleanly.

    You can browse all of these at https://elixir.bootlin.com/linux/latest/source, which is the cross-referenced Linux kernel source. It’s an invaluable resource for Linux kernel module programming.

    Where to Go From Here

    Writing a network driver in Linux gives you a perspective on the system that most developers never get. You stop thinking about the network as a black box and start seeing it for what it is: a chain of well-defined interfaces, from your physical NIC all the way up to your application’s socket.

    Once you’re comfortable with the basics covered here, the natural next steps are:

    • Learn ethtool support so users can query driver settings from userspace
    • Add netpoll support for use with network console and net dumping
    • Study XDP (eXpress Data Path) for high-performance packet processing that bypasses the normal networking stack
    • Understand device tree bindings if you’re writing drivers for embedded ARM boards
    • Look into PCIe driver initialization using pci_register_driver() for real hardware drivers

    The Linux kernel documentation at https://www.kernel.org/doc/html/latest/networking/index.html is solid and worth bookmarking. The book Linux Device Drivers by Corbet, Rubini, and Kroah-Hartman (available free at lwn.net) is the canonical reference.

    Summary

    Here’s everything we covered in one place:

    • A network driver in Linux connects the kernel’s networking stack to your hardware
    • Use alloc_etherdev() to allocate a net_device, not raw kmalloc
    • Fill in net_device_ops with at minimum ndo_open, ndo_stop, ndo_start_xmit, and ndo_get_stats
    • sk_buff (socket buffer) is how packets move through the kernel — know its key fields
    • Use register_netdev() to make your interface visible to the system
    • For real hardware, request an IRQ in ndo_open and use NAPI for receive processing
    • Study loopback.c and virtio_net.c as clean reference implementations
    • Always develop inside a VM to keep your main system safe

    The Linux networking stack is one of the best-designed subsystems in the entire kernel. Once you’ve written a driver that registers an interface, sends and receives real packets, and handles errors cleanly, you’ll have a deep appreciation for why Linux powers everything from smartphones to the largest data centers in the world.

    Go build something.

    FAQ: How to Write a Network Driver in Linux

    Q1. What is a network driver in Linux?

    A network driver in Linux is a piece of kernel code that sits between the Linux networking stack and your physical or virtual hardware. It translates high-level kernel requests like “send this packet” into hardware-specific instructions. Unlike character or block device drivers, network drivers don’t appear as files in /dev. Instead they register a net_device structure with the kernel and expose a set of operations the networking subsystem calls directly.

    Q2. Do I need to know C to write a Linux network driver?

    Yes. Linux kernel development is done entirely in C, specifically a subset of C that avoids certain features like floating point and standard library functions. You don’t need to be a C expert to get started, but you should be comfortable with pointers, structs, function pointers, and memory management. If you can write a linked list implementation in C from scratch, you have enough foundation to follow along.

    Q3. What is the net_device structure in Linux?

    The net_device structure is the central data structure for any Linux network interface driver. It holds everything the kernel needs to know about your network interface including its name, MAC address, MTU, flags, and a pointer to your net_device_ops. You never allocate it directly with malloc or kmalloc. Instead you use alloc_etherdev() for Ethernet devices or alloc_netdev() for other types. After filling it in, you register it with register_netdev().

    Q4. What is sk_buff in Linux and why does it matter?

    sk_buff stands for socket buffer. It is the data structure the Linux networking stack uses to pass packets between layers, from your application all the way down to the driver and back up again. When you receive a packet from hardware, you allocate an sk_buff, copy the data in, set the protocol, and hand it to the kernel via netif_rx(). When the kernel wants to send a packet, it passes you an sk_buff in your ndo_start_xmit function. Understanding skb->data, skb->len, skb_put(), and skb_reserve() is essential for any real network driver work.

    Q5. What is ndo_start_xmit and how does it work?

    ndo_start_xmit is the transmit function in your net_device_ops. The kernel calls it every time it wants your driver to send a packet. It receives a pointer to an sk_buff containing the packet data and a pointer to the net_device. Your job is to take that data, push it to the hardware transmit ring or buffer, update your TX statistics, free the sk_buff with dev_kfree_skb(), and return NETDEV_TX_OK. If your hardware buffer is full you can return NETDEV_TX_BUSY, but you must also call netif_stop_queue() before returning and wake the queue back up with netif_wake_queue() once the hardware has room again.

    Q6. What is the difference between netif_rx and napi_gro_receive?

    netif_rx() is the older, simpler way to pass a received packet up to the kernel. You call it directly from your interrupt handler or any context where you have a ready sk_buff. It works fine for low-traffic or virtual drivers. napi_gro_receive() is the modern approach used with NAPI. GRO stands for Generic Receive Offload. It allows the kernel to coalesce multiple small TCP segments into fewer larger ones before passing them up the stack, which reduces CPU overhead significantly at high packet rates. For production hardware drivers, napi_gro_receive() is the right choice.

    Q7. What is NAPI and should I use it in my driver?

    NAPI stands for New API. It is a hybrid interrupt-driven and polling mechanism designed to improve network performance under high load. Without NAPI, every incoming packet triggers a hardware interrupt. At high packet rates this causes interrupt storms that can saturate the CPU. With NAPI, your interrupt handler fires once to signal that packets are available, then disables further RX interrupts and schedules a polling function. The kernel calls your poll function in a softirq context to drain as many packets as possible up to a configurable budget. When the ring is empty you re-enable interrupts. For any driver that will handle real traffic loads, yes, you should use NAPI.

    Q8. How do I compile a Linux kernel module?

    You need the linux-headers package matching your running kernel, which you get with sudo apt install linux-headers-$(uname -r) on Debian-based systems. Your Makefile should use the kbuild system like this: obj-m += yourdriver.o and then call make with the -C flag pointing at /lib/modules/$(shell uname -r)/build. Run make to build, sudo insmod yourdriver.ko to load, and sudo rmmod yourdriver to unload. Use dmesg to see your printk output.

    Q9. How do I debug a Linux network driver?

    Your main tool is printk or the preferred wrapper netdev_info(dev, “message”). All output goes to the kernel ring buffer which you read with dmesg or dmesg -w for live output. For more control, use pr_debug() calls combined with the dynamic debug system, which lets you enable and disable specific debug messages at runtime without recompiling. For serious development, run everything inside a QEMU virtual machine so kernel panics don’t affect your host system. When you do get an Oops, the stack trace in dmesg contains hex addresses you can decode back to source lines using addr2line against your compiled module.

    Q10. Can I write a network driver without real hardware?

    Yes, and it is actually the best way to learn. You can write a fully functional virtual network driver that creates a real interface visible to tools like ip link and ifconfig, sends and receives packets, and maintains proper statistics, all without touching any hardware registers. The Linux loopback driver in drivers/net/loopback.c is a great example of this. The TUN/TAP driver in drivers/net/tun.c is another one. These are legitimate kernel drivers used in production and they work entirely in software.

    Q11. What is register_netdev and when do I call it?

    register_netdev() is the function that makes your network interface visible to the rest of the Linux system. You call it after you have allocated your net_device with alloc_etherdev(), set the netdev_ops pointer, configured the interface name, and set the MAC address. Once register_netdev() returns successfully, the interface will appear in ip link show and users can bring it up. You must call unregister_netdev() in your cleanup path before calling free_netdev(), otherwise you will leak the device or cause a kernel warning.

    Q12. What is the difference between alloc_netdev and alloc_etherdev?

    alloc_etherdev() is just a convenience wrapper around alloc_netdev() that additionally sets up Ethernet-specific defaults like the header operations, the hardware header length, and the address length. If you are writing an Ethernet driver, use alloc_etherdev(). If you are writing a non-Ethernet driver such as a point-to-point link or a tunnel, use alloc_netdev() directly and configure the type-specific fields yourself.

    Q13. How do I handle interrupts in a network driver?

    In your ndo_open function, call request_irq() with your interrupt number, your handler function, the IRQF_SHARED flag if needed, your driver name, and a pointer to your net_device as the dev_id. Your interrupt handler should be fast. It should determine if the interrupt was from your hardware, acknowledge the interrupt to clear it, and then either directly call netif_rx() for simple designs or schedule NAPI polling for production designs. Release the IRQ in your ndo_stop function using free_irq().

    Q14. What are the best Linux network driver examples to study?

    Start with drivers/net/loopback.c because it is tiny and clean. Then look at drivers/net/virtio_net.c which is a full NAPI-based virtual Ethernet driver used in QEMU and KVM virtual machines. For real hardware, the Intel e1000 driver in drivers/net/ethernet/intel/e1000/ is well documented and widely studied. The TUN driver at drivers/net/tun.c is excellent for understanding userspace-kernel bridging. You can browse all of these online at elixir.bootlin.com with full cross-referencing.

    Q15. Is it safe to develop kernel drivers on my main machine?

    No, not when you are learning. A bug in kernel code can panic the entire system instantly. Always use a virtual machine for development. QEMU with KVM works great and you can snapshot your VM state before loading any new module. Once your driver is stable and well-tested, then you can consider running it on real hardware. Many developers keep a dedicated test machine for that purpose.

    Next Steps: Check out our guides on SPI driver development, platform device drivers, and writing device tree overlays on embeddedprep.com/.

  • Master How to Write Platform Devices and Drivers (2026)

    Learn how to write Platform Devices and Drivers from scratch using Device Tree, I2C, interrupts, and testing, explained clearly for beginners.

    If you are stepping into Linux device driver development, sooner or later you will hear one phrase again and again: Platform Devices and Drivers.
    They sound complex at first, but once you understand the flow, they are actually one of the cleanest and most structured ways to write Linux drivers for embedded systems.

    In this article, we will go from zero to a working platform driver.
    We will start with the basic idea, then move step by step through implementation, device tree integration, I2C communication, interrupt handling, and finally testing and debugging.

    What Is Platform Devices and Drivers?

    Platform Devices and Drivers are a Linux kernel mechanism used to describe and manage on-board hardware that is not discoverable dynamically.

    Unlike USB or PCI devices, platform devices do not announce themselves.
    They are usually fixed on the board, soldered directly to the SoC or connected via internal buses like I2C or SPI.

    Examples include:

    • GPIO controllers
    • I2C sensors
    • RTC chips
    • Watchdog timers
    • Custom hardware blocks

    Linux needs a way to:

    1. Describe this hardware
    2. Match it with the correct driver
    3. Initialize it safely during boot

    That is exactly what platform devices and drivers do.

    Why Platform Devices and Drivers Matter in Embedded Linux

    If you work with embedded boards, you will almost always use Platform Devices and Drivers because:

    • Hardware is board-specific
    • There is no auto-detection
    • Device Tree is used to describe hardware
    • Drivers must bind cleanly during boot

    This model separates hardware description (Device Tree) from driver logic (kernel module), which makes systems easier to maintain and port.

    High-Level Architecture

    Before writing any code, let’s understand the flow:

    1. You buy an I2C chip (for example, a temperature sensor)
    2. You connect it to your board
    3. You describe it in the Device Tree
    4. Linux creates a platform device
    5. Your platform driver registers itself
    6. Kernel matches device and driver
    7. probe() function runs
    8. Driver initializes hardware
    9. Device becomes usable from user space

    Once you understand this flow, everything else fits naturally.

    From Purchase to Product: Real-World Scenario

    Let’s make this real.

    Imagine you purchased an I2C temperature sensor that:

    • Works over I2C
    • Has an interrupt pin
    • Is connected to your SoC

    Your goal:

    • Write a Linux driver
    • Handle I2C communication
    • Handle interrupts
    • Expose data to user space

    We will build this using Platform Devices and Drivers.

    Step 1: Understand the Hardware

    Before touching the kernel:

    • Read the datasheet
    • Note the I2C address
    • Register map
    • Interrupt behavior
    • Voltage levels

    Example details:

    • I2C address: 0x48
    • Interrupt active low
    • Data register at 0x00

    Never skip this step. Drivers written without understanding hardware always fail.

    Step 2: Device Tree Basics

    In modern Linux, Device Tree describes platform devices.

    The Device Tree tells the kernel:

    • Where the device is
    • How it is connected
    • What driver should bind to it

    Example Device Tree Node

    i2c1 {
        status = "okay";
    
        temp_sensor@48 {
            compatible = "vendor,temp-sensor";
            reg = <0x48>;
            interrupt-parent = <&gpio1>;
            interrupts = <12 IRQ_TYPE_EDGE_FALLING>;
        };
    };
    

    Important properties:

    • compatible → used for driver matching
    • reg → I2C address
    • interrupts → interrupt configuration

    This node becomes a platform device internally.

    Step 3: Platform Driver Structure

    A platform driver is a kernel module that registers itself using platform_driver.

    Basic Skeleton

    static int temp_probe(struct platform_device *pdev)
    {
        return 0;
    }
    
    static int temp_remove(struct platform_device *pdev)
    {
        return 0;
    }
    
    static const struct of_device_id temp_of_match[] = {
        { .compatible = "vendor,temp-sensor" },
        { }
    };
    MODULE_DEVICE_TABLE(of, temp_of_match);
    
    static struct platform_driver temp_driver = {
        .probe = temp_probe,
        .remove = temp_remove,
        .driver = {
            .name = "temp_sensor",
            .of_match_table = temp_of_match,
        },
    };
    
    module_platform_driver(temp_driver);
    

    This is the heart of Platform Devices and Drivers.

    Step 4: Driver and Device Matching

    Matching happens using the compatible string.

    • Device Tree provides compatible = "vendor,temp-sensor"
    • Driver declares the same string
    • Kernel binds them automatically

    If probe() is not called:

    • Check compatible string
    • Check Device Tree compilation
    • Check kernel logs

    Step 5: Accessing Device Tree Data

    Inside probe(), you can read properties from Device Tree.

    struct device *dev = &pdev->dev;
    struct device_node *np = dev->of_node;
    

    This lets you:

    • Read GPIO numbers
    • Read custom properties
    • Configure behavior per board

    This is why platform drivers are flexible.

    Step 6: Integrating I2C in Platform Drivers

    Many beginners get confused here.

    Yes, the device is on I2C, but the binding still happens via platform devices when using Device Tree.

    You usually:

    • Get the I2C adapter
    • Create an I2C client
    • Communicate using I2C APIs

    Example

    struct i2c_client *client;
    
    client = i2c_new_dummy_device(adapter, 0x48);
    

    Now you can read registers:

    i2c_smbus_read_byte_data(client, 0x00);
    

    This approach keeps hardware description separate from communication logic.

    Step 7: Interrupt Handling

    Interrupts are critical for real devices.

    Get IRQ Number

    int irq = platform_get_irq(pdev, 0);
    

    Register Interrupt Handler

    request_irq(irq, temp_irq_handler,
                IRQF_TRIGGER_FALLING,
                "temp_irq", dev);
    

    Interrupt Handler

    static irqreturn_t temp_irq_handler(int irq, void *dev_id)
    {
        // Read status register
        return IRQ_HANDLED;
    }
    

    Always keep interrupt handlers short and fast.

    Step 8: Exposing Data to User Space

    A driver is useless if user space cannot talk to it.

    Common approaches:

    • sysfs
    • character device
    • IIO subsystem (for sensors)

    Simple sysfs Example

    static ssize_t temp_show(struct device *dev,
                             struct device_attribute *attr,
                             char *buf)
    {
        return sprintf(buf, "25\n");
    }
    
    DEVICE_ATTR_RO(temp);
    

    This creates:

    /sys/devices/.../temp
    

    Step 9: Error Handling and Cleanup

    Good platform drivers always clean up.

    In remove():

    • Free IRQ
    • Unregister I2C client
    • Free memory
    free_irq(irq, dev);
    

    Never assume probe() always succeeds.

    Step 10: Building and Testing

    Compile the Driver

    • Add to kernel tree or as module
    • Enable in menuconfig

    Load Module

    insmod temp_driver.ko
    

    Check Logs

    dmesg | grep temp
    

    Verify Device Tree

    ls /proc/device-tree
    

    Testing is where most learning happens.

    Common Mistakes Beginners Make

    • Wrong compatible string
    • Forgetting to enable I2C bus
    • Interrupt polarity mismatch
    • Blocking code in IRQ handler
    • Ignoring return values

    Every one of these will cost you hours if you ignore basics.

    How to Write Platform Devices and Drivers

    // SPDX-License-Identifier: GPL-2.0
    /*
     * Production-ready Platform Driver example
     * - Device Tree based
     * - I2C sensor
     * - Interrupt handling
     * - sysfs interface
     */
    
    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/platform_device.h>
    #include <linux/of.h>
    #include <linux/of_irq.h>
    #include <linux/i2c.h>
    #include <linux/interrupt.h>
    #include <linux/slab.h>
    #include <linux/mutex.h>
    #include <linux/pm.h>
    #include <linux/sysfs.h>
    
    /* ---------- Driver Private Data ---------- */
    struct temp_dev {
    	struct device       *dev;
    	struct i2c_client   *client;
    	int                  irq;
    	int                  temperature;
    	struct mutex         lock;
    };
    
    /* ---------- I2C Read Helper ---------- */
    static int temp_sensor_read(struct temp_dev *tdev)
    {
    	int ret;
    
    	ret = i2c_smbus_read_byte_data(tdev->client, 0x00);
    	if (ret < 0)
    		dev_err(tdev->dev, "I2C read failed\n");
    
    	return ret;
    }
    
    /* ---------- Interrupt Handler ---------- */
    static irqreturn_t temp_irq_handler(int irq, void *data)
    {
    	struct temp_dev *tdev = data;
    	int temp;
    
    	mutex_lock(&tdev->lock);
    
    	temp = temp_sensor_read(tdev);
    	if (temp >= 0)
    		tdev->temperature = temp;
    
    	mutex_unlock(&tdev->lock);
    
    	dev_info(tdev->dev, "Interrupt: temperature=%d\n",
    		 tdev->temperature);
    
    	return IRQ_HANDLED;
    }
    
    /* ---------- sysfs Interface ---------- */
    static ssize_t temperature_show(struct device *dev,
    				struct device_attribute *attr,
    				char *buf)
    {
    	struct temp_dev *tdev = dev_get_drvdata(dev);
    	int temp;
    
    	mutex_lock(&tdev->lock);
    	temp = tdev->temperature;
    	mutex_unlock(&tdev->lock);
    
    	return sysfs_emit(buf, "%d\n", temp);
    }
    
    static DEVICE_ATTR_RO(temperature);
    
    static struct attribute *temp_attrs[] = {
    	&dev_attr_temperature.attr,
    	NULL,
    };
    
    static const struct attribute_group temp_attr_group = {
    	.attrs = temp_attrs,
    };
    
    /* ---------- Probe Function ---------- */
    static int temp_probe(struct platform_device *pdev)
    {
    	struct temp_dev *tdev;
    	struct i2c_adapter *adapter;
    	struct device *dev = &pdev->dev;
    	int ret;
    
    	dev_info(dev, "Probing temperature sensor\n");
    
    	tdev = devm_kzalloc(dev, sizeof(*tdev), GFP_KERNEL);
    	if (!tdev)
    		return -ENOMEM;
    
    	tdev->dev = dev;
    	mutex_init(&tdev->lock);
    	platform_set_drvdata(pdev, tdev);
    
    	/* Get I2C adapter (from DT bus number) */
    	adapter = i2c_get_adapter(1);
    	if (!adapter) {
    		dev_err(dev, "Failed to get I2C adapter\n");
    		return -ENODEV;
    	}
    
    	/* Create I2C client */
    	tdev->client = i2c_new_dummy_device(adapter, 0x48);
    	i2c_put_adapter(adapter);
    
    	if (IS_ERR(tdev->client)) {
    		dev_err(dev, "Failed to create I2C client\n");
    		return PTR_ERR(tdev->client);
    	}
    
    	/* Read initial value */
    	ret = temp_sensor_read(tdev);
    	if (ret >= 0)
    		tdev->temperature = ret;
    
    	/* Get IRQ from Device Tree */
    	tdev->irq = platform_get_irq(pdev, 0);
    	if (tdev->irq < 0) {
    		dev_err(dev, "Failed to get IRQ\n");
    		return tdev->irq;
    	}
    
    	ret = devm_request_irq(dev,
    			       tdev->irq,
    			       temp_irq_handler,
    			       IRQF_TRIGGER_FALLING,
    			       dev_name(dev),
    			       tdev);
    	if (ret) {
    		dev_err(dev, "Failed to request IRQ\n");
    		return ret;
    	}
    
    	/* Create sysfs group */
    	ret = sysfs_create_group(&dev->kobj, &temp_attr_group);
    	if (ret) {
    		dev_err(dev, "Failed to create sysfs group\n");
    		return ret;
    	}
    
    	dev_info(dev, "Temperature sensor driver loaded\n");
    	return 0;
    }
    
    /* ---------- Remove Function ---------- */
    static int temp_remove(struct platform_device *pdev)
    {
    	struct temp_dev *tdev = platform_get_drvdata(pdev);
    
    	sysfs_remove_group(&pdev->dev.kobj, &temp_attr_group);
    
    	if (tdev->client)
    		i2c_unregister_device(tdev->client);
    
    	dev_info(&pdev->dev, "Temperature sensor removed\n");
    	return 0;
    }
    
    /* ---------- Power Management ---------- */
    #ifdef CONFIG_PM_SLEEP
    static int temp_suspend(struct device *dev)
    {
    	dev_info(dev, "Suspending temperature sensor\n");
    	return 0;
    }
    
    static int temp_resume(struct device *dev)
    {
    	dev_info(dev, "Resuming temperature sensor\n");
    	return 0;
    }
    #endif
    
    static SIMPLE_DEV_PM_OPS(temp_pm_ops,
    			 temp_suspend,
    			 temp_resume);
    
    /* ---------- Device Tree Match ---------- */
    static const struct of_device_id temp_of_match[] = {
    	{ .compatible = "demo,temp-sensor" },
    	{ }
    };
    MODULE_DEVICE_TABLE(of, temp_of_match);
    
    /* ---------- Platform Driver ---------- */
    static struct platform_driver temp_driver = {
    	.probe  = temp_probe,
    	.remove = temp_remove,
    	.driver = {
    		.name           = "temp_sensor",
    		.of_match_table = temp_of_match,
    		.pm             = &temp_pm_ops,
    	},
    };
    
    module_platform_driver(temp_driver);
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Nishant Singh");
    MODULE_DESCRIPTION("Production-ready Platform Driver with I2C and Interrupt");
    

    Device Tree

    &i2c1 {
    	status = "okay";
    
    	temp_sensor@48 {
    		compatible = "demo,temp-sensor";
    		reg = <0x48>;
    		interrupt-parent = <&gpio1>;
    		interrupts = <12 IRQ_TYPE_EDGE_FALLING>;
    	};
    };
    

    User Space Test

    cat /sys/devices/platform/temp_sensor/temperature
    

    Why Platform Devices and Drivers Scale Well

    Once you master Platform Devices and Drivers, you can:

    • Port drivers across boards
    • Reuse Device Tree files
    • Support multiple variants
    • Keep drivers clean and readable

    This is why the Linux kernel strongly encourages this model.

    FAQs : Platform Devices and Drivers.

    1. What are Platform Devices and Drivers in Linux?

    Platform Devices and Drivers are a Linux kernel mechanism used for non-discoverable hardware. These are devices that are permanently attached to the board, like I2C sensors, GPIO controllers, RTCs, and on-chip peripherals. Since such hardware cannot announce itself, Linux relies on the Device Tree to describe it and platform drivers to manage it.

    2. Why do we need Platform Drivers when using Device Tree?

    Device Tree only describes hardware.
    Platform drivers contain the actual code that talks to the hardware. The kernel uses the compatible string in the Device Tree to match a platform device with the correct platform driver and then calls the driver’s probe() function.

    3. What is the role of the probe() function?

    The probe() function is where everything starts. It is called when the kernel successfully matches a platform device with its driver. In probe(), you:

    • Allocate memory
    • Read Device Tree properties
    • Initialize hardware
    • Register interrupts
    • Create sysfs or character devices

    If probe() fails, the device will not work.

    4. How does Device Tree match a Platform Driver?

    Matching is done using the compatible string.
    The Device Tree node provides a compatible property, and the platform driver provides an of_device_id table with the same string. If they match exactly, the kernel binds them together.

    5. Can Platform Drivers be used for I2C or SPI devices?

    Yes. This is very common.
    Even though the device communicates over I2C or SPI, the binding still happens through Platform Devices and Drivers when using Device Tree. Inside the platform driver, you create or access an I2C or SPI client to communicate with the hardware.

    6. What is the difference between a Platform Driver and an I2C Driver?

    An I2C driver is tied directly to the I2C subsystem and is usually auto-created by the I2C core.
    A Platform Driver is more generic and is often used when:

    • You need board-specific logic
    • The device uses multiple resources (IRQ, GPIO, regulators)
    • You want tighter control over initialization

    Both approaches are valid and used in production.

    7. How are interrupts handled in Platform Drivers?

    Interrupts are described in the Device Tree using the interrupts property.
    Inside the driver, you retrieve the IRQ number using platform_get_irq() and register a handler using request_irq() or devm_request_irq(). The interrupt handler should be fast and should avoid sleeping or heavy processing.

    8. What is devm_* and why should it be used?

    devm_* APIs automatically free resources when the device is removed.
    They reduce memory leaks and simplify error handling. In production drivers, devm_kzalloc(), devm_request_irq(), and similar APIs are strongly recommended.

    9. How do Platform Drivers expose data to user space?

    Common methods include:

    • sysfs attributes
    • character devices
    • standard kernel subsystems like IIO, input, or hwmon

    For simple data like sensor readings, sysfs is often enough. For high-performance or streaming data, character devices or IIO are better choices.

    10. What are the most common reasons probe() is not called?

    The most common reasons are:

    • Mismatch in compatible string
    • Device Tree node not compiled or loaded
    • Driver not enabled in kernel configuration
    • Incorrect Device Tree hierarchy (wrong bus node)

    Checking dmesg usually points you in the right direction.

    11. Are Platform Drivers used in real production kernels?

    Absolutely.
    Most SoC drivers, board-level drivers, and embedded peripherals in the Linux kernel are implemented using Platform Devices and Drivers. This model scales well and is heavily used by vendors and upstream kernel developers.

    12. When should I avoid using Platform Devices and Drivers?

    You should avoid platform drivers if:

    • The hardware is self-discoverable (USB, PCI)
    • The kernel already provides a dedicated subsystem driver
    • You are writing a pure user-space driver

    In those cases, platform drivers would add unnecessary complexity.

    You can also read : Linked List Coding Questions

  • How to Write Your First Hello World Driver with Yocto | Master Linux Driver Interview Question (2026)

    How to Write Your First Hello World Driver : Learn step-by-step how to write your first “Hello World” driver with Yocto. This beginner-friendly guide explains kernel module basics, creating a Yocto recipe, building with BitBake, and testing on your embedded Linux board.

    If you’re learning hello world yocto driver and want to understand how device drivers fit into an embedded Linux system, writing a simple Hello World driver is the best starting point. This article will guide you step by step on how to write, compile, and test a kernel module using Yocto.

    How to Write Your First Hello World Driver Step by Step

    Prerequisites for Writing a Hello World Driver with Yocto

    1. Basic Knowledge
      • Understanding of Linux basics (commands, file structure).
      • Some exposure to C programming (especially pointers and functions).
      • Awareness of what a kernel module is.
    2. Yocto Setup
      • A working Yocto build environment (Poky or a vendor BSP like meta-yocto, meta-ti, etc.).
      • You should be able to build at least a core-image-minimal successfully.
    3. Development Machine
      • Ubuntu (20.04 or 22.04 LTS) or Debian recommended.
      • Packages installed: sudo apt-get install gawk wget git-core diffstat unzip texinfo gcc \ build-essential chrpath socat cpio python3 python3-pip python3-pexpect \ xz-utils debianutils iputils-ping
    4. Target Hardware or Emulator
      • A real embedded board (e.g., BeagleBone Black, Raspberry Pi, STM32MP1, Qualcomm, etc.)
      • OR QEMU (Yocto supports running images in QEMU for testing).
    5. Cross-Compilation Knowledge
      • Basic idea of cross-compilation since Yocto builds software for a different architecture than your PC (e.g., ARM target vs x86 build machine).
    6. Kernel Source & Headers
      • Ensure your Yocto build has the kernel source available for building external modules (linux-yocto recipe).
    7. Bitbake & Layers
      • Familiarity with bitbake commands.
      • Knowledge of adding a custom layer using: bitbake-layers add-layer ../meta-myproject

    Git Clone Methods in Yocto Setup

    When working with Yocto, you usually clone the Poky repository (the reference distribution of Yocto). Depending on your internet and use case, you can use either HTTPS or SSH method.

    1. HTTPS Method (Recommended for Beginners)

    This is the easiest and most common. No special keys required.

    git clone git://git.yoctoproject.org/poky
    

    or sometimes:

    git clone https://git.yoctoproject.org/git/poky
    

    👉 Use this if you’re just learning and don’t want to deal with SSH keys.

    2. SSH Method (For Contributors/Advanced Users)

    If you plan to contribute to Yocto or push code, you need an SSH key.

    git clone git@yoctoproject.org:poky
    

    👉 Use this if you have a developer account with Yocto Project and want to push patches.

    3. Cloning a Specific Yocto Release

    Yocto has releases like dunfell, kirkstone, mickledore, etc. After cloning, you can check out a stable branch:

    cd poky
    git checkout kirkstone
    

    👉 Always use an LTS (Long-Term Support) branch if you’re learning (e.g., kirkstone is an LTS release).

    4. Shallow Clone (Faster, Less Disk Space)

    The Yocto repo is big. If you just want the latest branch, use:

    git clone --branch kirkstone --depth=1 git://git.yoctoproject.org/poky
    

    👉 This avoids downloading the full history.

    For Your Hello World Driver Project

    I recommend:

    git clone https://git.yoctoproject.org/git/poky
    cd poky
    git checkout kirkstone   # or the LTS release your board supports
    

    Then add BSP layers for your board (e.g., meta-raspberrypi, meta-ti).

    Step 1: What is Yocto?

    The Yocto Project is a build system for creating custom Linux distributions for embedded devices. It allows you to create minimal Linux images and include your own applications, libraries, and drivers.

    When working with Yocto, you usually create recipes (.bb files) that tell Yocto how to build and install your software.

    Step 2: Write a Simple “Hello World” Linux Driver

    Let’s create a very basic Linux kernel module (driver).

    👉 Create a file named hello.c

    #include <linux/init.h>      // For module init/exit macros
    #include <linux/module.h>    // For all kernel modules
    #include <linux/kernel.h>    // For printk()
    
    static int __init hello_init(void)
    {
        printk(KERN_INFO "Hello, World from Yocto Driver!\n");
        return 0;
    }
    
    static void __exit hello_exit(void)
    {
        printk(KERN_INFO "Goodbye, World from Yocto Driver!\n");
    }
    
    module_init(hello_init);
    module_exit(hello_exit);
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Beginner");
    MODULE_DESCRIPTION("A Simple Hello World Driver for Yocto");
    
    How to Write Your First Hello World Driver with Yocto Write a Simple "Hello World" Linux Driver

    This driver simply prints a message when it is loaded and unloaded.

    Step 3: Create a Makefile

    Create a file named Makefile in the same directory:

    obj-m += hello.o
    
    all:
    	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
    
    clean:
    	make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
    
    How to Write Your First Hello World Driver with Yocto  Makefile

    This allows you to build the kernel module outside the Yocto environment first (just to test).

    Run:

    make
    

    This will generate a file hello.ko (the kernel object module).

    👉 You can load it manually using:

    sudo insmod hello.ko
    dmesg | tail
    

    And remove it using:

    sudo rmmod hello
    dmesg | tail
    

    Step 4: Create a Yocto Recipe for Your Driver

    Now let’s integrate this driver into Yocto.

    Inside your Yocto layer (for example meta-myproject/), create a folder for your driver:

    How to Write Your First Hello World Driver with Yocto | RTOS Interview Question (2025)

    hello.bb (Recipe File)

    DESCRIPTION = "Simple Hello World Kernel Module"
    LICENSE = "GPLv2"
    LIC_FILES_CHKSUM = "file://hello.c;beginline=12;endline=22;md5=3c3e73c4e3f1c0b1c2b0ed8cfae1a777"
    
    SRC_URI = "file://hello.c \
               file://Makefile"
    
    S = "${WORKDIR}"
    
    inherit module
    
    

    Here:

    • inherit module tells Yocto it’s a kernel module.
    • SRC_URI tells Yocto where to find your driver files.

    Step 5: Build with Yocto

    1. Add your layer to Yocto:
    bitbake-layers add-layer ../meta-myproject
    1. Build your driver:
    bitbake hello
    

    After build, the module hello.ko will be available in the Yocto output.

    Step 6: Test the Driver on Target

    Copy the generated .ko file to your embedded board:

    scp tmp/deploy/ipk/*/hello_*.ipk user@board:/home/root/
    

    On the board, install and test:

    opkg install hello_*.ipk
    insmod hello.ko
    dmesg | tail
    

    You should see:

    Hello, World from Yocto Driver!
    

    When removing:

    Goodbye, World from Yocto Driver!
    

    Application Code

    #include <stdio.h>
    int main() {
        printf("Hello, Yocto Krikstone!\n");
        return 0;
    }
    

    Flashing of SD Card using Card Reader USB to SD Card Reader

    How to Write Your First Hello World Driver with Yocto  a)  SD Card Reader
    How to Write Your First Hello World Driver with Yocto  b) balena Tool to flash SD Card

    Target Preparation

    How to Write Your First Hello World Driver with Yocto  c) HW Connection
    How to Write Your First Hello World Driver with Yocto  d) output from serial console

    Conclusion

    Congratulations! 🎉 You just wrote your first Hello World driver with Yocto.

    • You learned how to write a basic Linux kernel module.
    • You created a Yocto recipe for your driver.
    • You built and tested it on your target board.

    This is the foundation. From here, you can extend your driver to work with real hardware like GPIO, I2C, or sensors.

    FAQ Writing Hello World Driver with Yocto

    1. What is Yocto used for?

    Ans: Yocto is a build system that helps developers create custom Linux distributions for embedded devices. It allows you to add drivers, applications, and libraries into your Linux image.

    2. What is a Hello World driver in Linux?

    Ans: A Hello World driver is the simplest Linux kernel module that just prints a message when loaded and unloaded. It helps beginners understand how kernel modules work.

    3. Do I need Yocto to write a Hello World driver?

    Ans : No, you can first write and test it on any Linux system using insmod and rmmod. Yocto is used when you want to integrate the driver into your embedded Linux distribution.

    4. What is the difference between a driver and a kernel module?

    Ans: A driver is a program that lets the kernel communicate with hardware. A kernel module is a piece of code that can be loaded into the Linux kernel at runtime—many drivers are kernel modules.

    5. How do I compile a Hello World driver in Linux?

    Ans: You write the driver code in C, create a Makefile, and run make to build a .ko (kernel object) file. Then use insmod to insert it and dmesg to check messages.

    6. How do I add a driver to Yocto?

    Ans: You create a recipe (.bb file) in a Yocto layer. The recipe tells Yocto how to compile and package your driver. Then you run bitbake to build it.

    7. What is a Yocto recipe?

    Ans: A recipe (.bb file) is a set of instructions used by Yocto to fetch, build, and package software like drivers or applications.

    8. Where can I find the Hello World driver after building with Yocto?

    Ans: Yocto puts the compiled driver (.ko file or .ipk package) in the tmp/deploy/ folder inside your build directory.

    9. How do I test my Yocto driver on the target board?

    Ans: Copy the .ko or .ipk file to your embedded board, use insmod to load the driver, and check logs with dmesg.

    10. Can I extend the Hello World driver to control real hardware?

    Ans: Yes ✅. Once you learn the basics, you can modify the driver to handle GPIO, I2C, SPI, or sensors. This is the next step after the Hello World driver.
    How to Write Your First Hello World Driver with Yocto
    How to Write Your First Hello World Driver with Yocto RTOS Interview Question (2025)