OS Lab 8 - Kernel modules. Character devices

De la WikiLabs
Jump to navigationJump to search

In the last lab, processes talked to each other through sockets, and the kernel carried the data between them. Until now, all our code ran in user space, and asked the kernel for everything through system calls. In this lab, we will write code which runs inside the kernel, as a kernel module. We will see the rules of kernel code, a few of the data structures which the kernel uses everywhere, and how a module makes a character device: a file in /dev whose read(), write() and ioctl() calls run our functions. In the next lab, the device behind such a file will be a real USB device.

Learning objectives

By the end of this lab you should be able to:

  1. build a kernel module, load it, and unload it;
  2. print to the kernel log, and read the log;
  3. choose the right type for a value in kernel code, in user code, and in a header which both share;
  4. report errors and clean up after them in the way of the kernel;
  5. keep objects in a kernel list, and get from a list element back to its object with container_of();
  6. create a character device, and implement its open(), read(), write() and ioctl();
  7. move data between user space and the kernel safely;
  8. protect shared data with a mutex.

The project

A module is built against the kernel it will be loaded into, with the kernel's own build system, kbuild. The driver project template has three parts: the module, a library which wraps it, and a program which uses the library. Download it and unpack it:

curl -OL https://wiki.dcae.pub.ro/images/3/33/Skeleton_driver.zip
unzip -d lab08 Skeleton_driver.zip
cd lab08
./make_kbuild.sh

make_kbuild.sh makes kbuild/, the build tree of the kernel which you are running. Run it in the folder of the project, before you open the folder in VS Code:

  • on OrbStack, it downloads the source of your kernel version and builds the whole kernel, which takes about half an hour;
  • on WSL, it downloads the source of Microsoft's kernel and builds it, which takes just as long;
  • on any other Linux, it installs the kernel headers package of your distribution, and kbuild links to it.

When you open the folder, VS Code configures the project and builds the driver once. After that, the editor knows every function and type you use (it suggests names as you type, shows errors before you build, and jumps to a definition with F12) in all three parts: for the kernel's functions in driver/, and for the C library in lib/ and app/.

Folder What
driver/ The module. Kbuild lists its files, Makefile builds, loads and unloads it
driver/uapi/ The headers which the driver shares with user space
lib/ A library which wraps the driver for programs
app/ The program, linked with the library
kbuild/ The kernel's build tree, made by make_kbuild.sh. Do not change it
What In VS Code From a terminal
Build everything Build button, or Ctrl/Cmd+Shift+B cmake --build --preset debug
Build only the driver make -C driver
Load the driver task load driver make -C driver load
Unload the driver task unload driver make -C driver unload
Watch the kernel log task kernel log sudo dmesg -w

Tasks are in Terminal → Run Task....

Note: If a module is already loaded, you must unload it before you can load a new version.
Note: If you update the kernel, kbuild/ no longer matches it, and insmod fails with Invalid module format. Delete kbuild, and run ./make_kbuild.sh again.
Note: Secure Boot (only for Linux installed directly on a PC, not OrbStack or WSL). With Secure Boot on, most distributions refuse unsigned modules, so insmod fails with Key was rejected by service. To check whether it is on, run mokutil --sb-state. You can fix this in one of two ways:
  • Turn Secure Boot off in the firmware settings (open them with F2, F10, F12 or Del at start-up). We recommend this for the lab. You can turn it back on when you're done.
  • Sign your modules with your own key. The steps to do this are described in the Debian wiki. Then sign each module after you build it: kbuild/scripts/sign-file sha256 MOK.priv MOK.der driver/klog.ko.

When the kernel crashes

A bug in a module is a bug in the kernel. There is no process around it to kill. A bad pointer in user space ends the program with SIGSEGV. In a module, it is an oops: the kernel prints a report to its log, with the name of the function and the call stack, and kills the process which was running the module's code. Whatever the module held at that moment stays held: a lock stays locked, and the module often cannot be unloaded anymore (rmmod says that it is in use). The only way out is to restart the machine.

Some systems go further. On OrbStack, sysctl kernel.panic_on_oops is 1: the first oops stops the whole VM, with all its machines. Restart it from the OrbStack menu, or with orb stop and orb start. On WSL, run wsl --shutdown in Windows, and open the terminal again.

The first time you load a module of your own, the kernel prints loading out-of-tree module taints kernel. A tainted kernel runs code which did not come with it. The kernel remembers this in /proc/sys/kernel/tainted (4096 means an out-of-tree module), and prints it at the top of every oops report.

A first module

 1#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 2
 3#include <linux/module.h>
 4#include <linux/printk.h>
 5
 6static char *name = "world";
 7module_param(name, charp, 0444);
 8MODULE_PARM_DESC(name, "Who to greet");
 9
10static int __init hello_init(void)
11{
12	pr_info("hello, %s\n", name);
13	return 0;
14}
15
16static void __exit hello_exit(void)
17{
18	pr_info("goodbye, %s\n", name);
19}
20
21module_init(hello_init);
22module_exit(hello_exit);
23
24MODULE_LICENSE("GPL");
25MODULE_AUTHOR("OS Lab");
26MODULE_DESCRIPTION("Says hello when loaded, and goodbye when unloaded");

A module has no main(). It has two functions, which the kernel calls:

  • the init function, named by module_init(), runs when the module is loaded. It should set up whatever the module provides, and should return 0 on success. If it returns an error (a negative number, see below), the module is not considered loaded;
  • the exit function, named by module_exit(), runs when the module is unloaded. It should undo everything that init did.

Aside from those two moments, the module's code runs only when somebody calls it: a process which uses its device, or a piece of hardware which needs attention.

__init and __exit mark the two functions, so that the kernel can save the memory they use when they are not needed:

Marker Put on Built as a module Built into the kernel
__init The init function Freed once the module is loaded Freed once the kernel has booted
__exit The exit function Kept, and run by rmmod Left out, since it could never be unloaded

Init runs only once, so nothing may call an __init function after loading.

The MODULE_* macros store information in the module file:

