GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GeezerVison is showing sysprog21.github.io (truncated) — The Linux Kernel Module Programming Guide The Linux Kernel Module Programming GuidePeter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram, Jim Huang September 7, 2026
1 Getting Started
1 Introduction 1.1 Authorship 1.2 Acknowledgements 1.3 What Is A Kernel Module? 1.4 Kernel module package 1.5 What Modules are in my Kernel? 1.6 Is there a need to download and compile the kernel? 1.7 Before We Begin 1.8 QEMU-Based Development Environment 2 Kernel Headers 3 Examples 4 Hello World 4.1 The Simplest Module 4.2 Hello and Goodbye 4.3 The __init and __exit Macros 4.4 Licensing and Module Documentation 4.5 Passing Command Line Arguments to a Module 4.6 Modules Spanning Multiple Files 4.7 Building modules for a precompiled kernel 2 Core Kernel Interfaces 5 Preliminaries 5.1 How modules begin and end 5.2 Functions available to modules 5.3 User Space vs Kernel Space 5.4 Name Space 5.5 Code space 5.6 Device Drivers 6 Character Device drivers 6.1 The file_operations Structure 6.2 The file structure 6.3 Registering A Device 6.4 Unregistering A Device 6.5 chardev.c 6.6 Writing Modules for Multiple Kernel Versions 7 The /proc Filesystem 7.1 The proc_ops Structure 7.2 Read and Write a /proc File 7.3 Manage /proc file metadata and access hooks 7.4 Manage /proc file with seq_file 8 sysfs: Interacting with your module 9 debugfs: Flexible debugging interfaces 10 Talking To Device Files 10.1 poll, select, and epoll 10.2 Asynchronous notification 3 Execution Context and Control Flow 11 System Calls 12 Blocking Processes and threads 12.1 Sleep 12.2 Completions 13 Synchronization 13.1 Mutex 13.2 Spinlocks 13.3 Read and write locks 13.4 Atomic operations 13.5 Read-Copy-Update (RCU) 14 Replacing Print Macros 14.1 Replacement 14.2 Flashing keyboard LEDs 4 Memory, Time, and Data Movement 15 Timekeeping and Deferred Execution 16 Memory Allocation and Ownership 17 Copying Data Across the User-Kernel Boundary 18 Memory-Mapped I/O and Register Access 19 DMA and mmap 19.1 DMA Addressing and Ownership Rules 19.2 Scatter-Gather and DMA API Patterns 19.3 DMA Debugging and Common Mistakes 20 Modern Interface Choices for Linux 5.10 and Later 5 Hardware Integration and Advanced Topics 21 GPIO 21.1 GPIO 21.2 Control the LED’s on/off state 21.3 DHT11 sensor 22 Scheduling Tasks 22.1 Tasklets 22.2 Work queues 23 Interrupt Handlers 23.1 Interrupt Handlers 23.2 Detecting button presses 23.3 Bottom Half 23.4 Threaded IRQ 24 Virtual Input Device Driver 25 PCI Drivers 26 USB Drivers 26.1 USB Device Model Basics 26.2 Endpoints, Pipes, and URBs 26.3 USB and Userspace Interfaces 26.4 Hotplug, Suspend, and Failure Modes 27 Block Drivers 27.1 The Modern Block Stack 27.2 BIOs, Requests, and Completion 27.3 Queue Limits, Flushes, and Reality 28 Network Drivers 28.1 net_device and netdev_ops 28.2 Socket Buffers and Receive Paths 28.3 NAPI, Interrupt Moderation, and Throughput 28.4 Offloads, Link State, and Userspace 29 Standardizing the interfaces: The Device Model 30 Device Tree 30.1 Introduction to Device Tree 30.2 Device Tree and Kernel Modules 30.3 Example: Device Tree Module 30.4 Device Tree Source Example 30.5 Testing Device Tree Modules 30.6 Common Device Tree Functions 31 Optimizations 31.1 Likely and Unlikely conditions 31.2 Static keys 32 Common Pitfalls 32.1 Using standard libraries 32.2 Disabling interrupts 32.3 Kernel stack is small 32.4 No floating point in the kernel 32.5 Initialize buffers before copying to user space 32.6 Double-underscore functions are internal 33 Secure Boot Signing Guide 33.1 Install Dependencies 33.2 Generate a MOK Key Pair 33.3 Enroll the Key with MOKutil 33.4 Complete Enrollment in UEFI 33.5 Sign Your Kernel Module 34 Where To Go From Here? Contents
1 Getting Started
1 Introduction 1.1 Authorship 1.2 Acknowledgements 1.3 What Is A Kernel Module? 1.4 Kernel module package 1.5 What Modules are in my Kernel? 1.6 Is there a need to download and compile the kernel? 1.7 Before We Begin 1.8 QEMU-Based Development Environment 2 Kernel Headers 3 Examples 4 Hello World 4.1 The Simplest Module 4.2 Hello and Goodbye 4.3 The __init and __exit Macros 4.4 Licensing and Module Documentation 4.5 Passing Command Line Arguments to a Module 4.6 Modules Spanning Multiple Files 4.7 Building modules for a precompiled kernel 2 Core Kernel Interfaces 5 Preliminaries 5.1 How modules begin and end 5.2 Functions available to modules 5.3 User Space vs Kernel Space 5.4 Name Space 5.5 Code space 5.6 Device Drivers 6 Character Device drivers 6.1 The file_operations Structure 6.2 The file structure 6.3 Registering A Device 6.4 Unregistering A Device 6.5 chardev.c 6.6 Writing Modules for Multiple Kernel Versions 7 The /proc Filesystem 7.1 The proc_ops Structure 7.2 Read and Write a /proc File 7.3 Manage /proc file metadata and access hooks 7.4 Manage /proc file with seq_file 8 sysfs: Interacting with your module 9 debugfs: Flexible debugging interfaces 10 Talking To Device Files 10.1 poll, select, and epoll 10.2 Asynchronous notification 3 Execution Context and Control Flow 11 System Calls 12 Blocking Processes and threads 12.1 Sleep 12.2 Completions 13 Synchronization 13.1 Mutex 13.2 Spinlocks 13.3 Read and write locks 13.4 Atomic operations 13.5 Read-Copy-Update (RCU) 14 Replacing Print Macros 14.1 Replacement 14.2 Flashing keyboard LEDs 4 Memory, Time, and Data Movement 15 Timekeeping and Deferred Execution 16 Memory Allocation and Ownership 17 Copying Data Across the User-Kernel Boundary 18 Memory-Mapped I/O and Register Access 19 DMA and mmap 19.1 DMA Addressing and Ownership Rules 19.2 Scatter-Gather and DMA API Patterns 19.3 DMA Debugging and Common Mistakes 20 Modern Interface Choices for Linux 5.10 and Later 5 Hardware Integration and Advanced Topics 21 GPIO 21.1 GPIO 21.2 Control the LED’s on/off state 21.3 DHT11 sensor 22 Scheduling Tasks 22.1 Tasklets 22.2 Work queues 23 Interrupt Handlers 23.1 Interrupt Handlers 23.2 Detecting button presses 23.3 Bottom Half 23.4 Threaded IRQ 24 Virtual Input Device Driver 25 PCI Drivers 26 USB Drivers 26.1 USB Device Model Basics 26.2 Endpoints, Pipes, and URBs 26.3 USB and Userspace Interfaces 26.4 Hotplug, Suspend, and Failure Modes 27 Block Drivers 27.1 The Modern Block Stack 27.2 BIOs, Requests, and Completion 27.3 Queue Limits, Flushes, and Reality 28 Network Drivers 28.1 net_device and netdev_ops 28.2 Socket Buffers and Receive Paths 28.3 NAPI, Interrupt Moderation, and Throughput 28.4 Offloads, Link State, and Userspace 29 Standardizing the interfaces: The Device Model 30 Device Tree 30.1 Introduction to Device Tree 30.2 Device Tree and Kernel Modules 30.3 Example: Device Tree Module 30.4 Device Tree Source Example 30.5 Testing Device Tree Modules 30.6 Common Device Tree Functions 31 Optimizations 31.1 Likely and Unlikely conditions 31.2 Static keys 32 Common Pitfalls 32.1 Using standard libraries 32.2 Disabling interrupts 32.3 Kernel stack is small 32.4 No floating point in the kernel 32.5 Initialize buffers before copying to user space 32.6 Double-underscore functions are internal 33 Secure Boot Signing Guide 33.1 Install Dependencies 33.2 Generate a MOK Key Pair 33.3 Enroll the Key with MOKutil 33.4 Complete Enrollment in UEFI 33.5 Sign Your Kernel Module 34 Where To Go From Here? Chapter 1
|
| Operation | Process ctx | Softirq/tasklet ctx | Hardirq ctx |
| Sleep / schedule | Yes | No | No |
| Access user memory (copy_to_user) | Yes | No | No |
| kmalloc(GFP_KERNEL) | Yes | No | No |
| kmalloc(GFP_ATOMIC) | Yes | Yes | Yes |
| Acquire mutex | Yes | No | No |
| Acquire spinlock | Yes | Yes | Yes |
| current pointer meaningful | Yes | No | No |
When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you are writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples’ global variables; some of the variable names can clash. When a program has lots of global variables which aren’t meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.
When writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue. The best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols. By convention, all kernel prefixes are lowercase. If you do not want to declare everything as static, another option is to declare a symbol table and register it with the kernel. We will get to this later.
The file /proc/kallsyms holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel’s codespace.
Memory management is a very complicated subject and the majority of O’Reilly’s Understanding The Linux Kernel exclusively covers memory management! We are not setting out to be experts on memory management, but we do need to know a couple of facts to even begin worrying about writing real modules.
If you have not thought about what a segfault really means, you may be surprised to hear that pointers do not actually point to memory locations. Not real ones, anyway. When a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about. This memory begins with 0x00000000 and extends up to whatever it needs to be. Since the memory space for any two processes does not overlap, every process that can access a memory address, say 0xbffff978, would be accessing a different location in real physical memory! The processes would be accessing an index named 0xbffff978 which points to some kind of offset into the region of memory set aside for that particular process. For the most part, a process like our Hello, World program cannot access the space of another process, although there are ways which we will talk about later.
The kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel’s codespace rather than having its own. Therefore, if your module segfaults, the kernel segfaults. And if you start writing over data because of an off-by-one error, then you’re trampling on kernel data (or code). This is even worse than it sounds, so try your best to be careful.
It should be noted that the aforementioned discussion applies to any operating system utilizing a monolithic kernel. This concept differs slightly from “building all your modules into the kernel”, although the underlying principle is similar. In contrast, there are microkernels, where modules are allocated their own code space. Two notable examples of microkernels include the GNU Hurd and the Zircon kernel of Google’s Fuchsia.
One class of module is the device driver, which provides functionality for hardware like a serial port. On Unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.ko sound card device driver might connect the /dev/sound device file to the Ensoniq ES1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed.
Let’s look at some device files. Here are device files which represent the first three partitions on the primary SCSI storage devices:
$ ls -l /dev/sda[1-3] brw-rw---- 1 root disk 8, 1 Apr 9 2025 /dev/sda1 brw-rw---- 1 root disk 8, 2 Apr 9 2025 /dev/sda2 brw-rw---- 1 root disk 8, 3 Apr 9 2025 /dev/sda3
Notice the column of numbers separated by a comma. The first number is called the device’s major number. The second number is the minor number. The major number tells you which driver is used to access the hardware. Each driver is assigned a unique major number; all device files with the same major number are controlled by the same driver. All the above major numbers are 8, because they’re all controlled by the same driver.
The minor number is used by the driver to distinguish between the various hardware it controls. Returning to the example above, although all three devices are handled by the same driver they have unique minor numbers because the driver sees them as being different pieces of hardware.
Devices are divided into two types: character devices and block devices. The difference is that block devices have a buffer for requests, so they can choose the best order in which to respond to the requests. This is important in the case of storage devices, where it is faster to read or write sectors which are close to each other, rather than those which are further apart. Another difference is that block devices can only accept input and return output in blocks (whose size can vary according to the device), whereas character devices are allowed to use as many or as few bytes as they like. Most devices in the world are character, because they don’t need this type of buffering, and they don’t operate with a fixed block size. You can tell whether a device file is for a block device or a character device by looking at the first character in the output of ls -l. If it is ‘b’ then it is a block device, and if it is ‘c’ then it is a character device. The devices you see above are block devices. Here are some character devices (the serial ports):
crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0 crw-r----- 1 root dial 4, 65 Nov 17 10:26 /dev/ttyS1 crw-rw---- 1 root dial 4, 66 Jul 5 2000 /dev/ttyS2 crw-rw---- 1 root dial 4, 67 Jul 5 2000 /dev/ttyS3
If you want to see which major numbers have been assigned, you can look at Documentation/admin-guide/devices.txt.
When the system was installed, all of those device files were created by the mknod command. To create a new char device named coffee with major/minor number 12 and 2, simply do mknod /dev/coffee c 12 2. You do not have to put your device files into /dev, but it is done by convention. Linus put his device files in /dev, and so should you. However, when creating a device file for testing purposes, it is probably OK to place it in your working directory where you compile the kernel module. Just be sure to put it in the right place when you’re done writing the device driver.
A few final points, although implicit in the previous discussion, are worth stating explicitly for clarity. When a device file is accessed, the kernel utilizes the file’s major number to identify the appropriate driver for handling the access. This indicates that the kernel does not necessarily rely on or need to be aware of the minor number. It is the driver that concerns itself with the minor number, using it to differentiate between various pieces of hardware.
It is important to note that when referring to “hardware”, the term is used in a slightly more abstract sense than just a physical PCI card that can be held in hand. Consider the following two device files:
$ ls -l /dev/sda /dev/sdb brw-rw---- 1 root disk 8, 0 Jan 3 09:02 /dev/sda brw-rw---- 1 root disk 8, 16 Jan 3 09:02 /dev/sdb
By now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 8). Sometimes two device files with the same major but different minor number can actually represent the same piece of physical hardware. So just be aware that the word “hardware” in our discussion can mean something very abstract.
The file_operations structure is defined in include/linux/fs.h, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.
For example, every character driver needs to define a function that reads from the device. The file_operations structure holds the address of the module’s function that performs that operation. Here is what the definition looks like for kernel 5.4 and later versions:
1 struct file_operations { 2 struct module *owner; 3 loff_t (*llseek) (struct file *, loff_t, int); 4 ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); 5 ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); 6 ssize_t (*read_iter) (struct kiocb *, struct iov_iter *); 7 ssize_t (*write_iter) (struct kiocb *, struct iov_iter *); 8 int (*iopoll)(struct kiocb *kiocb, bool spin); 9 int (*iterate) (struct file *, struct dir_context *); 10 int (*iterate_shared) (struct file *, struct dir_context *); 11 __poll_t (*poll) (struct file *, struct poll_table_struct *); 12 long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); 13 long (*compat_ioctl) (struct file *, unsigned int, unsigned long); 14 int (*mmap) (struct file *, struct vm_area_struct *); 15 unsigned long mmap_supported_flags; 16 int (*open) (struct inode *, struct file *); 17 int (*flush) (struct file *, fl_owner_t id); 18 int (*release) (struct inode *, struct file *); 19 int (*fsync) (struct file *, loff_t, loff_t, int datasync); 20 int (*fasync) (int, struct file *, int); 21 int (*lock) (struct file *, int, struct file_lock *); 22 ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); 23 unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); 24 int (*check_flags)(int); 25 int (*flock) (struct file *, int, struct file_lock *); 26 ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); 27 ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); 28 int (*setlease)(struct file *, long, struct file_lock **, void **); 29 long (*fallocate)(struct file *file, int mode, loff_t offset, 30 loff_t len); 31 void (*show_fdinfo)(struct seq_file *m, struct file *f); 32 ssize_t (*copy_file_range)(struct file *, loff_t, struct file *, 33 loff_t, size_t, unsigned int); 34 loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in, 35 struct file *file_out, loff_t pos_out, 36 loff_t len, unsigned int remap_flags); 37 int (*fadvise)(struct file *, loff_t, loff_t, int); 38 } __randomize_layout;
Some operations are not implemented by a driver. For example, a driver that handles a video card will not need to read from a directory structure. The corresponding entries in the file_operations structure should be set to NULL. 1
There is a gcc extension that makes assigning to this structure more convenient. You will see it in modern drivers, and may catch you by surprise. This is what the new way of assigning to the structure looks like:
1 struct file_operations fops = { 2 read: device_read, 3 write: device_write, 4 open: device_open, 5 release: device_release 6 };
However, there is also a C99 way of assigning to elements of a structure, designated initializers, and this is definitely preferred over using the GNU extension. You should use this syntax in case someone wants to port your driver. It will help with compatibility:
1 struct file_operations fops = { 2 .read = device_read, 3 .write = device_write, 4 .open = device_open, 5 .release = device_release 6 };
The meaning is clear, and you should be aware that any member of the structure which you do not explicitly assign will be initialized to NULL by gcc.
An instance of struct file_operations containing pointers to functions that are used to implement read, write, open, … system calls is commonly named fops.
Since Linux v3.14, the read, write and seek operations are guaranteed to be thread-safe by using the f_pos specific lock, which makes the file position update to become the mutual exclusion. So, we can safely implement those operations without unnecessary locking.
Additionally, since Linux v5.6, the proc_ops structure was introduced to replace the use of the file_operations structure when registering proc handlers. See more information in the Section 7.1.
Each device is represented in the kernel by a file structure, which is defined in include/linux/fs.h. Be aware that a file is a kernel level structure and never appears in a user space program. It is not the same thing as a FILE, which is defined by glibc and would never appear in a kernel space function. Also, its name is a bit misleading; it represents an abstract open ‘file’, not a file on a disk, which is represented by a structure named inode.
An instance of struct file is commonly named filp. You’ll also see it referred to as a struct file object. Resist the temptation.
Go ahead and look at the definition of file. Most of the entries you see, like struct dentry, are not used by device drivers, and you can ignore them. This is because drivers do not fill file directly; they only use structures contained in file which are created elsewhere.
One subtlety worth noting: the open callback is called once for every open() system call, but release is called only when the last file descriptor referring to that struct file is closed. If a process calls dup() or fork(), multiple file descriptors share the same struct file; release is deferred until all of them are gone. The flush callback, by contrast, is invoked on every close(). The private_data field of struct file is the standard place to attach per-open state allocated in open and freed in release.
As discussed earlier, char devices are accessed through device files, usually located in /dev. This is by convention. When writing a driver, it is OK to put the device file in your current directory. Just make sure you place it in /dev for a production driver. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it is operating on, just in case the driver handles more than one device.
Adding a driver to your system means registering it with the kernel. This is synonymous with assigning it a major number during the module’s initialization. You do this by using the register_chrdev function, defined by include/linux/fs.h.
1 int register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
Where unsigned int major is the major number you want to request, const char *name is the name of the device as it will appear in /proc/devices and struct file_operations *fops is a pointer to the file_operations table for your driver. A negative return value means the registration failed. Note that we didn’t pass the minor number to register_chrdev. That is because the kernel doesn’t care about the minor number; only our driver uses it.
Now the question is, how do you get a major number without hijacking one that’s already in use? The easiest way would be to look through Documentation/admin-guide/devices.txt and pick an unused one. That is a bad way of doing things because you will never be sure if the number you picked will be assigned later. The answer is that you can ask the kernel to assign you a dynamic major number.
If you pass a major number of 0 to register_chrdev, the return value will be the dynamically allocated major number. The downside is that you can not make a device file in advance, since you do not know what the major number will be. There are a couple of ways to do this. First, the driver itself can print the newly assigned number and we can make the device file by hand. Second, the newly registered device will have an entry in /proc/devices, and we can either make the device file by hand or write a shell script to read the file in and make the device file. The third method is that we can have our driver make the device file using the device_create function after a successful registration and device_destroy during the call to cleanup_module.
However, register_chrdev() would occupy a range of minor numbers associated with the given major. The recommended way to reduce waste for char device registration is using cdev interface.
The newer interface completes the char device registration in two distinct steps. First, we should register a range of device numbers, which can be completed with register_chrdev_region or alloc_chrdev_region.
1 int register_chrdev_region(dev_t from, unsigned count, const char *name); 2int alloc_chrdev_region(dev_t *dev, unsigned baseminor, unsigned count, const char *name);
The choice between two different functions depends on whether you know the major numbers for your device. Using register_chrdev_region if you know the device major number and alloc_chrdev_region if you would like to allocate a dynamically-allocated major number.
Second, we should initialize the data structure struct cdev for our char device and associate it with the device numbers. To initialize the struct cdev, we can achieve by the similar sequence of the following codes.
1 struct cdev *my_cdev = cdev_alloc(); 2my_cdev->ops = &my_fops;
However, the common usage pattern will embed the struct cdev within a device-specific structure of your own. In this case, we’ll need cdev_init for the initialization.
1 void cdev_init(struct cdev *cdev, const struct file_operations *fops);
Once we finish the initialization, we can add the char device to the system by using the cdev_add.
1 int cdev_add(struct cdev *p, dev_t dev, unsigned count);
To find an example using the interface, you can see ioctl.c described in Section 10.
We can not allow the kernel module to be rmmod’ed whenever root feels like it. If the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be. If we are lucky, no other code was loaded there, and we’ll get an ugly error message. If we are unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel. The results of this would be impossible to predict, but they can not be very positive.
Normally, when you do not want to allow something, you return an error code (a negative number) from the function which is supposed to do it. With cleanup_module that’s impossible because it is a void function. However, there is a counter which keeps track of how many processes are using your module. You can see what its value is by looking at the 3rd field with the command cat /proc/modules or lsmod. If this number isn’t zero, rmmod will fail. Note that you do not have to check the counter within cleanup_module because the check will be performed for you by the system call sys_delete_module, defined in include/linux/syscalls.h. You should not use this counter directly, but there are functions defined in include/linux/module.h which let you display this counter:
Note: The use of try_module_get(THIS_MODULE) and module_put(THIS_MODULE) within a module’s own code is considered unsafe and should be avoided. The kernel automatically manages the reference count when file operations are in progress, so manual reference counting is unnecessary and can lead to race conditions. For a deeper understanding of when and how to properly use module reference counting, see https://stackoverflow.com/questions/1741415/linux-kernel-modules-when-to-use-try-module-get-module-put.
The next code sample creates a char driver named chardev. You can verify it has been registered by checking:
1 cat /proc/devices
This will show the device’s major number. To actually use the device, you need to read from /dev/chardev (or open the file with a program) and the driver will put the number of times the device file has been read from into the file. We do not support writing to the file (like echo "hi" > /dev/chardev), but catch these attempts and tell the user that the operation is not supported. Do not worry if you do not see what we do with the data we read into the buffer; we do not do much with it. We simply read in the data and print a message acknowledging that we received it.
In a multi-threaded environment, without any protection, concurrent access to the same memory may lead to race conditions and will not preserve performance. In the kernel module, this problem may happen due to multiple instances accessing the shared resources. Therefore, a solution is to enforce exclusive access. We use atomic Compare-And-Swap (CAS) to maintain the states, CDEV_NOT_USED and CDEV_EXCLUSIVE_OPEN, to determine whether the file is currently opened by someone or not. CAS compares the contents of a memory location with the expected value and, only if they are the same, modifies the contents of that memory location to the desired value. See more concurrency details in the Section 13.
1/* 2 * chardev.c: Creates a read-only char device that says how many times 3 * you have read from the dev file 4 */ 5 6#include <linux/atomic.h> 7#include <linux/cdev.h> 8#include <linux/delay.h> 9#include <linux/device.h> 10#include <linux/fs.h> 11#include <linux/init.h> 12#include <linux/kernel.h> /* for sprintf() */ 13#include <linux/module.h> 14#include <linux/printk.h> 15#include <linux/types.h> 16#include <linux/uaccess.h> /* for get_user and put_user */ 17#include <linux/version.h> 18 19#include <asm/errno.h> 20 21/* Prototypes - this would normally go in a .h file */ 22static int device_open(struct inode *, struct file *); 23static int device_release(struct inode *, struct file *); 24static ssize_t device_read(struct file *, char __user *, size_t, loff_t *); 25static ssize_t device_write(struct file *, const char __user *, size_t, 26 loff_t *); 27 28#define DEVICE_NAME "chardev" /* Dev name as it appears in /proc/devices */ 29#define BUF_LEN 80 /* Max length of the message from the device */ 30 31/* Global variables are declared as static, so are global within the file. */ 32 33static int major; /* major number assigned to our device driver */ 34 35enum { 36 CDEV_NOT_USED, 37 CDEV_EXCLUSIVE_OPEN, 38}; 39 40/* Is device open? Used to prevent multiple access to device */ 41static atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED); 42 43static char msg[BUF_LEN + 1]; /* The msg the device will give when asked */ 44 45static struct class *cls; 46 47static struct file_operations chardev_fops = { 48 .read = device_read, 49 .write = device_write, 50 .open = device_open, 51 .release = device_release, 52}; 53 54static int __init chardev_init(void) 55{ 56 major = register_chrdev(0, DEVICE_NAME, &chardev_fops); 57 58 if (major < 0) { 59 pr_alert("Registering char device failed with %d\n", major); 60 return major; 61 } 62 63 pr_info("I was assigned major number %d.\n", major); 64 65#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0) 66 cls = class_create(DEVICE_NAME); 67#else 68 cls = class_create(THIS_MODULE, DEVICE_NAME); 69#endif 70 if (IS_ERR(cls)) { 71 pr_err("Failed to create class for device\n"); 72 unregister_chrdev(major, DEVICE_NAME); 73 return PTR_ERR(cls); 74 } 75 device_create(cls, NULL, MKDEV(major, 0), NULL, DEVICE_NAME); 76 77 pr_info("Device created on /dev/%s\n", DEVICE_NAME); 78 79 return 0; 80} 81 82static void __exit chardev_exit(void) 83{ 84 device_destroy(cls, MKDEV(major, 0)); 85 class_destroy(cls); 86 87 /* Unregister the device */ 88 unregister_chrdev(major, DEVICE_NAME); 89} 90 91/* Methods */ 92 93/* Called when a process tries to open the device file, like 94 * "sudo cat /dev/chardev" 95 */ 96static int device_open(struct inode *inode, struct file *file) 97{ 98 static int counter = 0; 99 100 if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN)) 101 return -EBUSY; 102 103 sprintf(msg, "I already told you %d times Hello world!\n", counter++); 104 105 return 0; 106} 107 108/* Called when a process closes the device file. */ 109static int device_release(struct inode *inode, struct file *file) 110{ 111 /* We're now ready for our next caller */ 112 atomic_set(&already_open, CDEV_NOT_USED); 113 114 return 0; 115} 116 117/* Called when a process, which already opened the dev file, attempts to 118 * read from it. 119 */ 120static ssize_t device_read(struct file *filp, /* see include/linux/fs.h */ 121 char __user *buffer, /* buffer to fill with data */ 122 size_t length, /* length of the buffer */ 123 loff_t *offset) 124{ 125 /* Number of bytes actually written to the buffer */ 126 int bytes_read = 0; 127 const char *msg_ptr = msg; 128 129 if (!*(msg_ptr + *offset)) { /* we are at the end of message */ 130 *offset = 0; /* reset the offset */ 131 return 0; /* signify end of file */ 132 } 133 134 msg_ptr += *offset; 135 136 /* Actually put the data into the buffer */ 137 while (length && *msg_ptr) { 138 /* The buffer is in the user data segment, not the kernel 139 * segment so "*" assignment won't work. We have to use 140 * put_user which copies data from the kernel data segment to 141 * the user data segment. 142 */ 143 put_user(*(msg_ptr++), buffer++); 144 length--; 145 bytes_read++; 146 } 147 148 *offset += bytes_read; 149 150 /* Most read functions return the number of bytes put into the buffer. */ 151 return bytes_read; 152} 153 154/* Called when a process writes to dev file: echo "hi" | sudo tee /dev/chardev */ 155static ssize_t device_write(struct file *filp, const char __user *buff, 156 size_t len, loff_t *off) 157{ 158 pr_alert("Sorry, this operation is not supported.\n"); 159 return -EINVAL; 160} 161 162module_init(chardev_init); 163module_exit(chardev_exit); 164 165MODULE_LICENSE("GPL");
The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility – a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.
There are differences between different kernel versions, and if you want to support
multiple kernel versions, you will find yourself having to code conditional compilation
directives. The way to do this is to compare the macro LINUX_VERSION_CODE to the
macro KERNEL_VERSION. In version a.b.c of the kernel, the value of this macro would
be .
In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the /proc filesystem. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as /proc/modules which provides the list of modules and /proc/meminfo which gathers memory usage statistics.
The method to use the proc filesystem is very similar to the one used with device drivers — a structure is created with all the information needed for the /proc file, including pointers to any handler functions (in our case there is only one, the one called when somebody attempts to read from the /proc file). Then, init_module registers the structure with the kernel and cleanup_module unregisters it.
Normal filesystems are located on a disk, rather than just in memory (which is where /proc is), and in that case the index-node (inode for short) number is a pointer to a disk location where the file’s inode is located. The inode contains information about the file, for example the file’s permissions, together with a pointer to the disk location or locations where the file’s data can be found.
Because we do not get called when the file is opened or closed, there is nowhere for us to put try_module_get and module_put in this module, and if the file is opened and then the module is removed, there is no way to avoid the consequences. The kernel’s automatic reference counting for file operations helps prevent module removal while files are in use, but /proc files require careful handling due to their different lifecycle.
Here is a simple example showing how to use a /proc file. This is the HelloWorld for the /proc filesystem. There are three parts: create the file /proc/helloworld in the function init_module, return a value (and a buffer) when the file /proc/helloworld is read in the callback function procfile_read, and delete the file /proc/helloworld in the function cleanup_module.
The /proc/helloworld is created when the module is loaded with the function proc_create. The return value is a pointer to struct proc_dir_entry, and it will be used to configure the file /proc/helloworld (for example, the owner of this file). A null return value means that the creation has failed.
Every time the file /proc/helloworld is read, the function procfile_read is called. Two parameters of this function are very important: the buffer (the second parameter) and the offset (the fourth one). The content of the buffer will be returned to the application which read it (for example the cat command). The offset is the current position in the file. If the return value of the function is not null, then this function is called again. So be careful with this function, if it never returns zero, the read function is called endlessly.
$ cat /proc/helloworld HelloWorld!
1/* 2 * procfs1.c 3 */ 4 5#include <linux/kernel.h> 6#include <linux/module.h> 7#include <linux/proc_fs.h> 8#include <linux/uaccess.h> 9#include <linux/version.h> 10 11#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) 12#define HAVE_PROC_OPS 13#endif 14 15#define procfs_name "helloworld" 16 17static struct proc_dir_entry *our_proc_file; 18 19static ssize_t procfile_read(struct file *file_pointer, char __user *buffer, 20 size_t buffer_length, loff_t *offset) 21{ 22 char s[13] = "HelloWorld!\n"; 23 int len = sizeof(s); 24 ssize_t ret = len; 25 26 if (*offset >= len || copy_to_user(buffer, s, len)) { 27 pr_info("copy_to_user failed\n"); 28 ret = 0; 29 } else { 30 pr_info("procfile read %s\n", file_pointer->f_path.dentry->d_name.name); 31 *offset += len; 32 } 33 34 return ret; 35} 36 37#ifdef HAVE_PROC_OPS 38static const struct proc_ops proc_file_fops = { 39 .proc_read = procfile_read, 40}; 41#else 42static const struct file_operations proc_file_fops = { 43 .read = procfile_read, 44}; 45#endif 46 47static int __init procfs1_init(void) 48{ 49 our_proc_file = proc_create(procfs_name, 0644, NULL, &proc_file_fops); 50 if (NULL == our_proc_file) { 51 pr_alert("Error:Could not initialize /proc/%s\n", procfs_name); 52 return -ENOMEM; 53 } 54 55 pr_info("/proc/%s created\n", procfs_name); 56 return 0; 57} 58 59static void __exit procfs1_exit(void) 60{ 61 proc_remove(our_proc_file); 62 pr_info("/proc/%s removed\n", procfs_name); 63} 64 65module_init(procfs1_init); 66module_exit(procfs1_exit); 67 68MODULE_LICENSE("GPL");
The proc_ops structure is defined in include/linux/proc_fs.h in Linux v5.6+. In older kernels, it used file_operations for custom hooks in /proc filesystem, but it contains some members that are unnecessary in VFS, and every time VFS expands file_operations set, /proc code comes bloated. On the other hand, not only the space, but also some operations were saved by this structure to improve its performance. For example, the file which never disappears in /proc can set the proc_flag as PROC_ENTRY_PERMANENT to save 2 atomic ops, 1 allocation, 1 free in per open/read/close sequence.
We have seen a very simple example for a /proc file where we only read the file /proc/helloworld. It is also possible to write in a /proc file. It works the same way as read, a function is called when the /proc file is written. But there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with copy_from_user or get_user)
The reason for copy_from_user or get_user is that Linux memory (on Intel architecture, it may be different under some other processors) is segmented. This means that a pointer, by itself, does not reference a unique location in memory, only a location in a memory segment, and you need to know which memory segment it is to be able to use it. There is one memory segment for the kernel, and one for each of the processes.
The only memory segment accessible to a process is its own, so when writing regular programs to run as processes, there is no need to worry about segments. When you write a kernel module, normally you want to access the kernel memory segment, which is handled automatically by the system. However, when the content of a memory buffer needs to be passed between the currently running process and the kernel, the kernel function receives a pointer to the memory buffer which is in the process segment. The put_user and get_user macros allow you to access that memory. These functions handle only one character, you can handle several characters with copy_to_user and copy_from_user. As the buffer (in read or write function) is in kernel space, for write function you need to import data because it comes from user space, but not for the read function because data is already in kernel space.
1/* 2 * procfs2.c - create a "file" in /proc 3 */ 4 5#include <linux/kernel.h> /* We're doing kernel work */ 6#include <linux/module.h> /* Specifically, a module */ 7#include <linux/proc_fs.h> /* Necessary because we use the proc fs */ 8#include <linux/uaccess.h> /* for copy_from_user */ 9#include <linux/version.h> 10 11#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) 12#define HAVE_PROC_OPS 13#endif 14 15#define PROCFS_MAX_SIZE 1024 16#define PROCFS_NAME "buffer1k" 17 18/* This structure hold information about the /proc file */ 19static struct proc_dir_entry *our_proc_file; 20 21/* The buffer used to store character for this module */ 22static char procfs_buffer[PROCFS_MAX_SIZE]; 23 24/* The size of the buffer */ 25static unsigned long procfs_buffer_size = 0; 26 27/* This function is called then the /proc file is read */ 28static ssize_t procfile_read(struct file *file_pointer, char __user *buffer, 29 size_t buffer_length, loff_t *offset) 30{ 31 char s[13] = "HelloWorld!\n"; 32 int len = sizeof(s); 33 ssize_t ret = len; 34 35 if (*offset >= len || copy_to_user(buffer, s, len)) { 36 pr_info("copy_to_user failed\n"); 37 ret = 0; 38 } else { 39 pr_info("procfile read %s\n", file_pointer->f_path.dentry->d_name.name); 40 *offset += len; 41 } 42 43 return ret; 44} 45 46/* This function is called when the /proc file is written. */ 47static ssize_t procfile_write(struct file *file, const char __user *buff, 48 size_t len, loff_t *off) 49{ 50 procfs_buffer_size = len; 51 if (procfs_buffer_size >= PROCFS_MAX_SIZE) 52 procfs_buffer_size = PROCFS_MAX_SIZE - 1; 53 54 if (copy_from_user(procfs_buffer, buff, procfs_buffer_size)) 55 return -EFAULT; 56 57 procfs_buffer[procfs_buffer_size] = '\0'; 58 *off += procfs_buffer_size; 59 pr_info("procfile write %s\n", procfs_buffer); 60 61 return procfs_buffer_size; 62} 63 64#ifdef HAVE_PROC_OPS 65static const struct proc_ops proc_file_fops = { 66 .proc_read = procfile_read, 67 .proc_write = procfile_write, 68}; 69#else 70static const struct file_operations proc_file_fops = { 71 .read = procfile_read, 72 .write = procfile_write, 73}; 74#endif 75 76static int __init procfs2_init(void) 77{ 78 our_proc_file = proc_create(PROCFS_NAME, 0644, NULL, &proc_file_fops); 79 if (NULL == our_proc_file) { 80 pr_alert("Error:Could not initialize /proc/%s\n", PROCFS_NAME); 81 return -ENOMEM; 82 } 83 84 pr_info("/proc/%s created\n", PROCFS_NAME); 85 return 0; 86} 87 88static void __exit procfs2_exit(void) 89{ 90 proc_remove(our_proc_file); 91 pr_info("/proc/%s removed\n", PROCFS_NAME); 92} 93 94module_init(procfs2_init); 95module_exit(procfs2_exit); 96 97MODULE_LICENSE("GPL");
We have seen how to read and write a /proc file with the /proc interface. The proc_create helper also lets us control metadata and add extra hooks, such as explicit open and release handlers. That is useful when we want more control than a minimal read/write example provides.
The sample in this section keeps the same read and write callbacks as before, but adds procfs_open and procfs_close to show where setup and teardown logic can live. This is also where you would normally attach per-open state if the file needed it.
Permissions are still important, but in this example they are controlled through the proc entry itself. The mode argument passed to proc_create sets the access bits, and proc_set_user adjusts the owner and group of the /proc entry.
Another helper used here is proc_set_size, which records the expected size of the virtual file. That information is optional, but it can improve the way user space tools report the entry.
It is important to note that the standard roles of read and write are reversed in the kernel. Read functions are used for output, whereas write functions are used for input. The reason for that is that read and write refer to the user’s point of view — if a process reads something from the kernel, then the kernel needs to output it, and if a process writes something to the kernel, then the kernel receives it as input.
1/* 2 * procfs3.c 3 */ 4 5#include <linux/kernel.h> 6#include <linux/module.h> 7#include <linux/proc_fs.h> 8#include <linux/sched.h> 9#include <linux/uaccess.h> 10#include <linux/version.h> 11#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 10, 0) 12#include <linux/minmax.h> 13#endif 14 15#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) 16#define HAVE_PROC_OPS 17#endif 18 19#define PROCFS_MAX_SIZE 2048UL 20#define PROCFS_ENTRY_FILENAME "buffer2k" 21 22static struct proc_dir_entry *our_proc_file; 23static char procfs_buffer[PROCFS_MAX_SIZE]; 24static unsigned long procfs_buffer_size = 0; 25 26static ssize_t procfs_read(struct file *filp, char __user *buffer, 27 size_t length, loff_t *offset) 28{ 29 if (*offset || procfs_buffer_size == 0) { 30 pr_debug("procfs_read: END\n"); 31 *offset = 0; 32 return 0; 33 } 34 procfs_buffer_size = min(procfs_buffer_size, length); 35 if (copy_to_user(buffer, procfs_buffer, procfs_buffer_size)) 36 return -EFAULT; 37 *offset += procfs_buffer_size; 38 39 pr_debug("procfs_read: read %lu bytes\n", procfs_buffer_size); 40 return procfs_buffer_size; 41} 42static ssize_t procfs_write(struct file *file, const char __user *buffer, 43 size_t len, loff_t *off) 44{ 45 procfs_buffer_size = min(PROCFS_MAX_SIZE, len); 46 if (copy_from_user(procfs_buffer, buffer, procfs_buffer_size)) 47 return -EFAULT; 48 *off += procfs_buffer_size; 49 50 pr_debug("procfs_write: write %lu bytes\n", procfs_buffer_size); 51 return procfs_buffer_size; 52} 53static int procfs_open(struct inode *inode, struct file *file) 54{ 55 return 0; 56} 57static int procfs_close(struct inode *inode, struct file *file) 58{ 59 return 0; 60} 61 62#ifdef HAVE_PROC_OPS 63static struct proc_ops file_ops_4_our_proc_file = { 64 .proc_read = procfs_read, 65 .proc_write = procfs_write, 66 .proc_open = procfs_open, 67 .proc_release = procfs_close, 68}; 69#else 70static const struct file_operations file_ops_4_our_proc_file = { 71 .read = procfs_read, 72 .write = procfs_write, 73 .open = procfs_open, 74 .release = procfs_close, 75}; 76#endif 77 78static int __init procfs3_init(void) 79{ 80 our_proc_file = proc_create(PROCFS_ENTRY_FILENAME, 0644, NULL, 81 &file_ops_4_our_proc_file); 82 if (our_proc_file == NULL) { 83 pr_debug("Error: Could not initialize /proc/%s\n", 84 PROCFS_ENTRY_FILENAME); 85 return -ENOMEM; 86 } 87 proc_set_size(our_proc_file, 80); 88 proc_set_user(our_proc_file, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); 89 90 pr_debug("/proc/%s created\n", PROCFS_ENTRY_FILENAME); 91 return 0; 92} 93 94static void __exit procfs3_exit(void) 95{ 96 remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); 97 pr_debug("/proc/%s removed\n", PROCFS_ENTRY_FILENAME); 98} 99 100module_init(procfs3_init); 101module_exit(procfs3_exit); 102 103MODULE_LICENSE("GPL");
Still hungry for procfs examples? Well, first of all keep in mind, there are rumors around, claiming that procfs is on its way out, consider using sysfs instead. Consider using this mechanism, in case you want to document something kernel related yourself.
As we have seen, writing a /proc file may be quite “complex”. So to help people writing /proc file, there is an API named seq_file that helps formatting a /proc file for output. It is based on sequence, which is composed of 3 functions: start(), next(), and stop(). The seq_file API starts a sequence when a user reads the /proc file.
A sequence begins with the call of the function start(). If the return is a non NULL value, the function next() is called; otherwise, the stop() function is called directly. This function is an iterator, the goal is to go through all the data. Each time next() is called, the function show() is also called. It writes data values in the buffer read by the user. The function next() is called until it returns NULL. The sequence ends when next() returns NULL, then the function stop() is called.
BE CAREFUL: when a sequence is finished, another one starts. That means that at the end of function stop(), the function start() is called again. This loop finishes when the function start() returns NULL. You can see a scheme of this in the Figure 2.1.
The seq_file provides basic functions for proc_ops, such as seq_read, seq_lseek, and some others. But nothing to write in the /proc file. Of course, you can still use the same way as in the previous example.
1/* 2 * procfs4.c - create a "file" in /proc 3 * This program uses the seq_file library to manage the /proc file. 4 */ 5 6#include <linux/kernel.h> /* We are doing kernel work */ 7#include <linux/module.h> /* Specifically, a module */ 8#include <linux/proc_fs.h> /* Necessary because we use proc fs */ 9#include <linux/seq_file.h> /* for seq_file */ 10#include <linux/version.h> 11 12#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) 13#define HAVE_PROC_OPS 14#endif 15 16#define PROC_NAME "iter" 17 18/* This function is called at the beginning of a sequence. 19 * ie, when: 20 * - the /proc file is read (first time) 21 * - after the function stop (end of sequence) 22 */ 23static void *my_seq_start(struct seq_file *s, loff_t *pos) 24{ 25 static unsigned long counter = 0; 26 27 /* beginning a new sequence? */ 28 if (*pos == 0) { 29 /* yes => return a non null value to begin the sequence */ 30 return &counter; 31 } 32 33 /* no => it is the end of the sequence, return end to stop reading */ 34 *pos = 0; 35 return NULL; 36} 37 38/* This function is called after the beginning of a sequence. 39 * It is called until the return is NULL (this ends the sequence). 40 */ 41static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos) 42{ 43 unsigned long *tmp_v = (unsigned long *)v; 44 (*tmp_v)++; 45 (*pos)++; 46 return NULL; 47} 48 49/* This function is called at the end of a sequence. */ 50static void my_seq_stop(struct seq_file *s, void *v) 51{ 52 /* nothing to do, we use a static value in start() */ 53} 54 55/* This function is called for each "step" of a sequence. */ 56static int my_seq_show(struct seq_file *s, void *v) 57{ 58 loff_t *spos = (loff_t *)v; 59 60 seq_printf(s, "%Ld\n", *spos); 61 return 0; 62} 63 64/* This structure gathers functions to manage the sequence */ 65static struct seq_operations my_seq_ops = { 66 .start = my_seq_start, 67 .next = my_seq_next, 68 .stop = my_seq_stop, 69 .show = my_seq_show, 70}; 71 72/* This function is called when the /proc file is open. */ 73static int my_open(struct inode *inode, struct file *file) 74{ 75 return seq_open(file, &my_seq_ops); 76}; 77 78/* This structure gathers functions that manage the /proc file */ 79#ifdef HAVE_PROC_OPS 80static const struct proc_ops my_file_ops = { 81 .proc_open = my_open, 82 .proc_read = seq_read, 83 .proc_lseek = seq_lseek, 84 .proc_release = seq_release, 85}; 86#else 87static const struct file_operations my_file_ops = { 88 .open = my_open, 89 .read = seq_read, 90 .llseek = seq_lseek, 91 .release = seq_release, 92}; 93#endif 94 95static int __init procfs4_init(void) 96{ 97 struct proc_dir_entry *entry; 98 99 entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops); 100 if (entry == NULL) { 101 pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME); 102 return -ENOMEM; 103 } 104 105 return 0; 106} 107 108static void __exit procfs4_exit(void) 109{ 110 remove_proc_entry(PROC_NAME, NULL); 111 pr_debug("/proc/%s removed\n", PROC_NAME); 112} 113 114module_init(procfs4_init); 115module_exit(procfs4_exit); 116 117MODULE_LICENSE("GPL");
If you want more information, you can read this web page:
You can also read the code of fs/seq_file.c in the Linux kernel.
sysfs allows you to interact with the running kernel from userspace by reading or setting variables inside of modules. This can be useful for debugging purposes, or just as an interface for applications or scripts. You can find sysfs directories and files under the /sys directory on your system.
1 ls -l /sys
Unlike /proc, which grew organically and mixes process information with driver knobs, sysfs is tightly tied to the kernel’s device model and provides multiple coherent views of the same hardware:
Every directory in sysfs corresponds to a struct kobject in the kernel. Files inside those directories are kobject attributes; read or write operations on them invoke show() or store() callbacks inside the driver. This one-value-per-file convention keeps the interface simple and scriptable compared to the free-form output of many /proc entries.
Attributes can be exported for kobjects in the form of regular files in the filesystem. Sysfs forwards file I/O operations to methods defined for the attributes, providing a means to read and write kernel attributes.
A simple attribute definition:
1 struct attribute { 2 char *name; 3 struct module *owner; 4 umode_t mode; 5}; 6 7int sysfs_create_file(struct kobject * kobj, const struct attribute * attr); 8 void sysfs_remove_file(struct kobject * kobj, const struct attribute * attr);
For example, the driver model defines struct device_attribute like:
1 struct device_attribute { 2 struct attribute attr; 3 ssize_t (*show)(struct device *dev, struct device_attribute *attr, 4 char *buf); 5 ssize_t (*store)(struct device *dev, struct device_attribute *attr, 6 const char *buf, size_t count); 7}; 8 9int device_create_file(struct device *, const struct device_attribute *); 10 void device_remove_file(struct device *, const struct device_attribute *);
To read or write attributes, the show() or store() method must be specified when declaring the attribute. For the common cases include/linux/sysfs.h provides convenience macros (__ATTR, __ATTR_RO, __ATTR_WO, etc.) to make defining attributes easier as well as making code more concise and readable.
An example of a hello world module which includes the creation of a variable accessible via sysfs is given below.
1/* 2 * hello-sysfs.c sysfs example 3 */ 4#include <linux/fs.h> 5#include <linux/init.h> 6#include <linux/kobject.h> 7#include <linux/module.h> 8#include <linux/string.h> 9#include <linux/sysfs.h> 10 11static struct kobject *mymodule; 12 13/* the variable you want to be able to change */ 14static int myvariable = 0; 15 16static ssize_t myvariable_show(struct kobject *kobj, 17 struct kobj_attribute *attr, char *buf) 18{ 19 return sprintf(buf, "%d\n", myvariable); 20} 21 22static ssize_t myvariable_store(struct kobject *kobj, 23 struct kobj_attribute *attr, const char *buf, 24 size_t count) 25{ 26 sscanf(buf, "%d", &myvariable); 27 return count; 28} 29 30static struct kobj_attribute myvariable_attribute = 31 __ATTR(myvariable, 0660, myvariable_show, myvariable_store); 32 33static int __init mymodule_init(void) 34{ 35 int error = 0; 36 37 pr_info("mymodule: initialized\n"); 38 39 mymodule = kobject_create_and_add("mymodule", kernel_kobj); 40 if (!mymodule) 41 return -ENOMEM; 42 43 error = sysfs_create_file(mymodule, &myvariable_attribute.attr); 44 if (error) { 45 kobject_put(mymodule); 46 pr_info("failed to create the myvariable file " 47 "in /sys/kernel/mymodule\n"); 48 } 49 50 return error; 51} 52 53static void __exit mymodule_exit(void) 54{ 55 pr_info("mymodule: Exit success\n"); 56 kobject_put(mymodule); 57} 58 59module_init(mymodule_init); 60module_exit(mymodule_exit); 61 62MODULE_LICENSE("GPL");
Make and install the module:
1 make 2sudo insmod hello-sysfs.ko
Check that it exists:
1 lsmod | grep hello_sysfs
What is the current value of myvariable ?
1 cat /sys/kernel/mymodule/myvariable
Set the value of myvariable and check that it changed.
1 echo "32" | sudo tee /sys/kernel/mymodule/myvariable 2cat /sys/kernel/mymodule/myvariable
Finally, remove the test module:
1 sudo rmmod hello_sysfs
In the above case, we use a simple kobject to create a directory under sysfs, and communicate with its attributes. Since Linux v2.6.0, the kobject structure made its appearance. It was initially meant as a simple way of unifying kernel code which manages reference counted objects. After a bit of mission creep, it is now the glue that holds much of the device model and its sysfs interface together. For more information about kobject and sysfs, see Documentation/driver-api/driver-model/driver.rst and https://lwn.net/Articles/51437/.
debugfs is a lightweight filesystem for exporting debugging information from the kernel to userspace. Unlike sysfs, it is not intended to provide a stable userspace ABI, and unlike /proc it does not try to model processes or broader kernel state. That makes it a good fit for ad hoc diagnostics, counters, and developer-oriented control points while a module is under active development.
The canonical introduction is Documentation/filesystems/debugfs.rst, which describes both the design goals and the helper APIs. On most systems, debugfs is mounted at /sys/kernel/debug:
1 mount | grep debugfs 2ls -l /sys/kernel/debug
To use the interface, include include/linux/debugfs.h and create a top-level directory for your module:
1 struct dentry *debugfs_create_dir(const char *name, struct dentry *parent);
Passing NULL as the parent places the new directory at the root of debugfs. When you unload the module, remove the whole subtree with debugfs_remove_recursive(). Note that debugfs_create_dir() and the other debugfs_create_*() helpers are designed to be used in a fire-and-forget fashion: their return values should not be checked. If debugfs is unavailable or an entry cannot be created, the helpers return an error pointer that is silently accepted by subsequent calls and by debugfs_remove_recursive(), so the module continues to work without its debug interface.
For simple scalar values, debugfs provides typed helpers that map a kernel variable directly to a file. Common examples include debugfs_create_u32(), debugfs_create_bool(), and the hexadecimal variants such as debugfs_create_x32(). These helpers are convenient when the data already lives in a fixed-size variable and does not need custom formatting.
The following example creates a debugfs directory and exports a writable integer plus a boolean flag:
1/* 2 * hello-debugfs.c - Export simple values through debugfs. 3 */ 4#include <linux/debugfs.h> 5#include <linux/init.h> 6#include <linux/module.h> 7#include <linux/moduleparam.h> 8#include <linux/printk.h> 9 10MODULE_DESCRIPTION("Export simple values through debugfs"); 11MODULE_LICENSE("GPL"); 12 13#define DEBUGFS_DIR "lkmpg_debugfs" 14 15static struct dentry *debugfs_dir; 16 17static u32 debug_value = 42; 18static bool debug_enabled = true; 19 20module_param(debug_value, uint, 0600); 21MODULE_PARM_DESC(debug_value, "Value exported through both sysfs and debugfs"); 22 23module_param(debug_enabled, bool, 0600); 24MODULE_PARM_DESC(debug_enabled, "Enable or disable the example flag"); 25 26static int __init hello_debugfs_init(void) 27{ 28 debugfs_dir = debugfs_create_dir(DEBUGFS_DIR, NULL); 29 30 debugfs_create_u32("debug_value", 0600, debugfs_dir, &debug_value); 31 debugfs_create_bool("debug_enabled", 0600, debugfs_dir, &debug_enabled); 32 33 pr_info("debugfs interface registered under /sys/kernel/debug/%s\n", 34 DEBUGFS_DIR); 35 return 0; 36} 37 38static void __exit hello_debugfs_exit(void) 39{ 40 debugfs_remove_recursive(debugfs_dir); 41 pr_info("debugfs example removed\n"); 42} 43 44module_init(hello_debugfs_init); 45module_exit(hello_debugfs_exit);
If you need a custom text format or more control over reads and writes, create a file with your own struct file_operations:
1 struct dentry *debugfs_create_file(const char *name, umode_t mode, 2 struct dentry *parent, void *data, 3 const struct file_operations *fops);
debugfs also includes helpers for a few common read-only payloads. One of them is debugfs_create_blob(), which exposes an existing memory region as a file.
The next example combines both approaches by creating a writable debugfs file and a read-only blob in the same directory:
1/* 2 * hello-debugfs-file.c - Custom debugfs file and blob examples. 3 */ 4#include <linux/debugfs.h> 5#include <linux/fs.h> 6#include <linux/init.h> 7#include <linux/module.h> 8#include <linux/mutex.h> 9#include <linux/printk.h> 10#include <linux/uaccess.h> 11 12MODULE_DESCRIPTION("Custom debugfs file and blob examples"); 13MODULE_LICENSE("GPL"); 14 15#define DEBUGFS_DIR "lkmpg_debugfs_file" 16#define MESSAGE_MAX_LEN 128 17 18static struct dentry *debugfs_dir; 19static DEFINE_MUTEX(message_lock); 20static char message[MESSAGE_MAX_LEN] = "debugfs says hello\n"; 21static size_t message_len = sizeof("debugfs says hello\n") - 1; 22 23static const char blob_data[] = 24 "This blob is read-only and exported with debugfs_create_blob().\n"; 25static struct debugfs_blob_wrapper debug_blob = { 26 .data = (void *)blob_data, 27 .size = sizeof(blob_data) - 1, 28}; 29 30static ssize_t message_read(struct file *file, char __user *buffer, size_t len, 31 loff_t *ppos) 32{ 33 ssize_t ret; 34 35 mutex_lock(&message_lock); 36 ret = simple_read_from_buffer(buffer, len, ppos, message, message_len); 37 mutex_unlock(&message_lock); 38 39 return ret; 40} 41 42static ssize_t message_write(struct file *file, const char __user *buffer, 43 size_t len, loff_t *ppos) 44{ 45 ssize_t copied; 46 47 if (*ppos != 0) 48 return -EINVAL; 49 50 mutex_lock(&message_lock); 51 copied = 52 simple_write_to_buffer(message, sizeof(message) - 1, ppos, buffer, len); 53 if (copied > 0) { 54 message_len = *ppos; 55 message[message_len] = '\0'; 56 } 57 mutex_unlock(&message_lock); 58 59 return copied; 60} 61 62static const struct file_operations message_fops = { 63 .owner = THIS_MODULE, 64 .read = message_read, 65 .write = message_write, 66 .llseek = default_llseek, 67}; 68 69static int __init hello_debugfs_file_init(void) 70{ 71 debugfs_dir = debugfs_create_dir(DEBUGFS_DIR, NULL); 72 73 debugfs_create_file("message", 0600, debugfs_dir, NULL, &message_fops); 74 debugfs_create_blob("blob", 0400, debugfs_dir, &debug_blob); 75 76 pr_info("debugfs file example registered under /sys/kernel/debug/%s\n", 77 DEBUGFS_DIR); 78 return 0; 79} 80 81static void __exit hello_debugfs_file_exit(void) 82{ 83 debugfs_remove_recursive(debugfs_dir); 84 pr_info("debugfs file example removed\n"); 85} 86 87module_init(hello_debugfs_file_init); 88module_exit(hello_debugfs_file_exit);
Because debugfs is explicitly for debugging, its contents should be treated as implementation details rather than a supported external interface. If a setting must remain stable for tooling, scripts, or end users, prefer sysfs or another documented ABI instead.
Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device_write.
This is not always enough. Imagine you had a serial port connected to a modem (even if you have an internal modem, it is still implemented from the CPU’s perspective as a serial port connected to a modem, so you don’t have to tax your imagination too hard). The natural thing to do would be to use the device file to write things to the modem (either modem commands or data to be sent through the phone line) and read things from the modem (either responses for commands or the data received through the phone line). However, this leaves open the question of what to do when you need to talk to the serial port itself, for example to configure the rate at which data is sent and received.
The answer in Unix is to use a special function called ioctl (short for Input Output ConTroL). Every device can have its own ioctl commands, which can be read ioctl operations (to send information from a process to the kernel), write ioctl operations (to return information to a process), both or neither. Notice here the roles of read and write are reversed again, so in ioctl operations, read is to send information to the kernel and write is to receive information from the kernel.
The ioctl function is called with three parameters: the file descriptor of the appropriate device file, the ioctl number, and a parameter, which is of type long so you can use a cast to use it to pass anything. You will not be able to pass a structure this way, but you will be able to pass a pointer to the structure. Here is an example:
1/* 2 * ioctl.c 3 */ 4#include <linux/cdev.h> 5#include <linux/fs.h> 6#include <linux/init.h> 7#include <linux/ioctl.h> 8#include <linux/module.h> 9#include <linux/slab.h> 10#include <linux/uaccess.h> 11#include <linux/version.h> 12 13struct ioctl_arg { 14 unsigned int val; 15}; 16 17/* Documentation/userspace-api/ioctl/ioctl-number.rst */ 18#define IOC_MAGIC '\x66' 19 20#define IOCTL_VALSET _IOW(IOC_MAGIC, 0, struct ioctl_arg) 21#define IOCTL_VALGET _IOR(IOC_MAGIC, 1, struct ioctl_arg) 22#define IOCTL_VALGET_NUM _IOR(IOC_MAGIC, 2, int) 23#define IOCTL_VALSET_NUM _IO(IOC_MAGIC, 3) 24 25#define IOCTL_VAL_MAXNR 3 26#define DRIVER_NAME "ioctltest" 27 28static unsigned int test_ioctl_major = 0; 29static unsigned int num_of_dev = 1; 30static struct cdev test_ioctl_cdev; 31static int ioctl_num = 0; 32 33struct test_ioctl_data { 34 unsigned char val; 35 rwlock_t lock; 36}; 37 38static long test_ioctl_ioctl(struct file *filp, unsigned int cmd, 39 unsigned long arg) 40{ 41 struct test_ioctl_data *ioctl_data = filp->private_data; 42 int retval = 0; 43 unsigned char val; 44 struct ioctl_arg data; 45 memset(&data, 0, sizeof(data)); 46 47 switch (cmd) { 48 case IOCTL_VALSET: 49 if (copy_from_user(&data, (int __user *)arg, sizeof(data))) { 50 retval = -EFAULT; 51 goto done; 52 } 53 54 pr_alert("IOCTL set val:%x .\n", data.val); 55 write_lock(&ioctl_data->lock); 56 ioctl_data->val = data.val; 57 write_unlock(&ioctl_data->lock); 58 break; 59 60 case IOCTL_VALGET: 61 read_lock(&ioctl_data->lock); 62 val = ioctl_data->val; 63 read_unlock(&ioctl_data->lock); 64 data.val = val; 65 66 if (copy_to_user((int __user *)arg, &data, sizeof(data))) { 67 retval = -EFAULT; 68 goto done; 69 } 70 71 break; 72 73 case IOCTL_VALGET_NUM: 74 retval = __put_user(ioctl_num, (int __user *)arg); 75 break; 76 77 case IOCTL_VALSET_NUM: 78 ioctl_num = arg; 79 break; 80 81 default: 82 retval = -ENOTTY; 83 } 84 85done: 86 return retval; 87} 88 89static ssize_t test_ioctl_read(struct file *filp, char __user *buf, 90 size_t count, loff_t *f_pos) 91{ 92 struct test_ioctl_data *ioctl_data = filp->private_data; 93 unsigned char val; 94 int retval; 95 int i = 0; 96 97 read_lock(&ioctl_data->lock); 98 val = ioctl_data->val; 99 read_unlock(&ioctl_data->lock); 100 101 for (; i < count; i++) { 102 if (copy_to_user(&buf[i], &val, 1)) { 103 retval = -EFAULT; 104 goto out; 105 } 106 } 107 108 retval = count; 109out: 110 return retval; 111} 112 113static int test_ioctl_close(struct inode *inode, struct file *filp) 114{ 115 pr_alert("%s call.\n", __func__); 116 117 if (filp->private_data) { 118 kfree(filp->private_data); 119 filp->private_data = NULL; 120 } 121 122 return 0; 123} 124 125static int test_ioctl_open(struct inode *inode, struct file *filp) 126{ 127 struct test_ioctl_data *ioctl_data; 128 129 pr_alert("%s call.\n", __func__); 130 ioctl_data = kmalloc(sizeof(struct test_ioctl_data), GFP_KERNEL); 131 132 if (ioctl_data == NULL) 133 return -ENOMEM; 134 135 rwlock_init(&ioctl_data->lock); 136 ioctl_data->val = 0xFF; 137 filp->private_data = ioctl_data; 138 139 return 0; 140} 141 142static struct file_operations fops = { 143 .owner = THIS_MODULE, 144 .open = test_ioctl_open, 145 .release = test_ioctl_close, 146 .read = test_ioctl_read, 147 .unlocked_ioctl = test_ioctl_ioctl, 148}; 149 150static int __init ioctl_init(void) 151{ 152 dev_t dev; 153 int ret; 154 155 ret = alloc_chrdev_region(&dev, 0, num_of_dev, DRIVER_NAME); 156 157 if (ret) 158 return ret; 159 160 test_ioctl_major = MAJOR(dev); 161 cdev_init(&test_ioctl_cdev, &fops); 162 ret = cdev_add(&test_ioctl_cdev, dev, num_of_dev); 163 164 if (ret) { 165 unregister_chrdev_region(dev, num_of_dev); 166 return ret; 167 } 168 169 pr_alert("%s driver(major: %d) installed.\n", DRIVER_NAME, 170 test_ioctl_major); 171 return 0; 172} 173 174static void __exit ioctl_exit(void) 175{ 176 dev_t dev = MKDEV(test_ioctl_major, 0); 177 178 cdev_del(&test_ioctl_cdev); 179 unregister_chrdev_region(dev, num_of_dev); 180 pr_alert("%s driver removed.\n", DRIVER_NAME); 181} 182 183module_init(ioctl_init); 184module_exit(ioctl_exit); 185 186MODULE_LICENSE("GPL"); 187MODULE_DESCRIPTION("This is test_ioctl module");
You can see there is an argument called cmd in test_ioctl_ioctl() function. It is the ioctl number. The ioctl number encodes the major device number, the type of the ioctl, the command, and the type of the parameter. This ioctl number is usually created by a macro call (_IO, _IOR, _IOW or _IOWR — depending on the type) in a header file. This header file should then be included both by the programs which will use ioctl (so they can generate the appropriate ioctl operations) and by the kernel module (so it can understand it). In the example below, the header file is chardev.h and the program which uses it is userspace_ioctl.c.
If you want to use ioctls in your own kernel modules, it is best to receive an official ioctl assignment, so if you accidentally get somebody else’s ioctls, or if they get yours, you’ll know something is wrong. For more information, consult the kernel source tree at Documentation/userspace-api/ioctl/ioctl-number.rst.
Also, we need to be careful that concurrent access to the shared resources will lead to the race condition. The solution is using atomic Compare-And-Swap (CAS), which we mentioned at Section 6.5, to enforce the exclusive access.
1/* 2 * chardev2.c - Create an input/output character device 3 */ 4 5#include <linux/atomic.h> 6#include <linux/cdev.h> 7#include <linux/delay.h> 8#include <linux/device.h> 9#include <linux/fs.h> 10#include <linux/init.h> 11#include <linux/module.h> /* Specifically, a module */ 12#include <linux/printk.h> 13#include <linux/types.h> 14#include <linux/uaccess.h> /* for get_user and put_user */ 15#include <linux/version.h> 16 17#include <asm/errno.h> 18 19#include "chardev.h" 20#define DEVICE_NAME "char_dev" 21#define BUF_LEN 80 22 23enum { 24 CDEV_NOT_USED, 25 CDEV_EXCLUSIVE_OPEN, 26}; 27 28/* Is the device open right now? Used to prevent concurrent access into 29 * the same device 30 */ 31static atomic_t already_open = ATOMIC_INIT(CDEV_NOT_USED); 32 33/* The message the device will give when asked */ 34static char message[BUF_LEN + 1]; 35 36static struct class *cls; 37 38/* This is called whenever a process attempts to open the device file */ 39static int device_open(struct inode *inode, struct file *file) 40{ 41 pr_info("device_open(%p)\n", file); 42 43 return 0; 44} 45 46static int device_release(struct inode *inode, struct file *file) 47{ 48 pr_info("device_release(%p,%p)\n", inode, file); 49 50 return 0; 51} 52 53/* This function is called whenever a process which has already opened the 54 * device file attempts to read from it. 55 */ 56static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ 57 char __user *buffer, /* buffer to be filled */ 58 size_t length, /* length of the buffer */ 59 loff_t *offset) 60{ 61 /* Number of bytes actually written to the buffer */ 62 int bytes_read = 0; 63 /* How far did the process reading the message get? Useful if the message 64 * is larger than the size of the buffer we get to fill in device_read. 65 */ 66 const char *message_ptr = message; 67 68 if (!*(message_ptr + *offset)) { /* we are at the end of message */ 69 *offset = 0; /* reset the offset */ 70 return 0; /* signify end of file */ 71 } 72 73 message_ptr += *offset; 74 75 /* Actually put the data into the buffer */ 76 while (length && *message_ptr) { 77 /* Because the buffer is in the user data segment, not the kernel 78 * data segment, assignment would not work. Instead, we have to 79 * use put_user which copies data from the kernel data segment to 80 * the user data segment. 81 */ 82 put_user(*(message_ptr++), buffer++); 83 length--; 84 bytes_read++; 85 } 86 87 pr_info("Read %d bytes, %ld left\n", bytes_read, length); 88 89 *offset += bytes_read; 90 91 /* Read functions are supposed to return the number of bytes actually 92 * inserted into the buffer. 93 */ 94 return bytes_read; 95} 96 97/* called when somebody tries to write into our device file. */ 98static ssize_t device_write(struct file *file, const char __user *buffer, 99 size_t length, loff_t *offset) 100{ 101 int i; 102 103 pr_info("device_write(%p,%p,%ld)", file, buffer, length); 104 105 for (i = 0; i < length && i < BUF_LEN; i++) 106 get_user(message[i], buffer + i); 107 108 /* Again, return the number of input characters used. */ 109 return i; 110} 111 112/* This function is called whenever a process tries to do an ioctl on our 113 * device file. We get two extra parameters (additional to the inode and file 114 * structures, which all device functions get): the number of the ioctl called 115 * and the parameter given to the ioctl function. 116 * 117 * If the ioctl is write or read/write (meaning output is returned to the 118 * calling process), the ioctl call returns the output of this function. 119 */ 120static long 121device_ioctl(struct file *file, /* ditto */ 122 unsigned int ioctl_num, /* number and param for ioctl */ 123 unsigned long ioctl_param) 124{ 125 int i; 126 long ret = 0; 127 128 /* We don't want to talk to two processes at the same time. */ 129 if (atomic_cmpxchg(&already_open, CDEV_NOT_USED, CDEV_EXCLUSIVE_OPEN)) 130 return -EBUSY; 131 132 /* Switch according to the ioctl called */ 133 switch (ioctl_num) { 134 case IOCTL_SET_MSG: { 135 /* Receive a pointer to a message (in user space) and set that to 136 * be the device's message. Get the parameter given to ioctl by 137 * the process. 138 */ 139 char __user *tmp = (char __user *)ioctl_param; 140 char ch; 141 142 /* Find the length of the message */ 143 get_user(ch, tmp); 144 for (i = 0; ch && i < BUF_LEN; i++, tmp++) 145 get_user(ch, tmp); 146 147 device_write(file, (char __user *)ioctl_param, i, NULL); 148 break; 149 } 150 case IOCTL_GET_MSG: { 151 loff_t offset = 0; 152 153 /* Give the current message to the calling process - the parameter 154 * we got is a pointer, fill it. 155 */ 156 i = device_read(file, (char __user *)ioctl_param, 99, &offset); 157 158 /* Put a zero at the end of the buffer, so it will be properly 159 * terminated. 160 */ 161 put_user('\0', (char __user *)ioctl_param + i); 162 break; 163 } 164 case IOCTL_GET_NTH_BYTE: 165 /* This ioctl is both input (ioctl_param) and output (the return 166 * value of this function). 167 */ 168 ret = (long)message[ioctl_param]; 169 break; 170 } 171 172 /* We're now ready for our next caller */ 173 atomic_set(&already_open, CDEV_NOT_USED); 174 175 return ret; 176} 177 178/* Module Declarations */ 179 180/* This structure will hold the functions to be called when a process does 181 * something to the device we created. Since a pointer to this structure 182 * is kept in the devices table, it can't be local to init_module. NULL is 183 * for unimplemented functions. 184 */ 185static struct file_operations fops = { 186 .read = device_read, 187 .write = device_write, 188 .unlocked_ioctl = device_ioctl, 189 .open = device_open, 190 .release = device_release, /* a.k.a. close */ 191}; 192 193/* Initialize the module - Register the character device */ 194static int __init chardev2_init(void) 195{ 196 /* Register the character device (at least try) */ 197 int ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &fops); 198 199 /* Negative values signify an error */ 200 if (ret_val < 0) { 201 pr_alert("%s failed with %d\n", 202 "Sorry, registering the character device ", ret_val); 203 return ret_val; 204 } 205 206#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 4, 0) 207 cls = class_create(DEVICE_FILE_NAME); 208#else 209 cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); 210#endif 211 if (IS_ERR(cls)) { 212 pr_err("Failed to create class for device\n"); 213 unregister_chrdev(MAJOR_NUM, DEVICE_NAME); 214 return PTR_ERR(cls); 215 } 216 device_create(cls, NULL, MKDEV(MAJOR_NUM, 0), NULL, DEVICE_FILE_NAME); 217 218 pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); 219 220 return 0; 221} 222 223/* Cleanup - unregister the appropriate file from /proc */ 224static void __exit chardev2_exit(void) 225{ 226 device_destroy(cls, MKDEV(MAJOR_NUM, 0)); 227 class_destroy(cls); 228 229 /* Unregister the device */ 230 unregister_chrdev(MAJOR_NUM, DEVICE_NAME); 231} 232 233module_init(chardev2_init); 234module_exit(chardev2_exit); 235 236MODULE_LICENSE("GPL");
1/* 2 * chardev.h - the header file with the ioctl definitions. 3 * 4 * The declarations here have to be in a header file, because they need 5 * to be known both to the kernel module (in chardev2.c) and the process 6 * calling ioctl() (in userspace_ioctl.c). 7 */ 8 9#ifndef CHARDEV_H 10#define CHARDEV_H 11 12#include <linux/ioctl.h> 13 14/* The major device number. We can not rely on dynamic registration 15 * any more, because ioctls need to know it. 16 */ 17#define MAJOR_NUM 100 18 19/* Set the message of the device driver */ 20#define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *) 21/* _IOW means that we are creating an ioctl command number for passing 22 * information from a user process to the kernel module. 23 * 24 * The first argument, MAJOR_NUM, is the major device number we are using. 25 * 26 * The second argument is the number of the command (there could be several 27 * with different meanings). 28 * 29 * The third argument is the type we want to get from the process to the 30 * kernel. 31 */ 32 33/* Get the message of the device driver */ 34#define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) 35/* This IOCTL is used for output, to get the message of the device driver. 36 * However, we still need the buffer to place the message in to be input, 37 * as it is allocated by the process. 38 */ 39 40/* Get the n'th byte of the message */ 41#define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) 42/* The IOCTL is used for both input and output. It receives from the user 43 * a number, n, and returns message[n]. 44 */ 45 46/* The name of the device file */ 47#define DEVICE_FILE_NAME "char_dev" 48#define DEVICE_PATH "/dev/char_dev" 49 50#endif
1 2/* userspace_ioctl.c - the process to use ioctl operations to control the kernel module 3 * 4 * Until now we could have used cat for input and output. But now 5 * we need to do ioctl operations, which require writing our own process. 6 */ 7 8/* device specifics, such as ioctl numbers and the 9 * major device file. */ 10#include "../chardev.h" 11 12#include <stdio.h> /* standard I/O */ 13#include <fcntl.h> /* open */ 14#include <unistd.h> /* close */ 15#include <stdlib.h> /* exit */ 16#include <sys/ioctl.h> /* ioctl */ 17 18/* Functions for the ioctl calls */ 19 20int ioctl_set_msg(int file_desc, char *message) 21{ 22 int ret_val; 23 24 ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); 25 26 if (ret_val < 0) { 27 printf("ioctl_set_msg failed:%d\n", ret_val); 28 } 29 30 return ret_val; 31} 32 33int ioctl_get_msg(int file_desc) 34{ 35 int ret_val; 36 char message[100] = { 0 }; 37 38 /* Warning - this is dangerous because we don't tell 39 * the kernel how far it's allowed to write, so it 40 * might overflow the buffer. In a real production 41 * program, we would have used two ioctls - one to tell 42 * the kernel the buffer length and another to give 43 * it the buffer to fill 44 */ 45 ret_val = ioctl(file_desc, IOCTL_GET_MSG, message); 46 47 if (ret_val < 0) { 48 printf("ioctl_get_msg failed:%d\n", ret_val); 49 } 50 printf("get_msg message:%s", message); 51 52 return ret_val; 53} 54 55int ioctl_get_nth_byte(int file_desc) 56{ 57 int i, c; 58 59 printf("get_nth_byte message:"); 60 61 i = 0; 62 do { 63 c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++); 64 65 if (c < 0) { 66 printf("\nioctl_get_nth_byte failed at the %d'th byte:\n", i); 67 return c; 68 } 69 70 putchar(c); 71 } while (c != 0); 72 73 return 0; 74} 75 76/* Main - Call the ioctl functions */ 77int main(void) 78{ 79 int file_desc, ret_val; 80 char *msg = "Message passed by ioctl\n"; 81 82 file_desc = open(DEVICE_PATH, O_RDWR); 83 if (file_desc < 0) { 84 printf("Can't open device file: %s, error:%d\n", DEVICE_PATH, 85 file_desc); 86 exit(EXIT_FAILURE); 87 } 88 89 ret_val = ioctl_set_msg(file_desc, msg); 90 if (ret_val) 91 goto error; 92 ret_val = ioctl_get_nth_byte(file_desc); 93 if (ret_val) 94 goto error; 95 ret_val = ioctl_get_msg(file_desc); 96 if (ret_val) 97 goto error; 98 99 close(file_desc); 100 return 0; 101error: 102 close(file_desc); 103 exit(EXIT_FAILURE); 104}
The traditional read() and write() paths are not enough for every character device. Many programs need to wait on multiple file descriptors at once, and for that they use poll(), select(), or most commonly epoll. If a driver can block in read() or write(), it usually also needs a poll callback so userspace can discover when the operation would make progress without spinning.
The kernel-side implementation is centered on the poll file operation. The callback receives a poll_table_struct, and the usual pattern is to register the caller with one or more wait queues using poll_wait() before computing the readiness mask to return. That mask is built from EPOLLIN, EPOLLOUT, EPOLLERR, EPOLLHUP, and related bits. The names still mention epoll, but the same mask is used by poll() and select().
Correct readiness reporting matters because modern event loops often rely on edge-triggered epoll. If a driver returns readable status without guaranteeing that a subsequent read() can consume data, or forgets to wake waiters after state changes, userspace can wedge in hard-to-debug ways. Likewise, returning EPOLLHUP or EPOLLERR too eagerly can make a device appear permanently dead. The rule of thumb is simple: the mask should describe what a nonblocking call would be able to do right now.
When device state changes, wake the relevant wait queue. If you want fine-grained wakeups, use wake_up_interruptible_poll() with the same event bits your poll callback reports. That allows userspace to sleep efficiently until the device becomes readable, writable, or otherwise transitions into a new state.
The sleep example in Section 12.1 already demonstrates the wait-queue side of blocking I/O. Adding poll support to a driver is mostly a matter of exposing that same state transition to event-driven applications instead of forcing them to block in one system call at a time.
Another classic mechanism described in LDD3 is asynchronous notification via SIGIO. This is implemented with the fasync file operation and helpers such as fasync_helper() and kill_fasync(). When enabled from userspace with fcntl(F\_SETFL, O\_ASYNC), the process receives a signal when the device becomes ready.
This interface still exists in Linux 5.10 and later, but it is much less common than poll and epoll-based designs. Signals are process-directed, relatively coarse, and awkward in multithreaded programs. For new user interfaces, a well-behaved poll implementation is usually the better default. Still, fasync remains useful for compatibility with older applications or for small control-style devices that only need to notify userspace that some event happened.
Kernel code runs under a variety of constraints depending on where it executes. Some paths may sleep, some must return quickly, and some need careful synchronization to stay correct on modern SMP systems. This chapter collects the mechanisms that shape control flow, blocking behavior, deferred work, and debugging.
So far, the only thing we’ve done was to use well defined kernel mechanisms to register /proc files and device handlers. This is fine if you want to do something the kernel programmers thought you’d want, such as write a device driver. But what if you want to do something unusual, to change the behavior of the system in some way? Then, you are mostly on your own.
Notice that this example has been unavailable since Linux v6.9. Specifically, after this commit, the system call dispatch mechanism changed from using an indirect function call table to a switch statement for security issues, such as mitigating Branch History Injection (BHI) attacks. See more information here.
Should one choose not to use a virtual machine, kernel programming can become risky. For example, while writing the code below, the open() system call was inadvertently disrupted. This resulted in an inability to open any files, run programs, or shut down the system, necessitating a restart of the virtual machine. Fortunately, no critical files were lost in this instance. However, if such modifications were made on a live, mission-critical system, the consequences could be severe. To mitigate the risk of file loss, even in a test environment, it is advised to execute sync right before using insmod and rmmod.
Forget about /proc files, forget about device files. They are just minor details. Minutiae in the vast expanse of the universe. The real process to kernel communication mechanism, the one used by all processes, is system calls. When a process requests a service from the kernel (such as opening a file, forking to a new process, or requesting more memory), this is the mechanism used. If you want to change the behaviour of the kernel in interesting ways, this is the place to do it. By the way, if you want to see which system calls a program uses, run strace <arguments>.
In general, a process is not supposed to be able to access the kernel. It can not access kernel memory and it can’t call kernel functions. The hardware of the CPU enforces this (that is the reason why it is called “protected mode” or “page protection”).
System calls are an exception to this general rule. What happens is that the process fills the registers with the appropriate values and then calls a special instruction which jumps to a previously defined location in the kernel (of course, that location is readable by user processes, it is not writable by them). Under Intel CPUs, this is done by means of interrupt 0x80. The hardware knows that once you jump to this location, you are no longer running in restricted user mode, but as the operating system kernel — and therefore you’re allowed to do whatever you want.
The location in the kernel a process can jump to is called system_call. The procedure at that location checks the system call number, which tells the kernel what service the process requested. Then, it looks at the table of system calls (sys_call_table) to see the address of the kernel function to call. Then it calls the function, and after it returns, does a few system checks and then return back to the process (or to a different process, if the process time ran out). If you want to read this code, it is at the source file arch/$(architecture)/kernel/entry.S, after the line ENTRY(system_call).
So, if we want to change the way a certain system call works, what we need to do is to write our own function to implement it (usually by adding a bit of our own code, and then calling the original function) and then change the pointer at sys_call_table to point to our function. Because we might be removed later and we don’t want to leave the system in an unstable state, it’s important for cleanup_module to restore the table to its original state.
To modify the content of sys_call_table, we need to consider the control register. A control register is a processor register that changes or controls the general behavior of the CPU. For x86 architecture, the cr0 register has various control flags that modify the basic operation of the processor. The WP flag in cr0 stands for write protection. Once the WP flag is set, the processor disallows further write attempts to the read-only sections. Therefore, we must disable the WP flag before modifying sys_call_table. Since Linux v5.3, the write_cr0 function cannot be used because of the sensitive cr0 bits pinned by the security issue, the attacker may write into CPU control registers to disable CPU protections like write protection. As a result, we have to provide the custom assembly routine to bypass it.
However, sys_call_table symbol is unexported to prevent misuse. But there have few ways to get the symbol, manual symbol lookup and kallsyms_lookup_name. Here we use both depend on the kernel version.
Because of the control-flow integrity, which is a technique to prevent the redirect execution code from the attacker, for making sure that the indirect calls go to the expected addresses and the return addresses are not changed. Since Linux v5.7, the kernel patched the series of control-flow enforcement (CET) for x86, and some configurations of GCC, like GCC versions 9 and 10 in Ubuntu Linux, will add with CET (the -fcf-protection option) in the kernel by default. Using that GCC to compile the kernel with retpoline off may result in CET being enabled in the kernel. You can use the following command to check out the -fcf-protection option is enabled or not:
$ gcc -v -Q -O2 --help=target | grep protection Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper ... gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04) COLLECT_GCC_OPTIONS='-v' '-Q' '-O2' '--help=target' '-mtune=generic' '-march=x86-64' /usr/lib/gcc/x86_64-linux-gnu/9/cc1 -v ... -fcf-protection ... GNU C17 (Ubuntu 9.3.0-17ubuntu1~20.04) version 9.3.0 (x86_64-linux-gnu) ...
But CET should not be enabled in the kernel, it may break the Kprobes and bpf. Consequently, CET is disabled since v5.11. To guarantee the manual symbol lookup worked, we only use up to v5.4.
Unfortunately, since Linux v5.7 kallsyms_lookup_name is also unexported, it needs certain trick to get the address of kallsyms_lookup_name. If CONFIG_KPROBES is enabled, we can facilitate the retrieval of function addresses by means of Kprobes to dynamically break into the specific kernel routine. Kprobes inserts a breakpoint at the entry of function by replacing the first bytes of the probed instruction. When a CPU hits the breakpoint, registers are stored, and the control will pass to Kprobes. It passes the addresses of the saved registers and the Kprobe struct to the handler you defined, then executes it. Kprobes can be registered by symbol name or address. Within the symbol name, the address will be handled by the kernel.
Otherwise, specify the address of sys_call_table from /proc/kallsyms and /boot/System.map into sym parameter. Following is the sample usage for /proc/kallsyms:
$ sudo grep sys_call_table /proc/kallsyms ffffffff82000280 R x32_sys_call_table ffffffff820013a0 R sys_call_table ffffffff820023e0 R ia32_sys_call_table $ sudo insmod syscall-steal.ko sym=0xffffffff820013a0
Using the address from /boot/System.map, be careful about KASLR (Kernel Address Space Layout Randomization). KASLR may randomize the address of kernel code and data at every boot time, such as the static address listed in /boot/System.map will offset by some entropy. The purpose of KASLR is to protect the kernel space from the attacker. Without KASLR, the attacker may find the target address in the fixed address easily. Then the attacker can use return-oriented programming to insert some malicious codes to execute or receive the target data by a tampered pointer. KASLR mitigates these kinds of attacks because the attacker cannot immediately know the target address, but a brute-force attack can still work. If the address of a symbol in /proc/kallsyms is different from the address in /boot/System.map, KASLR is enabled with the kernel, on which your system is running.
$ grep GRUB_CMDLINE_LINUX_DEFAULT /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" $ sudo grep sys_call_table /boot/System.map-$(uname -r) ffffffff82000300 R sys_call_table $ sudo grep sys_call_table /proc/kallsyms ffffffff820013a0 R sys_call_table # Reboot $ sudo grep sys_call_table /boot/System.map-$(uname -r) ffffffff82000300 R sys_call_table $ sudo grep sys_call_table /proc/kallsyms ffffffff86400300 R sys_call_table
If KASLR is enabled, we have to take care of the address from /proc/kallsyms each time we reboot the machine. In order to use the address from /boot/System.map, make sure that KASLR is disabled. You can add the nokaslr for disabling KASLR in next booting time:
$ grep GRUB_CMDLINE_LINUX_DEFAULT /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" $ sudo perl -i -pe 'm/quiet/ and s//quiet nokaslr/' /etc/default/grub $ grep quiet /etc/default/grub GRUB_CMDLINE_LINUX_DEFAULT="quiet nokaslr splash" $ sudo update-grub
For more information, check out the following:
The source code here is an example of such a kernel module. We want to “spy” on a certain user, and to pr_info() a message whenever that user opens a file. Towards this end, we replace the system call to open a file with our own function, called our_sys_openat. This function checks the uid (user’s id) of the current process, and if it is equal to the uid we spy on, it calls pr_info() to display the name of the file to be opened. Then, either way, it calls the original openat() function with the same parameters, to actually open the file.
The init_module function replaces the appropriate location in sys_call_table and keeps the original pointer in a variable. The cleanup_module function uses that variable to restore everything back to normal. This approach is dangerous, because of the possibility of two kernel modules changing the same system call. Imagine we have two kernel modules, A and B. A’s openat system call will be A_openat and B’s will be B_openat. Now, when A is inserted into the kernel, the system call is replaced with A_openat, which will call the original sys_openat when it is done. Next, B is inserted into the kernel, which replaces the system call with B_openat, which will call what it thinks is the original system call, A_openat, when it’s done.
Now, if B is removed first, everything will be well — it will simply restore the system call to A_openat, which calls the original. However, if A is removed and then B is removed, the system will crash. A’s removal will restore the system call to the original, sys_openat, cutting B out of the loop. Then, when B is removed, it will restore the system call to what it thinks is the original, A_openat, which is no longer in memory. At first glance, it appears we could solve this particular problem by checking if the system call is equal to our open function and if so not changing it at all (so that B won’t change the system call when it is removed), but that will cause an even worse problem. When A is removed, it sees that the system call was changed to B_openat so that it is no longer pointing to A_openat, so it will not restore it to sys_openat before it is removed from memory. Unfortunately, B_openat will still try to call A_openat which is no longer there, so that even without removing B the system would crash.
For x86 architecture, the system call table cannot be used to invoke a system call after commit 1e3ad78 since v6.9. This commit has been backported to long term stable kernels, like v5.15.154+, v6.1.85+, v6.6.26+ and v6.8.5+, see this answer for more details. In this case, thanks to Kprobes, a hook can be used instead on the system call entry to intercept the system call.
Note that all the related problems make syscall stealing unfeasible for production use. In order to keep people from doing potentially harmful things sys_call_table is no longer exported. This means, if you want to do something more than a mere dry run of this example, you will have to patch your current kernel in order to have sys_call_table exported.
1/* 2 * syscall-steal.c 3 * 4 * System call "stealing" sample. 5 * 6 * Disables page protection at a processor level by changing the 16th bit 7 * in the cr0 register (could be Intel specific). 8 */ 9 10#include <linux/delay.h> 11#include <linux/kernel.h> 12#include <linux/module.h> 13#include <linux/moduleparam.h> /* which will have params */ 14#include <linux/unistd.h> /* The list of system calls */ 15#include <linux/cred.h> /* For current_uid() */ 16#include <linux/uidgid.h> /* For __kuid_val() */ 17#include <linux/version.h> 18 19/* For the current (process) structure, we need this to know who the 20 * current user is. 21 */ 22#include <linux/sched.h> 23#include <linux/uaccess.h> 24 25/* The way we access "sys_call_table" varies as kernel internal changes. 26 * - Prior to v5.4 : manual symbol lookup 27 * - v5.5 to v5.6 : use kallsyms_lookup_name() 28 * - v5.7+ : Kprobes or specific kernel module parameter 29 */ 30 31/* The in-kernel calls to the ksys_close() syscall were removed in Linux v5.11+. 32 */ 33#if (LINUX_VERSION_CODE >= KERNEL_VERSION(5, 7, 0)) 34 35#if defined(CONFIG_KPROBES) 36#define HAVE_KPROBES 1 37#if defined(CONFIG_X86_64) 38/* If you have tried to use the syscall table to intercept syscalls and it 39 * doesn't work, you can try to use Kprobes to intercept syscalls. 40 * Set USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL to 1 to register a pre-handler 41 * before the syscall. 42 */ 43#define USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL 0 44#endif 45#include <linux/kprobes.h> 46#else 47#define HAVE_PARAM 1 48#include <linux/kallsyms.h> /* For sprint_symbol */ 49/* The address of the sys_call_table, which can be obtained with looking up 50 * "/boot/System.map" or "/proc/kallsyms". When the kernel version is v5.7+, 51 * without CONFIG_KPROBES, you can input the parameter or the module will look 52 * up all the memory. 53 */ 54static unsigned long sym = 0; 55module_param(sym, ulong, 0644); 56#endif /* CONFIG_KPROBES */ 57 58#else 59 60#if LINUX_VERSION_CODE <= KERNEL_VERSION(5, 4, 0) 61#define HAVE_KSYS_CLOSE 1 62#include <linux/syscalls.h> /* For ksys_close() */ 63#else 64#include <linux/kallsyms.h> /* For kallsyms_lookup_name */ 65#endif 66 67#endif /* Version >= v5.7 */ 68 69/* UID we want to spy on - will be filled from the command line. */ 70static uid_t uid = -1; 71module_param(uid, int, 0644); 72 73#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL 74 75/* syscall_sym is the symbol name of the syscall to spy on. The default is 76 * "__x64_sys_openat", which can be changed by the module parameter. You can 77 * look up the symbol name of a syscall in /proc/kallsyms. 78 */ 79static char *syscall_sym = "__x64_sys_openat"; 80module_param(syscall_sym, charp, 0644); 81 82static int sys_call_kprobe_pre_handler(struct kprobe *p, struct pt_regs *regs) 83{ 84 if (__kuid_val(current_uid()) != uid) { 85 return 0; 86 } 87 88 pr_info("%s called by %d\n", syscall_sym, uid); 89 return 0; 90} 91 92static struct kprobe syscall_kprobe = { 93 .symbol_name = "__x64_sys_openat", 94 .pre_handler = sys_call_kprobe_pre_handler, 95}; 96 97#else 98 99static unsigned long **sys_call_table_stolen; 100 101/* A pointer to the original system call. We retain this instead of 102 * calling the original function (sys_openat), because another 103 * module might have replaced the system call before us. Note that this is not 104 * 100% safe, because if another module replaced sys_openat before us, 105 * then when we are inserted, we will call the function in that module - 106 * and it might be removed before we are. 107 * 108 * Another reason for this is that we can not get sys_openat. 109 * It is a static function, so it is not exported. 110 */ 111#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER 112static asmlinkage long (*original_call)(const struct pt_regs *); 113#else 114static asmlinkage long (*original_call)(int, const char __user *, int, umode_t); 115#endif 116 117/* Our replacement function for sys_openat (the function called when you 118 * call the open system call). To find the exact prototype, with 119 * the number and type of arguments, we find the original function first 120 * (it is at fs/open.c). 121 * 122 * In theory, this means that we are tied to the current version of the 123 * kernel. In practice, the system calls almost never change (it would 124 * wreak havoc and require programs to be recompiled, since the system 125 * calls are the interface between the kernel and the processes). 126 */ 127#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER 128static asmlinkage long our_sys_openat(const struct pt_regs *regs) 129#else 130static asmlinkage long our_sys_openat(int dfd, const char __user *filename, 131 int flags, umode_t mode) 132#endif 133{ 134 int i = 0; 135 char ch; 136 137 if (__kuid_val(current_uid()) != uid) 138 goto orig_call; 139 140 /* Report the file, if relevant */ 141 pr_info("Opened file by %d: ", uid); 142 do { 143#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER 144 get_user(ch, (char __user *)regs->si + i); 145#else 146 get_user(ch, (char __user *)filename + i); 147#endif 148 i++; 149 pr_info("%c", ch); 150 } while (ch != 0); 151 pr_info("\n"); 152 153orig_call: 154 /* Call the original sys_openat - otherwise, we lose the ability to 155 * open files. 156 */ 157#ifdef CONFIG_ARCH_HAS_SYSCALL_WRAPPER 158 return original_call(regs); 159#else 160 return original_call(dfd, filename, flags, mode); 161#endif 162} 163 164static unsigned long **acquire_sys_call_table(void) 165{ 166#ifdef HAVE_KSYS_CLOSE 167 unsigned long int offset = PAGE_OFFSET; 168 unsigned long **sct; 169 170 while (offset < ULLONG_MAX) { 171 sct = (unsigned long **)offset; 172 173 if (sct[__NR_close] == (unsigned long *)ksys_close) 174 return sct; 175 176 offset += sizeof(void *); 177 } 178 179 return NULL; 180#endif 181 182#ifdef HAVE_PARAM 183 const char sct_name[15] = "sys_call_table"; 184 char symbol[40] = { 0 }; 185 186 if (sym == 0) { 187 pr_alert("For Linux v5.7+, Kprobes is the preferable way to get " 188 "symbol.\n"); 189 pr_info("If Kprobes is absent, you have to specify the address of " 190 "sys_call_table symbol\n"); 191 pr_info("by /boot/System.map or /proc/kallsyms, which contains all the " 192 "symbol addresses, into sym parameter.\n"); 193 return NULL; 194 } 195 sprint_symbol(symbol, sym); 196 if (!strncmp(sct_name, symbol, sizeof(sct_name) - 1)) 197 return (unsigned long **)sym; 198 199 return NULL; 200#endif 201 202#ifdef HAVE_KPROBES 203 unsigned long (*kallsyms_lookup_name)(const char *name); 204 struct kprobe kp = { 205 .symbol_name = "kallsyms_lookup_name", 206 }; 207 208 if (register_kprobe(&kp) < 0) 209 return NULL; 210 kallsyms_lookup_name = (unsigned long (*)(const char *name))kp.addr; 211 unregister_kprobe(&kp); 212#endif 213 214 return (unsigned long **)kallsyms_lookup_name("sys_call_table"); 215} 216 217#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 3, 0) 218static inline void __write_cr0(unsigned long cr0) 219{ 220 asm volatile("mov %0,%%cr0" : "+r"(cr0) : : "memory"); 221} 222#else 223#define __write_cr0 write_cr0 224#endif 225 226static void enable_write_protection(void) 227{ 228 unsigned long cr0 = read_cr0(); 229 set_bit(16, &cr0); 230 __write_cr0(cr0); 231} 232 233static void disable_write_protection(void) 234{ 235 unsigned long cr0 = read_cr0(); 236 clear_bit(16, &cr0); 237 __write_cr0(cr0); 238} 239#endif 240 241static int __init syscall_steal_start(void) 242{ 243#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL 244 int err; 245 /* use symbol name from the module parameter */ 246 syscall_kprobe.symbol_name = syscall_sym; 247 err = register_kprobe(&syscall_kprobe); 248 if (err) { 249 pr_err("register_kprobe() on %s failed: %d\n", syscall_sym, err); 250 pr_err("Please check the symbol name from 'syscall_sym' parameter.\n"); 251 return err; 252 } 253#else 254 if (!(sys_call_table_stolen = acquire_sys_call_table())) 255 return -1; 256 257 disable_write_protection(); 258 259 /* keep track of the original open function */ 260 original_call = (void *)sys_call_table_stolen[__NR_openat]; 261 262 /* use our openat function instead */ 263 sys_call_table_stolen[__NR_openat] = (unsigned long *)our_sys_openat; 264 265 enable_write_protection(); 266#endif 267 268 pr_info("Spying on UID:%d\n", uid); 269 return 0; 270} 271 272static void __exit syscall_steal_end(void) 273{ 274#if USE_KPROBES_PRE_HANDLER_BEFORE_SYSCALL 275 unregister_kprobe(&syscall_kprobe); 276#else 277 if (!sys_call_table_stolen) 278 return; 279 280 /* Return the system call back to normal */ 281 if (sys_call_table_stolen[__NR_openat] != (unsigned long *)our_sys_openat) { 282 pr_alert("Somebody else also played with the "); 283 pr_alert("open system call\n"); 284 pr_alert("The system may be left in "); 285 pr_alert("an unstable state.\n"); 286 } 287 288 disable_write_protection(); 289 sys_call_table_stolen[__NR_openat] = (unsigned long *)original_call; 290 enable_write_protection(); 291#endif 292 293 msleep(2000); 294} 295 296module_init(syscall_steal_start); 297module_exit(syscall_steal_end); 298 299MODULE_LICENSE("GPL");
What do you do when somebody asks you for something you can not do right away? If you are a human being and you are bothered by a human being, the only thing you can say is: "Not right now, I’m busy. Go away!". But if you are a kernel module and you are bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that is the way multiple processes appear to run on the same time on a single CPU).
This kernel module is an example of this. The file (called /proc/sleep) can only be opened by a single process at a time. If the file is already open, the kernel module calls wait_event_interruptible. The easiest way to keep a file open is to open it with:
1 tail -f
This function changes the status of the task (a task is the kernel data structure which holds information about a process and the system call it is in, if any) to TASK_INTERRUPTIBLE, which means that the task will not run until it is woken up somehow, and adds it to WaitQ, the queue of tasks waiting to access the file. Then, the function calls the scheduler to context switch to a different process, one which has some use for the CPU.
When a process is done with the file, it closes it, and module_close is called. That function wakes up all the processes in the queue (there’s no mechanism to only wake up one of them). It then returns and the process which just closed the file can continue to run. In time, the scheduler decides that that process has had enough and gives control of the CPU to another process. Eventually, one of the processes which was in the queue will be given control of the CPU by the scheduler. It starts at the point right after the call to wait_event_interruptible.
This means that the process is still in kernel mode - as far as the process is concerned, it issued the open system call and the system call has not returned yet. The process does not know somebody else used the CPU for most of the time between the moment it issued the call and the moment it returned.
It can then proceed to set a global variable to tell all the other processes that the file is still open and go on with its life. When the other processes get a piece of the CPU, they’ll see that global variable and go back to sleep.
So we will use tail -f to keep the file open in the background, and attempt to access it with another background process. This way, we don’t need to switch to another terminal window or virtual terminal to run the second process. As soon as the first background process is killed with kill %1 , the second is woken up, is able to access the file and finally terminates.
To make our life more interesting, module_close does not have a monopoly on waking up the processes which wait to access the file. A signal, such as Ctrl +c (SIGINT) can also wake up a process. This is because we used wait_event_interruptible. We could have used wait_event instead, but that would have resulted in extremely angry users whose Ctrl+c’s are ignored.
In that case, we want to return with -EINTR immediately. This is important so users can, for example, kill the process before it receives the file.
There is one more point to remember. Some times processes don’t want to sleep, they want either to get what they want immediately, or to be told it cannot be done. Such processes use the O_NONBLOCK flag when opening the file. The kernel is supposed to respond by returning with the error code -EAGAIN from operations which would otherwise block, such as opening the file in this example. The program cat_nonblock, available in the examples/other directory, can be used to open a file with O_NONBLOCK.
$ sudo insmod sleep.ko $ cat_nonblock /proc/sleep Last input: $ tail -f /proc/sleep & Last input: Last input: Last input: Last input: Last input: Last input: Last input: tail: /proc/sleep: file truncated [1] 6540 $ cat_nonblock /proc/sleep Open would block $ kill %1 [1]+ Terminated tail -f /proc/sleep $ cat_nonblock /proc/sleep Last input: $
1/* 2 * sleep.c - create a /proc file, and if several processes try to open it 3 * at the same time, put all but one to sleep. 4 */ 5 6#include <linux/atomic.h> 7#include <linux/fs.h> 8#include <linux/kernel.h> /* for sprintf() */ 9#include <linux/module.h> /* Specifically, a module */ 10#include <linux/printk.h> 11#include <linux/proc_fs.h> /* Necessary because we use proc fs */ 12#include <linux/types.h> 13#include <linux/uaccess.h> /* for get_user and put_user */ 14#include <linux/version.h> 15#include <linux/wait.h> /* For putting processes to sleep and 16 waking them up */ 17 18#include <asm/current.h> 19#include <asm/errno.h> 20 21#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0) 22#define HAVE_PROC_OPS 23#endif 24 25/* Here we keep the last message received, to prove that we can process our 26 * input. 27 */ 28#define MESSAGE_LENGTH 80 29static char message[MESSAGE_LENGTH]; 30 31static struct proc_dir_entry *our_proc_file; 32#define PROC_ENTRY_FILENAME "sleep" 33 34/* Since we use the file operations struct, we can't use the special proc 35 * output provisions - we have to use a standard read function, which is this 36 * function. 37 */ 38static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ 39 char __user *buf, /* The buffer to put data to 40 (in the user segment) */ 41 size_t len, /* The length of the buffer */ 42 loff_t *offset) 43{ 44 static int finished = 0; 45 int i; 46 char output_msg[MESSAGE_LENGTH + 30]; 47 48 /* Return 0 to signify end of file - that we have nothing more to say 49 * at this point. 50 */ 51 if (finished) { 52 finished = 0; 53 return 0; 54 } 55 56 sprintf(output_msg, "Last input:%s\n", message); 57 for (i = 0; i < len && output_msg[i]; i++) 58 put_user(output_msg[i], buf + i); 59 60 finished = 1; 61 return i; /* Return the number of bytes "read" */ 62} 63 64/* This function receives input from the user when the user writes to the 65 * /proc file. 66 */ 67static ssize_t module_input(struct file *file, /* The file itself */ 68 const char __user *buf, /* The buffer with input */ 69 size_t length, /* The buffer's length */ 70 loff_t *offset) /* offset to file - ignore */ 71{ 72 int i; 73 74 /* Put the input into message, where module_output will later be able 75 * to use it. 76 */ 77 for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) 78 get_user(message[i], buf + i); 79 /* we want a standard, zero terminated string */ 80 message[i] = '\0'; 81 82 /* We need to return the number of input characters used */ 83 return i; 84} 85 86/* 1 if the file is currently open by somebody */ 87static atomic_t already_open = ATOMIC_INIT(0); 88 89/* Queue of processes who want our file */ 90static DECLARE_WAIT_QUEUE_HEAD(waitq); 91 92/* Called when the /proc file is opened */ 93static int module_open(struct inode *inode, struct file *file) 94{ 95 /* Try to get without blocking */ 96 if (!atomic_cmpxchg(&already_open, 0, 1)) { 97 /* Success without blocking, allow the access */ 98 return 0; 99 } 100 /* If the file's flags include O_NONBLOCK, it means the process does not 101 * want to wait for the file. In this case, because the file is already open, 102 * we should fail with -EAGAIN, meaning "you will have to try again", 103 * instead of blocking a process which would rather stay awake. 104 */ 105 if (file->f_flags & O_NONBLOCK) 106 return -EAGAIN; 107 108 while (atomic_cmpxchg(&already_open, 0, 1)) { 109 int i, is_sig = 0; 110 111 /* This function puts the current process, including any system 112 * calls, such as us, to sleep. Execution will be resumed right 113 * after the function call, either because somebody called 114 * wake_up(&waitq) (only module_close does that, when the file 115 * is closed) or when a signal, such as Ctrl-C, is sent 116 * to the process 117 */ 118 wait_event_interruptible(waitq, !atomic_read(&already_open)); 119 120 /* If we woke up because we got a signal we're not blocking, 121 * return -EINTR (fail the system call). This allows processes 122 * to be killed or stopped. 123 */ 124 for (i = 0; i < _NSIG_WORDS && !is_sig; i++) 125 is_sig = current->pending.signal.sig[i] & ~current->blocked.sig[i]; 126 127 if (is_sig) { 128 /* Return -EINTR if we got a signal */ 129 return -EINTR; 130 } 131 } 132 133 return 0; /* Allow the access */ 134} 135 136/* Called when the /proc file is closed */ 137static int module_close(struct inode *inode, struct file *file) 138{ 139 /* Set already_open to zero, so one of the processes in the waitq will 140 * be able to set already_open back to one and to open the file. All 141 * the other processes will be called when already_open is back to one, 142 * so they'll go back to sleep. 143 */ 144 atomic_set(&already_open, 0); 145 146 /* Wake up all the processes in waitq, so if anybody is waiting for the 147 * file, they can have it. 148 */ 149 wake_up(&waitq); 150 151 return 0; /* success */ 152} 153 154/* Structures to register as the /proc file, with pointers to all the relevant 155 * functions. 156 */ 157 158/* File operations for our /proc file. This is where we place pointers to all 159 * the functions called when somebody tries to do something to our file. NULL 160 * means we don't want to deal with something. 161 */ 162#ifdef HAVE_PROC_OPS 163static const struct proc_ops file_ops_4_our_proc_file = { 164 .proc_read = module_output, /* "read" from the file */ 165 .proc_write = module_input, /* "write" to the file */ 166 .proc_open = module_open, /* called when the /proc file is opened */ 167 .proc_release = module_close, /* called when it's closed */ 168 .proc_lseek = noop_llseek, /* return file->f_pos */ 169}; 170#else 171static const struct file_operations file_ops_4_our_proc_file = { 172 .read = module_output, 173 .write = module_input, 174 .open = module_open, 175 .release = module_close, 176 .llseek = noop_llseek, 177}; 178#endif 179 180/* Initialize the module - register the /proc file */ 181static int __init sleep_init(void) 182{ 183 our_proc_file = 184 proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &file_ops_4_our_proc_file); 185 if (our_proc_file == NULL) { 186 pr_debug("Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME); 187 return -ENOMEM; 188 } 189 proc_set_size(our_proc_file, 80); 190 proc_set_user(our_proc_file, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID); 191 192 pr_info("/proc/%s created\n", PROC_ENTRY_FILENAME); 193 194 return 0; 195} 196 197/* Cleanup - unregister our file from /proc. This could get dangerous if 198 * there are still processes waiting in waitq, because they are inside our 199 * open function, which will get unloaded. I'll explain how to avoid removal 200 * of a kernel module in such a case in chapter 10. 201 */ 202static void __exit sleep_exit(void) 203{ 204 remove_proc_entry(PROC_ENTRY_FILENAME, NULL); 205 pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME); 206} 207 208module_init(sleep_init); 209module_exit(sleep_exit); 210 211MODULE_LICENSE("GPL");
1/* 2 * cat_nonblock.c - open a file and display its contents, but exit rather than 3 * wait for input. 4 */ 5#include <errno.h> /* for errno */ 6#include <fcntl.h> /* for open */ 7#include <stdio.h> /* standard I/O */ 8#include <stdlib.h> /* for exit */ 9#include <unistd.h> /* for read */ 10 11#define MAX_BYTES 1024 * 4 12 13int main(int argc, char *argv[]) 14{ 15 int fd; /* The file descriptor for the file to read */ 16 size_t bytes; /* The number of bytes read */ 17 char buffer[MAX_BYTES]; /* The buffer for the bytes */ 18 19 /* Usage */ 20 if (argc != 2) { 21 printf("Usage: %s <filename>\n", argv[0]); 22 puts("Reads the content of a file, but doesn't wait for input"); 23 exit(EXIT_FAILURE); 24 } 25 26 /* Open the file for reading in non blocking mode */ 27 fd = open(argv[1], O_RDONLY | O_NONBLOCK); 28 29 /* If open failed */ 30 if (fd == -1) { 31 puts(errno == EAGAIN ? "Open would block" : "Open failed"); 32 exit(EXIT_FAILURE); 33 } 34 35 /* Read the file and output its contents */ 36 do { 37 /* Read characters from the file */ 38 bytes = read(fd, buffer, MAX_BYTES); 39 40 /* If there's an error, report it and die */ 41 if (bytes == -1) { 42 if (errno == EAGAIN) 43 puts("Normally I'd block, but you told me not to"); 44 else 45 puts("Another read error"); 46 exit(EXIT_FAILURE); 47 } 48 49 /* Print the characters */ 50 if (bytes > 0) { 51 for (int i = 0; i < bytes; i++) 52 putchar(buffer[i]); 53 } 54 55 /* While there are no errors and the file isn't over */ 56 } while (bytes > 0); 57 58 close(fd); 59 return 0; 60}
Sometimes one thing should happen before another within a module having multiple threads. Rather than using /bin/sleep commands, the kernel has another way to do this which allows timeouts or interrupts to also happen.
Completions as code synchronization mechanism have three main parts, initialization of struct completion synchronization object, the waiting or barrier part through wait_for_completion(), and the signalling side through a call to complete().
In the subsequent example, two threads are initiated: crank and flywheel. It is imperative that the crank thread starts before the flywheel thread. A completion state is established for each of these threads, with a distinct completion defined for both the crank and flywheel threads. At the exit point of each thread the respective completion state is updated, and wait_for_completion is used by the flywheel thread to ensure that it does not begin prematurely. The crank thread uses the complete_all() function to update the completion, which lets the flywheel thread continue.
So even though flywheel_thread is started first you should notice when you load this module and run dmesg, that turning the crank always happens first because the flywheel thread waits for the crank thread to complete.
There are other variations of the wait_for_completion function, which include timeouts or being interrupted, but this basic mechanism is enough for many common situations without adding a lot of complexity.
1/* 2 * completions.c 3 */ 4#include <linux/completion.h> 5#include <linux/err.h> /* for IS_ERR() */ 6#include <linux/init.h> 7#include <linux/kthread.h> 8#include <linux/module.h> 9#include <linux/printk.h> 10#include <linux/version.h> 11 12static struct completion crank_comp; 13static struct completion flywheel_comp; 14 15static int machine_crank_thread(void *arg) 16{ 17 pr_info("Turn the crank\n"); 18 19 complete_all(&crank_comp); 20#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0) 21 kthread_complete_and_exit(&crank_comp, 0); 22#else 23 complete_and_exit(&crank_comp, 0); 24#endif 25} 26 27static int machine_flywheel_spinup_thread(void *arg) 28{ 29 wait_for_completion(&crank_comp); 30 31 pr_info("Flywheel spins up\n"); 32 33 complete_all(&flywheel_comp); 34#if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 17, 0) 35 kthread_complete_and_exit(&flywheel_comp, 0); 36#else 37 complete_and_exit(&flywheel_comp, 0); 38#endif 39} 40 41static int __init completions_init(void) 42{ 43 struct task_struct *crank_thread; 44 struct task_struct *flywheel_thread; 45 46 pr_info("completions example\n"); 47 48 init_completion(&crank_comp); 49 init_completion(&flywheel_comp); 50 51 crank_thread = kthread_create(machine_crank_thread, NULL, "KThread Crank"); 52 if (IS_ERR(crank_thread)) 53 goto ERROR_THREAD_1; 54 55 flywheel_thread = kthread_create(machine_flywheel_spinup_thread, NULL, 56 "KThread Flywheel"); 57 if (IS_ERR(flywheel_thread)) 58 goto ERROR_THREAD_2; 59 60 wake_up_process(flywheel_thread); 61 wake_up_process(crank_thread); 62 63 return 0; 64 65ERROR_THREAD_2: 66 kthread_stop(crank_thread); 67ERROR_THREAD_1: 68 69 return -1; 70} 71 72static void __exit completions_exit(void) 73{ 74 wait_for_completion(&crank_comp); 75 wait_for_completion(&flywheel_comp); 76 77 pr_info("completions exit\n"); 78} 79 80module_init(completions_init); 81module_exit(completions_exit); 82 83MODULE_DESCRIPTION("Completions example"); 84MODULE_LICENSE("GPL");
If processes running on different CPUs or in different threads try to access the same memory, then it is possible that strange things can happen or your system can lock up. To avoid this, various types of mutual exclusion kernel functions are available. These indicate if a section of code is "locked" or "unlocked" so that simultaneous attempts to run it can not happen.
You can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland. This may be all that is needed to avoid collisions in most cases.
Mutexes in the Linux kernel enforce strict ownership: only the task that successfully acquired the mutex can release (or unlock) it. Attempting to release a mutex held by another task or releasing an unheld mutex multiple times by the same task typically leads to errors or undefined behavior. If a task tries to lock a mutex it already holds, it may be blocked or sleep, where the task waits for itself to release the lock.
Before use, a mutex must be initialized through specific APIs (such as mutex_init or by using the DEFINE_MUTEX macro for compile-time initialization). And it is prohibited to directly modify the internal structure of a mutex using a memory manipulation function like memset.
1/* 2 * example_mutex.c 3 */ 4#include <linux/module.h> 5#include <linux/mutex.h> 6#include <linux/printk.h> 7 8static DEFINE_MUTEX(mymutex); 9 10static int __init example_mutex_init(void) 11{ 12 int ret; 13 14 pr_info("example_mutex init\n"); 15 16 ret = mutex_trylock(&mymutex); 17 if (ret != 0) { 18 pr_info("mutex is locked\n"); 19 20 if (mutex_is_locked(&mymutex) == 0) 21 pr_info("The mutex failed to lock!\n"); 22 23 mutex_unlock(&mymutex); 24 pr_info("mutex is unlocked\n"); 25 } else 26 pr_info("Failed to lock\n"); 27 28 return 0; 29} 30 31static void __exit example_mutex_exit(void) 32{ 33 pr_info("example_mutex exit\n"); 34} 35 36module_init(example_mutex_init); 37module_exit(example_mutex_exit); 38 39MODULE_DESCRIPTION("Mutex example"); 40MODULE_LICENSE("GPL");
The various suffixes appended to mutex functions in the Linux kernel primarily dictate how a task waiting to acquire a lock will behave, particularly concerning its interruptibility.
When a task calls mutex_lock(), and if the mutex is currently unavailable, the task enters a sleep state until it can successfully obtain the lock. During this period, the task cannot be interrupted. In contrast, functions with the _interruptible suffix, such as mutex_lock_interruptible(), behave similarly to mutex_lock() but allow the waiting process to be interrupted by signals. If a task receives a signal (like a termination signal) while waiting for the lock, it will exit the waiting state and return an error code (-EINTR). This is useful for applications that need to handle external events even while waiting for a lock.
Beyond these fundamental locking behaviors, other mutex functions offer specialized capabilities. Functions like mutex_lock_nested and mutex_lock_interruptible_nested() incorporate the __nested() functionality, providing support for nested locking. This prior locking mechanism aids in managing lock acquisition and preventing deadlocks, often employing a subclass parameter for more precise deadlock detection. The latter variant combines nested locking with the ability for the waiting process to be interrupted by signals. Another function is mutex_trylock(), which attempts to acquire the mutex without blocking. It returns 1 if the lock is successfully acquired and 0 if the mutex is already held by another task.
Despite the fact that mutex_trylock does not sleep, it is still generally not safe for use in interrupt context because its implementation isn’t atomic. If an interrupt occurs between checking the lock’s availability and its acquisition, this can lead to race conditions and potential data corruption.
As the name suggests, spinlocks lock up the CPU that the code is running on, taking 100% of its resources. Because of this you should only use the spinlock mechanism around code which is likely to take no more than a few milliseconds to run and so will not noticeably slow anything down from the user’s point of view.
The example here is "irq safe" in that if interrupts happen during the lock then they will not be forgotten and will activate when the unlock happens, using the flags variable to retain their state.
1/* 2 * example_spinlock.c 3 */ 4#include <linux/init.h> 5#include <linux/module.h> 6#include <linux/printk.h> 7#include <linux/spinlock.h> 8 9static DEFINE_SPINLOCK(sl_static); 10static spinlock_t sl_dynamic; 11 12static void example_spinlock_static(void) 13{ 14 unsigned long flags; 15 16 spin_lock_irqsave(&sl_static, flags); 17 pr_info("Locked static spinlock\n"); 18 19 /* Do something or other safely. Because this uses 100% CPU time, this 20 * code should take no more than a few milliseconds to run. 21 */ 22 23 spin_unlock_irqrestore(&sl_static, flags); 24 pr_info("Unlocked static spinlock\n"); 25} 26 27static void example_spinlock_dynamic(void) 28{ 29 unsigned long flags; 30 31 spin_lock_init(&sl_dynamic); 32 spin_lock_irqsave(&sl_dynamic, flags); 33 pr_info("Locked dynamic spinlock\n"); 34 35 /* Do something or other safely. Because this uses 100% CPU time, this 36 * code should take no more than a few milliseconds to run. 37 */ 38 39 spin_unlock_irqrestore(&sl_dynamic, flags); 40 pr_info("Unlocked dynamic spinlock\n"); 41} 42 43static int __init example_spinlock_init(void) 44{ 45 pr_info("example spinlock started\n"); 46 47 example_spinlock_static(); 48 example_spinlock_dynamic(); 49 50 return 0; 51} 52 53static void __exit example_spinlock_exit(void) 54{ 55 pr_info("example spinlock exit\n"); 56} 57 58module_init(example_spinlock_init); 59module_exit(example_spinlock_exit); 60 61MODULE_DESCRIPTION("Spinlock example"); 62MODULE_LICENSE("GPL");
Taking 100% of a CPU’s resources comes with greater responsibility. Situations where the kernel code monopolizes a CPU are called atomic contexts. Holding a spinlock is one of those situations. Sleeping in atomic contexts may leave the system hanging, as the occupied CPU devotes 100% of its resources doing nothing but sleeping. In some worse cases the system may crash. Thus, sleeping in atomic contexts is considered a bug in the kernel. They are sometimes called “sleep-in-atomic-context” in some materials.
Note that sleeping here is not limited to calling the sleep functions explicitly. If subsequent function calls eventually invoke a function that sleeps, it is also considered sleeping. Thus, it is important to pay attention to functions being used in atomic context. There’s no documentation recording all such functions, but code comments may help. Sometimes you may find comments in kernel source code stating that a function “may sleep”, “might sleep”, or more explicitly “the caller should not hold a spinlock”. Those comments are hints that a function may implicitly sleep and must not be called in atomic contexts.
Now, let’s differentiate between a few types of spinlock functions in the Linux kernel: spin_lock(), spin_lock_irq(), spin_lock_irqsave(), and spin_lock_bh().
spin_lock() does not allow the CPU to sleep while waiting for the lock, which makes it suitable for most use cases where the critical section is short. However, this is problematic for real-time Linux because spinlocks in this configuration behave as sleeping locks. This can prevent other tasks from running and cause the system to become unresponsive. To address this in real-time Linux environments, a raw_spin_lock() is used, which behaves similarly to a spin_lock() but without causing the system to sleep.
On non-PREEMPT_RT kernels, spin_lock_irq() disables local hard interrupts before acquiring the lock, and spin_unlock_irq() unconditionally re-enables them when the lock is released. Because this pair does not save the previous interrupt state, use it only when you know hard interrupts are enabled on entry and it is correct to re-enable them on exit. In contrast, spin_lock_irqsave() disables local hard interrupts and stores the previous state in an opaque unsigned long flags variable. The matching spin_unlock_irqrestore() restores that saved state, so it is safe regardless of whether hard interrupts were enabled or disabled before entering the critical section. This makes spin_lock_irqsave() the preferred interface when a function may be called from both process context and hardirq context, or from any path where the caller’s interrupt state is unknown. On PREEMPT_RT kernels, spinlock_t becomes an RT-mutex-based sleeping lock, so the _irq and _irqsave suffixes do not actually disable hardware interrupts. If you genuinely need hard interrupts disabled, use the raw_spin_lock_irqsave() family (see raw_spin_lock() above), but note that raw spinlocks really spin, disable preemption, and must not be held across any potentially sleeping operation.
Next, spin_lock_bh() disables softirqs (software interrupts) but allows hardware interrupts to continue. Unlike spin_lock_irq() and spin_lock_irqsave(), which disable both hardware and software interrupts, spin_lock_bh() is useful when hardware interrupts need to remain active.
A common deadlock scenario illustrates why the right variant matters. Suppose process-context code acquires a spinlock with plain spin_lock(), then a hardware interrupt fires on the same CPU. The interrupt handler tries to acquire the same lock and spins forever, because the CPU that holds the lock is the same CPU that needs to release it, but it is stuck in the interrupt handler. The solution: use spin_lock_irqsave() in the process-context path so that local interrupts are disabled while the lock is held. A hardirq top-half handler can normally use plain spin_lock() for that lock because local interrupts are already disabled on entry. Threaded IRQ handlers (registered with request_threaded_irq()) run in process context and follow process-context locking rules instead. The quick reference:
| Data shared between … | Recommended primitive |
| Process context only | spin_lock() / mutex_lock() |
| Process and softirq/tasklet | spin_lock_bh() |
| Process and hardirq | spin_lock_irqsave() |
| Hardirq and softirq | spin_lock_irqsave() (in softirq) |
For more information about spinlock usage and lock types, see the following resources:
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something. Like the earlier spinlocks example, the one below shows an "irq safe" situation in which if other functions were triggered from irqs which might also read and write to whatever you are concerned with then they would not disrupt the logic. As before it is a good idea to keep anything done within the lock as short as possible so that it does not hang up the system and cause users to start revolting against the tyranny of your module.
1/* 2 * example_rwlock.c 3 */ 4#include <linux/module.h> 5#include <linux/printk.h> 6#include <linux/rwlock.h> 7 8static DEFINE_RWLOCK(myrwlock); 9 10static void example_read_lock(void) 11{ 12 unsigned long flags; 13 14 read_lock_irqsave(&myrwlock, flags); 15 pr_info("Read Locked\n"); 16 17 /* Read from something */ 18 19 read_unlock_irqrestore(&myrwlock, flags); 20 pr_info("Read Unlocked\n"); 21} 22 23static void example_write_lock(void) 24{ 25 unsigned long flags; 26 27 write_lock_irqsave(&myrwlock, flags); 28 pr_info("Write Locked\n"); 29 30 /* Write to something */ 31 32 write_unlock_irqrestore(&myrwlock, flags); 33 pr_info("Write Unlocked\n"); 34} 35 36static int __init example_rwlock_init(void) 37{ 38 pr_info("example_rwlock started\n"); 39 40 example_read_lock(); 41 example_write_lock(); 42 43 return 0; 44} 45 46static void __exit example_rwlock_exit(void) 47{ 48 pr_info("example_rwlock exit\n"); 49} 50 51module_init(example_rwlock_init); 52module_exit(example_rwlock_exit); 53 54MODULE_DESCRIPTION("Read/Write locks example"); 55MODULE_LICENSE("GPL");
Of course, if you know for sure that there are no functions triggered by irqs which could possibly interfere with your logic then you can use the simpler read_lock(&myrwlock) and read_unlock(&myrwlock) or the corresponding write functions.
If you are doing simple arithmetic: adding, subtracting or bitwise operations, then there is another way in the multi-CPU and multi-hyperthreaded world to stop other parts of the system from messing with your mojo. By using atomic operations you can be confident that your addition, subtraction or bit flip did actually happen and was not overwritten by some other shenanigans. An example is shown below.
1/* 2 * example_atomic.c 3 */ 4#include <linux/atomic.h> 5#include <linux/bitops.h> 6#include <linux/module.h> 7#include <linux/printk.h> 8 9#define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" 10#define BYTE_TO_BINARY(byte) \ 11 ((byte & 0x80) ? '1' : '0'), ((byte & 0x40) ? '1' : '0'), \ 12 ((byte & 0x20) ? '1' : '0'), ((byte & 0x10) ? '1' : '0'), \ 13 ((byte & 0x08) ? '1' : '0'), ((byte & 0x04) ? '1' : '0'), \ 14 ((byte & 0x02) ? '1' : '0'), ((byte & 0x01) ? '1' : '0') 15 16static void atomic_add_subtract(void) 17{ 18 atomic_t debbie; 19 atomic_t chris = ATOMIC_INIT(50); 20 21 atomic_set(&debbie, 45); 22 23 /* subtract one */ 24 atomic_dec(&debbie); 25 26 atomic_add(7, &debbie); 27 28 /* add one */ 29 atomic_inc(&debbie); 30 31 pr_info("chris: %d, debbie: %d\n", atomic_read(&chris), 32 atomic_read(&debbie)); 33} 34 35static void atomic_bitwise(void) 36{ 37 unsigned long word = 0; 38 39 pr_info("Bits 0: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 40 set_bit(3, &word); 41 set_bit(5, &word); 42 pr_info("Bits 1: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 43 clear_bit(5, &word); 44 pr_info("Bits 2: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 45 change_bit(3, &word); 46 47 pr_info("Bits 3: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 48 if (test_and_set_bit(3, &word)) 49 pr_info("wrong\n"); 50 pr_info("Bits 4: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); 51 52 word = 255; 53 pr_info("Bits 5: " BYTE_TO_BINARY_PATTERN "\n", BYTE_TO_BINARY(word)); 54} 55 56static int __init example_atomic_init(void) 57{ 58 pr_info("example_atomic started\n"); 59 60 atomic_add_subtract(); 61 atomic_bitwise(); 62 63 return 0; 64} 65 66static void __exit example_atomic_exit(void) 67{ 68 pr_info("example_atomic exit\n"); 69} 70 71module_init(example_atomic_init); 72module_exit(example_atomic_exit); 73 74MODULE_DESCRIPTION("Atomic operations example"); 75MODULE_LICENSE("GPL");
Before the C11 standard adopted the built-in atomic types, the kernel already provided a small set of atomic types by using a bunch of tricky architecture-specific codes. Implementing the atomic types by C11 atomics may allow the kernel to throw away the architecture-specific codes and make the kernel code be more friendly to the people who understand the standard. But there are some problems, such as the memory model of the kernel doesn’t match the model formed by the C11 atomics. For further details, see:
Read-Copy-Update (RCU) is a synchronization mechanism that allows extremely fast, lock-free reads while still permitting concurrent updates. It is highly optimized for read-mostly scenarios.
Unlike spinlocks or mutexes, RCU readers do not acquire any locks or write to shared memory. This completely avoids cache-line bouncing and results in near-zero overhead for the read path. The tradeoff is that the updaters bear the cost of synchronization. When modifying a data structure, an updater creates a copy, modifies it, and then publishes the new version by replacing the old pointer in a single atomic operation.
Because concurrent readers might still be accessing the old data, the updater cannot free it immediately. Instead, it must wait for a "grace period" to elapse—a duration long enough to ensure that all pre-existing readers have left their critical sections. Only then can the old memory be safely reclaimed.
The RCU API relies on a few fundamental primitives:
Keep in mind that RCU only protects the readers. Concurrent writers must still serialize among themselves using a standard lock, such as a spinlock or a mutex. For more comprehensive details, you can refer to the official Linux kernel documentation on RCU: https://docs.kernel.org/RCU/whatisRCU.html.
The following example demonstrates a basic RCU implementation where a reader safely accesses shared data while a writer updates it.
1#include <linux/module.h> 2#include <linux/rcupdate.h> 3#include <linux/slab.h> 4#include <linux/spinlock.h> 5#include <linux/kthread.h> 6#include <linux/delay.h> 7 8struct my_data { 9 int value; 10}; 11 12static struct my_data __rcu *shared_data; 13static DEFINE_SPINLOCK(data_lock); 14static struct task_struct *reader_thread; 15 16static int reader_thread_fn(void *data) 17{ 18 while (!kthread_should_stop()) { 19 struct my_data *p; 20 int val; 21 bool valid = false; 22 23 rcu_read_lock(); 24 p = rcu_dereference(shared_data); 25 if (p) { 26 val = p->value; 27 valid = true; 28 } 29 rcu_read_unlock(); 30 31 if (valid) 32 pr_info("RCU Reader: value = %d\n", val); 33 else 34 pr_info("RCU Reader: data is NULL\n"); 35 36 msleep(500); 37 } 38 return 0; 39} 40 41static void update_data(int new_value) 42{ 43 struct my_data *new_p, *old_p; 44 45 new_p = kmalloc(sizeof(*new_p), GFP_KERNEL); 46 if (!new_p) 47 return; 48 new_p->value = new_value; 49 50 spin_lock(&data_lock); 51 52 old_p = rcu_dereference_protected(shared_data, lockdep_is_held(&data_lock)); 53 rcu_assign_pointer(shared_data, new_p); 54 55 spin_unlock(&data_lock); 56 57 if (old_p) { 58 synchronize_rcu(); 59 kfree(old_p); 60 pr_info("RCU Updater: old memory freed\n"); 61 } 62} 63 64static int __init example_rcu_init(void) 65{ 66 pr_info("Loading RCU example module\n"); 67 68 update_data(42); 69 70 reader_thread = kthread_run(reader_thread_fn, NULL, "rcu_reader"); 71 if (IS_ERR(reader_thread)) 72 return PTR_ERR(reader_thread); 73 74 msleep(1000); 75 update_data(100); 76 msleep(1000); 77 78 return 0; 79} 80 81static void __exit example_rcu_exit(void) 82{ 83 struct my_data *old_p; 84 85 pr_info("Unloading RCU example module\n"); 86 87 kthread_stop(reader_thread); 88 89 spin_lock(&data_lock); 90 old_p = rcu_dereference_protected(shared_data, lockdep_is_held(&data_lock)); 91 RCU_INIT_POINTER(shared_data, NULL); 92 spin_unlock(&data_lock); 93 94 if (old_p) { 95 synchronize_rcu(); 96 kfree(old_p); 97 } 98} 99 100module_init(example_rcu_init); 101module_exit(example_rcu_exit); 102 103MODULE_LICENSE("GPL"); 104MODULE_AUTHOR("Kuan-Wei Chiu <[email protected]>"); 105MODULE_DESCRIPTION("RCU Example Module");
In Section 1.7, it was noted that the X Window System and kernel module programming are not conducive to integration. This remains valid during the development of kernel modules. However, in practical scenarios, the necessity emerges to relay messages to the tty (teletype) originating the module load command.
The term “tty” originates from teletype, which initially referred to a combined keyboard-printer for Unix system communication. Today, it signifies a text stream abstraction employed by Unix programs, encompassing physical terminals, xterms in X displays, and network connections like SSH.
To achieve this, the “current” pointer is leveraged to access the active task’s tty structure. Within this structure lies a pointer to a string write function, facilitating the string’s transmission to the tty.
1/* 2 * print_string.c - Send output to the tty we're running on, regardless if 3 * it is through X11, telnet, etc. We do this by printing the string to the 4 * tty associated with the current task. 5 */ 6#include <linux/init.h> 7#include <linux/kernel.h> 8#include <linux/module.h> 9#include <linux/sched.h> /* For current */ 10#include <linux/tty.h> /* For the tty declarations */ 11 12static void print_string(char *str) 13{ 14 /* The tty for the current task */ 15 struct tty_struct *my_tty = get_current_tty(); 16 17 /* If my_tty is NULL, the current task has no tty you can print to (i.e., 18 * if it is a daemon). If so, there is nothing we can do. 19 */ 20 if (my_tty) { 21 const struct tty_operations *ttyops = my_tty->driver->ops; 22 /* my_tty->driver is a struct which holds the tty's functions, 23 * one of which (write) is used to write strings to the tty. 24 * It can be used to take a string either from the user's or 25 * kernel's memory segment. 26 * 27 * The function's 1st parameter is the tty to write to, because the 28 * same function would normally be used for all tty's of a certain 29 * type. 30 * The 2nd parameter is a pointer to a string. 31 * The 3rd parameter is the length of the string. 32 * 33 * As you will see below, sometimes it's necessary to use 34 * preprocessor stuff to create code that works for different 35 * kernel versions. The (naive) approach we've taken here does not 36 * scale well. The right way to deal with this is described in 37 * section 2 of 38 * linux/Documentation/SubmittingPatches 39 */ 40 (ttyops->write)(my_tty, /* The tty itself */ 41 str, /* String */ 42 strlen(str)); /* Length */ 43 44 /* ttys were originally hardware devices, which (usually) strictly 45 * followed the ASCII standard. In ASCII, to move to a new line you 46 * need two characters, a carriage return and a line feed. On Unix, 47 * the ASCII line feed is used for both purposes - so we can not 48 * just use \n, because it would not have a carriage return and the 49 * next line will start at the column right after the line feed. 50 * 51 * This is why text files are different between Unix and MS Windows. 52 * In CP/M and derivatives, like MS-DOS and MS Windows, the ASCII 53 * standard was strictly adhered to, and therefore a newline requires 54 * both a LF and a CR. 55 */ 56 (ttyops->write)(my_tty, "\015\012", 2); 57 } 58} 59 60static int __init print_string_init(void) 61{ 62 print_string("The module has been inserted. Hello world!"); 63 return 0; 64} 65 66static void __exit print_string_exit(void) 67{ 68 print_string("The module has been removed. Farewell world!"); 69} 70 71module_init(print_string_init); 72module_exit(print_string_exit); 73 74MODULE_LICENSE("GPL");
In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.
From v4.14 to v4.15, the timer API made a series of changes to improve memory safety. A buffer overflow in the area of a timer_list structure may be able to overwrite the function and data fields, providing the attacker with a way to use return-oriented programming (ROP) to call arbitrary functions within the kernel. Also, the function prototype of the callback, containing an unsigned long argument, will prevent the compiler from performing type checking. Furthermore, the function prototype with unsigned long argument may be an obstacle to the forward-edge protection of control-flow integrity. Thus, it is better to use a unique prototype to separate from the cluster that takes an unsigned long argument. The timer callback should be passed a pointer to the timer_list structure rather than an unsigned long argument. Then, it wraps all the information the callback needs, including the timer_list structure, into a larger structure, and it can use the container_of macro instead of the unsigned long value. For more information, see: Improving the kernel timers API.
Before Linux v4.14, setup_timer was used to initialize the timer and the timer_list structure looked like:
1 struct timer_list { 2 unsigned long expires; 3 void (*function)(unsigned long); 4 unsigned long data; 5 u32 flags; 6 /* ... */ 7}; 8 9void setup_timer(struct timer_list *timer, void (*callback)(unsigned long), 10 unsigned long data);
Since Linux v4.14, timer_setup is adopted and the kernel step by step converting to timer_setup from setup_timer. One of the reasons why the API was changed is that it needed to coexist with the old version of the interface. Moreover, the timer_setup was implemented by setup_timer at first.
1 void timer_setup(struct timer_list *timer, 2 void (*callback)(struct timer_list *), unsigned int flags);
The setup_timer was then removed since v4.15. As a result, the timer_list structure had changed to the following.
1 struct timer_list { 2 unsigned long expires; 3 void (*function)(struct timer_list *); 4 u32 flags; 5 /* ... */ 6 };
The following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded.
1/* 2 * kbleds.c - Blink keyboard leds until the module is unloaded. 3 */ 4 5#include <linux/init.h> 6#include <linux/kd.h> /* For KDSETLED */ 7#include <linux/module.h> 8#include <linux/version.h> 9#include <linux/tty.h> /* For tty_struct */ 10#include <linux/vt.h> /* For MAX_NR_CONSOLES */ 11#include <linux/vt_kern.h> /* for fg_console */ 12#include <linux/console_struct.h> /* For vc_cons */ 13 14MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); 15 16static struct timer_list my_timer; 17static struct tty_driver *my_driver; 18static unsigned long kbledstatus = 0; 19 20#define BLINK_DELAY HZ / 5 21#define ALL_LEDS_ON 0x07 22#define RESTORE_LEDS 0xFF 23 24/* Function my_timer_func blinks the keyboard LEDs periodically by invoking 25 * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual 26 * terminal ioctl operations, please see file: 27 * drivers/tty/vt/vt_ioctl.c, function vt_ioctl(). 28 * 29 * The argument to KDSETLED is alternatively set to 7 (thus causing the led 30 * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF 31 * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus 32 * the LEDs reflect the actual keyboard status). To learn more on this, 33 * please see file: drivers/tty/vt/keyboard.c, function setledstate(). 34 */ 35static void my_timer_func(struct timer_list *unused) 36{ 37 struct tty_struct *t = vc_cons[fg_console].d->port.tty; 38 39 if (kbledstatus == ALL_LEDS_ON) 40 kbledstatus = RESTORE_LEDS; 41 else 42 kbledstatus = ALL_LEDS_ON; 43 44 (my_driver->ops->ioctl)(t, KDSETLED, kbledstatus); 45 46 my_timer.expires = jiffies + BLINK_DELAY; 47 add_timer(&my_timer); 48} 49 50static int __init kbleds_init(void) 51{ 52 int i; 53 54 pr_info("kbleds: loading\n"); 55 pr_info("kbleds: fgconsole is %x\n", fg_console); 56 for (i = 0; i < MAX_NR_CONSOLES; i++) { 57 if (!vc_cons[i].d) 58 break; 59 pr_info("poet_atkm: console[%i/%i] #%i, tty %p\n", i, MAX_NR_CONSOLES, 60 vc_cons[i].d->vc_num, (void *)vc_cons[i].d->port.tty); 61 } 62 pr_info("kbleds: finished scanning consoles\n"); 63 64 my_driver = vc_cons[fg_console].d->port.tty->driver; 65 pr_info("kbleds: tty driver name %s\n", my_driver->driver_name); 66 67 /* Set up the LED blink timer the first time. */ 68 timer_setup(&my_timer, my_timer_func, 0); 69 my_timer.expires = jiffies + BLINK_DELAY; 70 add_timer(&my_timer); 71 72 return 0; 73} 74 75static void __exit kbleds_cleanup(void) 76{ 77 pr_info("kbleds: unloading...\n"); 78#if LINUX_VERSION_CODE >= KERNEL_VERSION(6, 2, 0) 79 timer_delete_sync(&my_timer); 80#else 81 del_timer_sync(&my_timer); 82#endif 83 (my_driver->ops->ioctl)(vc_cons[fg_console].d->port.tty, KDSETLED, 84 RESTORE_LEDS); 85} 86 87module_init(kbleds_init); 88module_exit(kbleds_cleanup); 89 90MODULE_LICENSE("GPL");
If none of the examples in this chapter fit your debugging needs, there might yet be some other tricks to try. Ever wondered what CONFIG_DEBUG_LL in make menuconfig is good for? If you activate that you get low level access to the serial port. While this might not sound very powerful by itself, you can patch kernel/printk/printk.c or any other essential kernel function to print ASCII characters, thus making it possible to trace virtually everything that your code does over a serial line. If you find yourself porting the kernel to some new and former unsupported architecture, this is usually amongst the first things that should be implemented. Logging over a netconsole might also be worth a try.
While you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive. Adding debug code can change the situation enough to make the bug seem to disappear. Thus, you should keep debug code to a minimum and make sure it does not show up in production code.
LDD3 devoted separate chapters to time handling, memory allocation, and moving data between the CPU, userspace, and devices. Those topics are still central in Linux 5.10 and later, but the modern kernel expects more care around sleeping rules, lifetime management, and API selection. This chapter collects the concepts that most often determine whether a driver is merely functional or actually robust.
Time in the kernel comes in several flavors, and choosing the wrong one is a common source of subtle bugs. For measuring elapsed intervals inside the kernel, prefer the monotonic clocks exposed through the ktime interfaces. For user-visible timestamps, use the real-time interfaces only if you truly want wall-clock behavior that can jump when the system clock is adjusted. Older code often leans heavily on jiffies; that is still valid for coarse timeouts, but newer code should treat jiffies as the low-resolution option rather than the universal time type.
Delays also need to match context. Busy-wait helpers such as udelay(), ndelay(), and mdelay() keep the CPU occupied and should be reserved for very short hardware sequences or atomic context where sleeping is forbidden. In process context, sleeping helpers such as msleep(), usleep_range(), and the wait-event family are usually preferable because they let the scheduler run other work. On a modern kernel, usleep_range() is often a better fit than udelay() once the delay is long enough that spinning would just waste CPU time and energy.
Kernel timers remain useful for deferred work that only needs a callback at some future point. As discussed in Section 14.2, recent kernels use timer_setup() and a typed struct timer_list * callback. For higher precision or explicit clock selection, hrtimer exists, but it comes with tighter constraints and is best introduced only when ordinary timers are not precise enough.
Deferred work now has a clearer hierarchy than many older texts suggest. If the work may sleep or needs to call APIs that can sleep, queue it to a workqueue. If it must run in hardirq or softirq context, keep it short and think carefully about whether a threaded interrupt handler or workqueue would be simpler. Tasklets still exist in current kernels, but they are being phased out and are best treated as legacy infrastructure for existing code rather than the default tool for new modules. The examples in Section 22.1, Section 22.2, and Section 23.4 show these tradeoffs in increasing order of flexibility.
Dynamic allocation is where driver correctness starts to depend on execution context. The first question is not “how much memory do I need?” but “am I allowed to sleep right now?”. Allocations with GFP_KERNEL may sleep and are therefore appropriate for process context. Allocations from hard interrupt context, softirq context, or any region holding a raw spinlock must use non-sleeping flags such as GFP_ATOMIC and should be kept small. Using the wrong flag is one of the fastest ways to trigger “sleeping function called from invalid context” warnings.
For most small and medium-sized objects, kmalloc() and its relatives are the starting point. kzalloc() is preferred when the object contains fields that should begin life zeroed, and kcalloc() avoids integer-overflow mistakes when allocating arrays. If the size can become large or highly variable, kvmalloc() is often the modern choice because it tries kmalloc() first and falls back to vmalloc() when needed. That keeps the common case fast without forcing the caller to maintain two code paths.
vmalloc() has a different tradeoff profile. It provides virtually contiguous memory, not physically contiguous memory, and therefore has higher overhead and different cache/TLB behavior. It is useful for large software buffers, but it is not a substitute for memory that must be physically contiguous for DMA. Similarly, driver authors should resist the temptation to guess at allocator internals or to depend on low-level layout details that are not part of the API.
When a module needs to frequently allocate and free objects of the same size—such as custom data structures, network packet descriptors, or state containers—using kmalloc() repeatedly can lead to memory fragmentation and unnecessary overhead. For these highly repetitive allocations, the slab allocator interface is the correct tool. Driver authors should use kmem_cache_create() during module initialization to set up a dedicated cache for their specific structure. Once the cache is created, kmem_cache_alloc() and kmem_cache_free() provide extremely fast, fragmentation-resistant memory management for those objects. It is crucial to symmetrically destroy the cache with kmem_cache_destroy() during module cleanup to prevent memory leaks.
For a practical demonstration of creating a custom slab cache, allocating objects from it, and ensuring proper cleanup, see the following example.
1/* 2 * kmem_cache.c - Demonstrates the use of the slab allocator. 3 */ 4#include <linux/init.h> 5#include <linux/module.h> 6#include <linux/slab.h> 7 8struct my_custom_struct { 9 int id; 10 char name[32]; 11}; 12 13static struct kmem_cache *my_cachep; 14static struct my_custom_struct *obj1, *obj2; 15 16static int __init kmem_cache_example_init(void) 17{ 18 pr_info("kmem_cache_example: Initializing module\n"); 19 20 my_cachep = 21 kmem_cache_create("my_custom_cache", sizeof(struct my_custom_struct), 0, 22 SLAB_HWCACHE_ALIGN, NULL); 23 24 if (!my_cachep) { 25 pr_err("kmem_cache_example: Failed to create cache\n"); 26 return -ENOMEM; 27 } 28 29 obj1 = kmem_cache_alloc(my_cachep, GFP_KERNEL); 30 obj2 = kmem_cache_alloc(my_cachep, GFP_KERNEL); 31 32 if (!obj1 || !obj2) { 33 pr_err("kmem_cache_example: Failed to allocate objects\n"); 34 if (obj1) 35 kmem_cache_free(my_cachep, obj1); 36 if (obj2) 37 kmem_cache_free(my_cachep, obj2); 38 kmem_cache_destroy(my_cachep); 39 return -ENOMEM; 40 } 41 42 obj1->id = 1; 43 obj2->id = 2; 44 pr_info("kmem_cache_example: Allocated obj1 at %p (id: %d)\n", obj1, 45 obj1->id); 46 pr_info("kmem_cache_example: Allocated obj2 at %p (id: %d)\n", obj2, 47 obj2->id); 48 49 return 0; 50} 51 52static void __exit kmem_cache_example_exit(void) 53{ 54 if (obj1) 55 kmem_cache_free(my_cachep, obj1); 56 if (obj2) 57 kmem_cache_free(my_cachep, obj2); 58 59 if (my_cachep) 60 kmem_cache_destroy(my_cachep); 61 62 pr_info("kmem_cache_example: Cleaned up and exited\n"); 63} 64 65module_init(kmem_cache_example_init); 66module_exit(kmem_cache_example_exit); 67 68MODULE_LICENSE("GPL"); 69MODULE_AUTHOR("Kuan-Wei Chiu <[email protected]>"); 70MODULE_DESCRIPTION("A simple example of kmem_cache");
Ownership is just as important as allocation. In Linux 5.10 and later, many drivers benefit from managed-resource helpers such as devm_kzalloc() and friends when they are written as proper device-model drivers with a struct device. Managed allocation ties resource cleanup to device detach and simplifies error paths considerably. For standalone modules or global objects, explicit unwind paths are still required, and they should be structured so that every successful acquisition has exactly one matching release.
Reference counting deserves dedicated attention. Do not use atomic_t as an ad hoc reference counter in new code. Use refcount_t or kref so overflow and misuse are easier to detect. When an object can outlive the operation that found it, the lifetime rules need to be stated clearly in code, not left as an implicit convention.
Every character driver eventually has to move data between userspace and kernel space. The important rule is that a userspace pointer is not a normal pointer. It may fault, it may refer to memory that disappears after rescheduling, and it must only be touched through the copy_to_user(), copy_from_user(), get_user(), and put_user() families or other APIs that explicitly document __user handling.
Dereferencing a user pointer directly (e.g. *ubuf) is never correct, even if the address looks valid. The kernel cannot simply trap a page fault the way a user process does: an unhandled fault in kernel mode triggers an oops or a panic. The copy_from_user() family works because each potentially faulting instruction is re
[Page truncated to keep GeezerVison snappy.]