Kernel Module Development
A comprehensive guide to writing Linux kernel modules, character drivers, and ioctl interfaces for extending kernel functionality.
A comprehensive guide to writing Linux kernel modules, character drivers, and ioctl interfaces for extending kernel functionality.
Introduction
Kernel module development is low-level Linux system programming. A module runs with kernel privileges, so a bug can affect the whole machine. Device drivers, filesystems, and other kernel extensions use modules when the kernel needs code that can be loaded at runtime.
A kernel module is a loadable object file (.ko) that can be linked into a running kernel without rebooting. The examples below use Linux’s external-module build system and character-device APIs. They do not target one kernel release or distribution and are teaching fragments, not a tested driver. For an actual build, use the kernel build tree or headers that match the target machine’s exact uname -r; distributions may backport changes, so the version number alone does not guarantee compatibility. See the kernel guide to building external modules.
Decide whether a module is needed
Before writing or loading a module, check whether the kernel already exposes the feature through a subsystem or supported interface. For a hardware driver, identify the device and check the matching driver first. If a standard interface, existing driver, user-space library, FUSE, or another user-space mechanism can do the job, prefer it. User-space code is easier to debug and normally cannot write kernel memory directly.
Continue with a module only when the work needs kernel privileges or a kernel subsystem hook that an existing interface does not provide. Then name the kernel releases and distributions you intend to support, find their matching development packages, and test against each target kernel. Do not treat a successful build against one distribution kernel as proof that the module works with another.
Load experimental code only in a disposable VM with a snapshot and a recovery console. Keep the VM’s module-signing policy enabled. If it rejects an unsigned module, use a test key trusted by that VM or the distribution’s supported signing workflow; do not disable Secure Boot or signature enforcement on your host to get past the check. The test procedure later in this post includes rollback steps.
When to use / when not to use
Kernel modules are appropriate when you need to:
- Interact with hardware directly — Writing drivers for custom or proprietary hardware that has no existing Linux support
- Intercept system calls — Building security modules, auditing systems, or sandboxing solutions
- Implement file systems — Creating custom file system drivers for specialized storage backends
- Add kernel-level performance optimizations — Offloading computation that would otherwise suffer from user/kernel context switches
Kernel modules are NOT appropriate when:
- User-space alternatives exist — FUSE allows file systems in user space with less risk
- Your driver only needs to communicate with existing hardware — The kernel already has thousands of drivers; write a kernel module only if no suitable existing driver exists
- You need debugging flexibility — Kernel bugs crash the entire system; user-space debugging is far safer
Architecture or flow diagram
flowchart TB
subgraph "User Space"
APP[Application Program]
IOCTL[ioctl System Call]
end
subgraph "Kernel Space"
VFS[Virtual File System Layer]
DRIVER[Char Driver Layer]
MODULE[Kernel Module]
KSU[Kernel Subsystems]
end
subgraph "Hardware"
HW[Hardware Device]
end
APP --> IOCTL
IOCTL --> VFS
VFS --> DRIVER
DRIVER --> MODULE
MODULE --> KSU
KSU --> HW
style MODULE stroke:#ff6b6b,stroke-width:3px
style DRIVER stroke:#ffa94d,stroke-width:3px
Core concepts
Module lifecycle
Every kernel module follows a standard lifecycle pattern:
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple example kernel module");
MODULE_VERSION("1.0");
/* Called when module is loaded */
static int __init my_module_init(void)
{
printk(KERN_INFO "my_module: initializer called\n");
/* Initialize your device, register character device, etc. */
return 0;
}
/* Called when module is unloaded */
static void __exit my_module_exit(void)
{
printk(KERN_INFO "my_module: cleanup called\n");
/* Release resources, unregister device, etc. */
}
module_init(my_module_init);
module_exit(my_module_exit);
Character driver registration
Character drivers provide a file-based interface to kernel functionality. The registration process involves:
#include <linux/errno.h>
#include <linux/ioctl.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/fs.h>
#include <linux/types.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "my_device"
#define MAX_BUFFER_SIZE 1024
#define MY_IOCTL_RESET _IO('M', 0)
#define MY_IOCTL_GET_STATUS _IOR('M', 1, __u32)
#define MY_IOCTL_SET_MODE _IOW('M', 2, __u32)
static dev_t dev_number;
static struct cdev my_cdev;
static char kernel_buffer[MAX_BUFFER_SIZE];
static __u32 mode_value;
static int device_open(struct inode *inode, struct file *file)
{
printk(KERN_INFO "my_device: opened\n");
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
printk(KERN_INFO "my_device: closed\n");
return 0;
}
static ssize_t device_read(struct file *file, char __user *user_buffer,
size_t len, loff_t *offset)
{
size_t bytes_to_copy = min(len, (size_t)(MAX_BUFFER_SIZE - *offset));
if (copy_to_user(user_buffer, kernel_buffer + *offset, bytes_to_copy))
return -EFAULT;
*offset += bytes_to_copy;
return bytes_to_copy;
}
static ssize_t device_write(struct file *file, const char __user *user_buffer,
size_t len, loff_t *offset)
{
size_t bytes_to_copy = min(len, (size_t)(MAX_BUFFER_SIZE - *offset));
if (copy_from_user(kernel_buffer + *offset, user_buffer, bytes_to_copy))
return -EFAULT;
*offset += bytes_to_copy;
return bytes_to_copy;
}
static long device_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
__u32 value;
switch (cmd) {
case MY_IOCTL_RESET:
memset(kernel_buffer, 0, MAX_BUFFER_SIZE);
mode_value = 0;
return 0;
case MY_IOCTL_GET_STATUS:
return put_user(mode_value, (__u32 __user *)arg);
case MY_IOCTL_SET_MODE:
if (copy_from_user(&value, (void __user *)arg, sizeof(value)))
return -EFAULT;
if (value > 1)
return -EINVAL;
mode_value = value;
return 0;
default:
return -ENOTTY;
}
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.open = device_open,
.release = device_release,
.read = device_read,
.write = device_write,
.unlocked_ioctl = device_ioctl,
};
static int __init my_driver_init(void)
{
int ret;
/* Dynamic device number allocation */
ret = alloc_chrdev_region(&dev_number, 0, 1, DEVICE_NAME);
if (ret) {
printk(KERN_ERR "my_device: failed to allocate device number\n");
return ret;
}
cdev_init(&my_cdev, &fops);
my_cdev.owner = THIS_MODULE;
ret = cdev_add(&my_cdev, dev_number, 1);
if (ret) {
unregister_chrdev_region(dev_number, 1);
return ret;
}
printk(KERN_INFO "my_device: registered as %u:%u\n",
MAJOR(dev_number), MINOR(dev_number));
return 0;
}
static void __exit my_driver_exit(void)
{
cdev_del(&my_cdev);
unregister_chrdev_region(dev_number, 1);
printk(KERN_INFO "my_device: unregistered\n");
}
module_init(my_driver_init);
module_exit(my_driver_exit);
This excerpt registers a cdev and prints its device number. It does not create /dev/my_device; a complete driver normally registers a device with the appropriate subsystem or device model so udev can create the node. The user-space example below assumes that node has been created with suitable permissions.
Test only in a disposable VM
Build and load the module inside a throwaway VM that runs the kernel you intend to target. Install that distribution’s matching kernel headers or development package first. In the module directory, with a Kbuild Makefile for the example:
# Run these commands inside the disposable VM, never on a production host.
make -C "/lib/modules/$(uname -r)/build" M="$PWD"
sudo insmod ./my_driver.ko
sudo dmesg | tail -n 50
sudo rmmod my_driver
The kernel build directory must match the running kernel. If the VM enforces module signatures, insmod will reject a module whose signature is absent or untrusted. Keep that policy enabled and follow the VM distribution’s documented signing and key-enrollment process. Kernel module signatures are checked by the kernel; a signed file must not be stripped or modified afterward. See the module-signing guide.
Take a VM snapshot before the first load and keep a working console available. After a normal test, remove any device node created for the test and unload with rmmod; if unloading fails because a process still has the device open, stop that process and close its file descriptors. Do not force-unload a module. If the VM hangs or panics, reboot it from the console and restore the snapshot or boot its known-good kernel. Keep the host’s Secure Boot settings and signing keys unchanged.
The commands above load and unload a module; they do not install it under /lib/modules. Keep experiments out of the host’s module tree. The module source also needs an appropriate Kbuild Makefile, for example obj-m := my_driver.o.
User-space interaction via ioctl
The ioctl interface allows user applications to send custom commands to kernel modules:
/* User-space side (example.c) */
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include <unistd.h>
#define MY_IOCTL_RESET _IO('M', 0)
#define MY_IOCTL_GET_STATUS _IOR('M', 1, uint32_t)
#define MY_IOCTL_SET_MODE _IOW('M', 2, uint32_t)
int main(void)
{
int fd = open("/dev/my_device", O_RDWR);
if (fd < 0) {
perror("open");
exit(EXIT_FAILURE);
}
uint32_t mode = 1;
if (ioctl(fd, MY_IOCTL_SET_MODE, &mode) == -1) {
perror("MY_IOCTL_SET_MODE");
close(fd);
return EXIT_FAILURE;
}
/* The driver rejects values greater than 1 with EINVAL. */
uint32_t status = 0;
if (ioctl(fd, MY_IOCTL_GET_STATUS, &status) == -1) {
perror("MY_IOCTL_GET_STATUS");
close(fd);
return EXIT_FAILURE;
}
if (ioctl(fd, MY_IOCTL_RESET) == -1) {
perror("MY_IOCTL_RESET");
close(fd);
return EXIT_FAILURE;
}
close(fd);
return 0;
}
Production failure scenarios
Scenario 1: module crashes during load
Problem: An initialization bug can trigger a kernel oops or panic and freeze the system.
The module’s __init function runs during loading. A normal error return, such as -ENOMEM after an allocation fails, makes the load fail; it does not automatically cause an oops. A bug such as dereferencing a NULL pointer or using an invalid device number can cause an oops or panic. That is why the first load belongs in a disposable VM with a snapshot and a working console, not on the host.
The mitigation strategy starts with defensive allocation. Every kmalloc, kzalloc, or devm_kzalloc call must be checked for NULL before use. If the allocation fails, the init function returns -ENOMEM immediately and any previously acquired resources must be released in reverse order. For example, if you allocate a device number successfully but then fail to initialize a cdev, you must call unregister_chrdev_region before returning the error code.
Beyond individual checks, wrap related resources in a cleanup goto chain:
static int __init my_driver_init(void)
{
int ret;
ret = alloc_chrdev_region(&dev_no, 0, 1, DEVICE_NAME);
if (ret)
return ret;
cdev_init(&my_cdev, &fops);
my_cdev.owner = THIS_MODULE;
ret = cdev_add(&my_cdev, dev_no, 1);
if (ret)
goto err_unregister_region;
/* If later registration fails, remove the cdev before freeing its range. */
/* more initialization... */
return 0;
err_unregister_region:
unregister_chrdev_region(dev_no, 1);
return ret;
}
For every additional resource acquired after cdev_add(), add a failure label that releases only the resources already acquired, in reverse order. If a later step fails, first call cdev_del(), then release the device-number range. Keep the normal exit path in the same reverse order.
Using __init annotations tells the kernel that the init function code can be freed after completion, reclaiming a modest amount of memory on single-purpose systems. For production deployments, always test module loading in a VM or sandboxed environment first. Tools like qemu with a minimal initramfs let you load and unload modules without risking the host system. Keep a serial console or network KVM accessible when testing on real hardware, since a failed module load on a remote server can leave you with no way to interact with the console.
Scenario 2: race conditions in multi-threaded access
Problem: Concurrent read/write operations corrupt shared kernel buffer.
The kernel runs on multiple CPU cores simultaneously, and character device file operations can be called from different processes at the same time. A race condition in this environment means that two concurrent executions modify shared state without seeing each other’s changes. The canonical failure looks like this: two threads both read the current *offset, both compute their bytes-to-copy based on that stale value, both write back their updated offset, and both return without the second update being reflected. The result is either data loss (same bytes returned twice) or a buffer overrun (writing past MAX_BUFFER_SIZE).
Use a spinlock only when the critical section is short and cannot sleep:
static ssize_t device_read(struct file *file, char __user *buf,
size_t len, loff_t *offset)
{
ssize_t bytes_read;
unsigned long flags;
spin_lock_irqsave(&dev_lock, flags);
/* critical section: read from kernel_buffer, update *offset */
bytes_read = min(len, (size_t)(MAX_BUFFER_SIZE - *offset));
if (copy_to_user(buf, kernel_buffer + *offset, bytes_read))
bytes_read = -EFAULT;
else
*offset += bytes_read;
spin_unlock_irqrestore(&dev_lock, flags);
return bytes_read;
}
For read/write operations that might sleep, such as those calling copy_from_user() on a userspace buffer that triggers a page fault, use a mutex. Every operation that touches kernel_buffer or *offset must hold the same lock through the full read-modify-write sequence. Reading the offset before taking the lock and protecting only the write can lose updates.
Deadlocks can also occur when code holds a lock while calling a callback or waiting, and that path tries to take the same lock. Choose one lock order and keep it everywhere. For example, if a driver uses a device lock and a per-buffer lock, always take them in the same order. Enable CONFIG_PROVE_LOCKING during development and check the kernel log for lockdep warnings.
Scenario 3: module version mismatch after a kernel update
Problem: Module compiled for one kernel version fails to load after kernel update.
Mitigation:
- Use
modinfoto check module compatibility - Rebuild modules after kernel updates
- Consider using the “staging” tree for drivers that need rapid iteration
- Sign modules with the same key used by the kernel (for secure boot systems)
Trade-off table
| Aspect | Kernel Module | User-Space Driver (FUSE) | Out-of-Tree Module |
|---|---|---|---|
| Performance | Highest—no context switches for I/O | Lower—FUSE adds overhead | Same as in-tree |
| Safety | Risky—bugs crash kernel | Safe—crashes only affect process | Risky, no upstream review |
| Maintenance | Mainlined = long-term support | Easier—standard debugging | High—manual tracking |
| Development Speed | Slower—kernel build cycles | Faster—familiar debugging | Varies |
Implementation snippet: device class registration
A modern approach to device registration uses the device model:
#include <linux/device.h>
#include <linux/platform_device.h>
static struct platform_device *my_platform_device;
static int my_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
printk(KERN_INFO "my_device: probing\n");
/* Use devm_* for automatic resource cleanup */
return 0;
}
static int my_remove(struct platform_device *pdev)
{
printk(KERN_INFO "my_device: removing\n");
return 0;
}
static const struct of_device_id my_of_match[] = {
{ .compatible = "vendor,my-device", },
{ }
};
MODULE_DEVICE_TABLE(of, my_of_match);
static struct platform_driver my_driver = {
.probe = my_probe,
.remove = my_remove,
.driver = {
.name = "my_device",
.of_match_table = my_of_match,
},
};
module_platform_driver(my_driver);
Observability checklist
For production kernel modules, monitor these aspects:
- dmesg output — Kernel log messages via
printkwith appropriate log levels - /proc/modules — Check module loaded state and memory usage
- /sys/module/
— Parameter values and statistics via module parameters - ftrace — Trace function calls within the module during debugging
- perf — Profile CPU usage attributed to module functions
Common pitfalls / anti-patterns
Resource management
Release kernel resources acquired during initialization in the exit function. Forgetting to unregister a character device, class, or platform driver can leave stale entries in /dev or /sys and leak kernel memory. Unregister resources in the reverse order in which initialization acquired them.
Memory leaks in kernel modules are particularly insidious because the kernel’s memory allocator has no process boundary to contain the damage. A single leaked kmalloc of a few kilobytes, if triggered repeatedly in a hot path, can exhaust the kernel’s low-memory pool and cause system-wide instability. Every allocation must have a corresponding deallocation, and the pairing must be verified in the failure paths of your init function as well as in the normal exit path.
The devm_* family ties supported resources to a device’s lifetime. The kernel releases them when the device is detached, which reduces manual cleanup in probe and remove paths. Allocation can still fail, and not every resource has a managed variant, so check return values and handle unmanaged resources explicitly.
Character drivers may manage device numbers, cdev structures, class devices, and IRQ lines. Release each resource with its matching API: unregister_chrdev_region(), cdev_del(), device_destroy() followed by class_destroy(), and free_irq(). Stop new operations and drain pending work before releasing resources that handlers or callbacks may still use.
Initialization failure paths need the same care as normal cleanup. The kernel does not call the exit function when initialization returns an error, so release each resource acquired before the failure. A goto cleanup chain keeps those releases in reverse acquisition order. Test failure paths in a disposable VM and check that the module is unloaded and no stale entries remain in /sys or /dev.
Concurrency and synchronization
The kernel is a preemptive, multithreaded environment where dozens of CPU cores can simultaneously execute code in the same module. Without explicit synchronization, shared data structures are corrupted silently and deterministically. A classic example: two threads reading *offset simultaneously before either writes it back cause one update to be lost, resulting in data corruption or a buffer overrun that crashes the system.
Deadlocks happen when two or more threads each hold a lock and wait for a lock held by the other. In kernel code, this often occurs when an interrupt handler (running in atomic context) tries to acquire a mutex that a thread holds while waiting for that handler to complete. Grab locks in a consistent global order, and never acquire sleeping locks (mutexes, semaphores) from atomic context. The kernel’s lockdep tool, enabled with CONFIG_PROVE_LOCKING, statically analyzes lock acquisition paths and reports circular dependencies at boot time.
Atomic context violations are serious. Code running in interrupt handlers, softirqs, or while holding a spinlock cannot safely call functions that might sleep, including kmalloc() with GFP_KERNEL, mutex_lock(), or copy_from_user(). Sleeping in atomic context produces a “scheduling while atomic” oops. Use GFP_ATOMIC for allocations in atomic context, and spinlocks for synchronization in interrupt handlers.
Choosing between a spinlock and a mutex depends on the execution context and the expected hold duration. A spinlock busy-waits by repeatedly attempting to acquire the lock in a tight loop. It has zero latency overhead for the lock holder but burns CPU cycles while waiting. Use it for critical sections that complete in a few dozen instructions, such as updating a linked list node or incrementing a counter. A mutex blocks by putting the current thread to sleep, yielding the CPU to other work until the lock is available. It carries the overhead of a context switch but is appropriate for operations that might take longer or that need to sleep for memory allocation or I/O. Holding a mutex across a function call that might trigger a page fault is a deadlock waiting to happen.
RCU (Read-Copy-Update) is a specialized synchronization primitive optimized for read-heavy workloads where readers never block and writers incur the cost of copying and a grace-period wait. In a driver context, RCU makes sense when your data structure is read far more often than it is modified, such as a routing table or a device list that changes only during probe and remove. The read-side critical section uses rcu_read_lock() and rcu_read_unlock(), which are nearly free on modern kernels. The write side must call synchronize_rcu() before modifying the underlying memory, which can take milliseconds. For drivers with frequent writes, RCU adds complexity without benefit and a simple mutex is clearer.
The nonseekable_open() call deserves a specific mention for character device authors. Regular files track a file position that userspace controls via lseek. Character devices that expose data streams do not have a meaningful position. Calling nonseekable_open() in your open handler tells the VFS that this file descriptor does not support seeking, which prevents the kernel from maintaining a position state for your device and avoids a class of bugs where llseek system calls produce unexpected behavior on stream-oriented devices.
User-kernel boundary
Treat user-space pointers as untrusted. Never dereference one directly in kernel code. Use get_user() and put_user() for simple values, or copy_from_user() and copy_to_user() for structures and buffers. Check the result every time: get_user() and put_user() return zero or -EFAULT, while the copy helpers return the number of bytes they could not transfer. A preliminary access_ok() check does not replace checking the copy result; use it when an API specifically requires it, such as the lower-level unchecked access helpers.
For ioctl interfaces, define commands with _IO, _IOR, _IOW, and _IOWR and choose command numbers that do not collide with another interface. _IOW describes data written by the caller and read by the driver. Copy it into a kernel variable with copy_from_user(), check the copy result, then validate its range before acting on it. A pointer check alone does not make the pointed-to value safe. Return -EFAULT for a failed copy, -EINVAL for an invalid value, and -ENOTTY for an unknown command. See the kernel ioctl interface guidance.
Licensing and security
The kernel gates symbol exports by license. When a module loads, the kernel checks MODULE_LICENSE() against a whitelist of GPL-compatible licenses. Only modules declaring a GPL-compatible license (“GPL”, “GPL v2”, “GPL and onwards”, “Dual BSD/GPL”, “Dual MIT/GPL”) get access to internal kernel symbols marked EXPORT_SYMBOL in the source. Proprietary modules with “Proprietary” or “Proprietary (GDT)” lose access to these symbols, which forces closed-source drivers to reimplement functionality the kernel already provides.
The MODULE_LICENSE() value affects which exported symbols a module may use; it does not establish the module’s legal license. Declare the license the code is actually distributed under. A proprietary module cannot use symbols exported only with EXPORT_SYMBOL_GPL().
Module-signing behavior depends on the kernel configuration and trust store. With signature enforcement enabled, the kernel loads only modules signed by a key it trusts; Secure Boot commonly enables a distribution-specific trust and enrollment flow, but MOK is not universal. Check the target distribution’s policy and use its supported process. Never work around a host rejection by disabling Secure Boot or signature enforcement. Protect any private signing key, and sign the final module only after all changes because modifying or stripping it invalidates the signature.
Minimize your module’s attack surface by exporting only the symbols that other modules genuinely need. Use EXPORT_SYMBOL_GPL() instead of EXPORT_SYMBOL() when your module’s functionality should remain exclusive to GPL-licensed consumers. Hide internal implementation details behind non-exported functions, and treat any user-supplied data as potentially malicious.
Quick recap checklist
- Kernel modules extend kernel functionality at runtime without rebooting
- Character drivers provide file-based interfaces via
file_operations - ioctl commands allow custom user-kernel communication
- Always validate and copy data between user and kernel space
- Use proper synchronization primitives for concurrent access
- Test extensively in VMs before production deployment
- Follow the GPL licensing requirement for module headers
- Use
devm_*functions for automatic resource management
Real-world case study: USB driver development
Consider developing a USB device driver for a custom hardware device. The driver must:
- Identify the device using USB vendor/product IDs via
USB_DEVICE() - Declare endpoints in the interrupt/bulk descriptors
- Implement probe/remove for device lifecycle management
- Handle URBs (USB Request Blocks) for async I/O
- Manage device power states with
usb_autopm_get_interface()
The USB subsystem handles descriptor parsing, bandwidth management, and hotplug coordination. A driver author still needs to implement probe/remove, submit URBs safely, and manage the device’s power state through the USB APIs.
Advanced topic: kernel symbols and EXPORT_SYMBOL
When one kernel module needs to call functions from another, the callee must explicitly export its symbols:
/* Symbol export example */
void internal_helper_function(int arg)
{
/* Implementation */
}
EXPORT_SYMBOL(internal_helper_function);
Exported symbols can be used by other modules when the kernel makes them available. Keep internal helpers unexported, and document any symbols your module intentionally exposes.
Interview questions
copy_from_user and get_user? When would you use each?get_user reads one simple value, while copy_from_user copies a buffer or structure. Both can fault and sleep, so call them from process context, not an interrupt handler. get_user returns zero or -EFAULT; copy_from_user returns the number of bytes it could not copy.
When modprobe fails, inspect the kernel log for the reported error. Check modinfo for module metadata and version information, then verify that required dependencies are available. Rebuild against the running kernel before trying another load.
__init and __exit annotations. Why are they important?__init marks functions called only during module initialization; the kernel can free their code memory after they complete. __exit marks functions only called during module unload; the kernel can omit them entirely if the module cannot be unloaded. These annotations optimize memory usage, especially important in embedded systems with limited RAM.
Always acquire locks in a consistent global order across all code paths. Use lockdep to detect potential deadlocks during development. Avoid calling user callbacks while holding locks—user code might try to acquire the same lock. Consider using mutex_lock_nested() with subclasses when the same lock type is used in nested contexts.
MODULE_LICENSE macro and why does it matter?MODULE_LICENSE supplies module metadata that affects access to symbols marked EXPORT_SYMBOL_GPL. It does not determine the legal license of the source code. A proprietary module cannot use GPL-only exported symbols.
alloc_chrdev_region and register_chrdev? When would you use each?register_chrdev registers a legacy character driver with a fixed major number (or requests dynamic allocation). alloc_chrdev_region always dynamically allocates a major number and provides a dev_t for use with the modern cdev interface. Use alloc_chrdev_region with cdev_init/cdev_add for new code—it integrates properly with the device model, sysfs, and udev. register_chrdev is legacy and doesn't create device nodes automatically.
Kernel objects can use struct kref for reference counting. A consumer calls kref_get to hold a reference and kref_put when it is done; the release function runs when the count reaches zero. File objects have their own reference-counting rules, so drivers should follow the relevant VFS APIs rather than manage the file count directly.
A spinlock busy-waits (spins) while waiting for the lock—appropriate for short critical sections in atomic context. A mutex can sleep (block) while waiting—appropriate for longer sections or when sleeping is allowed. Never use a mutex in interrupt context; never hold a spinlock while sleeping. Use spinlocks for short, quick operations (like updating a linked list). Use mutexes for operations that might take longer or require memory allocation.
The Linux Device Model (DM) provides a hierarchical tree of devices, buses, and drivers that enables: (1) power management coordination through the driver core, (2) dynamic device enumeration through sysfs, (3) driver binding and unbinding at runtime, (4) proper cleanup on device removal through reference counting. Before the DM, device handling was ad-hoc and led to duplicate code. It introducedstruct device, struct bus_type, and struct class as the canonical abstractions for representing hardware in the kernel.
User-access helpers may fault and sleep, so do not call get_user, put_user, or copy_from_user from hard IRQ or other atomic context. Copy the data in process context, validate it, then pass a kernel-owned copy to deferred work. Never retain a user pointer for later use.
Tasklets run in atomic context and cannot sleep. Workqueues run in process context and can sleep. Use a tasklet only for short work that must stay in atomic context; choose a workqueue when the deferred operation may block. schedule_work() queues work on the system workqueue. Use INIT_WORK() to initialize a work item or schedule_delayed_work() when it needs a delay.
Kernel objects (including modules) use struct kref for reference counting. When a module is loaded, its use count tracks consumers. try_module_get() increments; module_put() decrements. A module cannot be unloaded (rmmod fails) if use count is non-zero. This prevents unloading while in use. Example: a kernel module provides a device interface; module_get() is called when the device is opened and module_put() when closed. Additionally, modules can use __module_ref_get() / __module_ref_put() for fine-grained control. The kernel's lockdep can detect incorrect refcount use, and lsmod shows current refcounts.
Character devices (register_chrdev/alloc_chrdev_region + cdev_add) require: major/minor number allocation, explicit device node creation (mknod), manual permission management, and integration with udev rules. Misc devices (MISC_DYNAMIC_MINOR + misc_register) are a simplified wrapper: they use a single misc major number (10), dynamically assign minor numbers, auto-create device nodes in /dev, and provide a simpler API. Use misc devices for simple drivers that don't need complex device hierarchies (like sound cards, GPUs, or input devices that are one per system). For multiple instances of the same device type, character devices with dynamic allocation are more appropriate.
GFP_ATOMIC vs GFP_KERNEL for memory allocation in modules?GFP_KERNEL: Can sleep, waiting for memory if none available. Safe for process context, cannot be used in atomic context (interrupt handlers, spinlocks held). Uses the kernel's regular memory allocator which can compact and reclaim. GFP_ATOMIC: Cannot sleep—uses a pre-allocated pool (called the atomic reserve). If pool is exhausted, allocation fails. Required in: interrupt handlers, softirqs, spinlock-held contexts, tasklet handlers. Trade-offs: GFP_ATOMIC can fail if memory is fragmented; overusing it depletes the atomic pool. For modules that may run in any context, use GFP_ATOMIC in top-half handlers and defer allocation to bottom-half (workqueue) where GFP_KERNEL is safe.
Module parameters are declared with module_param(name, type, perm) and optionally MODULE_PARM_DESC(). At load time (insmod or modprobe), values can be set via: command line (insmod module.ko param=value) or /sys/module/<name>/parameters/<param> at runtime (if perm bits include write). Perm bits: 0 (hidden), 0644 (world-readable, root-only write), 0600 (root-only). The kernel stores parameters in a NULL-terminated array accessible via /sys/module/. For boolean parameters, use module_param_named() with bool type. Arrays use module_param_array() with separate count variable.
try_then_request_module() in the kernel API?try_then_request_module() is used to handle optional module dependencies. It first tries to resolve a symbol or function; if that fails (ENOSYS), it triggers a module load request and waits for the module to be loaded, then retries. Pattern: func = try_then_request_module(symbol_get, "module_name"). If symbol_get() returns NULL (symbol not present), userspace is notified to load the module, and the call blocks until request_module() completes. After the module loads, symbol_get() is retried. Used for: (1) optional kernel features that can be compiled as modules; (2) backing device drivers that may be loadable. The function combines symbol lookup with asynchronous module loading.
fasync ( asynchronous notification) notifies userspace when a device has data available without polling. It uses fasync_helper() in the driver's fasync file operation and kill_fasync() when data arrives. select/poll (poll_wait() + f_op->poll) allows userspace to wait for file descriptor readiness (readable, writable, error). Key difference: fasync pushes data to userspace via signal; poll is pulled (userspace calls select/poll and blocks). Use fasync for low-latency notification of asynchronous events (like incoming network packets); use poll for request-response style I/O. The poll method returns a bitmask of currently ready events; fasync is invoked only when the state actually changes.
owner field in struct file_operations?The .owner field (set to THIS_MODULE) tells the kernel that this driver owns a reference to the module. When the file operation is called, the kernel increments the module's use count, preventing module unloading while any file handle is open. This prevents rmmod from succeeding if a process has the device open. Without setting owner, unloading a module while its device is in use causes use-after-free bugs—processes with open file descriptors would be accessing freed memory. Always set .owner = THIS_MODULE in your file_operations structure. The only exception is for built-in drivers (no module to unload), where this is moot.
Coherent DMA (dma_alloc_coherent(), dma_free_coherent()): Allocates memory the device and CPU can access simultaneously. The kernel maintains the mapping for the lifetime of the allocation—simple but uses non-cacheable memory which is slower. Streaming DMA (dma_map_single(), dma_unmap_single()): Maps a buffer only for the duration of a DMA transfer. CPU may not access buffer during this time (or must call dma_sync). More efficient because the buffer can stay cached normally. Use coherent DMA for frequent, small accesses (descriptor rings); use streaming DMA for bulk transfers. For scatter-gather, use dma_map_sg() + dma_unmap_sg(). The dma_mask field in struct device controls addressing capabilities (32-bit vs 64-bit).
container_of macro in kernel development and when is it used?container_of(ptr, type, member) recovers the containing structure from a pointer to one of its fields. It uses offsetof() to find the field's position. Kernel lists use it through list_entry(), and callbacks often use it to recover driver data from an embedded structure. When a driver needs device-specific state, prefer the device model's data helpers where they fit.
Further reading
- Linux Device Driver Development - Jonathan Corbet, Alessandro Rubini, Greg Kroah-Hartman
- Linux Kernel Documentation - Official kernel docs for subsystems
- LWN.net Kernel Articles - Weekly kernel development news
- Kernel.org Bugzilla - Track kernel issues and patches
- Linux Driver Verification - Tools for driver testing and validation
- Device Drivers Architecture — Deep dive into Linux driver model
- Kernel Architecture Internals — Inside the Linux kernel design
Conclusion
Kernel modules extend Linux, but a mistake in one can affect the whole system. Check for an existing subsystem or user-space interface first. If a module is necessary, build against the target kernel, validate user input, and test initialization failure and cleanup in a disposable VM.
Use the kernel documentation for the subsystem you are working with. It covers that subsystem’s APIs and the debugging tools suited to it, such as ftrace or lockdep.
Category
Related Posts
Real-Time Operating Systems
Understand RTOS concepts, scheduling guarantees, latency bounds, and the PREEMPT_RT patch for achieving real-time Linux.
CPU Affinity & Real-Time Operating Systems
Learn how CPU affinity changes task placement, how Linux real-time policies differ, and why deadline guarantees depend on workload, configuration, and hardware.
Fork & Exec System Calls
How Unix-like systems use fork() to create a child process and exec() to replace its program image, with notes on threads and file descriptors.