Macro Meaning
MODULE_LICENSE() Required. Without it, the build fails with ERROR: modpost: missing MODULE_LICENSE(). Many kernel functions may only be used by modules whose license is "GPL"
MODULE_DESCRIPTION() One line description of the module
MODULE_AUTHOR() Author of the module
module_param(name, type, perm) Makes the variable name a parameter, which can be set when the module is loaded. type is int, uint, bool, charp (a string), ...
MODULE_PARM_DESC() One line description of a parameter

Trying it out

Save the module as driver/hello.c, and add it to the line obj-m in driver/Kbuild. Each name in obj-m is one module:

obj-m := klog.o hello.o

Then build it, and look at what the macros stored:

$ make -C driver
$ modinfo driver/hello.ko
filename:       /home/john/lab08/driver/hello.ko
license:        GPL
author:         OS Lab
description:    Says hello when loaded, and goodbye when unloaded
name:           hello
depends:
vermagic:       7.2.12-orbstack-00394-gbecdd6130068 SMP preempt mod_unload aarch64
parm:           name:Who to greet (charp)

vermagic is the kernel which the module was built for. The kernel refuses a module whose vermagic does not match its own.

Load it with insmod, see it in lsmod, and unload it with rmmod. The messages go to the kernel log, which dmesg prints:

$ sudo insmod driver/hello.ko
$ lsmod | grep hello
hello                  12288  0
$ cat /sys/module/hello/parameters/name
world
$ sudo rmmod hello
$ sudo insmod driver/hello.ko name=students
$ sudo rmmod hello
$ sudo dmesg | tail -4
[446617.235506] hello: hello, world
[446617.249769] hello: goodbye, world
[446617.259058] hello: hello, students
[446617.262071] hello: goodbye, students

The last column of lsmod counts the users of the module: while it is not 0, rmmod refuses to unload it.

The kernel log

// In: <linux/printk.h>
pr_emerg(fmt, ...)   pr_alert(fmt, ...)   pr_crit(fmt, ...)   pr_err(fmt, ...)
pr_warn(fmt, ...)    pr_notice(fmt, ...)  pr_info(fmt, ...)   pr_debug(fmt, ...)

The pr_* macros write a message to the kernel log, a buffer in memory. Every message has a level, from 0 (the system is unusable) to 7 (debugging), and each macro writes at its own level. Modules mostly use these four:

Macro Level When
pr_err() 3 Something failed
pr_warn() 4 Something is wrong, but the module goes on
pr_info() 6 Information: the module was loaded, a device was found, ...
pr_debug() 7 Details which only help while debugging

pr_emerg(), pr_alert() and pr_crit() are for when the whole system is in trouble, and pr_notice() sits between a warning and information. They are mostly used by core kernel code.

The format is that of printf(), with a few additions. %pe prints an error by name (-ENOMEM instead of -12). It takes a pointer, not an int: wrap the error code in ERR_PTR(), as in pr_err("...: %pe\n", ERR_PTR(ret)), or pass a pointer which already holds an error (see Returning errors). %*ph prints a buffer in hex, and takes its length, then the pointer. Every message should end with \n.

The line #define pr_fmt(fmt) ... at the top of the file sets a prefix for every pr_* message in it: each pr_* macro passes its format through pr_fmt(), and two string constants next to each other are joined into one. KBUILD_MODNAME is the name of the module, which kbuild defines when it compiles the file, so KBUILD_MODNAME ": " fmt becomes "hello: " fmt, and every message of the example starts with hello:. The line must come before the first #include, because <linux/printk.h> defines a pr_fmt() of its own (with no prefix) when it sees none.

pr_debug() prints nothing, unless DEBUG is defined when the file is compiled and the running kernel is configured to print debugging information. The template defines it in driver/Kbuild, with ccflags-y += -DDEBUG. If pr_debug() doesn't print anything on your machine, use pr_info() instead.

For example, this hello_init() prints a message at each level:

static int __init hello_init(void)
{
	u8 id[4] = { 0x12, 0x34, 0xab, 0xcd };

	pr_info("hello, %s\n", name);
	pr_info("device id: %*ph\n", (int)sizeof(id), id);
	pr_warn("only %d of %d buffers\n", 3, 4);
	pr_err("cannot allocate: %pe\n", ERR_PTR(-ENOMEM));
	pr_debug("init done\n");
	return 0;
}

To read the log, use sudo dmesg. -x adds the level of each message, -l shows only some levels:

$ sudo insmod driver/hello.ko
$ sudo dmesg -x | tail -5
kern  :info  : [454231.944115] hello: hello, world
kern  :info  : [454231.944130] hello: device id: 12 34 ab cd
kern  :warn  : [454231.944131] hello: only 3 of 4 buffers
kern  :err   : [454231.944131] hello: cannot allocate: -ENOMEM
kern  :debug : [454231.944156] hello: init done
$ sudo dmesg -l err,warn | tail -2
[454231.944131] hello: only 3 of 4 buffers
[454231.944131] hello: cannot allocate: -ENOMEM
Note: Once a module has a struct device, it should print with dev_err(dev, ...), dev_info(dev, ...), and so on, instead. They associate the message with a particular device, but are otherwise the same as pr_*.

Rules of kernel code

The kernel is one large program, and a module becomes part of it. A few rules follow from that:

  • Make everything static that can be: every function and every variable which is not shared with another file. A name which is not static is visible to the whole kernel when the code is built in, and can clash with another name.
  • Start every name with the name of the module (membuf_read, struct membuf).
  • Keep the state of a device in a structure, not in global variables. There may be multiple instances of the same device.
  • There is no C library. No printf(), malloc(), errno or <stdio.h>. The kernel has its own versions, in <linux/...> headers:
C library Kernel
printf() pr_info(), ...
malloc(), free() kmalloc(), kfree()
strcpy(), strncpy() strscpy()
strtol() kstrtol(), kstrtouint(), ...
sleep() msleep()
errno A negative return value
memcpy(), memset(), strlen(), strcmp() and snprintf() exist, with the same names.
  • Avoid (large) arrays on the stack and recursive functions: The stack is small. 16 KiB on x86-64 and arm64. Large arrays go on the heap (kmalloc()) or in a global.
  • No floating point. The kernel does not save the registers of the floating-point unit when it is entered, so it cannot use them. Trying to use them will make the module build fail, or the module not load: Unknown symbol __floatsidf. Use integers, for example millimetres instead of metres, nanoseconds instead of seconds.
  • Follow the kernel coding style. The kernel coding style is explained in Linux kernel coding style. Because the kernel is one large program, it is important to follow it.

