The Linux Kernel Module Programming Guide
The Linux Kernel Module Programming Guide
Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram, Jim Huang
0.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
0.1.1 Authorship . . . . . . . . . . . . . . . . . . . . . . . . . . 2
0.1.2 Acknowledgements . . . . . . . . . . . . . . . . . . . . . . 2
0.1.3 What Is A Kernel Module? . . . . . . . . . . . . . . . . . 2
0.1.4 Kernel module package . . . . . . . . . . . . . . . . . . . 2
0.1.5 What Modules are in my Kernel? . . . . . . . . . . . . . . 3
0.1.6 Do I need to download and compile the kernel? . . . . . . 3
0.1.7 Before We Begin . . . . . . . . . . . . . . . . . . . . . . . 3
0.2 Headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
0.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
0.4 Hello World . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
0.4.1 The Simplest Module . . . . . . . . . . . . . . . . . . . . 4
0.4.2 Hello and Goodbye . . . . . . . . . . . . . . . . . . . . . . 7
0.4.3 The __init and __exit Macros . . . . . . . . . . . . . . 8
0.4.4 Licensing and Module Documentation . . . . . . . . . . . 9
0.4.5 Passing Command Line Arguments to a Module . . . . . 10
0.4.6 Modules Spanning Multiple Files . . . . . . . . . . . . . . 12
0.4.7 Building modules for a precompiled kernel . . . . . . . . . 14
0.5 Preliminaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
0.5.1 How modules begin and end . . . . . . . . . . . . . . . . . 16
0.5.2 Functions available to modules . . . . . . . . . . . . . . . 16
0.5.3 User Space vs Kernel Space . . . . . . . . . . . . . . . . . 17
0.5.4 Name Space . . . . . . . . . . . . . . . . . . . . . . . . . . 18
0.5.5 Code space . . . . . . . . . . . . . . . . . . . . . . . . . . 18
0.5.6 Device Drivers . . . . . . . . . . . . . . . . . . . . . . . . 19
0.6 Character Device drivers . . . . . . . . . . . . . . . . . . . . . . . 21
0.6.1 The file_operations Structure . . . . . . . . . . . . . . . . 21
0.6.2 The file structure . . . . . . . . . . . . . . . . . . . . . . . 22
1
2
0.1 Introduction
The Linux Kernel Module Programming Guide is a free book; you may repro-
duce and/or modify it under the terms of the Open Software License, version
3.0.
This book is distributed in the hope it will be useful, but without any war-
ranty, without even the implied warranty of merchantability or fitness for a
particular purpose.
The author encourages wide distribution of this book for personal or com-
mercial use, provided the above copyright notice remains intact and the method
adheres to the provisions of the Open Software License. In summary, you may
copy and distribute this book free of charge or for a profit. No explicit permis-
sion is required from the author for reproduction of this book in any medium,
physical or electronic.
Derivative works and translations of this document must be placed un-
der the Open Software License, and the original copyright notice must remain
intact. If you have contributed new material to this book, you must make
the material and source code available for your revisions. Please make revi-
sions and updates available directly to the document maintainer, Jim Huang
<jserv@ccns.ncku.edu.tw>. This will allow for the merging of updates and
provide consistent revisions to the Linux community.
If you publish or distribute this book commercially, donations, royalties,
and/or printed copies are greatly appreciated by the author and the Linux
Documentation Project (LDP). Contributing in this way shows your support for
free software and the LDP. If you have questions or comments, please contact
the address above.
0.1.1 Authorship
The Linux Kernel Module Programming Guide was originally written for the
2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain
the document. After all, the Linux kernel is a fast moving target. Peter Jay
Salzman took over maintenance and updated it for the 2.4 kernels. Eventually,
Peter no longer had time to follow developments with the 2.6 kernel, so Michael
Burian became a co-maintainer to update the document for the 2.6 kernels. Bob
Mottram updated the examples for 3.8+ kernels. Jim Huang upgraded to recent
kernel versions (v5.x) and revised the LATEX document.
0.1.2 Acknowledgements
The following people have contributed corrections or good suggestions: Ignacio
Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon,
Horst Schirmeier, and Roman Lakeev.
0.1. INTRODUCTION 4
On Arch Linux:
1 sudo lsmod
Modules are stored within the file /proc/modules, so you can also see them
with:
This can be a long list, and you might prefer to search for something partic-
ular. To search for the fat module:
1. Modversioning. A module compiled for one kernel will not load if you boot
a different kernel unless you enable CONFIG_MODVERSIONS in the kernel.
We will not go into module versioning until later in this guide. Until we
cover modversions, the examples in the guide may not work if you are
running a kernel with modversioning turned on. However, most stock
Linux distribution kernels come with it turned on. If you are having
trouble loading the modules because of versioning errors, compile a kernel
with modversioning turned off.
0.2 Headers
Before you can build anything you’ll need to install the header files for your
kernel.
On Ubuntu/Debian:
On Arch Linux:
0.3. EXAMPLES 6
This will tell you what kernel header files are available. Then for example:
0.3 Examples
All the examples from this document are available within the examples subdi-
rectory.
If there are any compile errors then you might have a more recent kernel
version or need to install the corresponding kernel header files.
1 mkdir -p ~/develop/kernel/hello-1
2 cd ~/develop/kernel/hello-1
1 /*
2 * hello-1.c - The simplest kernel module.
3 */
4 #include <linux/kernel.h> /* Needed for pr_info() */
5 #include <linux/module.h> /* Needed by all modules */
6
7 int init_module(void)
8 {
9 pr_info("Hello world 1.\n");
10
11 /* A non 0 return means init_module failed; module can't be loaded. */
12 return 0;
13 }
14
0.4. HELLO WORLD 7
15 void cleanup_module(void)
16 {
17 pr_info("Goodbye world 1.\n");
18 }
19
20 MODULE_LICENSE("GPL");
Now you will need a Makefile. If you copy and paste this, change the
indentation to use tabs, not spaces.
1 obj-m += hello-1.o
2
3 all:
4 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
5
6 clean:
7 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
1 make
If all goes smoothly you should then find that you have a compiled hello-1.ko
module. You can find info on it with the command:
should return nothing. You can try loading your shiny new module with:
The dash character will get converted to an underscore, so when you again
try:
you should now see your loaded module. It can be removed again with:
Notice that the dash was replaced by an underscore. To see what just hap-
pened in the logs:
You now know the basics of creating, compiling, installing and removing
modules. Now for more of a description of how this module works.
Kernel modules must have at least two functions: a "start" (initialization)
function called init_module() which is called when the module is insmoded into
the kernel, and an "end" (cleanup) function called cleanup_module() which is
called just before it is removed from the kernel. Actually, things have changed
starting with kernel 2.3.13. You can now use whatever name you like for the
start and end functions of a module, and you will learn how to do this in
Section 0.4.2. In fact, the new method is the preferred method. However, many
people still use init_module() and cleanup_module() for their start and end
functions.
Typically, init_module() either registers a handler for something with the
kernel, or it replaces one of the kernel functions with its own code (usually code
to do something and then call the original function). The cleanup_module()
function is supposed to undo whatever init_module() did, so the module can
be unloaded safely.
Lastly, every kernel module needs to include <linux/module.h>. We needed
to include <linux/kernel.h> only for the macro expansion for the pr_alert()
log level, which you’ll learn about in Section 2.
1. A point about coding style. Another thing which may not be immediately
obvious to anyone getting started with kernel programming is that inden-
tation within your code should be using tabs and not spaces. It is one
of the coding conventions of the kernel. You may not like it, but you’ll
need to get used to it if you ever submit a patch upstream.
2. Introducing print macros. In the beginning there was printk, usually fol-
lowed by a priority such as KERN_INFO or KERN_DEBUG. More recently this
can also be expressed in abbreviated form using a set of print macros,
such as pr_info and pr_debug. This just saves some mindless key-
board bashing and looks a bit neater. They can be found within in-
clude/linux/printk.h. Take time to read through the available priority
macros.
3. About Compiling. Kernel modules need to be compiled a bit differently
from regular userspace apps. Former kernel versions required us to care
much about these settings, which are usually stored in Makefiles. Al-
though hierarchically organized, many redundant settings accumulated in
sublevel Makefiles and made them large and rather difficult to maintain.
Fortunately, there is a new way of doing these things, called kbuild, and
the build process for external loadable modules is now fully integrated into
0.4. HELLO WORLD 9
Here is another exercise for the reader. See that comment above
the return statement in init_module()? Change the return
value to something negative, recompile and load the module
again. What happens?
1 /*
2 * hello-2.c - Demonstrating the module_init() and module_exit() macros.
3 * This is preferred over using init_module() and cleanup_module().
4 */
5 #include <linux/init.h> /* Needed for the macros */
6 #include <linux/kernel.h> /* Needed for pr_info() */
7 #include <linux/module.h> /* Needed by all modules */
8
9 static int __init hello_2_init(void)
10 {
11 pr_info("Hello, world 2\n");
12 return 0;
13 }
14
15 static void __exit hello_2_exit(void)
16 {
17 pr_info("Goodbye, world 2\n");
18 }
19
20 module_init(hello_2_init);
21 module_exit(hello_2_exit);
22
23 MODULE_LICENSE("GPL");
So now we have two real kernel modules under our belt. Adding another
module is as simple as this:
1 obj-m += hello-1.o
2 obj-m += hello-2.o
0.4. HELLO WORLD 10
3
4 all:
5 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
6
7 clean:
8 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
1 /*
2 * hello-3.c - Illustrating the __init, __initdata and __exit macros.
3 */
4 #include <linux/init.h> /* Needed for the macros */
5 #include <linux/kernel.h> /* Needed for pr_info() */
6 #include <linux/module.h> /* Needed by all modules */
7
8 static int hello3_data __initdata = 3;
9
10 static int __init hello_3_init(void)
11 {
12 pr_info("Hello, world %d\n", hello3_data);
13 return 0;
14 }
15
16 static void __exit hello_3_exit(void)
17 {
18 pr_info("Goodbye, world 3\n");
0.4. HELLO WORLD 11
19 }
20
21 module_init(hello_3_init);
22 module_exit(hello_3_exit);
23
24 MODULE_LICENSE("GPL");
1 /*
2 * hello-4.c - Demonstrates module documentation.
3 */
4 #include <linux/init.h> /* Needed for the macros */
5 #include <linux/kernel.h> /* Needed for pr_info() */
6 #include <linux/module.h> /* Needed by all modules */
7
8 MODULE_LICENSE("GPL");
9 MODULE_AUTHOR("LKMPG");
10 MODULE_DESCRIPTION("A sample driver");
11
12 static int __init init_hello_4(void)
13 {
14 pr_info("Hello, world 4\n");
15 return 0;
16 }
17
18 static void __exit cleanup_hello_4(void)
19 {
20 pr_info("Goodbye, world 4\n");
21 }
22
23 module_init(init_hello_4);
24 module_exit(cleanup_hello_4);
0.4. HELLO WORLD 12
1 int myint = 3;
2 module_param(myint, int, 0);
Arrays are supported too, but things are a bit different now than they were
in the olden days. To keep track of the number of parameters you need to pass
a pointer to a count variable as third parameter. At your option, you could also
ignore the count and pass NULL instead. We show both possibilities here:
1 int myintarray[2];
2 module_param_array(myintarray, int, NULL, 0); /* not interested in count */
3
4 short myshortarray[4];
5 int count;
6 module_param_array(myshortarray, short, &count, 0); /* put count into "count"
,→ variable */
A good use for this is to have the module variable’s default values set, like
an port or IO address. If the variables contain the default values, then perform
autodetection (explained elsewhere). Otherwise, keep the current value. This
will be made clear later on.
Lastly, there is a macro function, MODULE_PARM_DESC(), that is used to
document arguments that the module can take. It takes two parameters: a
variable name and a free form string describing that variable.
1 /*
2 * hello-5.c - Demonstrates command line argument passing to a module.
3 */
4 #include <linux/init.h>
5 #include <linux/kernel.h>
6 #include <linux/module.h>
7 #include <linux/moduleparam.h>
8 #include <linux/stat.h>
0.4. HELLO WORLD 13
9
10 MODULE_LICENSE("GPL");
11
12 static short int myshort = 1;
13 static int myint = 420;
14 static long int mylong = 9999;
15 static char *mystring = "blah";
16 static int myintArray[2] = {420, 420};
17 static int arr_argc = 0;
18
19 /* module_param(foo, int, 0000)
20 * The first param is the parameters name.
21 * The second param is its data type.
22 * The final argument is the permissions bits,
23 * for exposing parameters in sysfs (if non-zero) at a later stage.
24 */
25 module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
26 MODULE_PARM_DESC(myshort, "A short integer");
27 module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
28 MODULE_PARM_DESC(myint, "An integer");
29 module_param(mylong, long, S_IRUSR);
30 MODULE_PARM_DESC(mylong, "A long integer");
31 module_param(mystring, charp, 0000);
32 MODULE_PARM_DESC(mystring, "A character string");
33
34 /* module_param_array(name, type, num, perm);
35 * The first param is the parameter's (in this case the array's) name.
36 * The second param is the data type of the elements of the array.
37 * The third argument is a pointer to the variable that will store the number.
38 * of elements of the array initialized by the user at module loading time.
39 * The fourth argument is the permission bits.
40 */
41 module_param_array(myintArray, int, &arr_argc, 0000);
42 MODULE_PARM_DESC(myintArray, "An array of integers");
43
44 static int __init hello_5_init(void)
45 {
46 int i;
47 pr_info("Hello, world 5\n=============\n");
48 pr_info("myshort is a short integer: %hd\n", myshort);
49 pr_info("myint is an integer: %d\n", myint);
50 pr_info("mylong is a long integer: %ld\n", mylong);
51 pr_info("mystring is a string: %s\n", mystring);
52
53 for (i = 0; i < (sizeof myintArray / sizeof(int)); i++)
54 pr_info("myintArray[%d] = %d\n", i, myintArray[i]);
55
56 pr_info("got %d arguments for myintArray.\n", arr_argc);
57 return 0;
58 }
59
60 static void __exit hello_5_exit(void)
61 {
62 pr_info("Goodbye, world 5\n");
63 }
64
65 module_init(hello_5_init);
0.4. HELLO WORLD 14
66 module_exit(hello_5_exit);
1 /*
2 * start.c - Illustration of multi filed modules
3 */
4
5 #include <linux/kernel.h> /* We are doing kernel work */
6 #include <linux/module.h> /* Specifically, a module */
7
8 int init_module(void)
9 {
10 pr_info("Hello, world - this is the kernel speaking\n");
11 return 0;
12 }
13
14 MODULE_LICENSE("GPL");
1 /*
2 * stop.c - Illustration of multi filed modules
3 */
4
5 #include <linux/kernel.h> /* We are doing kernel work */
6 #include <linux/module.h> /* Specifically, a module */
7
8 void cleanup_module()
9 {
10 pr_info("Short is the life of a kernel module\n");
11 }
12
13 MODULE_LICENSE("GPL");
1 obj-m += hello-1.o
2 obj-m += hello-2.o
3 obj-m += hello-3.o
4 obj-m += hello-4.o
5 obj-m += hello-5.o
6 obj-m += startstop.o
7 startstop-objs := start.o stop.o
8
9 all:
10 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
11
12 clean:
13 make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
This is the complete makefile for all the examples we have seen so far. The
first five lines are nothing special, but for the last example we will need two
lines. First we invent an object name for our combined module, second we tell
make what object files are part of that module.
you could require to compile and insert a module into a running kernel which
you are not allowed to recompile, or on a machine that you prefer not to reboot.
If you can’t think of a case that will force you to use modules for a precompiled
kernel you might want to skip this and treat the rest of this chapter as a big
footnote.
Now, if you just install a kernel source tree, use it to compile your kernel
module and you try to insert your module into the kernel, in most cases you
would obtain an error as follows:
insmod: ERROR: could not insert module poet.ko: Invalid module format
In other words, your kernel refuses to accept your module because version
strings (more precisely, version magic, see include/linux/vermagic.h) do not
match. Incidentally, version magic strings are stored in the module object in
the form of a static string, starting with vermagic:. Version data are inserted
in your module when it is linked against the kernel/module.o file. To inspect
version magics and other strings stored in a given module, issue the command
modinfo module.ko:
$ modinfo hello-4.ko
description: A sample driver
author: LKMPG
license: GPL
srcversion: B2AA7FBFCC2C39AED665382
depends:
retpoline: Y
name: hello_4
vermagic: 5.4.0-70-generic SMP mod_unload modversions
difference, namely the custom string which appears in the module’s version
magic and not in the kernel’s one, is due to a modification with respect to the
original, in the makefile that some distributions include. Then, examine your
Makefile, and make sure that the specified version information matches exactly
the one used for your current kernel. For example, you makefile could start as
follows:
VERSION = 5
PATCHLEVEL = 14
SUBLEVEL = 0
EXTRAVERSION = -rc2
Here linux-`uname -r` is the Linux kernel source you are attempting to build.
Now, please run make to update configuration and version headers and ob-
jects:
$ make
SYNC include/config/auto.conf.cmd
HOSTCC scripts/basic/fixdep
HOSTCC scripts/kconfig/conf.o
HOSTCC scripts/kconfig/confdata.o
HOSTCC scripts/kconfig/expr.o
LEX scripts/kconfig/lexer.lex.c
YACC scripts/kconfig/parser.tab.[ch]
HOSTCC scripts/kconfig/preprocess.o
HOSTCC scripts/kconfig/symbol.o
HOSTCC scripts/kconfig/util.o
HOSTCC scripts/kconfig/lexer.lex.o
HOSTCC scripts/kconfig/parser.tab.o
HOSTLD scripts/kconfig/conf
If you do not desire to actually compile the kernel, you can interrupt the
build process (CTRL-C) just after the SPLIT line, because at that time, the
files you need will be are ready. Now you can turn back to the directory of your
module and compile it: It will be built exactly according to your current kernel
settings, and it will load into it without any errors.
0.5. PRELIMINARIES 18
0.5 Preliminaries
0.5.1 How modules begin and end
A program usually begins with a main() function, executes a bunch of instruc-
tions and terminates upon completion of those instructions. Kernel modules
work a bit differently. A module always begin with either the init_module or
the function you specify with module_init call. This is the entry function for
modules; it tells the kernel what functionality the module provides and sets up
the kernel to run the module’s functions when they are needed. Once it does
this, entry function returns and the module does nothing until the kernel wants
to do something with the code that the module provides.
All modules end by calling either cleanup_module or the function you spec-
ify with the module_exit call. This is the exit function for modules; it undoes
whatever entry function did. It unregisters the functionality that the entry
function registered.
Every module must have an entry function and an exit function. Since
there’s more than one way to specify entry and exit functions, I will try my best
to use the terms “entry function” and “exit function”, but if I slip and simply
refer to them as init_module and cleanup_module, I think you will know what
I mean.
1 #include <stdio.h>
2
3 int main(void)
4 {
5 printf("hello");
6 return 0;
7 }
with gcc -Wall -o hello hello.c. Run the executable with strace ./hello.
Are you impressed? Every line you see corresponds to a system call. strace is
a handy program that gives you details about what system calls a program
is making, including which call is made, what its arguments are and what it
returns. It is an invaluable tool for figuring out things like what files a pro-
gram is trying to access. Towards the end, you will see a line which looks
like write(1, "hello", 5hello). There it is. The face behind the printf()
mask. You may not be familiar with write, since most people use library func-
tions for file I/O (like fopen, fputs, fclose). If that is the case, try looking
at man 2 write. The 2nd man section is devoted to system calls (like kill()
and read()). The 3rd man section is devoted to library calls, which you would
probably be more familiar with (like cosh() and random()).
You can even write modules to replace the kernel’s system calls, which we
will do shortly. Crackers often make use of this sort of thing for backdoors or
trojans, but you can write your own modules to do more benign things, like
have the kernel write Tee hee, that tickles! every time someone tries to delete a
file on your system.
By the way, I would like to point out that the above discussion is true for
any operating system which uses a monolithic kernel. This is not quite the same
thing as "building all your modules into the kernel", although the idea is the
same. There are things called microkernels which have modules which get their
own codespace. The GNU Hurd and the Zircon kernel of Google Fuchsia are
two examples of a microkernel.
$ ls -l /dev/hda[1-3]
brw-rw---- 1 root disk 3, 1 Jul 5 2000 /dev/hda1
brw-rw---- 1 root disk 3, 2 Jul 5 2000 /dev/hda2
brw-rw---- 1 root disk 3, 3 Jul 5 2000 /dev/hda3
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):
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.
I would like to make a few last points which are implicit from the above
discussion, but I would like to make them explicit just in case. When a device
file is accessed, the kernel uses the major number of the file to determine which
driver should be used to handle the access. This means that the kernel doesn’t
really need to use or even know about the minor number. The driver itself is
the only thing that cares about the minor number. It uses the minor number
to distinguish between different pieces of hardware.
By the way, when I say "hardware", I mean something a bit more abstract
than a PCI card that you can hold in your hand. Look at these 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.
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:
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;
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 v5.6, the proc_ops structure was introduced to replace the use
of the file_operations structure when registering proc handlers.
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 initial-
ization. You do this by using the register_chrdev function, defined by in-
clude/linux/fs.h.
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 num-
ber.
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.
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 sudo 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 increase,
decrease and display this counter:
0.6.5 chardev.c
The next code sample creates a char driver named chardev. You can cat its
device file.
1 cat /proc/devices
(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/hello), but catch these attempts and tell the
user that the operation is not supported. Don’t worry if you don’t see what we
do with the data we read into the buffer; we don’t do much with it. We simply
read in the data and print a message acknowledging that we received it.
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/cdev.h>
7 #include <linux/delay.h>
8 #include <linux/device.h>
0.6. CHARACTER DEVICE DRIVERS 27
9 #include <linux/fs.h>
10 #include <linux/init.h>
11 #include <linux/irq.h>
12 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/poll.h>
15
16 /* Prototypes - this would normally go in a .h file */
17 static int device_open(struct inode *, struct file *);
18 static int device_release(struct inode *, struct file *);
19 static ssize_t device_read(struct file *, char *, size_t, loff_t *);
20 static ssize_t device_write(struct file *, const char *, size_t, loff_t *);
21
22 #define SUCCESS 0
23 #define DEVICE_NAME "chardev" /* Dev name as it appears in /proc/devices */
24 #define BUF_LEN 80 /* Max length of the message from the device */
25
26 /* Global variables are declared as static, so are global within the file. */
27
28 static int major; /* major number assigned to our device driver
,→ */
29 static int open_device_cnt = 0; /* Is device open?
30 * Used to prevent multiple access to device
,→ */
31 static char msg[BUF_LEN]; /* The msg the device will give when asked */
32 static char *msg_ptr;
33
34 static struct class *cls;
35
36 static struct file_operations chardev_fops = {
37 .read = device_read,
38 .write = device_write,
39 .open = device_open,
40 .release = device_release,
41 };
42
43 static int __init chardev_init(void)
44 {
45 major = register_chrdev(0, DEVICE_NAME, &chardev_fops);
46
47 if (major < 0) {
48 pr_alert("Registering char device failed with %d\n", major);
49 return major;
50 }
51
52 pr_info("I was assigned major number %d.\n", major);
53
54 cls = class_create(THIS_MODULE, DEVICE_NAME);
55 device_create(cls, NULL, MKDEV(major, 0), NULL, DEVICE_NAME);
56
57 pr_info("Device created on /dev/%s\n", DEVICE_NAME);
58
59 return SUCCESS;
60 }
61
62 static void __exit chardev_exit(void)
63 {
0.6. CHARACTER DEVICE DRIVERS 28
121 /* The buffer is in the user data segment, not the kernel
122 * segment so "*" assignment won't work. We have to use
123 * put_user which copies data from the kernel data segment to
124 * the user data segment.
125 */
126 put_user(*(msg_ptr++), buffer++);
127
128 length--;
129 bytes_read++;
130 }
131
132 /* Most read functions return the number of bytes put into the buffer. */
133 return bytes_read;
134 }
135
136 /* Called when a process writes to dev file: echo "hi" > /dev/hello */
137 static ssize_t device_write(struct file *filp,
138 const char *buff,
139 size_t len,
140 loff_t *off)
141 {
142 pr_alert("Sorry, this operation is not supported.\n");
143 return -EINVAL;
144 }
145
146 module_init(chardev_init);
147 module_exit(chardev_exit);
148
149 MODULE_LICENSE("GPL");
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 file system 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 file systems are located on a disk, rather than just in memory (which
is where /proc is), and in that case the inode number is a pointer to a disk
location where the file’s index-node (inode for short) 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 don’t get called when the file is opened or closed, there’s 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’s no way to avoid the conse-
quences.
Here a simple example showing how to use a /proc file. This is the Hel-
loWorld 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 func-
tion proc_create. The return value is a 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>
0.7. THE /PROC FILE SYSTEM 31
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
17 struct proc_dir_entry *Our_Proc_File;
18
19
20 ssize_t procfile_read(struct file *filePointer,
21 char *buffer,
22 size_t buffer_length,
23 loff_t *offset)
24 {
25 char s[13] = "HelloWorld!\n";
26 int len = sizeof(s);
27 ssize_t ret = len;
28
29 if (*offset >= len || copy_to_user(buffer, s, len)) {
30 pr_info("copy_to_user failed\n");
31 ret = 0;
32 } else {
33 pr_info("procfile read %s\n",
,→ filePointer->f_path.dentry->d_name.name);
34 *offset += len;
35 }
36
37 return ret;
38 }
39
40 #ifdef HAVE_PROC_OPS
41 static const struct proc_ops proc_file_fops = {
42 .proc_read = procfile_read,
43 };
44 #else
45 static const struct file_operations proc_file_fops = {
46 .read = procfile_read,
47 };
48 #endif
49
50 static int __init procfs1_init(void)
51 {
52 Our_Proc_File = proc_create(procfs_name, 0644, NULL, &proc_file_fops);
53 if (NULL == Our_Proc_File) {
54 proc_remove(Our_Proc_File);
55 pr_alert("Error:Could not initialize /proc/%s\n", procfs_name);
56 return -ENOMEM;
57 }
58
59 pr_info("/proc/%s created\n", procfs_name);
60 return 0;
61 }
62
63 static void __exit procfs1_exit(void)
64 {
65 proc_remove(Our_Proc_File);
0.7. THE /PROC FILE SYSTEM 32
1 /*
2 * procfs2.c - create a "file" in /proc
0.7. THE /PROC FILE SYSTEM 33
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 */
19 static struct proc_dir_entry *Our_Proc_File;
20
21 /* The buffer used to store character for this module */
22 static char procfs_buffer[PROCFS_MAX_SIZE];
23
24 /* The size of the buffer */
25 static unsigned long procfs_buffer_size = 0;
26
27 /* This function is called then the /proc file is read */
28 ssize_t procfile_read(struct file *filePointer,
29 char *buffer,
30 size_t buffer_length,
31 loff_t *offset)
32 {
33 char s[13] = "HelloWorld!\n";
34 int len = sizeof(s);
35 ssize_t ret = len;
36
37 if (*offset >= len || copy_to_user(buffer, s, len)) {
38 pr_info("copy_to_user failed\n");
39 ret = 0;
40 } else {
41 pr_info("procfile read %s\n",
,→ filePointer->f_path.dentry->d_name.name);
42 *offset += len;
43 }
44
45 return ret;
46 }
47
48 /* This function is called with the /proc file is written. */
49 static ssize_t procfile_write(struct file *file,
50 const char *buff,
51 size_t len,
52 loff_t *off)
53 {
54 procfs_buffer_size = len;
55 if (procfs_buffer_size > PROCFS_MAX_SIZE)
56 procfs_buffer_size = PROCFS_MAX_SIZE;
57
58 if (copy_from_user(procfs_buffer, buff, procfs_buffer_size))
0.7. THE /PROC FILE SYSTEM 34
59 return -EFAULT;
60
61 procfs_buffer[procfs_buffer_size] = '\0';
62 return procfs_buffer_size;
63 }
64
65 #ifdef HAVE_PROC_OPS
66 static const struct proc_ops proc_file_fops = {
67 .proc_read = procfile_read,
68 .proc_write = procfile_write,
69 };
70 #else
71 static const struct file_operations proc_file_fops = {
72 .read = procfile_read,
73 .write = procfile_write,
74 };
75 #endif
76
77 static int __init procfs2_init(void)
78 {
79 Our_Proc_File = proc_create(PROCFS_NAME, 0644, NULL, &proc_file_fops);
80 if (NULL == Our_Proc_File) {
81 proc_remove(Our_Proc_File);
82 pr_alert("Error:Could not initialize /proc/%s\n", PROCFS_NAME);
83 return -ENOMEM;
84 }
85
86 pr_info("/proc/%s created\n", PROCFS_NAME);
87 return 0;
88 }
89
90 static void __exit procfs2_exit(void)
91 {
92 proc_remove(Our_Proc_File);
93 pr_info("/proc/%s removed\n", PROCFS_NAME);
94 }
95
96 module_init(procfs2_init);
97 module_exit(procfs2_exit);
98
99 MODULE_LICENSE("GPL");
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
12 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)
13 #define HAVE_PROC_OPS
14 #endif
15
16 #define PROCFS_MAX_SIZE 2048
17 #define PROCFS_ENTRY_FILENAME "buffer2k"
18
19 struct proc_dir_entry *Our_Proc_File;
20 static char procfs_buffer[PROCFS_MAX_SIZE];
21 static unsigned long procfs_buffer_size = 0;
22
23 static ssize_t procfs_read(struct file *filp,
24 char *buffer,
25 size_t length,
26 loff_t *offset)
27 {
28 static int finished = 0;
29 if (finished) {
30 pr_debug("procfs_read: END\n");
31 finished = 0;
32 return 0;
33 }
34 finished = 1;
0.7. THE /PROC FILE SYSTEM 36
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 in-
stead. Consider using this mechanism, in case you want to document something
kernel related yourself.
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 */
0.7. THE /PROC FILE SYSTEM 38
start() treatment
No
next() treatment
No
return is NULL?
Yes
stop() treatment
65 .start = my_seq_start,
66 .next = my_seq_next,
67 .stop = my_seq_stop,
68 .show = my_seq_show,
69 };
70
71 /* This function is called when the /proc file is open. */
72 static int my_open(struct inode *inode, struct file *file)
73 {
74 return seq_open(file, &my_seq_ops);
75 };
76
77 /* This structure gather "function" that manage the /proc file */
78 #ifdef HAVE_PROC_OPS
79 static const struct proc_ops my_file_ops = {
80 .proc_open = my_open,
81 .proc_read = seq_read,
82 .proc_lseek = seq_lseek,
83 .proc_release = seq_release,
84 };
85 #else
86 static const struct file_operations my_file_ops = {
87 .open = my_open,
88 .read = seq_read,
89 .llseek = seq_lseek,
90 .release = seq_release,
91 };
92 #endif
93
94 static int __init procfs4_init(void)
95 {
96 struct proc_dir_entry *entry;
97
98 entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops);
99 if (entry == NULL) {
100 remove_proc_entry(PROC_NAME, NULL);
101 pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME);
102 return -ENOMEM;
103 }
104
105 return 0;
106 }
107
108 static void __exit procfs4_exit(void)
109 {
110 remove_proc_entry(PROC_NAME, NULL);
111 pr_debug("/proc/%s removed\n", PROC_NAME);
112 }
113
114 module_init(procfs4_init);
115 module_exit(procfs4_exit);
116
117 MODULE_LICENSE("GPL");
If you want more information, you can read this web page:
• https://lwn.net/Articles/22355/
0.8. SYSFS: INTERACTING WITH YOUR MODULE 41
• https://kernelnewbies.org/Documents/SeqFileHowTo
You can also read the code of fs/seq_file.c in the linux kernel.
1 ls -l /sys
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
11 static struct kobject *mymodule;
12
13 /* the variable you want to be able to change */
14 static int myvariable = 0;
15
16 static ssize_t myvariable_show(struct kobject *kobj,
17 struct kobj_attribute *attr,
18 char *buf)
19 {
20 return sprintf(buf, "%d\n", myvariable);
21 }
22
23 static ssize_t myvariable_store(struct kobject *kobj,
24 struct kobj_attribute *attr,
25 char *buf,
26 size_t count)
27 {
28 sscanf(buf, "%du", &myvariable);
29 return count;
30 }
31
32
33 static struct kobj_attribute myvariable_attribute =
34 __ATTR(myvariable, 0660, myvariable_show, (void *) myvariable_store);
35
36 static int __init mymodule_init(void)
0.8. SYSFS: INTERACTING WITH YOUR MODULE 42
37 {
38 int error = 0;
39
40 pr_info("mymodule: initialised\n");
41
42 mymodule = kobject_create_and_add("mymodule", kernel_kobj);
43 if (!mymodule)
44 return -ENOMEM;
45
46 error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
47 if (error) {
48 pr_info(
49 "failed to create the myvariable file "
50 "in /sys/kernel/mymodule\n");
51 }
52
53 return error;
54 }
55
56 static void __exit mymodule_exit(void)
57 {
58 pr_info("mymodule: Exit success\n");
59 kobject_put(mymodule);
60 }
61
62 module_init(mymodule_init);
63 module_exit(mymodule_exit);
64
65 MODULE_LICENSE("GPL");
1 make
2 sudo insmod hello-sysfs.ko
1 cat /sys/kernel/mymodule/myvariable
1 /*
2 * chardev2.c - Create an input/output character device
0.9. TALKING TO DEVICE FILES 44
3 */
4
5 #include <linux/cdev.h>
6 #include <linux/delay.h>
7 #include <linux/device.h>
8 #include <linux/fs.h>
9 #include <linux/init.h>
10 #include <linux/irq.h>
11 #include <linux/kernel.h> /* We are doing kernel work */
12 #include <linux/module.h> /* Specifically, a module */
13 #include <linux/poll.h>
14
15 #include "chardev.h"
16 #define SUCCESS 0
17 #define DEVICE_NAME "char_dev"
18 #define BUF_LEN 80
19
20 /* Is the device open right now? Used to prevent concurrent access into
21 * the same device
22 */
23 static int Device_Open = 0;
24
25 /* The message the device will give when asked */
26 static char Message[BUF_LEN];
27
28 /* How far did the process reading the message get? Useful if the message
29 * is larger than the size of the buffer we get to fill in device_read.
30 */
31 static char *Message_Ptr;
32
33 /* Major number assigned to our device driver */
34 static int Major;
35 static struct class *cls;
36
37 /* This is called whenever a process attempts to open the device file */
38 static int device_open(struct inode *inode, struct file *file)
39 {
40 pr_info("device_open(%p)\n", file);
41
42 /* We don't want to talk to two processes at the same time. */
43 if (Device_Open)
44 return -EBUSY;
45
46 Device_Open++;
47 /* Initialize the message */
48 Message_Ptr = Message;
49 try_module_get(THIS_MODULE);
50 return SUCCESS;
51 }
52
53 static int device_release(struct inode *inode, struct file *file)
54 {
55 pr_info("device_release(%p,%p)\n", inode, file);
56
57 /* We're now ready for our next caller */
58 Device_Open--;
59
0.9. TALKING TO DEVICE FILES 45
60 module_put(THIS_MODULE);
61 return SUCCESS;
62 }
63
64 /* This function is called whenever a process which has already opened the
65 * device file attempts to read from it.
66 */
67 static ssize_t device_read(struct file *file, /* see include/linux/fs.h */
68 char __user *buffer, /* buffer to be filled */
69 size_t length, /* length of the buffer */
70 loff_t *offset)
71 {
72 /* Number of bytes actually written to the buffer */
73 int bytes_read = 0;
74
75 pr_info("device_read(%p,%p,%ld)\n", file, buffer, length);
76
77 /* If at the end of message, return 0 (which signifies end of file). */
78 if (*Message_Ptr == 0)
79 return 0;
80
81 /* Actually put the data into the buffer */
82 while (length && *Message_Ptr) {
83 /* Because the buffer is in the user data segment, not the kernel
84 * data segment, assignment would not work. Instead, we have to
85 * use put_user which copies data from the kernel data segment to
86 * the user data segment.
87 */
88 put_user(*(Message_Ptr++), buffer++);
89 length--;
90 bytes_read++;
91 }
92
93 pr_info("Read %d bytes, %ld left\n", bytes_read, length);
94
95 /* Read functions are supposed to return the number of bytes actually
96 * inserted into the buffer.
97 */
98 return bytes_read;
99 }
100
101 /* called when somebody tries to write into our device file. */
102 static ssize_t device_write(struct file *file,
103 const char __user *buffer,
104 size_t length,
105 loff_t *offset)
106 {
107 int i;
108
109 pr_info("device_write(%p,%s,%ld)", file, buffer, length);
110
111 for (i = 0; i < length && i < BUF_LEN; i++)
112 get_user(Message[i], buffer + i);
113
114 Message_Ptr = Message;
115
116 /* Again, return the number of input characters used. */
0.9. TALKING TO DEVICE FILES 46
117 return i;
118 }
119
120 /* This function is called whenever a process tries to do an ioctl on our
121 * device file. We get two extra parameters (additional to the inode and file
122 * structures, which all device functions get): the number of the ioctl
called
123 * and the parameter given to the ioctl function.
124 *
125 * If the ioctl is write or read/write (meaning output is returned to the
126 * calling process), the ioctl call returns the output of this function.
127 */
128 long device_ioctl(struct file *file, /* ditto */
129 unsigned int ioctl_num, /* number and param for ioctl */
130 unsigned long ioctl_param)
131 {
132 int i;
133 char *temp;
134 char ch;
135
136 /* Switch according to the ioctl called */
137 switch (ioctl_num) {
138 case IOCTL_SET_MSG:
139 /* Receive a pointer to a message (in user space) and set that to
140 * be the device's message. Get the parameter given to ioctl by
141 * the process.
142 */
143 temp = (char *) ioctl_param;
144
145 /* Find the length of the message */
146 get_user(ch, temp);
147 for (i = 0; ch && i < BUF_LEN; i++, temp++)
148 get_user(ch, temp);
149
150 device_write(file, (char *) ioctl_param, i, 0);
151 break;
152
153 case IOCTL_GET_MSG:
154 /* Give the current message to the calling process - the parameter
155 * we got is a pointer, fill it.
156 */
157 i = device_read(file, (char *) ioctl_param, 99, 0);
158
159 /* Put a zero at the end of the buffer, so it will be properly
160 * terminated.
161 */
162 put_user('\0', (char *) ioctl_param + i);
163 break;
164
165 case IOCTL_GET_NTH_BYTE:
166 /* This ioctl is both input (ioctl_param) and output (the return
167 * value of this function).
168 */
169 return Message[ioctl_param];
170 break;
171 }
172
0.9. TALKING TO DEVICE FILES 47
1 /*
0.9. TALKING TO DEVICE FILES 48
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>
0.9. TALKING TO DEVICE FILES 49
9 #include <linux/slab.h>
10 #include <linux/uaccess.h>
11
12 struct ioctl_arg {
13 unsigned int reg;
14 unsigned int val;
15 };
16
17 /* Documentation/ioctl/ioctl-number.txt */
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 _IOW(IOC_MAGIC, 3, int)
24
25 #define IOCTL_VAL_MAXNR 3
26 #define DRIVER_NAME "ioctltest"
27
28 static unsigned int test_ioctl_major = 0;
29 static unsigned int num_of_dev = 1;
30 static struct cdev test_ioctl_cdev;
31 static int ioctl_num = 0;
32
33 struct test_ioctl_data {
34 unsigned char val;
35 rwlock_t lock;
36 };
37
38 static long test_ioctl_ioctl(struct file *filp,
39 unsigned int cmd,
40 unsigned long arg)
41 {
42 struct test_ioctl_data *ioctl_data = filp->private_data;
43 int retval = 0;
44 unsigned char val;
45 struct ioctl_arg data;
46 memset(&data, 0, sizeof(data));
47
48 switch (cmd) {
49 case IOCTL_VALSET:
50 if (copy_from_user(&data, (int __user *) arg, sizeof(data))) {
51 retval = -EFAULT;
52 goto done;
53 }
54
55 pr_alert("IOCTL set val:%x .\n", data.val);
56 write_lock(&ioctl_data->lock);
57 ioctl_data->val = data.val;
58 write_unlock(&ioctl_data->lock);
59 break;
60
61 case IOCTL_VALGET:
62 read_lock(&ioctl_data->lock);
63 val = ioctl_data->val;
64 read_unlock(&ioctl_data->lock);
65 data.val = val;
0.9. TALKING TO DEVICE FILES 50
66
67 if (copy_to_user((int __user *) arg, &data, sizeof(data))) {
68 retval = -EFAULT;
69 goto done;
70 }
71
72 break;
73
74 case IOCTL_VALGET_NUM:
75 retval = __put_user(ioctl_num, (int __user *) arg);
76 break;
77
78 case IOCTL_VALSET_NUM:
79 ioctl_num = arg;
80 break;
81
82 default:
83 retval = -ENOTTY;
84 }
85
86 done:
87 return retval;
88 }
89
90 ssize_t test_ioctl_read(struct file *filp,
91 char __user *buf,
92 size_t count,
93 loff_t *f_pos)
94 {
95 struct test_ioctl_data *ioctl_data = filp->private_data;
96 unsigned char val;
97 int retval;
98 int i = 0;
99 read_lock(&ioctl_data->lock);
100 val = ioctl_data->val;
101 read_unlock(&ioctl_data->lock);
102
103 for (; i < count; i++) {
104 if (copy_to_user(&buf[i], &val, 1)) {
105 retval = -EFAULT;
106 goto out;
107 }
108 }
109
110 retval = count;
111 out:
112 return retval;
113 }
114
115 static int test_ioctl_close(struct inode *inode, struct file *filp)
116 {
117 pr_alert("%s call.\n", __func__);
118
119 if (filp->private_data) {
120 kfree(filp->private_data);
121 filp->private_data = NULL;
122 }
0.9. TALKING TO DEVICE FILES 51
123
124 return 0;
125 }
126
127 static int test_ioctl_open(struct inode *inode, struct file *filp)
128 {
129 struct test_ioctl_data *ioctl_data;
130 pr_alert("%s call.\n", __func__);
131 ioctl_data = kmalloc(sizeof(struct test_ioctl_data), GFP_KERNEL);
132
133 if (ioctl_data == NULL) {
134 return -ENOMEM;
135 }
136
137 rwlock_init(&ioctl_data->lock);
138 ioctl_data->val = 0xFF;
139 filp->private_data = ioctl_data;
140 return 0;
141 }
142
143 struct file_operations fops = {
144 .owner = THIS_MODULE,
145 .open = test_ioctl_open,
146 .release = test_ioctl_close,
147 .read = test_ioctl_read,
148 .unlocked_ioctl = test_ioctl_ioctl,
149 };
150
151 static int ioctl_init(void)
152 {
153 dev_t dev = MKDEV(test_ioctl_major, 0);
154 int alloc_ret = 0;
155 int cdev_ret = 0;
156 alloc_ret = alloc_chrdev_region(&dev, 0, num_of_dev, DRIVER_NAME);
157
158 if (alloc_ret) {
159 goto error;
160 }
161
162 test_ioctl_major = MAJOR(dev);
163 cdev_init(&test_ioctl_cdev, &fops);
164 cdev_ret = cdev_add(&test_ioctl_cdev, dev, num_of_dev);
165
166 if (cdev_ret) {
167 goto error;
168 }
169
170 pr_alert("%s driver(major: %d) installed.\n", DRIVER_NAME,
171 test_ioctl_major);
172 return 0;
173 error:
174
175 if (cdev_ret == 0) {
176 cdev_del(&test_ioctl_cdev);
177 }
178
179 if (alloc_ret == 0) {
0.10. SYSTEM CALLS 52
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.
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_open. 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
open() 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 open system call will be
A_open and B’s will be B_open. Now, when A is inserted into the kernel, the
system call is replaced with A_open, which will call the original sys_open when
it is done. Next, B is inserted into the kernel, which replaces the system call
with B_open, which will call what it thinks is the original system call, A_open,
when it’s done.
Now, if B is removed first, everything will be well — it will simply restore
the system call to A_open, 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_open, 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_open, 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
0.10. SYSTEM CALLS 54
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_open so that it is
no longer pointing to A_open, so it will not restore it to sys_open before it is
removed from memory. Unfortunately, B_open will still try to call A_open which
is no longer there, so that even without removing B the system would crash.
Note that all the related problems make syscall stealing unfeasible for pro-
duction use. In order to keep people from doing potential harmful things
sys_call_table is no longer exported. This means, if you want to do some-
thing 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. In the example di-
rectory you will find a README and the patch. As you can imagine, such
modifications are not to be taken lightly. Do not try this on valuable systems
(ie systems that you do not own - or cannot restore easily). You will need to
get the complete sourcecode of this guide as a tarball in order to get the patch
and the README. Depending on your kernel version, you might even need to
hand apply the patch.
1 /*
2 * syscall.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 * Based on example by Peter Jay Salzman and
10 * https://bbs.archlinux.org/viewtopic.php?id=139406
11 */
12
13 #include <linux/delay.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/moduleparam.h> /* which will have params */
17 #include <linux/unistd.h> /* The list of system calls */
18 #include <linux/version.h>
19
20 /* For the current (process) structure, we need this to know who the
21 * current user is.
22 */
23 #include <linux/sched.h>
24 #include <linux/uaccess.h>
25
26 /* The in-kernel calls to the ksys_close() syscall were removed in Linux
,→ v5.11+.
27 */
28 #if (LINUX_VERSION_CODE < KERNEL_VERSION(5, 11, 0))
29 #include <linux/syscalls.h> /* ksys_close() wrapper for backward compatibility
,→ */
30 #define close_fd ksys_close
31 #else
32 #include <linux/fdtable.h> /* For close_fd */
33 #endif
34
0.10. SYSTEM CALLS 55
1 tail -f
This function changes the status of the task (a task is the kernel data struc-
ture 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 mech-
anism 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
module_interruptible_sleep_on.
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, while trying
to access it with another process (again in the background, so that we need not
switch to a different vt). 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
0.11. BLOCKING PROCESSES AND THREADS 58
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/kernel.h> /*
We're 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/sched.h> /*
For putting processes to sleep and
10 waking them up */
11 #include <linux/uaccess.h> /* for get_user and put_user */
12 #include <linux/version.h>
13
14 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 6, 0)
0.11. BLOCKING PROCESSES AND THREADS 59
15 #define HAVE_PROC_OPS
16 #endif
17
18 /* Here we keep the last message received, to prove that we can process our
19 * input.
20 */
21 #define MESSAGE_LENGTH 80
22 static char Message[MESSAGE_LENGTH];
23
24 static struct proc_dir_entry *Our_Proc_File;
25 #define PROC_ENTRY_FILENAME "sleep"
26
27 /* Since we use the file operations struct, we can't use the special proc
28 * output provisions - we have to use a standard read function, which is this
29 * function.
30 */
31 static ssize_t module_output(struct file *file, /* see include/linux/fs.h */
32 char *buf, /* The buffer to put data to
33 (in the user segment) */
34 size_t len, /* The length of the buffer */
35 loff_t *offset)
36 {
37 static int finished = 0;
38 int i;
39 char message[MESSAGE_LENGTH + 30];
40
41 /* Return 0 to signify end of file - that we have nothing more to say
42 * at this point.
43 */
44 if (finished) {
45 finished = 0;
46 return 0;
47 }
48
49 sprintf(message, "Last input:%s\n", Message);
50 for (i = 0; i < len && message[i]; i++)
51 put_user(message[i], buf + i);
52
53 finished = 1;
54 return i; /* Return the number of bytes "read" */
55 }
56
57 /* This function receives input from the user when the user writes to the
58 * /proc file.
59 */
60 static ssize_t module_input(struct file *file, /* The file itself */
61 const char *buf, /* The buffer with input */
62 size_t length, /* The buffer's length */
63 loff_t *offset) /* offset to file - ignore */
64 {
65 int i;
66
67 /* Put the input into Message, where module_output will later be able
68 * to use it.
69 */
70 for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++)
71 get_user(Message[i], buf + i);
0.11. BLOCKING PROCESSES AND THREADS 60
185 #endif
186
187 /* Initialize the module - register the proc file */
188 static int __init sleep_init(void)
189 {
190 Our_Proc_File =
191 proc_create(PROC_ENTRY_FILENAME, 0644, NULL,
,→ &File_Ops_4_Our_Proc_File);
192 if (Our_Proc_File == NULL) {
193 remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
194 pr_debug("Error: Could not initialize /proc/%s\n",
,→ PROC_ENTRY_FILENAME);
195 return -ENOMEM;
196 }
197 proc_set_size(Our_Proc_File, 80);
198 proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
199
200 pr_info("/proc/%s created\n", PROC_ENTRY_FILENAME);
201
202 return 0;
203 }
204
205 /* Cleanup - unregister our file from /proc. This could get dangerous if
206 * there are still processes waiting in WaitQ, because they are inside our
207 * open function, which will get unloaded. I'll explain how to avoid removal
208 * of a kernel module in such a case in chapter 10.
209 */
210 static void __exit sleep_exit(void)
211 {
212 remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
213 pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME);
214 }
215
216 module_init(sleep_init);
217 module_exit(sleep_exit);
218
219 MODULE_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
13 int 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
0.11. BLOCKING PROCESSES AND THREADS 63
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(-1);
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(-1);
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(-1);
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 return 0;
59 }
0.11.2 Completions
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.
In the following example two threads are started, but one needs to start
before another.
1 /*
2 * completions.c
3 */
4 #include <linux/completion.h>
0.11. BLOCKING PROCESSES AND THREADS 64
5 #include <linux/init.h>
6 #include <linux/kernel.h>
7 #include <linux/kthread.h>
8 #include <linux/module.h>
9
10 static struct {
11 struct completion crank_comp;
12 struct completion flywheel_comp;
13 } machine;
14
15 static int machine_crank_thread(void *arg)
16 {
17 pr_info("Turn the crank\n");
18
19 complete_all(&machine.crank_comp);
20 complete_and_exit(&machine.crank_comp, 0);
21 }
22
23 static int machine_flywheel_spinup_thread(void *arg)
24 {
25 wait_for_completion(&machine.crank_comp);
26
27 pr_info("Flywheel spins up\n");
28
29 complete_all(&machine.flywheel_comp);
30 complete_and_exit(&machine.flywheel_comp, 0);
31 }
32
33 static int completions_init(void)
34 {
35 struct task_struct *crank_thread;
36 struct task_struct *flywheel_thread;
37
38 pr_info("completions example\n");
39
40 init_completion(&machine.crank_comp);
41 init_completion(&machine.flywheel_comp);
42
43 crank_thread = kthread_create(machine_crank_thread, NULL, "KThread
,→ Crank");
44 if (IS_ERR(crank_thread))
45 goto ERROR_THREAD_1;
46
47 flywheel_thread = kthread_create(machine_flywheel_spinup_thread, NULL,
48 "KThread Flywheel");
49 if (IS_ERR(flywheel_thread))
50 goto ERROR_THREAD_2;
51
52 wake_up_process(flywheel_thread);
53 wake_up_process(crank_thread);
54
55 return 0;
56
57 ERROR_THREAD_2:
58 kthread_stop(crank_thread);
59 ERROR_THREAD_1:
60
0.12. AVOIDING COLLISIONS AND DEADLOCKS 65
61 return -1;
62 }
63
64 void completions_exit(void)
65 {
66 wait_for_completion(&machine.crank_comp);
67 wait_for_completion(&machine.flywheel_comp);
68
69 pr_info("completions exit\n");
70 }
71
72 module_init(completions_init);
73 module_exit(completions_exit);
74
75 MODULE_DESCRIPTION("Completions example");
76 MODULE_LICENSE("GPL");
The machine structure stores the completion states for the two 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.
So even though flywheel_thread is started first you should notice if you
load this module and run dmesg that turning the crank always happens first
because the flywheel thread waits for it to complete.
There are other variations upon 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.
0.12.1 Mutex
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.
1 /*
2 * example_mutex.c
3 */
4 #include <linux/init.h>
5 #include <linux/kernel.h>
6 #include <linux/module.h>
7 #include <linux/mutex.h>
0.12. AVOIDING COLLISIONS AND DEADLOCKS 66
8
9 DEFINE_MUTEX(mymutex);
10
11 static int example_mutex_init(void)
12 {
13 int ret;
14
15 pr_info("example_mutex init\n");
16
17 ret = mutex_trylock(&mymutex);
18 if (ret != 0) {
19 pr_info("mutex is locked\n");
20
21 if (mutex_is_locked(&mymutex) == 0)
22 pr_info("The mutex failed to lock!\n");
23
24 mutex_unlock(&mymutex);
25 pr_info("mutex is unlocked\n");
26 } else
27 pr_info("Failed to lock\n");
28
29 return 0;
30 }
31
32 static void example_mutex_exit(void)
33 {
34 pr_info("example_mutex exit\n");
35 }
36
37 module_init(example_mutex_init);
38 module_exit(example_mutex_exit);
39
40 MODULE_DESCRIPTION("Mutex example");
41 MODULE_LICENSE("GPL");
0.12.2 Spinlocks
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/interrupt.h>
6 #include <linux/kernel.h>
7 #include <linux/module.h>
0.12. AVOIDING COLLISIONS AND DEADLOCKS 67
8 #include <linux/spinlock.h>
9
10 DEFINE_SPINLOCK(sl_static);
11 spinlock_t sl_dynamic;
12
13 static void example_spinlock_static(void)
14 {
15 unsigned long flags;
16
17 spin_lock_irqsave(&sl_static, flags);
18 pr_info("Locked static spinlock\n");
19
20 /* Do something or other safely. Because this uses 100% CPU time, this
21 * code should take no more than a few milliseconds to run.
22 */
23
24 spin_unlock_irqrestore(&sl_static, flags);
25 pr_info("Unlocked static spinlock\n");
26 }
27
28 static void example_spinlock_dynamic(void)
29 {
30 unsigned long flags;
31
32 spin_lock_init(&sl_dynamic);
33 spin_lock_irqsave(&sl_dynamic, flags);
34 pr_info("Locked dynamic spinlock\n");
35
36 /* Do something or other safely. Because this uses 100% CPU time, this
37 * code should take no more than a few milliseconds to run.
38 */
39
40 spin_unlock_irqrestore(&sl_dynamic, flags);
41 pr_info("Unlocked dynamic spinlock\n");
42 }
43
44 static int example_spinlock_init(void)
45 {
46 pr_info("example spinlock started\n");
47
48 example_spinlock_static();
49 example_spinlock_dynamic();
50
51 return 0;
52 }
53
54 static void example_spinlock_exit(void)
55 {
56 pr_info("example spinlock exit\n");
57 }
58
59 module_init(example_spinlock_init);
60 module_exit(example_spinlock_exit);
61
62 MODULE_DESCRIPTION("Spinlock example");
63 MODULE_LICENSE("GPL");
0.12. AVOIDING COLLISIONS AND DEADLOCKS 68
1 /*
2 * example_rwlock.c
3 */
4 #include <linux/interrupt.h>
5 #include <linux/kernel.h>
6 #include <linux/module.h>
7
8 DEFINE_RWLOCK(myrwlock);
9
10 static 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
23 static 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
36 static int 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 }
0.12. AVOIDING COLLISIONS AND DEADLOCKS 69
45
46 static void example_rwlock_exit(void)
47 {
48 pr_info("example_rwlock exit\n");
49 }
50
51 module_init(example_rwlock_init);
52 module_exit(example_rwlock_exit);
53
54 MODULE_DESCRIPTION("Read/Write locks example");
55 MODULE_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.
1 /*
2 * example_atomic.c
3 */
4 #include <linux/interrupt.h>
5 #include <linux/kernel.h>
6 #include <linux/module.h>
7
8 #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c"
9 #define BYTE_TO_BINARY(byte) \
10 (byte & 0x80 ? '1' : '0'), (byte & 0x40 ? '1' : '0'), \
11 (byte & 0x20 ? '1' : '0'), (byte & 0x10 ? '1' : '0'), \
12 (byte & 0x08 ? '1' : '0'), (byte & 0x04 ? '1' : '0'), \
13 (byte & 0x02 ? '1' : '0'), (byte & 0x01 ? '1' : '0')
14
15 static void atomic_add_subtract(void)
16 {
17 atomic_t debbie;
18 atomic_t chris = ATOMIC_INIT(50);
19
20 atomic_set(&debbie, 45);
21
22 /* subtract one */
23 atomic_dec(&debbie);
24
25 atomic_add(7, &debbie);
26
27 /* add one */
0.13. REPLACING PRINT MACROS 70
28 atomic_inc(&debbie);
29
30 pr_info("chris: %d, debbie: %d\n", atomic_read(&chris),
31 atomic_read(&debbie));
32 }
33
34 static void atomic_bitwise(void)
35 {
36 unsigned long word = 0;
37
38 pr_info("Bits 0: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
39 set_bit(3, &word);
40 set_bit(5, &word);
41 pr_info("Bits 1: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
42 clear_bit(5, &word);
43 pr_info("Bits 2: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
44 change_bit(3, &word);
45
46 pr_info("Bits 3: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
47 if (test_and_set_bit(3, &word))
48 pr_info("wrong\n");
49 pr_info("Bits 4: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
50
51 word = 255;
52 pr_info("Bits 5: " BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
53 }
54
55 static int example_atomic_init(void)
56 {
57 pr_info("example_atomic started\n");
58
59 atomic_add_subtract();
60 atomic_bitwise();
61
62 return 0;
63 }
64
65 static void example_atomic_exit(void)
66 {
67 pr_info("example_atomic exit\n");
68 }
69
70 module_init(example_atomic_init);
71 module_exit(example_atomic_exit);
72
73 MODULE_DESCRIPTION("Atomic operations example");
74 MODULE_LICENSE("GPL");
want to be able to send messages to whichever tty the command to load the
module came from.
"tty" is an abbreviation of teletype: originally a combination keyboard-
printer used to communicate with a Unix system, and today an abstraction
for the text stream used for a Unix program, whether it is a physical terminal,
an xterm on an X display, a network connection used with ssh, etc.
The way this is done is by using current, a pointer to the currently running
task, to get the current task’s tty structure. Then, we look inside that tty
structure to find a pointer to a string write function, which we use to write a
string 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
12 static void print_string(char *str)
13 {
14 struct tty_struct *my_tty;
15 const struct tty_operations *ttyops;
16
17 /* The tty for the current task, for 2.6.6+ kernels */
18 my_tty = get_current_tty();
19 ttyops = my_tty->driver->ops;
20
21 /* If my_tty is NULL, the current task has no tty you can print to (i.e.,
22 * if it is a daemon). If so, there is nothing we can do.
23 */
24 if (my_tty) {
25 /* my_tty->driver is a struct which holds the tty's functions,
26 * one of which (write) is used to write strings to the tty.
27 * It can be used to take a string either from the user's or
28 * kernel's memory segment.
29 *
30 * The function's 1st parameter is the tty to write to, because the
31 * same function would normally be used for all tty's of a certain
32 * type.
33 * The 2nd parameter is a pointer to a string.
34 * The 3rd parameter is the length of the string.
35 *
36 * As you will see below, sometimes it's necessary to use
37 * preprocessor stuff to create code that works for different
38 * kernel versions. The (naive) approach we've taken here does not
39 * scale well. The right way to deal with this is described in
40 * section 2 of
41 * linux/Documentation/SubmittingPatches
42 */
43 (ttyops->write)(my_tty, /* The tty itself */
44 str, /* String */
0.13. REPLACING PRINT MACROS 72
45 strlen(str)); /* Length */
46
47 /* ttys were originally hardware devices, which (usually) strictly
48 * followed the ASCII standard. In ASCII, to move to a new line you
49 * need two characters, a carriage return and a line feed. On Unix,
50 * the ASCII line feed is used for both purposes - so we can not
51 * just use \n, because it would not have a carriage return and the
52 * next line will start at the column right after the line feed.
53 *
54 * This is why text files are different between Unix and MS Windows.
55 * In CP/M and derivatives, like MS-DOS and MS Windows, the ASCII
56 * standard was strictly adhered to, and therefore a newline requirs
57 * both a LF and a CR.
58 */
59 (ttyops->write)(my_tty, "\015\012", 2);
60 }
61 }
62
63 static int __init print_string_init(void)
64 {
65 print_string("The module has been inserted. Hello world!");
66 return 0;
67 }
68
69 static void __exit print_string_exit(void)
70 {
71 print_string("The module has been removed. Farewell world!");
72 }
73
74 module_init(print_string_init);
75 module_exit(print_string_exit);
76
77 MODULE_LICENSE("GPL");
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/tty.h> /* For fg_console, MAX_NR_CONSOLES */
0.13. REPLACING PRINT MACROS 73
9 #include <linux/vt.h>
10 #include <linux/vt_kern.h> /* for fg_console */
11
12 #include <linux/console_struct.h> /* For vc_cons */
13
14 MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs.");
15
16 struct timer_list my_timer;
17 struct tty_driver *my_driver;
18 char 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 */
35
36 static void my_timer_func(unsigned long ptr)
37 {
38 unsigned long *pstatus = (unsigned long *) ptr;
39 struct tty_struct *t = vc_cons[fg_console].d->port.tty;
40
41 if (*pstatus == ALL_LEDS_ON)
42 *pstatus = RESTORE_LEDS;
43 else
44 *pstatus = ALL_LEDS_ON;
45
46 (my_driver->ops->ioctl)(t, KDSETLED, *pstatus);
47
48 my_timer.expires = jiffies + BLINK_DELAY;
49 add_timer(&my_timer);
50 }
51
52 static int __init kbleds_init(void)
53 {
54 int i;
55
56 pr_info("kbleds: loading\n");
57 pr_info("kbleds: fgconsole is %x\n", fg_console);
58 for (i = 0; i < MAX_NR_CONSOLES; i++) {
59 if (!vc_cons[i].d)
60 break;
61 pr_info("poet_atkm: console[%i/%i] #%i, tty %lx\n", i,
,→ MAX_NR_CONSOLES,
62 vc_cons[i].d->vc_num, (unsigned long) vc_cons[i].d->port.tty);
63 }
0.14. SCHEDULING TASKS 74
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_LL_DEBUG 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.c or any other essential syscall to print ASCII characters,
thus making it possible to trace virtually everything what 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
dissappear. Thus you should try to keep debug code to a minimum and make
sure it does not show up in production code.
0.14.1 Tasklets
Here is an example tasklet module. The tasklet_fn function runs for a few
seconds and in the mean time execution of the example_tasklet_init function
continues to the exit point.
1 /*
2 * example_tasklet.c
3 */
4 #include <linux/delay.h>
5 #include <linux/interrupt.h>
6 #include <linux/kernel.h>
7 #include <linux/module.h>
8
9 /* Macro DECLARE_TASKLET_OLD exists for compatibiity.
10 * See https://lwn.net/Articles/830964/
11 */
12 #ifndef DECLARE_TASKLET_OLD
13 #define DECLARE_TASKLET_OLD(arg1, arg2) DECLARE_TASKLET(arg1, arg2, 0L)
14 #endif
15
16 static void tasklet_fn(unsigned long data)
17 {
18 pr_info("Example tasklet starts\n");
19 mdelay(5000);
20 pr_info("Example tasklet ends\n");
21 }
22
23 DECLARE_TASKLET_OLD(mytask, tasklet_fn);
24
25 static int example_tasklet_init(void)
26 {
27 pr_info("tasklet example init\n");
28 tasklet_schedule(&mytask);
29 mdelay(200);
30 pr_info("Example tasklet init continues...\n");
31 return 0;
32 }
33
34 static void example_tasklet_exit(void)
35 {
36 pr_info("tasklet example exit\n");
37 tasklet_kill(&mytask);
38 }
39
40 module_init(example_tasklet_init);
41 module_exit(example_tasklet_exit);
42
43 MODULE_DESCRIPTION("Tasklet example");
44 MODULE_LICENSE("GPL");
Although tasklet is easy to use, it comes with several defators, and developers
are discussing about getting rid of tasklet in linux kernel. The tasklet callback
runs in atomic context, inside a software interrupt, meaning that it cannot sleep
or access user-space data, so not all work can be done in a tasklet handler. Also,
the kernel only allows one instance of any given tasklet to be running at any
given time; multiple different tasklet callbacks can run in parallel.
In recent kernels, tasklets can be replaced by workqueues, timers, or threaded
interrupts.1 While the removal of tasklets remains a longer-term goal, the cur-
rent kernel contains more than a hundred uses of tasklets. Now developers are
proceeding with the API changes and the macro DECLARE_TASKLET_OLD exists
for compatibiity. For further information, see https://lwn.net/Articles/
830964/.
1 /*
2 * sched.c
3 */
4 #include <linux/init.h>
5 #include <linux/module.h>
6 #include <linux/workqueue.h>
7
8 static struct workqueue_struct *queue = NULL;
9 static struct work_struct work;
10
11 static void work_handler(struct work_struct *data)
12 {
13 pr_info("work handler function.\n");
14 }
15
16 static int __init sched_init(void)
17 {
18 queue = alloc_workqueue("HELLOWORLD", WQ_UNBOUND, 1);
19 INIT_WORK(&work, work_handler);
20 schedule_work(&work);
21
22 return 0;
23 }
24
25 static void __exit sched_exit(void)
26 {
27 destroy_workqueue(queue);
1 The goal of threaded interrupts is to push more of the work to separate threads, so that
the minimum needed for acknowledging an interrupt is reduced, and therefore the time spent
handling the interrupt (where it can’t handle any other interrupts at the same time) is reduced.
See https://lwn.net/Articles/302043/
0.15. INTERRUPT HANDLERS 77
28 }
29
30 module_init(sched_init);
31 module_exit(sched_exit);
32
33 MODULE_LICENSE("GPL");
34 MODULE_DESCRIPTION("Workqueue example");
1 /*
2 * intrpt.c - Handling GPIO with interrupts
3 *
4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de)
5 * from:
6 * https://github.com/wendlers/rpi-kmod-samples
7 *
8 * Press one button to turn on a LED and another to turn it off.
9 */
10
11 #include <linux/gpio.h>
12 #include <linux/interrupt.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15
16 static int button_irqs[] = {-1, -1};
17
0.15. INTERRUPT HANDLERS 79
1 /*
2 * bottomhalf.c - Top and bottom half interrupt handling
3 *
4 * Based upon the RPi example by Stefan Wendler (devnull@kaltpost.de)
5 * from:
6 * https://github.com/wendlers/rpi-kmod-samples
7 *
8 * Press one button to turn on a LED and another to turn it off
9 */
10
11 #include <linux/delay.h>
12 #include <linux/gpio.h>
13 #include <linux/interrupt.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16
17 /* Macro DECLARE_TASKLET_OLD exists for compatibiity.
18 * See https://lwn.net/Articles/830964/
19 */
20 #ifndef DECLARE_TASKLET_OLD
21 #define DECLARE_TASKLET_OLD(arg1, arg2) DECLARE_TASKLET(arg1, arg2, 0L)
22 #endif
23
24 static int button_irqs[] = {-1, -1};
25
26 /* Define GPIOs for LEDs.
27 * TODO: Change the numbers for the GPIO on your board.
28 */
29 static struct gpio leds[] = {{4, GPIOF_OUT_INIT_LOW, "LED 1"}};
30
0.15. INTERRUPT HANDLERS 82
88
89 ret = gpio_to_irq(buttons[0].gpio);
90
91 if (ret < 0) {
92 pr_err("Unable to request IRQ: %d\n", ret);
93 goto fail2;
94 }
95
96 button_irqs[0] = ret;
97
98 pr_info("Successfully requested BUTTON1 IRQ # %d\n", button_irqs[0]);
99
100 ret = request_irq(button_irqs[0], button_isr,
101 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
102 "gpiomod#button1", NULL);
103
104 if (ret) {
105 pr_err("Unable to request IRQ: %d\n", ret);
106 goto fail2;
107 }
108
109
110 ret = gpio_to_irq(buttons[1].gpio);
111
112 if (ret < 0) {
113 pr_err("Unable to request IRQ: %d\n", ret);
114 goto fail2;
115 }
116
117 button_irqs[1] = ret;
118
119 pr_info("Successfully requested BUTTON2 IRQ # %d\n", button_irqs[1]);
120
121 ret = request_irq(button_irqs[1], button_isr,
122 IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING,
123 "gpiomod#button2", NULL);
124
125 if (ret) {
126 pr_err("Unable to request IRQ: %d\n", ret);
127 goto fail3;
128 }
129
130 return 0;
131
132 /* cleanup what has been setup so far */
133 fail3:
134 free_irq(button_irqs[0], NULL);
135
136 fail2:
137 gpio_free_array(buttons, ARRAY_SIZE(leds));
138
139 fail1:
140 gpio_free_array(leds, ARRAY_SIZE(leds));
141
142 return ret;
143 }
144
0.16. CRYPTO 84
0.16 Crypto
At the dawn of the internet, everybody trusted everybody completely. . . but
that did not work out so well. When this guide was originally written, it was a
more innocent era in which almost nobody actually gave a damn about crypto
- least of all kernel developers. That is certainly no longer the case now. To
handle crypto stuff, the kernel has its own API enabling common methods of
encryption, decryption and your favourite hash functions.
1 /*
2 * cryptosha256.c
3 */
4 #include <crypto/internal/hash.h>
5 #include <linux/module.h>
6
7 #define SHA256_LENGTH 32
8
9 static void show_hash_result(char *plaintext, char *hash_sha256)
10 {
11 int i;
12 char str[SHA256_LENGTH * 2 + 1];
13
0.16. CRYPTO 85
1 make
2 sudo insmod cryptosha256.ko
0.16. CRYPTO 86
3 dmesg
And you should see that the hash was calculated for the test string.
Finally, remove the test module:
1 /*
2 * cryptosk.c
3 */
4 #include <crypto/internal/skcipher.h>
5 #include <linux/crypto.h>
6 #include <linux/module.h>
7 #include <linux/random.h>
8 #include <linux/scatterlist.h>
9
10 #define SYMMETRIC_KEY_LENGTH 32
11 #define CIPHER_BLOCK_SIZE 16
12
13 struct tcrypt_result {
14 struct completion completion;
15 int err;
16 };
17
18 struct skcipher_def {
19 struct scatterlist sg;
20 struct crypto_skcipher *tfm;
21 struct skcipher_request *req;
22 struct tcrypt_result result;
23 char *scratchpad;
24 char *ciphertext;
25 char *ivdata;
26 };
27
28 static struct skcipher_def sk;
29
30 static void test_skcipher_finish(struct skcipher_def *sk)
31 {
32 if (sk->tfm)
33 crypto_free_skcipher(sk->tfm);
34 if (sk->req)
35 skcipher_request_free(sk->req);
36 if (sk->ivdata)
37 kfree(sk->ivdata);
38 if (sk->scratchpad)
39 kfree(sk->scratchpad);
40 if (sk->ciphertext)
0.16. CRYPTO 87
41 kfree(sk->ciphertext);
42 }
43
44 static int test_skcipher_result(struct skcipher_def *sk, int rc)
45 {
46 switch (rc) {
47 case 0:
48 break;
49 case -EINPROGRESS || -EBUSY:
50 rc = wait_for_completion_interruptible(&sk->result.completion);
51 if (!rc && !sk->result.err) {
52 reinit_completion(&sk->result.completion);
53 break;
54 }
55 pr_info("skcipher encrypt returned with %d result %d\n", rc,
56 sk->result.err);
57 break;
58 default:
59 pr_info("skcipher encrypt returned with %d result %d\n", rc,
60 sk->result.err);
61 break;
62 }
63
64 init_completion(&sk->result.completion);
65
66 return rc;
67 }
68
69 static void test_skcipher_callback(struct crypto_async_request *req, int
,→ error)
70 {
71 struct tcrypt_result *result = req->data;
72
73 if (error == -EINPROGRESS)
74 return;
75
76 result->err = error;
77 complete(&result->completion);
78 pr_info("Encryption finished successfully\n");
79
80 /* decrypt data */
81 #if 0
82 memset((void*)sk.scratchpad, '-', CIPHER_BLOCK_SIZE);
83 ret = crypto_skcipher_decrypt(sk.req);
84 ret = test_skcipher_result(&sk, ret);
85 if (ret)
86 return;
87
88 sg_copy_from_buffer(&sk.sg, 1, sk.scratchpad, CIPHER_BLOCK_SIZE);
89 sk.scratchpad[CIPHER_BLOCK_SIZE-1] = 0;
90
91 pr_info("Decryption request successful\n");
92 pr_info("Decrypted: %s\n", sk.scratchpad);
93 #endif
94 }
95
96 static int test_skcipher_encrypt(char *plaintext,
0.16. CRYPTO 88
97 char *password,
98 struct skcipher_def *sk)
99 {
100 int ret = -EFAULT;
101 unsigned char key[SYMMETRIC_KEY_LENGTH];
102
103 if (!sk->tfm) {
104 sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0);
105 if (IS_ERR(sk->tfm)) {
106 pr_info("could not allocate skcipher handle\n");
107 return PTR_ERR(sk->tfm);
108 }
109 }
110
111 if (!sk->req) {
112 sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL);
113 if (!sk->req) {
114 pr_info("could not allocate skcipher request\n");
115 ret = -ENOMEM;
116 goto out;
117 }
118 }
119
120 skcipher_request_set_callback(sk->req, CRYPTO_TFM_REQ_MAY_BACKLOG,
121 test_skcipher_callback, &sk->result);
122
123 /* clear the key */
124 memset((void *) key, '\0', SYMMETRIC_KEY_LENGTH);
125
126 /* Use the world's favourite password */
127 sprintf((char *) key, "%s", password);
128
129 /* AES 256 with given symmetric key */
130 if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) {
131 pr_info("key could not be set\n");
132 ret = -EAGAIN;
133 goto out;
134 }
135 pr_info("Symmetric key: %s\n", key);
136 pr_info("Plaintext: %s\n", plaintext);
137
138 if (!sk->ivdata) {
139 /* see https://en.wikipedia.org/wiki/Initialization_vector */
140 sk->ivdata = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
141 if (!sk->ivdata) {
142 pr_info("could not allocate ivdata\n");
143 goto out;
144 }
145 get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE);
146 }
147
148 if (!sk->scratchpad) {
149 /* The text to be encrypted */
150 sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
151 if (!sk->scratchpad) {
152 pr_info("could not allocate scratchpad\n");
153 goto out;
0.17. STANDARDIZING THE INTERFACES: THE DEVICE MODEL 89
154 }
155 }
156 sprintf((char *) sk->scratchpad, "%s", plaintext);
157
158 sg_init_one(&sk->sg, sk->scratchpad, CIPHER_BLOCK_SIZE);
159 skcipher_request_set_crypt(sk->req, &sk->sg, &sk->sg, CIPHER_BLOCK_SIZE,
160 sk->ivdata);
161 init_completion(&sk->result.completion);
162
163 /* encrypt data */
164 ret = crypto_skcipher_encrypt(sk->req);
165 ret = test_skcipher_result(sk, ret);
166 if (ret)
167 goto out;
168
169 pr_info("Encryption request successful\n");
170
171 out:
172 return ret;
173 }
174
175 int cryptoapi_init(void)
176 {
177 /* The world's favorite password */
178 char *password = "password123";
179
180 sk.tfm = NULL;
181 sk.req = NULL;
182 sk.scratchpad = NULL;
183 sk.ciphertext = NULL;
184 sk.ivdata = NULL;
185
186 test_skcipher_encrypt("Testing", password, &sk);
187 return 0;
188 }
189
190 void cryptoapi_exit(void)
191 {
192 test_skcipher_finish(&sk);
193 }
194
195 module_init(cryptoapi_init);
196 module_exit(cryptoapi_exit);
197
198 MODULE_DESCRIPTION("Symmetric key encryption example");
199 MODULE_LICENSE("GPL");
start, suspend and resume a device a device model was added. An example
is shown below, and you can use this as a template to add your own suspend,
resume or other interface functions.
1 /*
2 * devicemodel.c
3 */
4 #include <linux/kernel.h>
5 #include <linux/module.h>
6 #include <linux/platform_device.h>
7
8 struct devicemodel_data {
9 char *greeting;
10 int number;
11 };
12
13 static int devicemodel_probe(struct platform_device *dev)
14 {
15 struct devicemodel_data *pd =
16 (struct devicemodel_data *) (dev->dev.platform_data);
17
18 pr_info("devicemodel probe\n");
19 pr_info("devicemodel greeting: %s; %d\n", pd->greeting, pd->number);
20
21 /* Your device initialization code */
22
23 return 0;
24 }
25
26 static int devicemodel_remove(struct platform_device *dev)
27 {
28 pr_info("devicemodel example removed\n");
29
30 /* Your device removal code */
31
32 return 0;
33 }
34
35 static int devicemodel_suspend(struct device *dev)
36 {
37 pr_info("devicemodel example suspend\n");
38
39 /* Your device suspend code */
40
41 return 0;
42 }
43
44 static int devicemodel_resume(struct device *dev)
45 {
46 pr_info("devicemodel example resume\n");
47
48 /* Your device resume code */
49
50 return 0;
51 }
52
53 static const struct dev_pm_ops devicemodel_pm_ops = {
0.18. OPTIMIZATIONS 91
54 .suspend = devicemodel_suspend,
55 .resume = devicemodel_resume,
56 .poweroff = devicemodel_suspend,
57 .freeze = devicemodel_suspend,
58 .thaw = devicemodel_resume,
59 .restore = devicemodel_resume,
60 };
61
62 static struct platform_driver devicemodel_driver = {
63 .driver =
64 {
65 .name = "devicemodel_example",
66 .owner = THIS_MODULE,
67 .pm = &devicemodel_pm_ops,
68 },
69 .probe = devicemodel_probe,
70 .remove = devicemodel_remove,
71 };
72
73 static int devicemodel_init(void)
74 {
75 int ret;
76
77 pr_info("devicemodel init\n");
78
79 ret = platform_driver_register(&devicemodel_driver);
80
81 if (ret) {
82 pr_err("Unable to register driver\n");
83 return ret;
84 }
85
86 return 0;
87 }
88
89 static void devicemodel_exit(void)
90 {
91 pr_info("devicemodel exit\n");
92 platform_driver_unregister(&devicemodel_driver);
93 }
94
95 module_init(devicemodel_init);
96 module_exit(devicemodel_exit);
97
98 MODULE_LICENSE("GPL");
99 MODULE_DESCRIPTION("Linux Device Model example");
0.18 Optimizations
0.18.1 Likely and Unlikely conditions
Sometimes you might want your code to run as quickly as possible, especially
if it is handling an interrupt or doing something which might cause noticeable
latency. If your code contains boolean conditions and if you know that the
0.19. COMMON PITFALLS 92
conditions are almost always likely to evaluate as either true or false, then
you can allow the compiler to optimize for this using the likely and unlikely
macros. For example, when allocating memory you are almost always expecting
this to succeed.
When the unlikely macro is used, the compiler alters its machine instruc-
tion output, so that it continues along the false branch and only jumps if the
condition is true. That avoids flushing the processor pipeline. The opposite
happens if you use the likely macro.