Tag: Linux kernel development

  • 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

  • Master Char Driver Model in Linux (2026): Architecture, Flow & Real Examples

    Learn the Char Driver Model in Linux with a clear, beginner-friendly explanation. Understand structure, flow, key APIs, and real interview-focused concepts step by step.

    The Char Driver Model is one of the most important building blocks in Linux device driver development. It defines how hardware devices that transfer data as a stream of bytes are exposed to user space and controlled through standard system calls. If you want to understand how Linux talks to real hardware, this is where the journey truly begins.

    The article starts by clearly explaining what character drivers are and why they are widely used in Linux systems, especially in embedded, automotive, and custom hardware platforms. You will understand how synchronous drivers work, why blocking behavior exists, and how the kernel efficiently puts processes to sleep instead of wasting CPU cycles.

    We then walk through driver registration and de-registration, explaining how major and minor numbers connect device files in /dev to the correct kernel driver. You will learn how Linux knows which driver should handle a read or write request and why proper cleanup during driver removal is critical for system stability.

    The guide dives deep into the driver file interface, showing how character devices integrate with the Virtual File System. Each device file operation such as open, read, write, release, ioctl, poll, and mmap is explained in plain language with real-world meaning, not just definitions.

    Special focus is given to driver data structures, helping you understand how drivers manage internal state, handle multiple devices, and support multiple processes safely. You will also learn how device configuration operations using ioctl allow flexible control of hardware without breaking user space compatibility.

    Advanced but essential topics like wait queues and polling are covered with clarity, explaining how Linux handles blocking and non-blocking I/O, event-driven applications, and efficient synchronization. The section on memory mapping explains how high-performance drivers avoid unnecessary data copying and safely expose device memory to user space.

    To prepare you for real-world interviews, the guide also aligns closely with Round 1 and Round 2 interview expectations, helping you understand not just what the Char Driver Model is, but how and why it is designed this way.

    By the end of this article, you will have a strong, practical understanding of the Char Driver Model, making you confident in Linux driver interviews, embedded system projects, and kernel-level development work.

    Introduction: Why the Char Driver Model Still Matters

    If you are learning Linux device drivers, the Char Driver Model is not optional knowledge. It is the foundation. Almost every serious kernel developer starts here, because character drivers teach you how the kernel and user space talk to each other.

    Whether you are working on:

    • Embedded Linux
    • Automotive platforms
    • BSP development
    • Custom hardware bring-up

    You will meet character drivers early and often.

    A char driver handles devices that:

    • Transfer data as a stream of bytes
    • Do not use fixed block sizes
    • Often require synchronous or event-driven access

    Examples include:

    • Serial ports
    • GPIO drivers
    • I2C and SPI devices
    • Sensors
    • Custom hardware peripherals

    Understanding the Char Driver Model means understanding how Linux exposes hardware safely, cleanly, and efficiently to user space.

    What Is the Char Driver Model?

    At its core, the Char Driver Model defines how a character device is:

    • Registered with the kernel
    • Exposed to user space as a device file
    • Accessed using standard system calls like open, read, write, and ioctl

    Unlike block drivers (used for disks) or network drivers (used for packets), a char driver:

    • Reads and writes bytes
    • Works sequentially
    • Often operates synchronously

    This makes char drivers simpler to understand and perfect for learning Linux driver architecture.

    Synchronous Drivers Defined

    Let’s clarify something early because this topic confuses beginners.

    What does “synchronous driver” mean?

    A synchronous driver blocks the calling process until an operation completes.

    Example:

    • A user calls read()
    • The driver waits until data is available
    • The process sleeps
    • Data arrives
    • The process wakes up
    • read() returns

    This behavior is extremely common in char drivers.

    Why synchronous behavior matters

    Synchronous drivers:

    • Are easier to reason about
    • Avoid race conditions when designed correctly
    • Match how real hardware behaves

    Linux also supports non-blocking and asynchronous I/O, but the Char Driver Model is built around synchronous behavior first, then extended using:

    • Wait queues
    • Polling
    • Select
    • Async notifications

    We will cover those later.

    Char Driver Model Architecture Overview

    Let’s zoom out and look at the big picture.

    User space talks to a char driver through:

    • /dev device files
    • Standard POSIX system calls

    The kernel connects everything using:

    • Major and minor numbers
    • File operations
    • Internal driver data structures

    The flow looks like this:

    1. Application opens /dev/mydevice
    2. Kernel maps it to a registered char driver
    3. Kernel calls driver callbacks
    4. Driver talks to hardware
    5. Data flows back to user space

    Simple concept. Powerful mechanism.

    Driver Registration and De-registration

    This is where every char driver begins and ends.

    Why registration exists

    Linux needs to know:

    • Which driver owns which device
    • How to route file operations to the correct code

    This is done through driver registration.

    Registering a Char Driver

    The kernel identifies char drivers using:

    • Major number: identifies the driver
    • Minor number: identifies devices handled by that driver

    There are two common approaches:

    Static major number

    You pick a number yourself (not recommended anymore).

    Dynamic major number

    The kernel assigns one for you.

    Modern drivers always use dynamic registration.

    Typical steps:

    1. Allocate device numbers
    2. Initialize character device structure
    3. Add the device to the kernel

    This is where the Char Driver Model starts to feel real.

    Driver De-registration

    When a driver is removed:

    • Device numbers must be freed
    • Kernel objects must be cleaned
    • Memory must be released

    Failing to de-register properly leads to:

    • Kernel crashes
    • Memory leaks
    • Broken /dev nodes

    Clean de-registration is a sign of a professional driver.

    Driver File Interface

    The driver file interface is how Linux makes your hardware look like a file.

    That is not a metaphor. It is literal.

    Everything in Linux is a file, including:

    • Sensors
    • LEDs
    • UARTs
    • Custom ASICs

    The Char Driver Model plugs into the VFS (Virtual File System) layer.

    The Role of /dev

    When you create a device file like:

    /dev/my_char_device
    

    Linux connects:

    • User space file operations
    • To your driver callbacks

    That connection happens through the file operations structure.

    Device File Operations

    This is the heart of the Char Driver Model.

    What are device file operations?

    They are function pointers that define how your driver responds to:

    • open()
    • read()
    • write()
    • close()
    • ioctl()
    • poll()
    • mmap()

    When a user calls read(), the kernel does not read hardware itself.
    It calls your function.

    Common file operations explained

    open

    Called when a process opens the device file.

    Used to:

    • Initialize private data
    • Allocate resources
    • Check permissions

    read

    Transfers data from kernel space to user space.

    Key responsibilities:

    • Copy data safely
    • Handle blocking behavior
    • Respect file position

    write

    Transfers data from user space to kernel space.

    Used for:

    • Sending commands
    • Writing configuration
    • Controlling hardware behavior

    release (close)

    Called when the file descriptor is closed.

    Used to:

    • Free resources
    • Decrement usage counters

    ioctl: Device configuration ops

    This deserves its own section.

    Device Configuration Ops (ioctl)

    Not all device control fits into read and write.

    That is why device configuration ops exist.

    The ioctl() system call allows:

    • Sending control commands
    • Passing structured data
    • Changing device modes

    Examples:

    • Set baud rate
    • Enable interrupts
    • Switch operating modes
    • Query device status

    In the Char Driver Model, ioctl is how drivers stay flexible without breaking APIs.

    Why ioctl must be designed carefully

    Bad ioctl design causes:

    • ABI breakage
    • Security issues
    • Maintenance nightmares

    Good ioctl design:

    • Uses versioned commands
    • Validates input
    • Copies data safely

    Driver Data Structures

    Behind every clean driver is a solid data model.

    Why driver data structures matter

    Drivers need to store:

    • Device state
    • Hardware configuration
    • Buffers
    • Synchronization primitives

    This data must:

    • Be private to the driver
    • Be safe in concurrent access
    • Scale across multiple devices

    Common driver data structures

    Most char drivers use:

    • A per-device structure
    • A pointer stored in file->private_data

    This allows:

    • Multiple processes
    • Multiple devices
    • Clean separation of state

    Good data structure design makes the rest of the driver simpler.

    Wait Queues and Polling

    Now we get into real-world behavior.

    Why wait queues exist

    Hardware is slow. CPUs are fast.

    Instead of busy-waiting, Linux uses wait queues.

    When a process needs data:

    • It sleeps
    • The driver puts it on a wait queue
    • Hardware interrupt occurs
    • Driver wakes the process

    This is efficient and scalable.

    Blocking vs non-blocking I/O

    Blocking:

    • read() waits until data is ready

    Non-blocking:

    • read() returns immediately
    • Application retries later

    The Char Driver Model supports both.

    Polling and select

    Applications often want to wait on:

    • Multiple devices
    • Timers
    • Sockets

    The poll() and select() interfaces allow this.

    Your driver must:

    • Implement a poll callback
    • Report readiness correctly

    This is essential for:

    • Event-driven applications
    • GUI programs
    • Embedded control loops

    Memory Mapping

    This is where char drivers become powerful.

    What is memory mapping?

    Memory mapping allows:

    • User space to access device memory directly
    • Zero-copy data transfer
    • High performance I/O

    Instead of copying data, the kernel maps memory into user space.

    When memory mapping is useful

    Common use cases:

    • Frame buffers
    • ADC buffers
    • DMA memory
    • High-speed sensors

    The Char Driver Model supports memory mapping using mmap().

    Safety considerations

    Memory mapping must:

    • Restrict access properly
    • Prevent kernel memory leaks
    • Validate ranges

    Done correctly, it is fast and safe.

    Done poorly, it crashes systems.

    How All Pieces Fit Together

    Let’s connect everything.

    A typical char driver:

    • Registers itself with the kernel
    • Creates a device file
    • Implements file operations
    • Manages driver data structures
    • Handles synchronous access
    • Uses wait queues for blocking I/O
    • Supports polling for event-driven apps
    • Exposes configuration via ioctl
    • Optionally supports memory mapping

    This is the Char Driver Model in action.

    Common Mistakes Beginners Make

    Let’s be honest.

    Most first drivers fail because of:

    • Poor synchronization
    • Missing error handling
    • Incorrect user memory access
    • Forgetting de-registration
    • Unsafe ioctl implementations

    Avoiding these mistakes puts you ahead of 80 percent of beginners.

    Why the Char Driver Model Is Still Relevant in 2026

    Despite newer frameworks:

    • Char drivers remain the backbone
    • Many subsystems still rely on them
    • Embedded Linux depends heavily on char devices

    If you want to:

    • Write custom drivers
    • Understand kernel internals
    • Debug low-level issues

    You must master the Char Driver Model.

    Char Driver Model Interview Questions and Answers

    ROUND 1: Basics & Conceptual Questions

    1. What is a character driver in Linux?

    A character driver is a Linux device driver that transfers data as a stream of bytes. It does not use fixed-size blocks like disk drivers. User space interacts with it using standard system calls like open, read, write, and ioctl through a device file in /dev.

    2. What is the Char Driver Model?

    The Char Driver Model defines how a character device is registered with the kernel, how it is exposed to user space, and how file operations from applications are handled inside the driver.

    3. What are some real examples of character devices?

    Serial ports, GPIO drivers, I2C devices, SPI devices, sensors, LEDs, RTCs, and many embedded peripherals are implemented as character drivers.

    4. What is meant by synchronous drivers?

    Synchronous drivers block the calling process until the requested operation completes. For example, a read call waits until data is available instead of returning immediately.

    5. What is a device file?

    A device file is a special file created in /dev that represents a hardware device. It acts as the connection point between user space and the kernel driver.

    6. What is a major number?

    The major number identifies the driver in the kernel. When a device file is accessed, the kernel uses the major number to find which driver should handle the request.

    7. What is a minor number?

    The minor number identifies a specific device instance handled by the same driver. One driver can manage multiple devices using different minor numbers.

    8. How does user space talk to a char driver?

    Through system calls like open, read, write, close, ioctl, poll, and mmap on the device file.

    9. What is driver registration?

    Driver registration is the process where a character driver informs the kernel about its existence, the device numbers it handles, and the file operations it supports.

    10. Why is driver de-registration important?

    If a driver is not properly de-registered, it can leave dangling references, memory leaks, or crash the kernel when the module is removed.

    11. What is the file operations structure?

    It is a structure that contains function pointers to driver callbacks like open, read, write, release, ioctl, poll, and mmap. The kernel calls these functions when user space performs file operations.

    12. What happens when an application calls read()?

    The kernel calls the driver’s read callback, and the driver copies data from kernel space to user space, possibly blocking until data is available.

    13. What is ioctl used for?

    Ioctl is used for device-specific control operations that do not fit into read or write, such as configuring hardware settings or querying device status.

    14. Can multiple processes access a char device?

    Yes, multiple processes can access a char device unless the driver explicitly restricts access using synchronization or open logic.

    15. What is blocking I/O?

    Blocking I/O means the calling process sleeps until the requested operation can be completed, such as waiting for data from hardware.

    ROUND 2: Deep-Dive & Scenario-Based Questions

    16. How does the kernel know which driver handles a device file?

    When a device file is opened, the kernel checks its major number and routes the request to the registered char driver associated with that major number.

    17. What happens internally when open() is called?

    The kernel creates a file structure, links it to the inode, and then calls the driver’s open callback, allowing the driver to initialize device-specific data.

    18. Why do drivers use file->private_data?

    It allows the driver to store per-open or per-device data so that each process has its own context when accessing the device.

    19. What are driver data structures?

    They are internal structures used by the driver to store device state, buffers, configuration, synchronization objects, and hardware-specific information.

    20. How does a driver handle concurrent access?

    Using synchronization mechanisms like mutexes, spinlocks, atomic variables, and wait queues to protect shared data.

    21. What are wait queues?

    Wait queues allow processes to sleep until a specific condition occurs, such as data becoming available or a hardware interrupt firing.

    22. Why are wait queues better than busy waiting?

    Busy waiting wastes CPU cycles. Wait queues put the process to sleep and wake it only when needed, making the system efficient.

    23. How does a driver wake up sleeping processes?

    Usually from an interrupt handler or workqueue using wake-up functions associated with the wait queue.

    24. What is polling in char drivers?

    Polling allows applications to check whether a device is ready for read or write without blocking, commonly used with select or poll system calls.

    25. When should poll() be implemented?

    When your device generates events or data asynchronously and applications need to monitor readiness along with other file descriptors.

    26. What is non-blocking I/O?

    Non-blocking I/O returns immediately if data is not available, instead of putting the process to sleep.

    27. How does a driver support non-blocking read?

    By checking the file flags and returning an error code instead of sleeping if data is not ready.

    28. What is memory mapping in char drivers?

    Memory mapping allows a driver to map kernel or device memory directly into user space so applications can access it without copying.

    29. Why is mmap useful?

    It improves performance for large data transfers like video frames, DMA buffers, or continuous sensor data.

    30. What are risks of memory mapping?

    If not handled carefully, it can expose kernel memory, cause security issues, or crash the system.

    31. What is the role of ioctl in device configuration ops?

    Ioctl allows structured control commands to configure hardware settings that cannot be represented as simple read or write operations.

    32. How do you design safe ioctl commands?

    By validating inputs, checking user memory, using versioned commands, and maintaining backward compatibility.

    33. What happens if a driver forgets to free resources on exit?

    It can cause memory leaks, dangling device nodes, or kernel panics when the module is unloaded.

    34. How does the Char Driver Model support multiple devices?

    By using multiple minor numbers and separate device data structures for each instance.

    35. Why is error handling important in char drivers?

    Because a mistake can crash the entire kernel, not just one application.

    36. What debugging methods are used for char drivers?

    Kernel logs, printk, dynamic debug, ftrace, crash dumps, and careful code review.

    37. What is the difference between char and block drivers?

    Char drivers work with byte streams and sequential access, while block drivers work with fixed-size blocks and random access.

    38. Is Char Driver Model still relevant today?

    Yes. It is widely used in embedded systems, automotive platforms, and custom hardware even in modern Linux kernels.

    39. What does an interviewer expect from a char driver engineer?

    Clear understanding of kernel-user interaction, synchronization, clean resource management, and safe hardware access.

    40. How do you explain Char Driver Model in one line?

    It is the Linux framework that lets hardware behave like a file so applications can interact with it safely and efficiently.

    Final Thoughts

    The Char Driver Model is not just a learning step.
    It is a professional skill.

    Once you understand:

    • Synchronous drivers
    • Driver registration and de-registration
    • Driver file interface
    • Device file operations
    • Driver data structures
    • Device configuration ops
    • Wait queues and polling
    • Memory mapping

    You are no longer “learning drivers.”
    You are writing real Linux drivers.

    FAQ : Char Driver Model in Linux

    1. What is the Char Driver Model in Linux?

    The Char Driver Model is a Linux kernel framework used to handle character devices that transfer data one byte at a time, such as keyboards, sensors, serial ports, and GPIO-based devices.

    2. Why is a character driver called a “char” driver?

    It is called a char driver because it handles data as a stream of characters (bytes) rather than fixed-size blocks like block drivers.

    3. Where is the Char Driver Model used in real systems?

    Char drivers are used in UART devices, I2C sensors, GPIO interfaces, RTCs, touch controllers, and many embedded and automotive Linux systems.

    4. What are the main components of the Char Driver Model?

    The core components are:

    • Major and minor numbers
    • file_operations structure
    • Device file in /dev
    • Kernel module initialization and cleanup functions

    5. What is a major and minor number in a char driver?

    The major number identifies the driver, while the minor number identifies individual devices handled by the same driver.

    6. What is the role of file_operations in a char driver?

    file_operations links user-space system calls like open(), read(), and write() to kernel-space driver functions.

    7. How does user space communicate with a char driver?

    User space communicates through system calls using a device file created in /dev, such as /dev/mydevice.

    8. What is register_chrdev() used for?

    register_chrdev() is used to register a character driver with the kernel and assign it a major number.

    9. What is cdev and why is it important?

    cdev is a kernel structure that represents a character device and connects it to the VFS layer for proper device handling.

    10. How is a device file created for a char driver?

    A device file can be created manually using mknod or automatically using udev with class_create() and device_create().

    11. What is the difference between char driver and block driver?

    Char drivers handle data byte-by-byte, while block drivers manage fixed-size blocks and support random access, such as hard disks.

    12. What happens when open() is called on a char device?

    The kernel invokes the driver’s open() callback, allowing the driver to initialize hardware or allocate resources.

    13. What is ioctl() in the Char Driver Model?

    ioctl() allows custom control commands from user space to the driver, commonly used for configuration and device control.

    14. Are char drivers used in embedded Linux?

    Yes, char drivers are heavily used in embedded Linux for sensors, communication interfaces, and hardware control.

    15. Is learning the Char Driver Model important for interviews?

    Yes, it is a core Linux driver topic and is frequently asked in embedded Linux and kernel developer interviews.

    Read More about Process : What is is Process

    Read More about System Call in Linux : What is System call

    Read More about IPC : What is IPC

  • Kernel Symbol Table in Linux: 7 Powerful Reasons Every Beginner Must Understand

    When diving into Linux kernel development, you will often hear the term Kernel Symbol Table in Linux. But what exactly is it, and why is it important for Linux developers? Let’s break it down in a simple way.

    What is the Kernel Symbol Table in Linux?

    The Kernel Symbol Table in Linux is essentially a lookup table that the kernel maintains to store symbols (like function names, variables, and constants) along with their corresponding memory addresses. Think of it as a giant dictionary for the kernel, allowing it to know where things are stored and how to access them.

    For example, when a kernel module needs to call a function defined in another module or in the kernel itself, it looks up the symbol table to find that function’s address.

    Why is the Kernel Symbol Table Important?

    The kernel symbol table plays a critical role in:

    • Module Loading: When you insert a module, the kernel checks the symbol table to resolve references to functions and variables.
    • Debugging: Developers use tools like ksymoops, cat /proc/kallsyms, or nm to inspect symbols for troubleshooting.
    • Kernel Development: It helps in creating efficient and modular kernel code by enabling symbol sharing.

    How to View the Kernel Symbol Table in Linux

    The easiest way to view the kernel symbol table is through the /proc/kallsyms file:

    For a deeper understanding of how symbols are connected to modules and dependencies in Linux, check out this detailed guide on Tracking Module Dependency in Linux. It explains how module dependencies relate to the kernel symbol table and how tools like depmod and modprobe work together for efficient module management.

    cat /proc/kallsyms
    

    This command lists all symbols currently available in the kernel along with their memory addresses and type.
    Example output:

    c0100000 T _stext
    c0100040 t startup_64
    c0100080 T rest_init
    

    Here, each line shows a symbol address, type, and name.

    Understanding Symbol Types in the Kernel Symbol Table

    Symbols in Linux are categorized using single-character codes:

    • T — Text section (kernel functions)
    • D — Data section (global variables)
    • B — BSS section (uninitialized global variables)
    • R — Read-only data

    Knowing these types helps developers quickly understand what each symbol represents.

    How Kernel Symbol Table Works with Modules

    When you write a kernel module, you might want to use functions or variables defined in the kernel or another module. The kernel symbol table allows your module to link dynamically to those definitions.

    For example:

    #include <linux/module.h>
    #include <linux/kernel.h>
    
    extern int my_global_var; // Symbol from another module
    
    static int __init my_module_init(void) {
        printk(KERN_INFO "Value: %d\n", my_global_var);
        return 0;
    }
    
    static void __exit my_module_exit(void) {
        printk(KERN_INFO "Module exiting\n");
    }
    
    module_init(my_module_init);
    module_exit(my_module_exit);
    
    MODULE_LICENSE("GPL");
    

    If my_global_var is exported from another module using EXPORT_SYMBOL(), the kernel symbol table will resolve it automatically when your module loads.

    Key Tools to Work with Kernel Symbol Table

    Some common tools for working with the Kernel Symbol Table in Linux include:

    • nm — Displays symbol names and addresses in object files.
    • ksymoops — Decodes kernel oops messages using symbol tables.
    • /proc/kallsyms — Direct access to the live kernel symbol table.

    Advantages of the Kernel Symbol Table in Linux

    • Enables dynamic linking for kernel modules.
    • Helps debugging by exposing kernel symbols.
    • Improves modularity and code reuse in kernel development.

    Disadvantages of Kernel Symbol Table

    • Exposure of symbols can be a security risk.
    • Large symbol tables can consume kernel memory.
    • Incorrect symbol resolution may lead to module loading errors.

    Real-Life Applications of Kernel Symbol Table

    • Device Driver Development: Allows sharing of symbols between modules.
    • Kernel Debugging: Helps developers trace and resolve errors quickly.
    • Performance Monitoring: Tools like perf use kernel symbols for profiling.

    Conclusion

    Understanding the Kernel Symbol Table in Linux is essential for kernel developers and those interested in deep Linux internals. It’s the backbone for symbol resolution, module management, and debugging in the Linux kernel world.

    10 Detailed FAQs – Kernel Symbol Table in Linux

    1. What is the Kernel Symbol Table in Linux?

    The Kernel Symbol Table in Linux is a core part of the Linux kernel that acts like a directory of all available functions, variables, and constants within the kernel space. Each symbol in the table is linked to its memory address, which allows the kernel and loaded modules to locate and use them efficiently.

    In simpler terms, it’s a reference guide for the kernel — much like a phonebook where you look up names and get addresses. This is essential for dynamic linking when kernel modules are loaded.

    2. How do I view the Kernel Symbol Table in Linux?

    You can access the kernel symbol table through the /proc/kallsyms file. This special file shows a live snapshot of all symbols the kernel currently knows.

    Command:

    cat /proc/kallsyms
    

    Example output:

    c0100000 T _stext
    c0100040 t startup_64
    c0100080 T rest_init
    

    Here:

    • The first column is the address of the symbol.
    • The second column is the symbol type.
    • The third column is the symbol name.

    This view is useful for debugging, development, and understanding how the kernel resolves symbol references.

    3. Why is the Kernel Symbol Table important in Linux kernel development?

    The kernel symbol table is crucial because it enables:

    • Dynamic linking of kernel modules — modules can use symbols defined in the core kernel or other modules without recompiling the entire kernel.
    • Code reuse — allows developers to call shared functions without duplication.
    • Debugging — tools and developers use it to resolve addresses in crash logs or kernel oops messages.
    • System efficiency — reduces memory overhead by preventing redundant copies of functions or variables.

    Without the kernel symbol table, every module would have to contain all definitions, making kernel modules large, redundant, and inefficient.

    4. What are the common symbol types in the kernel symbol table?

    Symbols are tagged with a single-letter type code:

    • T — Text section (kernel functions).
    • D — Initialized global variables.
    • B — Uninitialized global variables (BSS section).
    • R — Read-only data.

    These codes help developers understand the role of each symbol and where it resides in memory, which is important for debugging and module linking.

    5. How does EXPORT_SYMBOL work with the Kernel Symbol Table?

    When you want to share a function or variable from one kernel module to another, you use EXPORT_SYMBOL() or EXPORT_SYMBOL_GPL().

    Example:

    EXPORT_SYMBOL(my_function);
    

    This command tells the kernel to add my_function to the Kernel Symbol Table, making it available to other modules at runtime. Without exporting a symbol, it will not appear in /proc/kallsyms, and other modules won’t be able to access it.

    6. Which tools help to explore the Kernel Symbol Table in Linux

    Several tools help in working with the kernel symbol table:

    • cat /proc/kallsyms — shows live kernel symbols.
    • nm — lists symbols and their addresses from object files.
    • ksymoops — decodes kernel oops logs using symbol tables.

    These tools are essential for debugging, symbol resolution, and kernel module development.

    7. Can the Kernel Symbol Table affect Linux security?

    Yes. While the kernel symbol table is useful, exposing too many symbols can present security risks. Attackers could potentially use symbol addresses to exploit vulnerabilities.

    For this reason, symbol exporting is controlled, and developers often limit symbol visibility using kernel configuration settings. Linux distributions may also strip unnecessary symbols for production builds.

    8. What happens if a kernel module cannot find a symbol in the Kernel Symbol Table?

    If a module tries to reference a symbol not present in the kernel symbol table, it will fail to load. The kernel will log an unresolved symbol error.

    Example error message:

    Unknown symbol my_function (err 0)
    

    To resolve this:

    • Ensure the symbol is exported with EXPORT_SYMBOL().
    • Verify that the dependent module providing the symbol is loaded first.

    9. How is the Kernel Symbol Table related to module dependencies in Linux?

    Module dependencies occur when one kernel module relies on symbols defined in another module or the kernel itself. The kernel symbol table acts as the reference that resolves these dependencies during module loading.

    Commands like depmod generate dependency information based on symbols listed in the table, and modprobe uses this information to load modules in the correct order.

    10. Is there a performance cost for maintaining the Kernel Symbol Table?

    Yes — maintaining a large kernel symbol table consumes memory, and symbol resolution during module loading can add slight overhead. However, these costs are outweighed by the benefits: modular design, dynamic linking, and easier debugging.

    Kernel developers carefully balance symbol exporting to maintain performance while ensuring functionality.

  • Embedded Firmware Software Engineer – Enfabrica | Hyderabad | Embedded Job 2026

    Company: Enfabrica
    Experience Required: 3 – 6 years
    Location: Hyderabad
    Employment Type: Full Time, Permanent
    Industry: FinTech / Payments
    Openings: 1
    Posted: 3+ weeks ago

    Job Overview Enfabrica | Embedded Job 2025

    Enfabrica is seeking a highly skilled Embedded Firmware Software Engineer with expertise in low-level firmware development, Linux systems, and board support packages (BSPs). This role is ideal for professionals who enjoy working at the intersection of hardware and software, ensuring seamless integration and performance of in-house developed PCBs.

    You will play a key role in developing and optimizing firmware using Rust, C, and C++, while collaborating closely with hardware engineers to deliver robust solutions for networking and high-performance computing applications.

    🛠 Key Responsibilities

    • Design, implement, and maintain low-level firmware for custom PCBs using Rust.
    • Develop and optimize drivers for CPLDs, Ethernet OSFPs, PCIe CEM via I2C and SPI interfaces.
    • Collaborate with hardware teams to understand board specifications and requirements.
    • Work with Linux systems and kernel drivers for firmware integration and board-level support.
    • Debug and troubleshoot hardware/software issues using industry-standard tools.
    • Write and maintain comprehensive technical documentation for firmware and BSPs.
    • Participate in code reviews and contribute to best practices in embedded development.

    🎓 Qualifications

    • Bachelor’s degree in Computer Science, Electrical Engineering, or related field (or equivalent experience).
    • Proven experience in low-level system programming or embedded development (C, C++, or Rust).
    • Strong knowledge of Linux internals and their interaction with firmware.
    • Hands-on experience developing drivers for CPLDs, PCIe, Ethernet OSFPs, and related hardware.
    • Proficiency in debugging techniques for both hardware and software issues.
    • Excellent problem-solving, documentation, and communication skills.

    🌟 Preferred Qualifications

    • Prior experience with the Rust programming language (desired but not mandatory).
    • Familiarity with embedded systems and microcontroller architectures.
    • Experience with embedded RTOS (Hubris knowledge is a plus).
    • Proficiency with version control systems (Git); familiarity with Bazel build tooling is a plus.

    📌 Role Details

    • Role Category: Software Development
    • Department: Engineering – Software & QA
    • Role: Embedded Firmware Software Engineer
    • Type: Full Time, Permanent

    🔑 Key Skills

    • Embedded Firmware
    • System Programming (C, C++, Rust)
    • Linux Kernel & Device Drivers
    • RTOS
    • Networking & Ethernet
    • PCIe / CPLD / I2C / SPI
    • Debugging & Troubleshooting
    • Automotive & Embedded Software

    📍 How to Apply

    Interested candidates can apply directly through the Enfabrica careers portal.

    Why Join Enfabrica?

    At Enfabrica, you’ll be working on cutting-edge embedded systems and networking solutions that power next-generation FinTech and payment platforms. This is an excellent opportunity for engineers who want to push the boundaries of low-level programming and firmware design while working in a collaborative, innovation-driven environment.

  • Master Hello World using Yocto | Build & Run a Linux Kernel Driver on BeagleBone Black (2026)

    Hello World using Yocto : Learn how to build a simple “Hello World” Linux kernel module from scratch using the Yocto Project for the BeagleBone Black. This step-by-step guide covers everything you need — from installing essential build tools, cloning the Yocto and meta-ti layers, creating a custom meta layer for your kernel module, writing the driver code, creating the recipe, to building and deploying the image on your BeagleBone Black device. Perfect for embedded Linux developers and beginners, this tutorial ensures you understand how to integrate and run out-of-tree kernel modules efficiently using Yocto’s powerful build system.

    What is Yocto?

    Yocto Project is an open-source collaboration project that helps developers create custom Linux-based systems for embedded devices. It provides tools, templates, and methods to build your own Linux distribution tailored to your hardware and software needs.

    Why use Yocto?

    • Custom Linux builds: You can create a Linux system optimized for your specific hardware (like BeagleBone Black, Raspberry Pi, etc.).
    • Reproducible builds: You can reproduce the exact same Linux image anytime.
    • Cross-compilation: It simplifies building software on your desktop machine for another target platform.
    • Scalability: Use it for small embedded devices or large, complex systems.
    • Community support: Backed by many companies and contributors in the embedded world.

    Key components of Yocto

    • BitBake: The build engine (like make but more powerful for embedded Linux).
    • Poky: The reference distribution and set of metadata recipes.
    • Recipes: Scripts that define how to build packages, kernels, and images.
    • Layers: Collections of recipes and configuration that can be added to customize the build.

    Who uses Yocto?

    • Embedded system developers building custom Linux for hardware like automotive infotainment, IoT devices, industrial controllers, and more.
    • Companies wanting to maintain full control over their embedded Linux stack.

    What is Poky?

    Poky is the reference build system and distribution provided by the Yocto Project. It’s basically a set of metadata, tools, and configurations that you use as a starting point to build your own custom embedded Linux images.

    Details:

    • Poky = Yocto Project reference system
      It includes the BitBake build tool plus a collection of recipes, configuration files, and classes that define how to build software packages, the Linux kernel, and the overall system image.
    • It’s a base for your custom Linux
      When you start a Yocto Project build, most tutorials and examples use Poky because it’s a complete and tested setup.
    • Contains layers like:
      • meta: core metadata layer with basic recipes and configurations
      • meta-poky: specific poky configurations and utilities
      • meta-yocto: essential recipes for a minimal embedded Linux distribution

    Why is Poky important?

    • It’s the default “reference distro” for Yocto, meaning it provides a working baseline system.
    • You can extend or modify Poky with additional layers to support your hardware and software requirements.
    • It helps you understand how the Yocto build system works before diving into more complex customizations.

    What is BitBake?

    BitBake is the build engine/tool used by the Yocto Project (and Poky) to compile and assemble software components into a complete Linux image for embedded systems.

    Details:

    • It’s like “make” on steroids but designed specifically for building embedded Linux systems.
    • BitBake reads special files called recipes (.bb files), which describe how to fetch, configure, compile, and package software.
    • It manages complex build tasks, dependencies, and executes them in the right order.
    • BitBake supports cross-compilation, so you can build software on your development machine for a different target device.
    • It also handles layers, configuration, and task scheduling.

    Why is BitBake important?

    • It automates the entire build process for embedded Linux, from downloading source code to creating a final flashable image.
    • It ensures reproducibility — builds can be repeated with the same results.
    • BitBake is highly extensible and can be customized with your own recipes.

    Install Yocto Prerequisites

    On your Ubuntu/Debian build machine:

    sudo apt update
    sudo apt install -y gawk wget git-core diffstat unzip texinfo \
      gcc build-essential chrpath socat cpio python3 python3-pip python3-pexpect \
      xz-utils debianutils iputils-ping python3-git python3-jinja2 \
      libegl1-mesa libsdl1.2-dev pylint3 xterm
    

    These are the official Yocto host dependencies.

    Download Yocto (Poky) and BeagleBone BSP Layer

    We’ll use the Yocto Kirkstone LTS release and meta-ti for TI boards like the BBB.

    mkdir ~/yocto-bbb
    cd ~/yocto-bbb
    
    # Poky (Yocto core)
    git clone -b kirkstone git://git.yoctoproject.org/poky
    
    # TI BSP layer (BeagleBone support)
    git clone -b kirkstone git://git.yoctoproject.org/meta-ti
    

    Set Up the Build Environment

    cd poky
    source oe-init-build-env
    

    This creates and moves you into a build/ directory.

    Add BeagleBone Black Layers

    bitbake-layers add-layer ../meta-ti
    

    Set the Machine to BeagleBone Black

    Edit conf/local.conf:

    MACHINE = "beaglebone"
    

    Create Your Custom Layer for the Driver

    cd ~/yocto-bbb
    bitbake-layers create-layer meta-hello
    bitbake-layers add-layer ../meta-hello
    

    Create the Hello World Kernel Module

    Directory Structure:

    meta-hello/
    └── recipes-kernel/
        └── hello-module/
            ├── files/
            │   ├── hello.c
            │   ├── Makefile
            │   └── COPYING
            └── hello-module_0.1.bb
    

    hello.c

    #include <linux/module.h>
    #include <linux/kernel.h>
    #include <linux/init.h>
    
    MODULE_LICENSE("GPL");
    MODULE_AUTHOR("Nish");
    MODULE_DESCRIPTION("Hello World Kernel Module for BeagleBone Black");
    
    static int __init hello_init(void)
    {
        printk(KERN_INFO "Hello, BeagleBone World!\n");
        return 0;
    }
    
    static void __exit hello_exit(void)
    {
        printk(KERN_INFO "Goodbye, BeagleBone World!\n");
    }
    
    module_init(hello_init);
    module_exit(hello_exit);
    

    Makefile

    obj-m := hello.o
    

    COPYING

    GNU GENERAL PUBLIC LICENSE
    Version 2, June 1991
    

    Get its checksum:

    md5sum COPYING
    

    hello-module_0.1.bb

    SUMMARY = "Hello World Kernel Module for BeagleBone Black"
    DESCRIPTION = "A simple kernel module built with Yocto for BBB"
    LICENSE = "GPL-2.0"
    LIC_FILES_CHKSUM = "file://COPYING;md5=<paste-md5-here>"
    
    SRC_URI = "file://hello.c \
               file://Makefile \
               file://COPYING"
    
    S = "${WORKDIR}"
    
    inherit module
    

    Include the Module in the Image

    Edit conf/local.conf:

    IMAGE_INSTALL_append = " kernel-module-hello"
    

    (Optional: Auto-load at boot)

    KERNEL_MODULE_AUTOLOAD += "hello"
    

    Build the Image

    cd ~/yocto-bbb/poky
    source oe-init-build-env
    bitbake core-image-minimal
    

    After the build completes, the image will be in:

    tmp/deploy/images/beaglebone/
    

    Flash to SD Card

    Insert your SD card and find its device name:

    lsblk
    

    Flash:

    sudo dd if=tmp/deploy/images/beaglebone/core-image-minimal-beaglebone.wic of=/dev/sdX bs=4M status=progress
    sync
    

    Boot BeagleBone Black

    • Insert SD card into BBB
    • Power it up (hold BOOT button if needed to boot from SD)

    Test the Module on BBB

    # Check if auto-loaded
    lsmod | grep hello
    
    # If not, load manually
    sudo modprobe hello
    
    # Check kernel logs
    dmesg | tail
    
    # Remove module
    sudo rmmod hello
    dmesg | tail
    

    Expected output:

    [   15.123456] Hello, BeagleBone World!
    [   20.654321] Goodbye, BeagleBone World!
    

    ✅ You’ve successfully built, packaged, and run a Hello World Linux kernel driver on BeagleBone Black using Yocto!

    Frequently asked questions (FAQ) | Hello World using Yocto

    1. What is Yocto and why use it for building kernel modules?

    Yocto is a powerful open-source build system for creating custom Linux distributions for embedded devices like BeagleBone Black. Using Yocto to build kernel modules ensures reproducible builds, automatic packaging, and easy integration into your custom image.

    2. How do I install the necessary host tools for Yocto?

    On Ubuntu/Debian, run:

    sudo apt install gawk wget git-core diffstat unzip texinfo gcc build-essential chrpath socat cpio python3 python3-pip python3-pexpect xz-utils
    

    This installs all required tools and dependencies for Yocto to build properly.

    3. Why do I need to clone both ‘poky’ and ‘meta-ti’ repositories?

    ‘poky’ is the main Yocto reference distribution containing BitBake and core layers. ‘meta-ti’ provides board support packages (BSP) and recipes specific to Texas Instruments devices like the BeagleBone Black.

    4. How do I add my own kernel module to the Yocto build?

    Create a custom meta layer (meta-hello), add your kernel module source and recipe inside it, then add this layer to your build using bitbake-layers add-layer. Finally, append your kernel module package to IMAGE_INSTALL in local.conf.

    5. What does inherit module do in the recipe?

    It tells Yocto that this recipe builds a kernel module, so it sets up the proper build environment, compiles the code against the kernel headers, and packages the module correctly.

    6. How do I ensure my module loads automatically on boot?

    Set the variable KERNEL_MODULE_AUTOLOAD += "hello" in your local.conf or image recipe. Yocto will then create the necessary config files to load your module during system startup.

    7. What if my module doesn’t load or I get errors?

    • Check kernel logs with dmesg to see error messages.
    • Verify that the module is actually included in your image (IMAGE_INSTALL).
    • Make sure the kernel version on your target matches the one you built the module for.
    • Use modprobe instead of insmod to handle dependencies.

    8. How do I flash the Yocto-built image to the BeagleBone Black?

    Use dd to write the .wic image to your SD card:

    sudo dd if=core-image-minimal-beaglebone.wic of=/dev/sdX bs=4M status=progress && sync
    

    Replace /dev/sdX with your actual SD card device.

    9. Can I build and test the kernel module without building the entire image?

    Yes! You can build just the module by running:

    bitbake hello-module
    

    Then manually copy the resulting .ko file to the target and load it with insmod or modprobe.

    10. Where can I find more resources to learn Yocto and kernel module development?