Data types

Only a subset of primitive data types usable in C are common in kernel code.

Kernel code uses its own names for integers of a fixed size, from <linux/types.h>. When code needs to be shared between kernel and user code, an even smaller subset is used:

Value Kernel code User code Shared header
8 bits, unsigned u8 uint8_t __u8
8 bits, signed s8 int8_t __s8
16 bits, unsigned u16 uint16_t __u16
16 bits, signed s16 int16_t __s16
32 bits, unsigned u32 uint32_t __u32
32 bits, signed s32 int32_t __s32
64 bits, unsigned u64 uint64_t __u64
64 bits, signed s64 int64_t __s64
A character of text char char char
True or false bool bool __u8 (0 or 1)
A size in bytes size_t size_t __u32 or __u64
An address, or a value as wide as a register long or unsigned long intptr_t or uintptr_t __u64

Types used in the kernel:

  • An exact size, for registers, protocol fields, counters: u8 ... u64, s8 ... s64.
  • Text: char, and only for text. For bytes which are not text, use u8.
  • int for the values which are int by convention: file descriptors, error codes, the return value of most functions.
  • long and unsigned long for values as wide as a register: the arguments of a system call, the argument of ioctl(), addresses.
  • size_t, ssize_t, loff_t where they are used conventionally: sizes, the results of read() and write(), file positions.
  • bool for true or false.
  • Nothing else: no short, long long, unsigned on its own, and no float or double at all.

In a shared header, only use __u8 ... __s64. The size of long and of a pointer differs between 32-bit and 64-bit programs, and a 32-bit program can run on a 64-bit kernel. The size of bool and of an enum is up to the compiler, and the kernel compiler and the userspace compiler may disagree.

Errors and memory

Returning errors

There is no errno in the kernel. A function which can fail returns 0, or a positive result, on success, and a negative error code on failure: return -ENOMEM;. When a system call returns a negative value to user space, the C library stores it in errno, without the minus, and returns -1 to the program.

Error Meaning
-EINVAL An argument is invalid
-EFAULT A pointer from user space does not point to memory which the process may use
-ENOMEM Out of memory
-ENOTTY The device does not know this ioctl() command
-EBUSY Resource requested is in use
-EAGAIN Not now: the call would block, and the file was opened with O_NONBLOCK
-ENOSPC No room left on device
-ENODEV The device doesn't exist (anymore)
-ERESTARTSYS A signal interrupted a wait. User space never sees it: the kernel runs the signal handler, and restarts the system call or makes it fail with EINTR

Functions which return a pointer cannot return a negative number, so they hide the error in the pointer:

// In: <linux/err.h>
void *ERR_PTR(long error); // An error as a pointer
bool IS_ERR(const void *ptr); // Is the pointer an error?
long PTR_ERR(const void *ptr); // The error in the pointer
dev = device_create(&membuf_class, NULL, MEMBUF_DEVT, NULL, "membuf");
if (IS_ERR(dev)) {
	ret = PTR_ERR(dev);
	goto err_class;
}

Read the documentation of each function: some return NULL on failure, others an error pointer.

Cleaning up with goto

C does not have automatic destructors, so care must be taken when errors occur so that partially initialized structures are deallocated before references to them are lost.

The kernel convention is to use a series of goto labels to clean up initializations in reverse order when we need to return with a failure.

	ret = register_chrdev_region(MEMBUF_DEVT, 1, "membuf");
	if (ret)
		return ret;

	cdev_init(&membuf.cdev, &membuf_fops);
	membuf.cdev.owner = THIS_MODULE;
	ret = cdev_add(&membuf.cdev, MEMBUF_DEVT, 1);
	if (ret)
		goto err_region;

	ret = class_register(&membuf_class);
	if (ret)
		goto err_cdev;

	dev = device_create(&membuf_class, NULL, MEMBUF_DEVT, NULL, "membuf");
	if (IS_ERR(dev)) {
		ret = PTR_ERR(dev);
		goto err_class;
	}
	return 0;

err_class:
	class_unregister(&membuf_class);
err_cdev:
	cdev_del(&membuf.cdev);
err_region:
	unregister_chrdev_region(MEMBUF_DEVT, 1);
	pr_err("cannot load: %pe\n", ERR_PTR(ret));
	return ret;

kmalloc() and kfree()

// In: <linux/slab.h>
void *kmalloc(size_t size, gfp_t flags);
void *kzalloc(size_t size, gfp_t flags); // Like kmalloc(), and zeroes the memory
void kfree(const void *ptr);

They return NULL when there is no memory, which must be checked.

flags says what the allocation may do to find memory:

Flag Meaning
GFP_KERNEL It may sleep, while the kernel frees memory. Used in most kernel code
GFP_ATOMIC It never sleeps, and fails instead if it cannot find memory quickly. It should be used only where sleeping is not allowed: while holding a spinlock, or in an interrupt handler
Note: Nothing is freed for you. When a process ends, the kernel frees all its memory, but when a module is unloaded, what it allocated and did not free is lost until the machine restarts.

Kernel data structures

In user space, the usual way to keep many objects is a dynamic array: a block of memory which is replaced by a larger one, and copied, whenever it fills up (a vector in C++ and Rust, a list in Python). It is simple and fast to walk, but the kernel mostly uses linked lists instead for the following reasons:

  • growing an array needs a new, larger block of contiguous memory, which may not be available, so adding an object can fail at any time;
  • growing an array moves the objects, and the kernel keeps pointers to its objects everywhere: in open files, in other lists, in the hardware's own queues. A pointer to an object in a list stays valid as long as the object exists;
  • objects in the kernel come and go in any order (devices are plugged and unplugged, files are opened and closed), and removing one from the middle of an array means moving all the ones after it.

Intrusive structures and container_of()

A list in user space usually has nodes which point to the data. The kernel's lists do it the other way around: the node, a struct list_head, is a member of the data. The list links these members, and knows nothing about the structures around them. Such a structure is called intrusive:

// In: <linux/list.h>
struct list_head {
	struct list_head *next, *prev;
};
struct student {
	char name[16];
	u8 grade;
	struct list_head node; /* links this student into the list */
};
A list of three students. The head and the node member of each student form a circle. container_of() goes from a node back to the start of its student.

Walking the list gives pointers to node members. container_of() turns such a pointer into a pointer to the structure around it:

// In: <linux/container_of.h>
container_of(ptr, type, member)

It subtracts the offset of member in type from ptr. It is used everywhere in the kernel: the kernel hands a module a pointer to a member which it knows about (a struct list_head, a struct cdev, a struct kref), and the module gets back to its own structure.

The list gives a pointer to node. container_of() goes back by the offset of node, 24 bytes, to the start of the student.

Several members of the same type

A structure may have several members of the same type, for example to be in two lists at once. The name of the member tells container_of() which offset to subtract, so it must be the member which the pointer really points to:

struct course_student {
	char name[16];
	struct list_head by_name;  /* offset 16: in the list sorted by name */
	struct list_head by_grade; /* offset 32: in the list sorted by grade */
};

/* p came from the list sorted by grade, so it points to a by_grade member */
struct course_student *cs = container_of(p, struct course_student, by_grade);

With by_name instead, the code still builds, since both members are struct list_head, but cs is 16 bytes past the real structure, and every field read through it is wrong. The same happens with a pointer which is not inside a struct course_student at all. container_of() cannot check this: the programmer must know where the pointer came from.

In real code

The kernel calls a module with a pointer to a member which the kernel knows about, and the module uses container_of() to get back to its own structure. Two cases appear in this lab:

/* open(): the inode of a device file points to the struct cdev which was
 * registered for its number, and the cdev is a member of our structure. */
static int membuf_open(struct inode *inode, struct file *file)
{
	struct membuf *mb = container_of(inode->i_cdev, struct membuf, cdev);
	...
}

/* Walking a list by hand: each next pointer is a node member. */
struct list_head *first = students.next;
struct student *s = container_of(first, struct student, node);

The list_*_entry() macros below, such as list_for_each_entry(), call container_of() for you: that is what their member argument is for.

Lists

The kernel uses its doubly linked list for almost every collection, with a few properties:

  • the links are inside the object, so adding an object to a list allocates nothing, and cannot fail;
  • given an object, it can be removed from its list in constant time, without searching;
  • an object can be in several lists at once, with one struct list_head for each;
  • one implementation, in <linux/list.h>, works for every type.

A list starts at a head, a struct list_head which is not part of any object. An empty list is a head which points to itself.

Macro What it does
LIST_HEAD(name) Defines an empty list called name
INIT_LIST_HEAD(&head) Makes head an empty list, for a head inside a structure
list_add(&obj->node, &head) Adds at the start
list_add_tail(&obj->node, &head) Adds at the end
list_del(&obj->node) Removes the object from its list
list_move_tail(&obj->node, &head) Moves the object to the end of a list
list_empty(&head) True if the list is empty
list_first_entry_or_null(&head, type, member) The first object, or NULL if the list is empty
list_for_each_entry(pos, &head, member) A loop over every object: pos points to each one, in turn
list_for_each_entry_safe(pos, tmp, &head, member) The same, but pos may be removed and freed inside the loop

member is the name of the struct list_head in the type, node in our case. The following module keeps a list of students:

  1// SPDX-License-Identifier: GPL-2.0
  2#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  3
  4#include <linux/list.h>
  5#include <linux/module.h>
  6#include <linux/slab.h>
  7#include <linux/string.h>
  8
  9struct student {
 10	char name[16];
 11	u8 grade;
 12	struct list_head node; /* links this student into the list */
 13};
 14
 15static LIST_HEAD(students); /* an empty list: the head points to itself */
 16
 17static int student_add(const char *name, u8 grade)
 18{
 19	struct student *s = kzalloc(sizeof(*s), GFP_KERNEL);
 20
 21	if (!s)
 22		return -ENOMEM;
 23	strscpy(s->name, name, sizeof(s->name));
 24	s->grade = grade;
 25	list_add_tail(&s->node, &students);
 26	return 0;
 27}
 28
 29static void students_print(const char *title)
 30{
 31	struct student *s;
 32
 33	pr_info("%s:\n", title);
 34	list_for_each_entry(s, &students, node)
 35		pr_info("  %s %u\n", s->name, s->grade);
 36}
 37
 38static void students_free(void)
 39{
 40	struct student *s, *tmp;
 41
 42	list_for_each_entry_safe(s, tmp, &students, node) {
 43		list_del(&s->node);
 44		kfree(s);
 45	}
 46}
 47
 48static int __init lists_init(void)
 49{
 50	static const struct {
 51		const char *name;
 52		u8 grade;
 53	} start[] = { { "ana", 9 }, { "bob", 4 }, { "eve", 10 }, { "dan", 3 } };
 54	struct student *s, *tmp;
 55	struct list_head *first;
 56
 57	for (size_t i = 0; i < ARRAY_SIZE(start); i++) {
 58		if (student_add(start[i].name, start[i].grade)) {
 59			students_free();
 60			return -ENOMEM;
 61		}
 62	}
 63	students_print("all");
 64
 65	/*
 66	 * The list only links the list_head members. Get back to the student
 67	 * around one of them with container_of().
 68	 */
 69	first = students.next;
 70	s = container_of(first, struct student, node);
 71	pr_info("first: %s\n", s->name);
 72
 73	/*
 74	 * Remove while walking the list: the _safe version keeps the next
 75	 * element in tmp, before s is freed.
 76	 */
 77	list_for_each_entry_safe(s, tmp, &students, node) {
 78		if (s->grade < 5) {
 79			list_del(&s->node);
 80			kfree(s);
 81		}
 82	}
 83	students_print("passed");
 84
 85	/* Move the first student to the end. */
 86	s = list_first_entry_or_null(&students, struct student, node);
 87	if (s)
 88		list_move_tail(&s->node, &students);
 89	students_print("rotated");
 90	return 0;
 91}
 92
 93static void __exit lists_exit(void)
 94{
 95	students_free();
 96	pr_info("list empty: %d\n", list_empty(&students));
 97}
 98
 99module_init(lists_init);
100module_exit(lists_exit);
101
102MODULE_LICENSE("GPL");
103MODULE_DESCRIPTION("Kernel lists: add, walk, remove, container_of");
$ sudo insmod driver/lists.ko
$ sudo rmmod lists
$ sudo dmesg | tail -13
[446617.269675] lists: all:
[446617.269680] lists:   ana 9
[446617.269681] lists:   bob 4
[446617.269681] lists:   eve 10
[446617.269681] lists:   dan 3
[446617.269682] lists: first: ana
[446617.269682] lists: passed:
[446617.269682] lists:   ana 9
[446617.269682] lists:   eve 10
[446617.269683] lists: rotated:
[446617.269683] lists:   eve 10
[446617.269683] lists:   ana 9
[446617.272695] lists: list empty: 1
Note: A list does no locking of its own. If two processes can change it at the same time, you must protect it with a lock (see below).

The kernel has other intrusive structures, built in the same way: hlist for hash tables, rbtree for sorted data, xarray for arrays indexed by number, kfifo for queues of bytes and kref for reference counting.

Declaring a device

Device numbers

A device file in /dev holds no data. It holds a pair of numbers, major:minor, which names one device. The device belongs to whichever driver registered that pair. ls -l shows the numbers where the size would be:

$ ls -l /dev/null /dev/zero
crw-rw-rw- 1 root root 1, 3 Nov 12 14:59 /dev/null
crw-rw-rw- 1 root root 1, 5 Nov 12 14:59 /dev/zero

The c means a character device: one which is read and written as a stream of bytes. When a process opens such a file, the kernel looks up the driver which registered the numbers, and from then on, every system call on the file descriptor calls a function of that driver.

Often a driver has a whole major number, and its devices are the minors (/dev/null and /dev/zero are two devices of the driver of major 1), but that is only a habit: a driver registers a range of numbers, and several drivers can share a major. All misc devices have major 10, and on OrbStack, USB devices and this lab's drivers share major 180 (see below).

The kernel keeps both numbers in an integer dev_t type:

// In: <linux/kdev_t.h>
dev_t MKDEV(unsigned int major, unsigned int minor);
unsigned int MAJOR(dev_t dev);
unsigned int MINOR(dev_t dev);

Registering a character device

It takes three steps: get a number, connect it to the driver's functions, and tell user space that the device exists.

// In: <linux/fs.h>
int alloc_chrdev_region(dev_t *dev, unsigned int firstminor, unsigned int count, const char *name);
int register_chrdev_region(dev_t first, unsigned int count, const char *name);
void unregister_chrdev_region(dev_t first, unsigned int count);

// In: <linux/cdev.h>
void cdev_init(struct cdev *cdev, const struct file_operations *fops);
int cdev_add(struct cdev *cdev, dev_t dev, unsigned int count);
void cdev_del(struct cdev *cdev);

// In: <linux/device.h>
int class_register(const struct class *class);
void class_unregister(const struct class *class);
struct device *device_create(const struct class *class, struct device *parent, dev_t devt,
                             void *drvdata, const char *fmt, ...);
void device_destroy(const struct class *class, dev_t devt);

The init function does the three steps in this order, and the exit function undoes them in the reverse order:

Step Init calls Exit calls After this step
1. Reserve a number register_chrdev_region() or alloc_chrdev_region() unregister_chrdev_region() No other driver can take the number. Nothing happens yet when it is opened
2. Connect the number to the functions cdev_init(), then cdev_add() cdev_del() Opening a file with this number calls the driver. There is no such file yet
3. Make the file in /dev class_register(), then device_create() device_destroy(), then class_unregister() /dev/<name> exists, and programs can open it

Step 1. register_chrdev_region() takes count numbers starting at first, chosen by the driver, and fails with -EBUSY if another driver has them. alloc_chrdev_region() lets the kernel choose: it finds count free numbers, and stores the first one in *dev.

Step 2. A struct cdev is the kernel's record of a character device: which numbers it has, and its struct file_operations, the table of the driver's functions (see File operations). It is usually a member of the driver's own structure, which is how open() finds that structure again with container_of(). cdev_init() fills it in, and cdev_add() makes it live. From that moment, the driver's functions can be called, so everything they use must be ready before cdev_add().

Step 3. After steps 1 and 2, the number works, but there is still no file in /dev: reserving a number and adding a struct cdev does not create one. The file is created only when the driver adds a device with that number. class_register() registers a class, a group of devices of one kind, and device_create() adds a device to it. The device appears in /sys/class/<class>/<name>/, where the file dev holds its numbers. On most systems, /dev is a devtmpfs, a file system kept by the kernel itself, and the kernel adds /dev/<name> to it at the same moment. A program called udev then sees the new device, and can change the owner and mode of the file, or add links to it, following its rules.

If a step fails, init must undo the steps before it, in the reverse order, and return the error: this is what the labels of Cleaning up with goto are for. The template's klog_init() and klog_exit() show all three steps and their cleanup.

The kernel gives the new file the mode 0600, unless the class says otherwise. Its devnode function can change it:

static char *membuf_devnode(const struct device *dev, umode_t *mode)
{
	if (mode)
		*mode = 0666;
	return NULL;
}

static const struct class membuf_class = {
	.name = "membuf",
	.devnode = membuf_devnode,
};
Note: A driver with a single device can do all three steps with one call. misc_register(), from <linux/miscdevice.h>, takes a struct miscdevice with a name, the struct file_operations and the mode, and makes a misc device: major number 10, a free minor number, the struct cdev, and the device in the class misc. misc_deregister() removes it. Misc devices do not work on OrbStack (see below).

Device numbers on OrbStack

OrbStack (the macOS virtual machine we recommend) lets its machines open only the device numbers on a fixed list. Opening any other device file fails with EPERM, even for root. The number which alloc_chrdev_region() or misc_register() picks is not on that list, so the device registers, and nobody can open it.

The whole of major number 180 is on the list, for USB devices. The kernel's USB code uses only its minor numbers 0 to 255, so the examples in this lab, and the template, take a fixed number above them with register_chrdev_region(): 180:256 for the template, 180:257 for membuf.

/* OrbStack only allows device numbers on its list: see the lab. */
#define MEMBUF_DEVT MKDEV(180, 257)

OrbStack's /dev is also not a devtmpfs, but an ordinary tmpfs, into which OrbStack mounts a few chosen device files, and udev does not create files itself, so nothing creates the file in /dev. make load in the template creates it with mknod, from the numbers in /sys/class/<class>/<name>/dev.

Note: A serious driver does not pick its number by hand, to avoid clashing with other drivers. On a real production project, use alloc_chrdev_region() or a misc device.

File operations

The struct file_operations of a driver says which function runs for each system call on its files. It is a structure of function pointers, one for each operation. These are the members which character devices typically use:

// In: <linux/fs.h>
struct file_operations {
	struct module *owner;
	loff_t (*llseek) (struct file *, loff_t, int);
	ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
	ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
	__poll_t (*poll) (struct file *, struct poll_table_struct *);
	long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
	long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
	int (*mmap) (struct file *, struct vm_area_struct *);
	int (*open) (struct inode *, struct file *);
	int (*release) (struct inode *, struct file *);
	// ... and about 25 more, mostly for regular files
};

A driver fills in only the members it needs, with designated initializers. Members which are not set get a default behaviour, usually an error to userspace if the associated system call is called.

static const struct file_operations membuf_fops = {
	.owner = THIS_MODULE,
	.open = membuf_open,
	.read = membuf_read,
	.write = membuf_write,
	.unlocked_ioctl = membuf_ioctl,
	.compat_ioctl = compat_ptr_ioctl,
};
Member System call If it is not set
open open() The open succeeds
release The last close() of the file Nothing happens
read read() EINVAL
write write() EINVAL
unlocked_ioctl ioctl() ENOTTY
compat_ioctl ioctl() from a 32-bit program on a 64-bit kernel ENOTTY
llseek lseek() ESPIPE

.owner = THIS_MODULE keeps the module loaded while one of its files is open: rmmod fails.

Every function gets the struct file of the open file. It holds the flags of open() in f_flags, and a generic pointer which belongs to and is interpreted by the driver, private_data.

open() and release()

int (*open)(struct inode *inode, struct file *file);
int (*release)(struct inode *inode, struct file *file);

open() usually finds the device which the file is for, and sets a pointer to it in file->private_data, where the other functions called later will find it. The struct inode of a device file points to the struct cdev of the device, which is a member of the driver's structure:

static int membuf_open(struct inode *inode, struct file *file)
{
	struct membuf *mb = container_of(inode->i_cdev, struct membuf, cdev);

	file->private_data = mb;
	return 0;
}

open() may also refuse to open the file, by returning an error: -EBUSY if only one process may use the device at a time, for example. release() undoes what open() did, if anything. It runs when the last file descriptor which refers to the open file is closed.

read() and write()

ssize_t (*read)(struct file *file, char __user *buf, size_t count, loff_t *ppos);
ssize_t (*write)(struct file *file, const char __user *buf, size_t count, loff_t *ppos);
Parameter Description
buf The buffer of the process, in user space (see below)
count How many bytes the process asked for
ppos The position in the file. The driver decides what it means, and is responsible for moving it forward

They return how many bytes they read or wrote, or an error. This is what the process gets from read() and write():

  • fewer bytes than count is not an error. Programs are responsible for calling read() and write() again;
  • read() returning 0 means the end of the file;
  • write() returning 0 is generally malformed and programs may try again forever or may treat it as an opaque error. When there is no more room to write additional data, return an error, such as -ENOSPC.

ioctl()

long (*unlocked_ioctl)(struct file *file, unsigned int cmd, unsigned long arg);
long (*compat_ioctl) (struct file *file, unsigned int cmd, unsigned long arg);

ioctl() (unlocked_ioctl) is for everything which is not reading or writing data: settings, status, commands. cmd says what to do. arg is usually a pointer to a structure in user space.

Each command is a number made with a macro, in the header which the driver shares with user space:

// In: <linux/ioctl.h>
_IO(type, nr)               // No argument
_IOR(type, nr, argtype)     // The driver writes an argtype to arg: user space reads it
_IOW(type, nr, argtype)     // User space writes an argtype for the driver to read
_IOWR(type, nr, argtype)    // Both

type is one byte, the same for all the commands of a driver, so that a command for one driver is not mistaken for a command of another. nr numbers the commands. The macros also put the size of argtype and the direction into the number.

An unknown command should return -ENOTTY.

compat_ioctl is called when a 32-bit program calls ioctl on a 64-bit system. The kernel provides a wrapper: .compat_ioctl = compat_ptr_ioctl, which calls unlocked_ioctl, and works for drivers whose arg is always a pointer (or unused).

Working with user data

User pointers

Pointers which come from user space are marked __user, as buf above. Never dereference them in the kernel:

  • the process may have passed any number, by mistake or on purpose: an address in the kernel, or nothing at all;
  • the memory may be in swap, and may need to be read from disk;
  • recent x86-64 and arm64 processors make the kernel fault on any access to user memory which does not go through the functions below.

The functions below check the address, and handle a missing page. They may sleep while the data is read from disk, in case of swapped out or not-yet-allocated memory (see: mmap lazy allocation).

copy_from_user() and copy_to_user()

// In: <linux/uaccess.h>
unsigned long copy_from_user(void *to, const void __user *from, unsigned long n);
unsigned long copy_to_user(void __user *to, const void *from, unsigned long n);

copy_from_user() and copy_to_user() return how many bytes they could not copy: 0 means success. A driver should turn anything else into -EFAULT:

	if (copy_to_user(ubuf, mb->data + *ppos, count)) {
		ret = -EFAULT;
		goto out;
	}
Note: When creating a structure which will be copied to user space, always zero it at the beginning, for example with struct membuf_info info = {};. The compiler may leave gaps between members, and whatever was on the kernel stack in those gaps would go to the process, which would be a security issue.

The shared header

The driver and the programs which use it must agree exactly on a few definitions: the ioctl numbers, the structures which the ioctls carry, and constants such as sizes. Rather than describe them in a document, and write them twice, the kernel keeps them in C headers which both sides include, called uapi headers (for user-space API). The C definitions are then the only description, and the two sides cannot drift apart. A uapi header must compile both in the kernel and in a program, which limits what it may use (see below).

For our project, we store these in driver/uapi/, which the driver and the library both include.

 1/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */
 2#ifndef MEMBUF_H
 3#define MEMBUF_H
 4
 5#include <linux/ioctl.h>
 6#include <linux/types.h>
 7
 8#define MEMBUF_SIZE 4096
 9
10struct membuf_info {
11	__u32 size; /* MEMBUF_SIZE */
12	__u32 used; /* bytes in the buffer */
13	__u64 writes; /* write() calls since it was loaded */
14};
15
16#define MEMBUF_IOC_MAGIC 0xB8
17#define MEMBUF_IOC_GET_INFO _IOR(MEMBUF_IOC_MAGIC, 1, struct membuf_info)
18#define MEMBUF_IOC_CLEAR _IO(MEMBUF_IOC_MAGIC, 2)
19
20#endif /* MEMBUF_H */

The structure must have the same layout in the kernel, in 64-bit programs, and in 32-bit ones:

  • only __u8 ... __s64, never int, long, u8, s64, bool, an enum or a pointer;
  • the larger members first, or explicit padding members (__u32 pad;), so that the compiler adds no gaps.
  • a pointer to more user memory travels as a __u64. The driver can turn it back into a pointer with u64_to_user_ptr().

In user space, the program includes the same header, and passes a pointer to the structure:

 1#include <errno.h>
 2#include <fcntl.h>
 3#include <stdio.h>
 4#include <stdlib.h>
 5#include <string.h>
 6#include <sys/ioctl.h>
 7#include <unistd.h>
 8
 9#include "membuf.h"
10
11static void print_error(const char *what)
12{
13    char msg[256];
14    snprintf(msg, sizeof msg, "%s: %s\n", what, strerror(errno));
15    write(STDERR_FILENO, msg, strlen(msg));
16}
17
18int main(int argc, char *argv[])
19{
20    int fd = open("/dev/membuf", O_RDONLY);
21    if (fd == -1) {
22        print_error("open /dev/membuf");
23        return EXIT_FAILURE;
24    }
25    if (argc == 2 && strcmp(argv[1], "clear") == 0) {
26        if (ioctl(fd, MEMBUF_IOC_CLEAR) == -1) {
27            print_error("MEMBUF_IOC_CLEAR");
28            return EXIT_FAILURE;
29        }
30    }
31    struct membuf_info info;
32    if (ioctl(fd, MEMBUF_IOC_GET_INFO, &info) == -1) {
33        print_error("MEMBUF_IOC_GET_INFO");
34        return EXIT_FAILURE;
35    }
36    char line[128];
37    int len = snprintf(line, sizeof line, "%u of %u bytes used, %llu writes\n",
38                       info.used, info.size, (unsigned long long)info.writes);
39    write(STDOUT_FILENO, line, len);
40    close(fd);
41    return EXIT_SUCCESS;
42}

Locking

Two processes may use the same device at the same moment, on two processors. Two threads may even use the same file descriptor. The driver's functions then run at the same time, on the same data. If one write() reads used, and another one changes it before the first one stores the new value, one of the writes is lost.

A mutex lets only one task at a time run the code between mutex_lock() and mutex_unlock(). The others wait, asleep:

// In: <linux/mutex.h>
DEFINE_MUTEX(name); // A mutex outside a structure
void mutex_init(struct mutex *lock); // A mutex inside a structure
void mutex_lock(struct mutex *lock);
int mutex_lock_interruptible(struct mutex *lock); // A signal ends the wait: returns -EINTR
void mutex_unlock(struct mutex *lock);
  • Put the mutex in the structure which it protects, and say in a comment what it protects.
  • Where a process waits for the lock on behalf of a system call, prefer mutex_lock_interruptible(), so that Ctrl+C still works, and return -ERESTARTSYS if it fails.
  • Never return with the lock held. The goto out at the end of a function makes sure of it.
  • A task holding a mutex may sleep, so copy_to_user() and kmalloc(..., GFP_KERNEL) are fine under it.

The kernel also has spinlocks (spinlock_t, spin_lock(), spin_unlock()), whose waiters spin on the processor instead of sleeping. Code which holds a spinlock must not sleep in the critical section: no copy_to_user(), no GFP_KERNEL. They are needed where sleeping is not allowed at all, such as in interrupt handlers, as well as being generally faster than mutexes when the critical section is very short (a few microseconds).


A complete example: membuf

membuf is a buffer of 4 KiB in the kernel, behind /dev/membuf. The module allocates it with kzalloc() when it loads, and frees it when it unloads:

  • write() adds to the end of the buffer, and fails with ENOSPC when it is full;
  • read() reads the buffer from the start, up to the bytes written so far. An empty buffer reads as the end of the file;
  • MEMBUF_IOC_GET_INFO returns the size, the bytes used and the number of writes, and MEMBUF_IOC_CLEAR empties the buffer.
  1// SPDX-License-Identifier: GPL-2.0
  2/*
  3 * membuf: a 4 KiB buffer in the kernel, /dev/membuf.
  4 *
  5 *   write()  adds to the end of the buffer
  6 *   read()   reads it from the start
  7 *   ioctl()  MEMBUF_IOC_GET_INFO, MEMBUF_IOC_CLEAR
  8 */
  9#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
 10
 11#include <linux/cdev.h>
 12#include <linux/device.h>
 13#include <linux/fs.h>
 14#include <linux/module.h>
 15#include <linux/mutex.h>
 16#include <linux/slab.h>
 17#include <linux/uaccess.h>
 18
 19#include "membuf.h"
 20
 21/* OrbStack only allows device numbers on its list: see the lab. */
 22#define MEMBUF_DEVT MKDEV(180, 257)
 23
 24struct membuf {
 25	struct cdev cdev;
 26	struct mutex lock; /* protects everything below */
 27	char *data; /* MEMBUF_SIZE bytes, from kzalloc() */
 28	size_t used;
 29	u64 writes;
 30};
 31
 32static struct membuf membuf;
 33
 34static int membuf_open(struct inode *inode, struct file *file)
 35{
 36	struct membuf *mb = container_of(inode->i_cdev, struct membuf, cdev);
 37
 38	file->private_data = mb;
 39	return 0;
 40}
 41
 42static ssize_t membuf_read(struct file *file, char __user *ubuf, size_t count,
 43			   loff_t *ppos)
 44{
 45	struct membuf *mb = file->private_data;
 46	ssize_t ret;
 47
 48	if (mutex_lock_interruptible(&mb->lock))
 49		return -ERESTARTSYS;
 50
 51	if (*ppos >= mb->used) {
 52		ret = 0; /* end of file */
 53		goto out;
 54	}
 55	count = min_t(size_t, count, mb->used - *ppos);
 56	if (copy_to_user(ubuf, mb->data + *ppos, count)) {
 57		ret = -EFAULT;
 58		goto out;
 59	}
 60	*ppos += count;
 61	ret = count;
 62out:
 63	mutex_unlock(&mb->lock);
 64	return ret;
 65}
 66
 67static ssize_t membuf_write(struct file *file, const char __user *ubuf,
 68			    size_t count, loff_t *ppos)
 69{
 70	struct membuf *mb = file->private_data;
 71	ssize_t ret;
 72
 73	if (mutex_lock_interruptible(&mb->lock))
 74		return -ERESTARTSYS;
 75
 76	if (mb->used == MEMBUF_SIZE) {
 77		ret = -ENOSPC;
 78		goto out;
 79	}
 80	count = min_t(size_t, count, MEMBUF_SIZE - mb->used);
 81	if (copy_from_user(mb->data + mb->used, ubuf, count)) {
 82		ret = -EFAULT;
 83		goto out;
 84	}
 85	mb->used += count;
 86	mb->writes++;
 87	ret = count;
 88out:
 89	mutex_unlock(&mb->lock);
 90	return ret;
 91}
 92
 93static long membuf_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
 94{
 95	struct membuf *mb = file->private_data;
 96	struct membuf_info info = {}; /* zeroed, padding included */
 97
 98	switch (cmd) {
 99	case MEMBUF_IOC_GET_INFO:
100		mutex_lock(&mb->lock);
101		info.size = MEMBUF_SIZE;
102		info.used = mb->used;
103		info.writes = mb->writes;
104		mutex_unlock(&mb->lock);
105		if (copy_to_user((void __user *)arg, &info, sizeof(info)))
106			return -EFAULT;
107		return 0;
108	case MEMBUF_IOC_CLEAR:
109		mutex_lock(&mb->lock);
110		mb->used = 0;
111		mutex_unlock(&mb->lock);
112		return 0;
113	default:
114		return -ENOTTY;
115	}
116}
117
118static const struct file_operations membuf_fops = {
119	.owner = THIS_MODULE,
120	.open = membuf_open,
121	.read = membuf_read,
122	.write = membuf_write,
123	.unlocked_ioctl = membuf_ioctl,
124	.compat_ioctl = compat_ptr_ioctl,
125};
126
127static char *membuf_devnode(const struct device *dev, umode_t *mode)
128{
129	if (mode)
130		*mode = 0666;
131	return NULL;
132}
133
134static const struct class membuf_class = {
135	.name = "membuf",
136	.devnode = membuf_devnode,
137};
138
139static int __init membuf_init(void)
140{
141	struct device *dev;
142	int ret;
143
144	mutex_init(&membuf.lock);
145	membuf.data = kzalloc(MEMBUF_SIZE, GFP_KERNEL);
146	if (!membuf.data)
147		return -ENOMEM;
148
149	ret = register_chrdev_region(MEMBUF_DEVT, 1, "membuf");
150	if (ret)
151		goto err_free;
152
153	cdev_init(&membuf.cdev, &membuf_fops);
154	membuf.cdev.owner = THIS_MODULE;
155	ret = cdev_add(&membuf.cdev, MEMBUF_DEVT, 1);
156	if (ret)
157		goto err_region;
158
159	ret = class_register(&membuf_class);
160	if (ret)
161		goto err_cdev;
162
163	dev = device_create(&membuf_class, NULL, MEMBUF_DEVT, NULL, "membuf");
164	if (IS_ERR(dev)) {
165		ret = PTR_ERR(dev);
166		goto err_class;
167	}
168	return 0;
169
170err_class:
171	class_unregister(&membuf_class);
172err_cdev:
173	cdev_del(&membuf.cdev);
174err_region:
175	unregister_chrdev_region(MEMBUF_DEVT, 1);
176err_free:
177	kfree(membuf.data);
178	pr_err("cannot load: %pe\n", ERR_PTR(ret));
179	return ret;
180}
181
182static void __exit membuf_exit(void)
183{
184	device_destroy(&membuf_class, MEMBUF_DEVT);
185	class_unregister(&membuf_class);
186	cdev_del(&membuf.cdev);
187	unregister_chrdev_region(MEMBUF_DEVT, 1);
188	kfree(membuf.data);
189}
190
191module_init(membuf_init);
192module_exit(membuf_exit);
193
194MODULE_LICENSE("GPL");
195MODULE_DESCRIPTION("A 4 KiB buffer in the kernel");

To build the example, write membuf.c in driver/, membuf.h in driver/uapi/, and the program in app/main.c. Add membuf.o to obj-m in driver/Kbuild. Build everything, and load the module. MODULE=membuf tells the Makefile which module to load:

$ cmake --build --preset debug
$ make -C driver load MODULE=membuf
$ ls -l /dev/membuf
crw-rw-rw- 1 root root 180, 257 Nov 18 12:47 /dev/membuf

Write to it, and read it back. cat stops at the end of the data:

$ echo hello > /dev/membuf
$ echo kernel >> /dev/membuf
$ cat /dev/membuf
hello
kernel
$ ./build/debug/app
13 of 4096 bytes used, 2 writes

Fill it up, and empty it:

$ head -c 5000 /dev/zero > /dev/membuf
head: error writing 'standard output': No space left on device
$ ./build/debug/app
4096 of 4096 bytes used, 3 writes
$ ./build/debug/app clear
0 of 4096 bytes used, 3 writes

head wrote 5000 bytes. The driver took the 4083 which fit, and refused the rest with ENOSPC.

Some things to try:

  • Read the empty buffer with cat /dev/membuf. Which line of membuf_read() returns, and with what?
  • Keep the file open with exec 3</dev/membuf, and run sudo rmmod membuf. Why does it fail? Close the file with exec 3<&-, and try again.
  • Read the buffer with dd if=/dev/membuf bs=3. How many times is membuf_read() called, and what does *ppos hold each time?
  • Remove the zeroing of info in membuf_ioctl(). Does the program see any difference? Would it, if the structure had a gap?