diff --git a/4.12.12/LKMPG-4.12.12.html b/4.12.12/LKMPG-4.12.12.html index d552d99..edd0508 100644 --- a/4.12.12/LKMPG-4.12.12.html +++ b/4.12.12/LKMPG-4.12.12.html @@ -3,7 +3,7 @@ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- +The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 3.0.
@@ -401,18 +401,18 @@ If you publish or distribute this book commercially, donations, royalties, and/oThe 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 and later kernels, added the sysfs chapter and modified or updated other chapters.
The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch of the LKMPG for each new stable kernel version. So version LKMPG 4.12.x will address Linux kernel 4.12.x and LKMPG 2.6.x will address Linux kernel 2.6. No attempt will be made to archive historical information; a person wishing this information should read the appropriately versioned LKMPG.
@@ -423,18 +423,18 @@ The source code and discussions should apply to most architectures, but I can'tThe following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon, Horst Schirmeier, Bob Mottram and Roman Lakeev.
So, you want to write a kernel module. You know C, you've written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot.
@@ -445,9 +445,9 @@ What exactly is a kernel module? Modules are pieces of code that can be loaded aLinux distros provide the commands modprobe, insmod and depmod within a package.
@@ -457,8 +457,8 @@ On Debian:sudo apt-get install build-essential kmod
-
+sudo apt-get install build-essential kmod +
@@ -466,22 +466,22 @@ On Parabola:
sudo pacman -S gcc kmod
-
+sudo pacman -S gcc kmod +
To discover what modules are already loaded within your current kernel use the command lsmod.
sudo lsmod
-
+sudo lsmod +
@@ -489,8 +489,8 @@ Modules are stored within the file /proc/modules, so you can also see them with:
sudo cat /proc/modules
-
+sudo cat /proc/modules +
@@ -498,39 +498,39 @@ This can be a long list, and you might prefer to search for something particular
sudo lsmod | grep fat
-
+sudo lsmod | grep fat +
For the purposes of following this guide you don't necessarily need to do that. However, it would be wise to run the examples within a test distro running on a virtual machine in order to avoid any possibility of messing up your system.
Before we delve into code, there are a few issues we need to cover. Everyone's system is different and everyone has their own groove. Getting your first "hello world" program to compile and load correctly can sometimes be a trick. Rest assured, after you get over the initial hurdle of doing it for the first time, it will be smooth sailing thereafter.
A module compiled for one kernel won't load if you boot a different kernel unless you enable CONFIG_MODVERSIONS in the kernel. We won't go into module versioning until later in this guide. Until we cover modversions, the examples in the guide may not work if you're running a kernel with modversioning turned on. However, most stock Linux distro kernels come with it turned on. If you're having trouble loading the modules because of versioning errors, compile a kernel with modversioning turned off.
It is highly recommended that you type in, compile and load all the examples this guide discusses. It's also highly recommended you do this from a console. You should not be working on this stuff in X.
@@ -544,16 +544,16 @@ Modules can't print to the screen like printf() can, but they can log informatioBefore you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux:
sudo pacman -S linux-libre-headers
-
+sudo pacman -S linux-libre-headers +
@@ -561,9 +561,9 @@ On Debian:
sudo apt-get update
+sudo apt-get update
apt-cache search linux-headers-$(uname -r)
-
+
@@ -571,22 +571,22 @@ This will tell you what kernel header files are available. Then for example:
sudo apt-get install kmod linux-headers-4.12.12-1-amd64
-
+sudo apt-get install kmod linux-headers-4.12.12-1-amd64 +
All the examples from this document are available within the examples subdirectory. To test that they compile:
cd examples
+cd examples
make
-
+
@@ -594,13 +594,13 @@ If there are any compile errors then you might have a more recent kernel version
Most people learning programming start out with some sort of "hello world" example. I don't know what happens to people who break with this tradition, but I think it's safer not to find out. We'll start with a series of hello world programs that demonstrate the different aspects of the basics of writing a kernel module.
@@ -614,9 +614,9 @@ Make a test directory:mkdir -p ~/develop/kernel/hello-1
+mkdir -p ~/develop/kernel/hello-1
cd ~/develop/kernel/hello-1
-
+
@@ -624,7 +624,7 @@ Paste this into you favourite editor and save it as hello-1.c:
/*
+/*
* hello-1.c - The simplest kernel module.
*/
#include <linux/module.h> /* Needed by all modules */
@@ -632,7 +632,7 @@ Paste this into you favourite editor and save it as hello-1.c:
int init_module(void)
{
- printk(KERN_INFO "Hello world 1.\n");
+ pr_info("Hello world 1.\n");
/*
* A non 0 return means init_module failed; module can't be loaded.
@@ -642,9 +642,9 @@ Paste this into you favourite editor and save it as hello-1.c:
void cleanup_module(void)
{
- printk(KERN_INFO "Goodbye world 1.\n");
+ pr_info("Goodbye world 1.\n");
}
-
+
@@ -652,14 +652,14 @@ Now you'll need a Makefile. If you copy and paste this change the indentation to
obj-m += hello-1.o
+obj-m += hello-1.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
-
+
@@ -667,8 +667,8 @@ And finally just:
make
-
+make +
@@ -676,8 +676,8 @@ If all goes smoothly you should then find that you have a compiled hello-1.ko
sudo modinfo hello-1.ko
-
+sudo modinfo hello-1.ko +
@@ -685,8 +685,8 @@ At this point the command:
sudo lsmod | grep hello
-
+sudo lsmod | grep hello +
@@ -694,8 +694,8 @@ should return nothing. You can try loading your shiny new module with:
sudo insmod hello-1.ko
-
+sudo insmod hello-1.ko +
@@ -703,8 +703,8 @@ The dash character will get converted to an underscore, so when you again try:
sudo lsmod | grep hello
-
+sudo lsmod | grep hello +
@@ -712,8 +712,8 @@ you should now see your loaded module. It can be removed again with:
sudo rmmod hello_1
-
+sudo rmmod hello_1 +
@@ -721,8 +721,8 @@ Notice that the dash was replaced by an underscore. To see what just happened in
journalctl --since "1 hour ago" | grep kernel
-
+journalctl --since "1 hour ago" | grep kernel
+
@@ -739,36 +739,28 @@ Typically, init_module() either registers a handler for something with the kerne
-Lastly, every kernel module needs to include linux/module.h. We needed to include linux/kernel.h only for the macro expansion for the printk() log level, KERN_ALERT, which you'll learn about in Section 2.1.1. +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.1.
Another thing which may not be immediately obvious to anyone getting started with kernel programming is that indentation within your code should be using tabs and not spaces. It's 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.
-Despite what you might think, printk() was not meant to communicate information to the user, even though we used it for exactly this purpose in hello-1! It happens to be a logging mechanism for the kernel, and is used to log information or give warnings. Therefore, each printk() statement comes with a priority, which is the <1> and KERN_ALERT you see. There are 8 priorities and the kernel has macros for them, so you don't have to use cryptic numbers, and you can view them (and their meanings) in linux/kernel.h. If you don't specify a priority level, the default priority, DEFAULT_MESSAGE_LOGLEVEL, will be used. -
- --Take time to read through the priority macros. The header file also describes what each priority means. In practise, don't use number, like <4>. Always use the macro, like KERN_WARNING. -
- --If the priority is less than int console_loglevel, the message is printed on your current terminal. If both syslogd and klogd are running, then the message will also get appended to the systemd journal, whether it got printed to the console or not. We use a high priority, like KERN_ALERT, to make sure the printk() messages get printed to your console rather than just logged to the journal. When you write real modules, you'll want to use priorities that are meaningful for the situation at hand. +In the beginning there was printk, usually followed 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 keyboard bashing and looks a bit neater. They can be found within linux/printk.h. Take time to read through the available priority macros.
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. Although 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 the standard kernel build mechanism. To learn more on how to compile modules which are not part of the official kernel (such as all the examples you'll find in this guide), see file linux/Documentation/kbuild/modules.txt.
@@ -787,15 +779,15 @@ Here's another exercise for the reader. See that comment above the return statemIn early kernel versions you had to use the init_module and cleanup_module functions, as in the first hello world example, but these days you can name those anything you want by using the module_init and module_exit macros. These macros are defined in linux/init.h. The only requirement is that your init and cleanup functions must be defined before calling the those macros, otherwise you'll get compilation errors. Here's an example of this technique:
/*
+/*
* hello-2.c - Demonstrating the module_init() and module_exit() macros.
* This is preferred over using init_module() and cleanup_module().
*/
@@ -805,18 +797,18 @@ In early kernel versions you had to use the init_module and cleanup_mo
static int __init hello_2_init(void)
{
- printk(KERN_INFO "Hello, world 2\n");
+ pr_info("Hello, world 2\n");
return 0;
}
static void __exit hello_2_exit(void)
{
- printk(KERN_INFO "Goodbye, world 2\n");
+ pr_info("Goodbye, world 2\n");
}
module_init(hello_2_init);
module_exit(hello_2_exit);
-
+
@@ -824,7 +816,7 @@ So now we have two real kernel modules under our belt. Adding another module is
obj-m += hello-1.o
+obj-m += hello-1.o
obj-m += hello-2.o
all:
@@ -832,7 +824,7 @@ So now we have two real kernel modules under our belt. Adding another module is
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
-
+
@@ -841,9 +833,9 @@ Now have a look at linux/drivers/char/Makefile for a real world example. As you
This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The __init macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers, but not loadable modules. If you think about when the init function is invoked, this makes perfect sense.
@@ -861,7 +853,7 @@ These macros are defined in linux/init.h and serve to free up kernel memo/*
+/*
* hello-3.c - Illustrating the __init, __initdata and __exit macros.
*/
#include <linux/module.h> /* Needed by all modules */
@@ -872,35 +864,35 @@ These macros are defined in linux/init.h and serve to free up kernel memo
static int __init hello_3_init(void)
{
- printk(KERN_INFO "Hello, world %d\n", hello3_data);
+ pr_info("Hello, world %d\n", hello3_data);
return 0;
}
static void __exit hello_3_exit(void)
{
- printk(KERN_INFO "Goodbye, world 3\n");
+ pr_info("Goodbye, world 3\n");
}
module_init(hello_3_init);
module_exit(hello_3_exit);
-
+
Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this:
# insmod xxxxxx.o
+# insmod xxxxxx.o
Warning: loading xxxxxx.ko will taint the kernel: no license
See http://www.tux.org/lkml/#export-tainted for information about tainted modules
Module xxxxxx loaded, with warnings
-
+
@@ -912,7 +904,7 @@ To reference what license you're using a macro is available called MODULE_LIC
/*
+/*
* hello-4.c - Demonstrates module documentation.
*/
#include <linux/module.h> /* Needed by all modules */
@@ -926,25 +918,25 @@ MODULE_SUPPORTED_DEVICE("testdevice");
static int __init init_hello_4(void)
{
- printk(KERN_INFO "Hello, world 4\n");
+ pr_info("Hello, world 4\n");
return 0;
}
static void __exit cleanup_hello_4(void)
{
- printk(KERN_INFO "Goodbye, world 4\n");
+ pr_info("Goodbye, world 4\n");
}
module_init(init_hello_4);
module_exit(cleanup_hello_4);
-
+
Modules can take command line arguments, but not with the argc/argv you might be used to.
@@ -958,9 +950,9 @@ The module_param() macro takes 3 arguments: the name of the variable, its type aint myint = 3;
+int myint = 3;
module_param(myint, int, 0);
-
+
@@ -968,13 +960,13 @@ Arrays are supported too, but things are a bit different now than they were in t
int myintarray[2];
+int myintarray[2];
module_param_array(myintarray, int, NULL, 0); /* not interested in count */
short myshortarray[4];
int count;
module_parm_array(myshortarray, short, &count, 0); /* put count into "count" variable */
-
+
@@ -986,7 +978,7 @@ Lastly, there's a macro function, MODULE_PARM_DESC(), that is used to doc
/*
+/*
* hello-5.c - Demonstrates command line argument passing to a module.
*/
#include <linux/module.h>
@@ -1036,27 +1028,27 @@ MODULE_PARM_DESC(myintArray, "An array of integers"static int __init hello_5_init(void)
{
int i;
- printk(KERN_INFO "Hello, world 5\n=============\n");
- printk(KERN_INFO "myshort is a short integer: %hd\n", myshort);
- printk(KERN_INFO "myint is an integer: %d\n", myint);
- printk(KERN_INFO "mylong is a long integer: %ld\n", mylong);
- printk(KERN_INFO "mystring is a string: %s\n", mystring);
+ pr_info("Hello, world 5\n=============\n");
+ pr_info("myshort is a short integer: %hd\n", myshort);
+ pr_info("myint is an integer: %d\n", myint);
+ pr_info("mylong is a long integer: %ld\n", mylong);
+ pr_info("mystring is a string: %s\n", mystring);
for (i = 0; i < (sizeof myintArray / sizeof (int)); i++)
{
- printk(KERN_INFO "myintArray[%d] = %d\n", i, myintArray[i]);
+ pr_info("myintArray[%d] = %d\n", i, myintArray[i]);
}
- printk(KERN_INFO "got %d arguments for myintArray.\n", arr_argc);
+ pr_info("got %d arguments for myintArray.\n", arr_argc);
return 0;
}
static void __exit hello_5_exit(void)
{
- printk(KERN_INFO "Goodbye, world 5\n");
+ pr_info("Goodbye, world 5\n");
}
module_init(hello_5_init);
module_exit(hello_5_exit);
-
+
@@ -1064,7 +1056,7 @@ I would recommend playing around with this code:
# sudo insmod hello-5.ko mystring="bebop" mybyte=255 myintArray=-1
+# sudo insmod hello-5.ko mystring="bebop" mybyte=255 myintArray=-1
mybyte is an 8 bit integer: 255
myshort is a short integer: 1
myint is an integer: 20
@@ -1089,14 +1081,14 @@ Goodbye, world 5
# sudo insmod hello-5.ko mylong=hello
hello-5.o: invalid argument syntax for mylong: 'h'
-
+
Sometimes it makes sense to divide a kernel module between several source files.
@@ -1106,7 +1098,7 @@ Here's an example of such a kernel module./*
+/*
* start.c - Illustration of multi filed modules
*/
@@ -1115,10 +1107,10 @@ Here's an example of such a kernel module.
int init_module(void)
{
- printk(KERN_INFO "Hello, world - this is the kernel speaking\n");
+ pr_info("Hello, world - this is the kernel speaking\n");
return 0;
}
-
+
@@ -1126,7 +1118,7 @@ The next file:
/*
+/*
* stop.c - Illustration of multi filed modules
*/
@@ -1135,9 +1127,9 @@ The next file:
void cleanup_module()
{
- printk(KERN_INFO "Short is the life of a kernel module\n");
+ pr_info("Short is the life of a kernel module\n");
}
-
+
@@ -1145,7 +1137,7 @@ And finally, the makefile:
obj-m += hello-1.o
+obj-m += hello-1.o
obj-m += hello-2.o
obj-m += hello-3.o
obj-m += hello-4.o
@@ -1158,7 +1150,7 @@ And finally, the makefile:
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
-
+
@@ -1167,9 +1159,9 @@ This is the complete makefile for all the examples we've seen so far. The first
Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features, such as forced module unloading (MODULE_FORCE_UNLOAD): when this option is enabled, you can force the kernel to unload a module even when it believes it is unsafe, via a sudo rmmod -f module command. This option can save you a lot of time and a number of reboots during the development of a module. If you don't want to recompile your kernel then you should consider running the examples within a test distro on a virtual machine. If you mess anything up then you can easily reboot or restore the VM.
@@ -1183,8 +1175,8 @@ Now, if you just install a kernel source tree, use it to compile your kernel modinsmod: error inserting 'poet_atkm.ko': -1 Invalid module format
-
+insmod: error inserting 'poet_atkm.ko': -1 Invalid module format +
@@ -1192,9 +1184,9 @@ Less cryptical information are logged to the systemd journal:
Jun 4 22:07:54 localhost kernel: poet_atkm: version magic '2.6.5-1.358custom 686
+Jun 4 22:07:54 localhost kernel: poet_atkm: version magic '2.6.5-1.358custom 686
REGPARM 4KSTACKS gcc-3.3' should be '2.6.5-1.358 686 REGPARM 4KSTACKS gcc-3.3'
-
+
@@ -1202,13 +1194,13 @@ In other words, your kernel refuses to accept your module because version string
# sudo modinfo hello-4.ko
+# sudo modinfo hello-4.ko
license: GPL
author: Bob Mottram <bob@freedombone.net>
description: A sample driver
vermagic: 4.12.12-1.358 amd64 REGPARM 4KSTACKS gcc-4.9.2
depends:
-
+
@@ -1224,11 +1216,11 @@ Let's focus again on the previous error message: a closer look at the version ma
VERSION = 4
+VERSION = 4
PATCHLEVEL = 7
SUBLEVEL = 4
EXTRAVERSION = -1.358custom
-
+
@@ -1240,7 +1232,7 @@ Now, please run make to update configuration and version headers and objects:
# make
+# make
CHK include/linux/version.h
UPD include/linux/version.h
SYMLINK include/asm -> include/asm-i386
@@ -1251,7 +1243,7 @@ HOSTCC scripts/basic/docproc
HOSTCC scripts/conmakehash
HOSTCC scripts/kallsyms
CC scripts/empty.o
-
+
@@ -1261,13 +1253,13 @@ If you do not desire to actually compile the kernel, you can interrupt the build
A program usually begins with a main() function, executes a bunch of instructions 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're 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.
@@ -1282,15 +1274,15 @@ Every module must have an entry function and an exit function. Since there's morProgrammers use functions they don't define all the time. A prime example of this is printf(). You use these library functions which are provided by the standard C library, libc. The definitions for these functions don't actually enter your program until the linking stage, which insures that the code (for printf() for example) is available, and fixes the call instruction to point to that code.
-Kernel modules are different here, too. In the hello world example, you might have noticed that we used a function, printk() but didn't include a standard I/O library. That's because modules are object files whose symbols get resolved upon insmod'ing. The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel. If you're curious about what symbols have been exported by your kernel, take a look at /proc/kallsyms. +Kernel modules are different here, too. In the hello world example, you might have noticed that we used a function, pr_info() but didn't include a standard I/O library. That's because modules are object files whose symbols get resolved upon insmod'ing. The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel. If you're curious about what symbols have been exported by your kernel, take a look at /proc/kallsyms.
@@ -1302,14 +1294,14 @@ Would you like to see what system calls are made by printf()? It's easy! Compile
#include <stdio.h>
+#include <stdio.h>
int main(void)
{
printf("hello");
return 0;
}
-
+
@@ -1322,9 +1314,9 @@ You can even write modules to replace the kernel's system calls, which we'll do
A kernel is all about access to resources, whether the resource in question happens to be a video card, a hard drive or even memory. Programs often compete for the same resource. As I just saved this document, updatedb started updating the locate database. My vim session and updatedb are both using the hard drive concurrently. The kernel needs to keep things orderly, and not give users access to resources whenever they feel like it. To this end, a CPU can run in different modes. Each mode gives a different level of freedom to do what you want on the system. The Intel 80386 architecture had 4 of these modes, which were called rings. Unix uses only two rings; the highest ring (ring 0, also known as `supervisor mode' where everything is allowed to happen) and the lowest ring, which is called `user mode'.
@@ -1335,9 +1327,9 @@ Recall the discussion about library functions vs system calls. Typically, you usWhen you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you're writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash. When a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.
@@ -1352,9 +1344,9 @@ The file /proc/kallsyms holds all the symbols that the kernel knows aboutMemory management is a very complicated subject and the majority of O'Reilly's "Understanding The Linux Kernel" exclusively covers memory management! We're not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.
@@ -1373,27 +1365,27 @@ By the way, I would like to point out that the above discussion is true for anyOne class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.o sound card device driver might connect the /dev/sound device file to the Ensoniq IS1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed.
Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive:
# ls -l /dev/hda[1-3]
+# 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
-
+
@@ -1409,11 +1401,11 @@ Devices are divided into two types: character devices and block devices. The dif
crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0
+crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0
crw-r----- 1 root dial 4, 65 Nov 17 10:26 /dev/ttyS1
crw-rw---- 1 root dial 4, 66 Jul 5 2000 /dev/ttyS2
crw-rw---- 1 root dial 4, 67 Jul 5 2000 /dev/ttyS3
-
+
@@ -1433,10 +1425,10 @@ By the way, when I say `hardware', I mean something a bit more abstract than a P
% ls -l /dev/fd0 /dev/fd0u1680
+% ls -l /dev/fd0 /dev/fd0u1680
brwxrwxrwx 1 root floppy 2, 0 Jul 5 2000 /dev/fd0
brw-rw---- 1 root floppy 2, 44 Jul 5 2000 /dev/fd0u1680
-
+
@@ -1448,13 +1440,13 @@ By now you can look at these two device files and know instantly that they are b
The file_operations structure is defined in /usr/include/linux/fs.h, and holds pointers to functions defined by the driver that perform various operations on the device. Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.
@@ -1464,7 +1456,7 @@ For example, every character driver needs to define a function that reads from tstruct file_operations {
+struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
@@ -1494,7 +1486,7 @@ For example, every character driver needs to define a function that reads from t
loff_t len);
int (*show_fdinfo)(struct seq_file *m, struct file *f);
};
-
+
@@ -1506,13 +1498,13 @@ There is a gcc extension that makes assigning to this structure more convenient.
struct file_operations fops = {
+struct file_operations fops = {
read: device_read,
write: device_write,
open: device_open,
release: device_release
};
-
+
@@ -1520,13 +1512,13 @@ However, there's also a C99 way of assigning to elements of a structure, and thi
struct file_operations fops = {
+struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
-
+
@@ -1539,9 +1531,9 @@ An instance of struct file_operations containing pointers to functions that are
Each device is represented in the kernel by a file structure, which is defined in linux/fs.h. Be aware that a file is a kernel level structure and never appears in a user space program. It's not the same thing as a FILE, which is defined by glibc and would never appear in a kernel space function. Also, its name is a bit misleading; it represents an abstract open `file', not a file on a disk, which is represented by a structure named inode.
@@ -1556,9 +1548,9 @@ Go ahead and look at the definition of file. Most of the entries you see, like sAs discussed earlier, char devices are accessed through device files, usually located in /dev. This is by convention. When writing a driver, it's OK to put the device file in your current directory. Just make sure you place it in /dev for a production driver. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it's operating on, just in case the driver handles more than one device.
@@ -1568,8 +1560,8 @@ Adding a driver to your system means registering it with the kernel. This is synint register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
-
+int register_chrdev(unsigned int major, const char *name, struct file_operations *fops); +
@@ -1586,9 +1578,9 @@ If you pass a major number of 0 to register_chrdev, the return value will be the
We can't allow the kernel module to be rmmod'ed whenever root feels like it. If the device file is opened by a process and then we remove the kernel module, using the file would cause a call to the memory location where the appropriate function (read/write) used to be. If we're lucky, no other code was loaded there, and we'll get an ugly error message. If we're unlucky, another kernel module was loaded into the same location, which means a jump into the middle of another function within the kernel. The results of this would be impossible to predict, but they can't be very positive.
@@ -1608,16 +1600,16 @@ It's important to keep the counter accurate; if you ever do lose track of the coThe next code sample creates a char driver named chardev. You can cat its device file.
cat /proc/devices
-
+cat /proc/devices +
@@ -1625,7 +1617,7 @@ The next code sample creates a char driver named chardev. You can cat its device
/*
+/*
* chardev.c: Creates a read-only char device that says how many times
* you've read from the dev file
*/
@@ -1674,16 +1666,16 @@ The next code sample creates a char driver named chardev. You can cat its device
Major = register_chrdev(0, DEVICE_NAME, &fops);
if (Major < 0) {
- printk(KERN_ALERT "Registering char device failed with %d\n", Major);
+ pr_alert("Registering char device failed with %d\n", Major);
return Major;
}
- printk(KERN_INFO "I was assigned major number %d. To talk to\n", Major);
- printk(KERN_INFO "the driver, create a dev file with\n");
- printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major);
- printk(KERN_INFO "Try various minor numbers. Try to cat and echo to\n");
- printk(KERN_INFO "the device file.\n");
- printk(KERN_INFO "Remove the device file and module when done.\n");
+ pr_info("I was assigned major number %d. To talk to\n", Major);
+ pr_info("the driver, create a dev file with\n");
+ pr_info("'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major);
+ pr_info("Try various minor numbers. Try to cat and echo to\n");
+ pr_info("the device file.\n");
+ pr_info("Remove the device file and module when done.\n");
return SUCCESS;
}
@@ -1790,17 +1782,17 @@ The next code sample creates a char driver named chardev. You can cat its device
size_t len,
loff_t * off)
{
- printk(KERN_ALERT "Sorry, this operation isn't supported.\n");
+ pr_alert("Sorry, this operation isn't supported.\n");
return -EINVAL;
}
-
+
The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility – a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.
@@ -1824,9 +1816,9 @@ You might already have noticed that recent kernels look different. In case you hIn Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the /proc file system. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as /proc/modules which provides the list of modules and /proc/meminfo which stats memory usage statistics.
@@ -1856,13 +1848,13 @@ Each time, everytime the file /proc/helloworld is read, the function p# cat /proc/helloworld
+# cat /proc/helloworld
HelloWorld!
-
+
/*
+/*
procfs1.c
*/
@@ -1881,7 +1873,7 @@ HelloWorld!
{
int ret=0;
if(strlen(buffer) ==0) {
- printk(KERN_INFO "procfile read %s\n",filePointer->f_path.dentry->d_name.name);
+ pr_info("procfile read %s\n",filePointer->f_path.dentry->d_name.name);
ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n"));
ret=sizeof("HelloWorld!\n");
}
@@ -1899,26 +1891,26 @@ HelloWorld!
Our_Proc_File = proc_create(procfs_name,0644,NULL,&proc_file_fops);
if(NULL==Our_Proc_File) {
proc_remove(Our_Proc_File);
- printk(KERN_ALERT "Error:Could not initialize /proc/%s\n",procfs_name);
+ pr_alert("Error:Could not initialize /proc/%s\n",procfs_name);
return -ENOMEM;
}
- printk(KERN_INFO "/proc/%s created\n", procfs_name);
+ pr_info("/proc/%s created\n", procfs_name);
return 0;
}
void cleanup_module()
{
proc_remove(Our_Proc_File);
- printk(KERN_INFO "/proc/%s removed\n", procfs_name);
+ pr_info("/proc/%s removed\n", procfs_name);
}
-
+
We have seen a very simple example for a /proc file where we only read the file /proc/helloworld. It's also possible to write in a /proc file. It works the same way as read, a function is called when the /proc file is written. But there is a little difference with read, data comes from user, so you have to import data from user space to kernel space (with copy_from_user or get_user)
@@ -1932,7 +1924,7 @@ The only memory segment accessible to a process is its own, so when writing regu/**
+/**
* procfs2.c - create a "file" in /proc
*
*/
@@ -1972,7 +1964,7 @@ The only memory segment accessible to a process is its own, so when writing regu
{
int ret=0;
if(strlen(buffer) ==0) {
- printk(KERN_INFO "procfile read %s\n",filePointer->f_path.dentry->d_name.name);
+ pr_info("procfile read %s\n",filePointer->f_path.dentry->d_name.name);
ret=copy_to_user(buffer,"HelloWorld!\n",sizeof("HelloWorld!\n"));
ret=sizeof("HelloWorld!\n");
}
@@ -2013,11 +2005,11 @@ The only memory segment accessible to a process is its own, so when writing regu
Our_Proc_File = proc_create(PROCFS_NAME,0644,NULL,&proc_file_fops);
if(NULL==Our_Proc_File) {
proc_remove(Our_Proc_File);
- printk(KERN_ALERT "Error:Could not initialize /proc/%s\n",PROCFS_NAME);
+ pr_alert("Error:Could not initialize /proc/%s\n",PROCFS_NAME);
return -ENOMEM;
}
- printk(KERN_INFO "/proc/%s created\n", PROCFS_NAME);
+ pr_info("/proc/%s created\n", PROCFS_NAME);
return 0;
}
@@ -2028,16 +2020,16 @@ The only memory segment accessible to a process is its own, so when writing regu
void cleanup_module()
{
proc_remove(Our_Proc_File);
- printk(KERN_INFO "/proc/%s removed\n", PROCFS_NAME);
+ pr_info("/proc/%s removed\n", PROCFS_NAME);
}
-
+
We have seen how to read and write a /proc file with the /proc interface. But it's also possible to manage /proc file with inodes. The main concern is to use advanced functions, like permissions.
@@ -2063,7 +2055,7 @@ It's important to note that the standard roles of read and write are reversed in/*
+/*
procfs3.c
*/
@@ -2086,14 +2078,14 @@ It's important to note that the standard roles of read and write are reversed in
static int finished = 0;
if(finished)
{
- printk(KERN_DEBUG "procfs_read: END\n");
+ pr_debug("procfs_read: END\n");
finished = 0;
return 0;
}
finished = 1;
if(copy_to_user(buffer, procfs_buffer, procfs_buffer_size))
return -EFAULT;
- printk(KERN_DEBUG "procfs_read: read %lu bytes\n", procfs_buffer_size);
+ pr_debug("procfs_read: read %lu bytes\n", procfs_buffer_size);
return procfs_buffer_size;
}
static ssize_t procfs_write(struct file *file, const char *buffer,
@@ -2105,7 +2097,7 @@ It's important to note that the standard roles of read and write are reversed in
procfs_buffer_size = len;
if(copy_from_user(procfs_buffer, buffer, procfs_buffer_size))
return -EFAULT;
- printk(KERN_DEBUG "procfs_write: write %lu bytes\n", procfs_buffer_size);
+ pr_debug("procfs_write: write %lu bytes\n", procfs_buffer_size);
return procfs_buffer_size;
}
int procfs_open(struct inode *inode, struct file *file)
@@ -2132,21 +2124,21 @@ It's important to note that the standard roles of read and write are reversed in
if(Our_Proc_File == NULL)
{
remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL);
- printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROCFS_ENTRY_FILENAME);
+ pr_debug("Error: Could not initialize /proc/%s\n", PROCFS_ENTRY_FILENAME);
return -ENOMEM;
}
proc_set_size(Our_Proc_File, 80);
proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
- printk(KERN_DEBUG "/proc/%s created\n", PROCFS_ENTRY_FILENAME);
+ pr_debug("/proc/%s created\n", PROCFS_ENTRY_FILENAME);
return 0;
}
void cleanup_module()
{
remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL);
- printk(KERN_DEBUG "/proc/%s removed\n", PROCFS_ENTRY_FILENAME);
+ pr_debug("/proc/%s removed\n", PROCFS_ENTRY_FILENAME);
}
-
+
@@ -2155,9 +2147,9 @@ Still hungry for procfs examples? Well, first of all keep in mind, there are rum
As we have seen, writing a /proc file may be quite "complex". So to help people writting /proc file, there is an API named seq_file that helps @@ -2192,7 +2184,7 @@ Seq_file provides basic functions for file_operations, as seq_read, seq_lseek, a
/**
+/**
* procfs4.c - create a "file" in /proc
* This program uses the seq_file library to manage the /proc file.
*
@@ -2310,7 +2302,7 @@ MODULE_LICENSE("GPL");
if(entry == NULL)
{
remove_proc_entry(PROC_NAME, NULL);
- printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROC_NAME);
+ pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME);
return -ENOMEM;
}
@@ -2324,9 +2316,9 @@ MODULE_LICENSE("GPL");
void cleanup_module(void)
{
remove_proc_entry(PROC_NAME, NULL);
- printk(KERN_DEBUG "/proc/%s removed\n", PROC_NAME);
+ pr_debug("/proc/%s removed\n", PROC_NAME);
}
-
+
@@ -2347,16 +2339,16 @@ You can also read the code of fs/seq_file.c in the linux kernel.
sysfs allows you to interact with the running kernel from userspace by reading or setting variables inside of modules. This can be useful for debugging purposes, or just as an interface for applications or scripts. You can find sysfs directories and files under the sys directory on your system.
ls -l /sys
-
+ls -l /sys +
@@ -2364,12 +2356,11 @@ An example of a hello world module which includes the creation of a variable acc
/*
+/*
* hello-sysfs.c sysfs example
*/
#include <linux/module.h>
-#include <linux/printk.h>
#include <linux/kobject.h>
#include <linux/sysfs.h>
#include <linux/init.h>
@@ -2408,7 +2399,7 @@ MODULE_AUTHOR("Bob Mottram");
{
int error = 0;
- printk(KERN_INFO "mymodule: initialised\n");
+ pr_info("mymodule: initialised\n");
mymodule =
kobject_create_and_add("mymodule", kernel_kobj);
@@ -2417,7 +2408,7 @@ MODULE_AUTHOR("Bob Mottram");
error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
if (error) {
- printk(KERN_INFO "failed to create the myvariable file " \
+ pr_info("failed to create the myvariable file " \
"in /sys/kernel/mymodule\n");
}
@@ -2426,13 +2417,13 @@ MODULE_AUTHOR("Bob Mottram");
static void __exit mymodule_exit (void)
{
- printk(KERN_INFO "mymodule: Exit success\n");
+ pr_info("mymodule: Exit success\n");
kobject_put(mymodule);
}
module_init(mymodule_init);
module_exit(mymodule_exit);
-
+
@@ -2440,9 +2431,9 @@ Make and install the module:
make
+make
sudo insmod hello-sysfs.ko
-
+
@@ -2450,8 +2441,8 @@ Check that it exists:
sudo lsmod | grep hello_sysfs
-
+sudo lsmod | grep hello_sysfs +
@@ -2459,8 +2450,8 @@ What is the current value of myvariable ?
cat /sys/kernel/mymodule/myvariable
-
+cat /sys/kernel/mymodule/myvariable +
@@ -2468,9 +2459,9 @@ Set the value of myvariable and check that it changed.
echo "32" > /sys/kernel/mymodule/myvariable
+echo "32" > /sys/kernel/mymodule/myvariable
cat /sys/kernel/mymodule/myvariable
-
+
@@ -2478,15 +2469,15 @@ Finally, remove the test module:
sudo rmmod hello_sysfs
-
+sudo rmmod hello_sysfs +
Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device_write.
@@ -2512,7 +2503,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o/*
+/*
* chardev2.c - Create an input/output character device
*/
@@ -2550,7 +2541,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
static int device_open(struct inode *inode, struct file *file)
{
#ifdef DEBUG
- printk(KERN_INFO "device_open(%p)\n", file);
+ pr_info("device_open(%p)\n", file);
#endif
/*
@@ -2571,7 +2562,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
static int device_release(struct inode *inode, struct file *file)
{
#ifdef DEBUG
- printk(KERN_INFO "device_release(%p,%p)\n", inode, file);
+ pr_info("device_release(%p,%p)\n", inode, file);
#endif
/*
@@ -2599,7 +2590,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
int bytes_read = 0;
#ifdef DEBUG
- printk(KERN_INFO "device_read(%p,%p,%d)\n", file, buffer, length);
+ pr_info("device_read(%p,%p,%d)\n", file, buffer, length);
#endif
/*
@@ -2627,7 +2618,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
}
#ifdef DEBUG
- printk(KERN_INFO "Read %d bytes, %d left\n", bytes_read, length);
+ pr_info("Read %d bytes, %d left\n", bytes_read, length);
#endif
/*
@@ -2648,7 +2639,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
int i;
#ifdef DEBUG
- printk(KERN_INFO "device_write(%p,%s,%d)", file, buffer, length);
+ pr_info("device_write(%p,%s,%d)", file, buffer, length);
#endif
for (i = 0; i < length && i < BUF_LEN; i++)
@@ -2760,20 +2751,20 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
* Negative values signify an error
*/
if (ret_val < 0) {
- printk(KERN_ALERT "%s failed with %d\n",
+ pr_alert("%s failed with %d\n",
"Sorry, registering the character device ", ret_val);
return ret_val;
}
- printk(KERN_INFO "%s The major device number is %d.\n",
+ pr_info("%s The major device number is %d.\n",
"Registeration is a success", MAJOR_NUM);
- printk(KERN_INFO "If you want to talk to the device driver,\n");
- printk(KERN_INFO "you'll have to create a device file. \n");
- printk(KERN_INFO "We suggest you use:\n");
- printk(KERN_INFO "mknod %s c %d 0\n", DEVICE_FILE_NAME, MAJOR_NUM);
- printk(KERN_INFO "The device file name is important, because\n");
- printk(KERN_INFO "the ioctl program assumes that's the\n");
- printk(KERN_INFO "file you'll use.\n");
+ pr_info("If you want to talk to the device driver,\n");
+ pr_info("you'll have to create a device file. \n");
+ pr_info("We suggest you use:\n");
+ pr_info("mknod %s c %d 0\n", DEVICE_FILE_NAME, MAJOR_NUM);
+ pr_info("The device file name is important, because\n");
+ pr_info("the ioctl program assumes that's the\n");
+ pr_info("file you'll use.\n");
return 0;
}
@@ -2788,11 +2779,11 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
*/
unregister_chrdev(MAJOR_NUM, DEVICE_NAME);
}
-
+
/*
+/*
* chardev.h - the header file with the ioctl definitions.
*
* The declarations here have to be in a header file, because
@@ -2858,11 +2849,11 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
#define DEVICE_FILE_NAME "char_dev"
#endif
-
+
/*
+/*
* ioctl.c - the process to use ioctl's to control the kernel module
*
* Until now we could have used cat for input and output. But now
@@ -2966,14 +2957,14 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
close(file_desc);
return 0;
}
-
+
So far, the only thing we've done was to use well defined kernel mechanisms to register /proc files and device handlers. This is fine if you want to do something the kernel programmers thought you'd want, such as write a device driver. But what if you want to do something unusual, to change the behavior of the system in some way? Then, you're mostly on your own.
@@ -3003,7 +2994,7 @@ So, if we want to change the way a certain system call works, what we need to do-The source code here is an example of such a kernel module. We want to "spy" on a certain user, and to printk() 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's equal to the uid we spy on, it calls printk() 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 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's 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.
@@ -3019,7 +3010,7 @@ Note that all the related problems make syscall stealing unfeasiable for product
/*
+/*
* syscall.c
*
* System call "stealing" sample.
@@ -3093,13 +3084,13 @@ asmlinkage int our
/*
* Report the file, if relevant
*/
- printk("Opened file by %d: ", uid);
+ pr_info("Opened file by %d: ", uid);
do {
get_user(ch, filename + i);
i++;
- printk("%c", ch);
+ pr_info("%c", ch);
} while (ch != 0);
- printk("\n");
+ pr_info("\n");
/*
* Call the original sys_open - otherwise, we lose
@@ -3142,7 +3133,7 @@ asmlinkage int our
write_cr0(original_cr0);
- printk(KERN_INFO "Spying on UID:%d\n", uid);
+ pr_info("Spying on UID:%d\n", uid);
return 0;
}
@@ -3157,10 +3148,10 @@ asmlinkage int our
* Return the system call back to normal
*/
if (sys_call_table[__NR_open] != (unsigned long *)our_sys_open) {
- printk(KERN_ALERT "Somebody else also played with the ");
- printk(KERN_ALERT "open system call\n");
- printk(KERN_ALERT "The system may be left in ");
- printk(KERN_ALERT "an unstable state.\n");
+ pr_alert("Somebody else also played with the ");
+ pr_alert("open system call\n");
+ pr_alert("The system may be left in ");
+ pr_alert("an unstable state.\n");
}
write_cr0(original_cr0 & ~0x00010000);
@@ -3174,18 +3165,18 @@ module_init(syscall_start);
module_exit(syscall_end);
MODULE_LICENSE("GPL");
-
+
What do you do when somebody asks you for something you can't do right away? If you're a human being and you're bothered by a human being, the only thing you can say is: "Not right now, I'm busy. Go away!". But if you're a kernel module and you're bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that's the way multiple processes appear to run on the same time on a single CPU).
@@ -3195,8 +3186,8 @@ This kernel module is an example of this. The file (called /proc/sleep) ctail -f
-
+tail -f +
@@ -3232,7 +3223,7 @@ There is one more point to remember. Some times processes don't want to sleep, t
hostname:~/lkmpg-examples/09-BlockingProcesses# insmod sleep.ko
+hostname:~/lkmpg-examples/09-BlockingProcesses# insmod sleep.ko
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
Last input:
hostname:~/lkmpg-examples/09-BlockingProcesses# tail -f /proc/sleep &
@@ -3252,11 +3243,11 @@ hostname:~/lkmpg-examples/09-BlockingProcesses# kill %1
hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep
Last input:
hostname:~/lkmpg-examples/09-BlockingProcesses#
-
+
/*
+/*
* sleep.c - create a /proc file, and if several processes try to open it at
* the same time, put all but one to sleep
*/
@@ -3499,13 +3490,13 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
if(Our_Proc_File == NULL)
{
remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
- printk(KERN_DEBUG "Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME);
+ pr_debug("Error: Could not initialize /proc/%s\n", PROC_ENTRY_FILENAME);
return -ENOMEM;
}
proc_set_size(Our_Proc_File, 80);
proc_set_user(Our_Proc_File, GLOBAL_ROOT_UID, GLOBAL_ROOT_GID);
- printk(KERN_INFO "/proc/test created\n");
+ pr_info("/proc/test created\n");
return 0;
}
@@ -3519,13 +3510,13 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
void cleanup_module()
{
remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
- printk(KERN_DEBUG "/proc/%s removed\n", PROC_ENTRY_FILENAME);
+ pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME);
}
-
+
/* cat_noblock.c - open a file and display its contents, but exit rather than
+/* cat_noblock.c - open a file and display its contents, but exit rather than
* wait for input */
/* Copyright (C) 1998 by Ori Pomerantz */
@@ -3590,14 +3581,14 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
} while (bytes > 0);
return 0;
}
-
+
Sometimes one thing should happen before another within a module having multiple threads. Rather than using /proc/sleep commands the kernel has another way to do this which allows timeouts or interrupts to also happen.
@@ -3607,7 +3598,7 @@ In the following example two threads are started, but one needs to start before#include <linux/init.h>
+#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/kthread.h>
@@ -3620,7 +3611,7 @@ In the following example two threads are started, but one needs to start before
static int machine_crank_thread(void* arg)
{
- printk("Turn the crank\n");
+ pr_info("Turn the crank\n");
complete_all(&machine.crank_comp);
complete_and_exit(&machine.crank_comp, 0);
@@ -3630,7 +3621,7 @@ In the following example two threads are started, but one needs to start before
{
wait_for_completion(&machine.crank_comp);
- printk("Flywheel spins up\n");
+ pr_info("Flywheel spins up\n");
complete_all(&machine.flywheel_comp);
complete_and_exit(&machine.flywheel_comp, 0);
@@ -3641,7 +3632,7 @@ In the following example two threads are started, but one needs to start before
struct task_struct* crank_thread;
struct task_struct* flywheel_thread;
- printk("completions example\n");
+ pr_info("completions example\n");
init_completion(&machine.crank_comp);
init_completion(&machine.flywheel_comp);
@@ -3675,7 +3666,7 @@ In the following example two threads are started, but one needs to start before
wait_for_completion(&machine.crank_comp);
wait_for_completion(&machine.flywheel_comp);
- printk("completions exit\n");
+ pr_info("completions exit\n");
}
module_init(completions_init);
@@ -3684,7 +3675,7 @@ module_exit(completions_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Completions example");
MODULE_LICENSE("GPL");
-
+
@@ -3702,22 +3693,22 @@ There are other variations upon the wait_for_completion function, which i
If processes running on different CPUs or in different threads try to access the same memory then it's possible that strange things can happen or your system can lock up. To avoid this various types of mutual exclusion kernel functions are available. These indicate if a section of code is "locked" or "unlocked" so that simultaneous attempts to run it can't happen.
You can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland. This may be all that's needed to avoid collisions in most cases.
#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/mutex.h>
@@ -3728,27 +3719,27 @@ DEFINE_MUTEX(mymutex);
{
int ret;
- printk("example_mutex init\n");
+ pr_info("example_mutex init\n");
ret = mutex_trylock(&mymutex);
if (ret != 0) {
- printk("mutex is locked\n");
+ pr_info("mutex is locked\n");
if (mutex_is_locked(&mymutex) == 0)
- printk("The mutex failed to lock!\n");
+ pr_info("The mutex failed to lock!\n");
mutex_unlock(&mymutex);
- printk("mutex is unlocked\n");
+ pr_info("mutex is unlocked\n");
}
else
- printk("Failed to lock\n");
+ pr_info("Failed to lock\n");
return 0;
}
static void example_mutex_exit(void)
{
- printk("example_mutex exit\n");
+ pr_info("example_mutex exit\n");
}
module_init(example_mutex_init);
@@ -3757,13 +3748,13 @@ module_exit(example_mutex_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Mutex example");
MODULE_LICENSE("GPL");
-
+
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 won't noticably slow anything down from the user's point of view.
@@ -3773,7 +3764,7 @@ The example here is "irq safe" in that if interrupts happen during the lo#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/spinlock.h>
@@ -3787,7 +3778,7 @@ DEFINE_SPINLOCK(sl_static);
unsigned long flags;
spin_lock_irqsave(&sl_static, flags);
- printk("Locked static spinlock\n");
+ pr_info("Locked static spinlock\n");
/* Do something or other safely.
Because this uses 100% CPU time this
@@ -3795,7 +3786,7 @@ DEFINE_SPINLOCK(sl_static);
milliseconds to run */
spin_unlock_irqrestore(&sl_static, flags);
- printk("Unlocked static spinlock\n");
+ pr_info("Unlocked static spinlock\n");
}
static void example_spinlock_dynamic(void)
@@ -3804,7 +3795,7 @@ DEFINE_SPINLOCK(sl_static);
spin_lock_init(&sl_dynamic);
spin_lock_irqsave(&sl_dynamic, flags);
- printk("Locked dynamic spinlock\n");
+ pr_info("Locked dynamic spinlock\n");
/* Do something or other safely.
Because this uses 100% CPU time this
@@ -3812,12 +3803,12 @@ DEFINE_SPINLOCK(sl_static);
milliseconds to run */
spin_unlock_irqrestore(&sl_dynamic, flags);
- printk("Unlocked dynamic spinlock\n");
+ pr_info("Unlocked dynamic spinlock\n");
}
static int example_spinlock_init(void)
{
- printk("example spinlock started\n");
+ pr_info("example spinlock started\n");
example_spinlock_static();
example_spinlock_dynamic();
@@ -3827,7 +3818,7 @@ DEFINE_SPINLOCK(sl_static);
static void example_spinlock_exit(void)
{
- printk("example spinlock exit\n");
+ pr_info("example spinlock exit\n");
}
module_init(example_spinlock_init);
@@ -3836,20 +3827,20 @@ module_exit(example_spinlock_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Spinlock example");
MODULE_LICENSE("GPL");
-
+
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something. Like the earlier spinlocks example the one below shows an "irq safe" situation in which if other functions were triggered from irqs which might also read and write to whatever you are concerned with then they wouldn't disrupt the logic. As before it's a good idea to keep anything done within the lock as short as possible so that it doesn't hang up the system and cause users to start revolting against the tyranny of your module.
#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
@@ -3860,12 +3851,12 @@ DEFINE_RWLOCK(myrwlock);
unsigned long flags;
read_lock_irqsave(&myrwlock, flags);
- printk("Read Locked\n");
+ pr_info("Read Locked\n");
/* Read from something */
read_unlock_irqrestore(&myrwlock, flags);
- printk("Read Unlocked\n");
+ pr_info("Read Unlocked\n");
}
static void example_write_lock(void)
@@ -3873,17 +3864,17 @@ DEFINE_RWLOCK(myrwlock);
unsigned long flags;
write_lock_irqsave(&myrwlock, flags);
- printk("Write Locked\n");
+ pr_info("Write Locked\n");
/* Write to something */
write_unlock_irqrestore(&myrwlock, flags);
- printk("Write Unlocked\n");
+ pr_info("Write Unlocked\n");
}
static int example_rwlock_init(void)
{
- printk("example_rwlock started\n");
+ pr_info("example_rwlock started\n");
example_read_lock();
example_write_lock();
@@ -3893,7 +3884,7 @@ DEFINE_RWLOCK(myrwlock);
static void example_rwlock_exit(void)
{
- printk("example_rwlock exit\n");
+ pr_info("example_rwlock exit\n");
}
module_init(example_rwlock_init);
@@ -3902,7 +3893,7 @@ module_exit(example_rwlock_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Read/Write locks example");
MODULE_LICENSE("GPL");
-
+
@@ -3910,15 +3901,15 @@ Of course if you know for sure that there are no functions triggered by irqs whi
If you're doing simple arithmetic: adding, subtracting or bitwise operations then there's another way in the multi-CPU and multi-hyperthreaded world to stop other parts of the system from messing with your mojo. By using atomic operations you can be confident that your addition, subtraction or bit flip did actually happen and wasn't overwritten by some other shenanigans. An example is shown below.
#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
@@ -3948,7 +3939,7 @@ If you're doing simple arithmetic: adding, subtracting or bitwise operations the
/* add one */
atomic_inc(&debbie);
- printk("chris: %d, debbie: %d\n",
+ pr_info("chris: %d, debbie: %d\n",
atomic_read(&chris), atomic_read(&debbie));
}
@@ -3956,26 +3947,26 @@ If you're doing simple arithmetic: adding, subtracting or bitwise operations the
{
unsigned long word = 0;
- printk("Bits 0: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("Bits 0: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
set_bit(3, &word);
set_bit(5, &word);
- printk("Bits 1: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("Bits 1: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
clear_bit(5, &word);
- printk("Bits 2: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("Bits 2: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
change_bit(3, &word);
- printk("Bits 3: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("Bits 3: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
if (test_and_set_bit(3, &word))
- printk("wrong\n");
- printk("Bits 4: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("wrong\n");
+ pr_info("Bits 4: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
word = 255;
- printk("Bits 5: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
+ pr_info("Bits 5: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word));
}
static int example_atomic_init(void)
{
- printk("example_atomic started\n");
+ pr_info("example_atomic started\n");
atomic_add_subtract();
atomic_bitwise();
@@ -3985,7 +3976,7 @@ If you're doing simple arithmetic: adding, subtracting or bitwise operations the
static void example_atomic_exit(void)
{
- printk("example_atomic exit\n");
+ pr_info("example_atomic exit\n");
}
module_init(example_atomic_init);
@@ -3994,18 +3985,18 @@ module_exit(example_atomic_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Atomic operations example");
MODULE_LICENSE("GPL");
-
+
In Section 1.2.1.2, I said that X and kernel module programming don't mix. That's true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty the command to load the module came from.
@@ -4019,7 +4010,7 @@ The way this is done is by using current, a pointer to the currently running tas/*
+/*
* print_string.c - Send output to the tty we're running on, regardless if it's
* through X11, telnet, etc. We do this by printing the string to the tty
* associated with the current task.
@@ -4127,14 +4118,14 @@ MODULE_AUTHOR("Peter Jay Salzman");
module_init(print_string_init);
module_exit(print_string_exit);
-
+
In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.
@@ -4144,7 +4135,7 @@ The following source code illustrates a minimal kernel module which, when loaded/*
+/*
* kbleds.c - Blink keyboard leds until the module is unloaded.
*/
@@ -4203,19 +4194,19 @@ MODULE_LICENSE("GPL");
{
int i;
- printk(KERN_INFO "kbleds: loading\n");
- printk(KERN_INFO "kbleds: fgconsole is %x\n", fg_console);
+ pr_info("kbleds: loading\n");
+ pr_info("kbleds: fgconsole is %x\n", fg_console);
for (i = 0; i < MAX_NR_CONSOLES; i++) {
if (!vc_cons[i].d)
break;
- printk(KERN_INFO "poet_atkm: console[%i/%i] #%i, tty %lx\n", i,
+ pr_info("poet_atkm: console[%i/%i] #%i, tty %lx\n", i,
MAX_NR_CONSOLES, vc_cons[i].d->vc_num,
(unsigned long)vc_cons[i].d->port.tty);
}
- printk(KERN_INFO "kbleds: finished scanning consoles\n");
+ pr_info("kbleds: finished scanning consoles\n");
my_driver = vc_cons[fg_console].d->port.tty->driver;
- printk(KERN_INFO "kbleds: tty driver magic %x\n", my_driver->magic);
+ pr_info("kbleds: tty driver magic %x\n", my_driver->magic);
/*
* Set up the LED blink timer the first time
@@ -4231,7 +4222,7 @@ MODULE_LICENSE("GPL");
static void __exit kbleds_cleanup(void)
{
- printk(KERN_INFO "kbleds: unloading...\n");
+ pr_info("kbleds: unloading...\n");
del_timer(&my_timer);
(my_driver->ops->ioctl) (vc_cons[fg_console].d->port.tty,
KDSETLED, RESTORE_LEDS);
@@ -4239,11 +4230,11 @@ MODULE_LICENSE("GPL");
module_init(kbleds_init);
module_exit(kbleds_cleanup);
-
+
-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 use printascii, thus makeing 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. +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 use printascii, thus makeing 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.
@@ -4253,48 +4244,48 @@ While you have seen lots of stuff that can be used to aid debugging here, there
There are two main ways of running tasks: tasklets and work queues. Tasklets are a quick and easy way of scheduling a single function to be run, for example when triggered from an interrupt, whereas work queues are more complicated but also better suited to running multiple things in a sequence.
Here's 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.
#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
static void tasklet_fn(unsigned long data)
{
- printk("Example tasklet starts\n");
+ pr_info("Example tasklet starts\n");
mdelay(5000);
- printk("Example tasklet ends\n");
+ pr_info("Example tasklet ends\n");
}
DECLARE_TASKLET(mytask, tasklet_fn, 0L);
static int example_tasklet_init(void)
{
- printk("tasklet example init\n");
+ pr_info("tasklet example init\n");
tasklet_schedule(&mytask);
mdelay(200);
- printk("Example tasklet init continues...\n");
+ pr_info("Example tasklet init continues...\n");
return 0;
}
static void example_tasklet_exit(void)
{
- printk("tasklet example exit\n");
+ pr_info("tasklet example exit\n");
tasklet_kill(&mytask);
}
@@ -4304,7 +4295,7 @@ module_exit(example_tasklet_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Tasklet example");
MODULE_LICENSE("GPL");
-
+
@@ -4312,17 +4303,17 @@ So with this example loaded dmesg should show:
tasklet example init
+tasklet example init
Example tasklet starts
Example tasklet init continues...
Example tasklet ends
-
+
Very often, we have "housekeeping" tasks which have to be done at a certain time, or every so often. If the task is to be done by a process, we do it by putting it in the crontab file. If the task is to be done by a kernel module, we have two possibilities. The first is to put a process in the crontab file which will wake up the module by a system call when necessary, for example by opening a file. This is terribly inefficient, however – we run a new process off of crontab, read a new executable to memory, and all this just to wake up a kernel module which is in memory anyway.
@@ -4336,7 +4327,7 @@ There's one more point we need to remember here. When a module is removed by rmm/*
+/*
* sched.c - schedule a function to be called on every timer interrupt.
*
* Copyright (C) 2001 by Peter Jay Salzman
@@ -4455,8 +4446,8 @@ MODULE_LICENSE("GPL");
if (Our_Proc_File == NULL) {
remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
- printk(KERN_ALERT "Error: Could not initialize /proc/%s\n",
- PROC_ENTRY_FILENAME);
+ pr_alert("Error: Could not initialize /proc/%s\n",
+ PROC_ENTRY_FILENAME);
return -ENOMEM;
}
proc_set_size(Our_Proc_File, 80);
@@ -4469,7 +4460,7 @@ MODULE_LICENSE("GPL");
my_workqueue = create_workqueue(MY_WORK_QUEUE_NAME);
queue_delayed_work(my_workqueue, &Task, 100);
- printk(KERN_INFO "/proc/%s created\n", PROC_ENTRY_FILENAME);
+ pr_info("/proc/%s created\n", PROC_ENTRY_FILENAME);
return 0;
}
@@ -4483,7 +4474,7 @@ MODULE_LICENSE("GPL");
* Unregister our /proc file
*/
remove_proc_entry(PROC_ENTRY_FILENAME, NULL);
- printk(KERN_INFO "/proc/%s removed\n", PROC_ENTRY_FILENAME);
+ pr_info("/proc/%s removed\n", PROC_ENTRY_FILENAME);
die = 1; /* keep intrp_routine from queueing itself */
cancel_delayed_work(&Task); /* no "new ones" */
@@ -4500,19 +4491,19 @@ MODULE_LICENSE("GPL");
* routine it's time to die.
*/
}
-
+
Except for the last chapter, everything we did in the kernel so far we've done as a response to a process asking for it, either by dealing with a special file, sending an ioctl(), or issuing a system call. But the job of the kernel isn't just to respond to process requests. Another job, which is every bit as important, is to speak to the hardware connected to the machine.
@@ -4543,9 +4534,9 @@ This function receives the IRQ number, the name of the function, flags, a name fMany popular single board computers, such as Raspberry Pis or Beagleboards, have a bunch of GPIO pins. Attaching buttons to those and then having a button press do something is a classic case in which you might need to use interrupts so that instead of having the CPU waste time and battery power polling for a change in input state it's better for the input to trigger the CPU to then run a particular handling function.
@@ -4555,7 +4546,7 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L/*
+/*
* intrpt.c - Handling GPIO with interrupts
*
* Copyright (C) 2017 by Bob Mottram
@@ -4605,13 +4596,13 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
{
int ret = 0;
- printk(KERN_INFO "%s\n", __func__);
+ pr_info("%s\n", __func__);
/* register LED gpios */
ret = gpio_request_array(leds, ARRAY_SIZE(leds));
if (ret) {
- printk(KERN_ERR "Unable to request GPIOs for LEDs: %d\n", ret);
+ pr_err("Unable to request GPIOs for LEDs: %d\n", ret);
return ret;
}
@@ -4619,23 +4610,23 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));
if (ret) {
- printk(KERN_ERR "Unable to request GPIOs for BUTTONs: %d\n", ret);
+ pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret);
goto fail1;
}
- printk(KERN_INFO "Current button1 value: %d\n",
+ pr_info("Current button1 value: %d\n",
gpio_get_value(buttons[0].gpio));
ret = gpio_to_irq(buttons[0].gpio);
if (ret < 0) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
button_irqs[0] = ret;
- printk(KERN_INFO "Successfully requested BUTTON1 IRQ # %d\n",
+ pr_info("Successfully requested BUTTON1 IRQ # %d\n",
button_irqs[0]);
ret = request_irq(button_irqs[0], button_isr,
@@ -4643,7 +4634,7 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
"gpiomod#button1", NULL);
if (ret) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
@@ -4651,13 +4642,13 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
ret = gpio_to_irq(buttons[1].gpio);
if (ret < 0) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
button_irqs[1] = ret;
- printk(KERN_INFO "Successfully requested BUTTON2 IRQ # %d\n",
+ pr_info("Successfully requested BUTTON2 IRQ # %d\n",
button_irqs[1]);
ret = request_irq(button_irqs[1], button_isr,
@@ -4665,7 +4656,7 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
"gpiomod#button2", NULL);
if (ret) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail3;
}
@@ -4688,7 +4679,7 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
{
int i;
- printk(KERN_INFO "%s\n", __func__);
+ pr_info("%s\n", __func__);
/* free irqs */
free_irq(button_irqs[0], NULL);
@@ -4706,14 +4697,14 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Handle some GPIO interrupts");
-
+
Suppose you want to do a bunch of stuff inside of an interrupt routine. A common way to do that without rendering the interrupt unavailable for a significant duration is to combine it with a tasklet. This pushes the bulk of the work off into the scheduler.
@@ -4723,7 +4714,7 @@ The example below modifies the previous example to also run an additional task w/*
+/*
* bottomhalf.c - Top and bottom half interrupt handling
*
* Copyright (C) 2017 by Bob Mottram
@@ -4758,10 +4749,10 @@ The example below modifies the previous example to also run an additional task w
/* Tasklet containing some non-trivial amount of processing */
static void bottomhalf_tasklet_fn(unsigned long data)
{
- printk("Bottom half tasklet starts\n");
+ pr_info("Bottom half tasklet starts\n");
/* do something which takes a while */
mdelay(500);
- printk("Bottom half tasklet ends\n");
+ pr_info("Bottom half tasklet ends\n");
}
DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
@@ -4787,13 +4778,13 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
{
int ret = 0;
- printk(KERN_INFO "%s\n", __func__);
+ pr_info("%s\n", __func__);
/* register LED gpios */
ret = gpio_request_array(leds, ARRAY_SIZE(leds));
if (ret) {
- printk(KERN_ERR "Unable to request GPIOs for LEDs: %d\n", ret);
+ pr_err("Unable to request GPIOs for LEDs: %d\n", ret);
return ret;
}
@@ -4801,23 +4792,23 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
ret = gpio_request_array(buttons, ARRAY_SIZE(buttons));
if (ret) {
- printk(KERN_ERR "Unable to request GPIOs for BUTTONs: %d\n", ret);
+ pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret);
goto fail1;
}
- printk(KERN_INFO "Current button1 value: %d\n",
+ pr_info("Current button1 value: %d\n",
gpio_get_value(buttons[0].gpio));
ret = gpio_to_irq(buttons[0].gpio);
if (ret < 0) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
button_irqs[0] = ret;
- printk(KERN_INFO "Successfully requested BUTTON1 IRQ # %d\n",
+ pr_info("Successfully requested BUTTON1 IRQ # %d\n",
button_irqs[0]);
ret = request_irq(button_irqs[0], button_isr,
@@ -4825,7 +4816,7 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
"gpiomod#button1", NULL);
if (ret) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
@@ -4833,13 +4824,13 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
ret = gpio_to_irq(buttons[1].gpio);
if (ret < 0) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail2;
}
button_irqs[1] = ret;
- printk(KERN_INFO "Successfully requested BUTTON2 IRQ # %d\n",
+ pr_info("Successfully requested BUTTON2 IRQ # %d\n",
button_irqs[1]);
ret = request_irq(button_irqs[1], button_isr,
@@ -4847,7 +4838,7 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
"gpiomod#button2", NULL);
if (ret) {
- printk(KERN_ERR "Unable to request IRQ: %d\n", ret);
+ pr_err("Unable to request IRQ: %d\n", ret);
goto fail3;
}
@@ -4870,7 +4861,7 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
{
int i;
- printk(KERN_INFO "%s\n", __func__);
+ pr_info("%s\n", __func__);
/* free irqs */
free_irq(button_irqs[0], NULL);
@@ -4888,28 +4879,28 @@ DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Interrupt with top and bottom half");
-
+
At the dawn of the internet everybody trusted everybody completely…but that didn't 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's 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.
Calculating and checking the hashes of things is a common operation. Here is a demonstration of how to calculate a sha256 hash within a kernel module.
#include <linux/module.h>
+#include <linux/module.h>
#include <crypto/internal/hash.h>
#define SHA256_LENGTH (256/8)
@@ -4919,11 +4910,11 @@ Calculating and checking the hashes of things is a common operation. Here is a d
int i;
char str[SHA256_LENGTH*2 + 1];
- printk("sha256 test for string: \"%s\"\n", plaintext);
+ pr_info("sha256 test for string: \"%s\"\n", plaintext);
for (i = 0; i < SHA256_LENGTH ; i++)
sprintf(&str[i*2],"%02x", (unsigned char)hash_sha256[i]);
str[i*2] = 0;
- printk("%s\n", str);
+ pr_info("%s\n", str);
}
int cryptosha256_init(void)
@@ -4973,7 +4964,7 @@ module_exit(cryptosha256_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("sha256 hash test");
MODULE_LICENSE("GPL");
-
+
@@ -4981,10 +4972,10 @@ Make and install the module:
make
+make
sudo insmod cryptosha256.ko
dmesg
-
+
@@ -4996,20 +4987,20 @@ Finally, remove the test module:
sudo rmmod cryptosha256
-
+sudo rmmod cryptosha256 +
Here is an example of symmetrically encrypting a string using the AES algorithm and a password.
#include <crypto/internal/skcipher.h>
+#include <crypto/internal/skcipher.h>
#include <linux/module.h>
#include <linux/crypto.h>
@@ -5061,7 +5052,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
break;
}
default:
- printk("skcipher encrypt returned with %d result %d\n",
+ pr_info("skcipher encrypt returned with %d result %d\n",
rc, sk->result.err);
break;
}
@@ -5081,7 +5072,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
result->err = error;
complete(&result->completion);
- printk("Encryption finished successfully\n");
+ pr_info("Encryption finished successfully\n");
}
static int test_skcipher_encrypt(char * plaintext, char * password,
@@ -5093,7 +5084,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
if (!sk->tfm) {
sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0);
if (IS_ERR(sk->tfm)) {
- printk("could not allocate skcipher handle\n");
+ pr_info("could not allocate skcipher handle\n");
return PTR_ERR(sk->tfm);
}
}
@@ -5101,7 +5092,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
if (!sk->req) {
sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL);
if (!sk->req) {
- printk("could not allocate skcipher request\n");
+ pr_info("could not allocate skcipher request\n");
ret = -ENOMEM;
goto out;
}
@@ -5119,18 +5110,18 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
/* AES 256 with given symmetric key */
if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) {
- printk("key could not be set\n");
+ pr_info("key could not be set\n");
ret = -EAGAIN;
goto out;
}
- printk("Symmetric key: %s\n", key);
- printk("Plaintext: %s\n", plaintext);
+ pr_info("Symmetric key: %s\n", key);
+ pr_info("Plaintext: %s\n", plaintext);
if (!sk->ivdata) {
/* see https://en.wikipedia.org/wiki/Initialization_vector */
sk->ivdata = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
if (!sk->ivdata) {
- printk("could not allocate ivdata\n");
+ pr_info("could not allocate ivdata\n");
goto out;
}
get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE);
@@ -5140,7 +5131,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
/* The text to be encrypted */
sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL);
if (!sk->scratchpad) {
- printk("could not allocate scratchpad\n");
+ pr_info("could not allocate scratchpad\n");
goto out;
}
}
@@ -5157,7 +5148,7 @@ Here is an example of symmetrically encrypting a string using the AES algorithm
if (ret)
goto out;
- printk("Encryption request successful\n");
+ pr_info("Encryption request successful\n");
out:
return ret;
@@ -5189,20 +5180,20 @@ module_exit(cryptoapi_exit);
MODULE_AUTHOR("Bob Mottram");
MODULE_DESCRIPTION("Symmetric key encryption example");
MODULE_LICENSE("GPL");
-
+
Up to this point we've seen all kinds of modules doing all kinds of things, but there was no consistency in their interfaces with the rest of the kernel. To impose some consistency such that there is at minimum a standardised way to start, suspend and resume a device a device model was added. An example is show below, and you can use this as a template to add your own suspend, resume or other interface functions.
#include <linux/kernel.h>
+#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
@@ -5215,8 +5206,8 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
{
struct devicemodel_data *pd = (struct devicemodel_data *)(dev->dev.platform_data);
- printk("devicemodel probe\n");
- printk("devicemodel greeting: %s; %d\n", pd->greeting, pd->number);
+ pr_info("devicemodel probe\n");
+ pr_info("devicemodel greeting: %s; %d\n", pd->greeting, pd->number);
/* Your device initialisation code */
@@ -5225,7 +5216,7 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
static int devicemodel_remove(struct platform_device *dev)
{
- printk("devicemodel example removed\n");
+ pr_info("devicemodel example removed\n");
/* Your device removal code */
@@ -5234,7 +5225,7 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
static int devicemodel_suspend(struct device *dev)
{
- printk("devicemodel example suspend\n");
+ pr_info("devicemodel example suspend\n");
/* Your device suspend code */
@@ -5243,7 +5234,7 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
static int devicemodel_resume(struct device *dev)
{
- printk("devicemodel example resume\n");
+ pr_info("devicemodel example resume\n");
/* Your device resume code */
@@ -5274,12 +5265,12 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
{
int ret;
- printk("devicemodel init\n");
+ pr_info("devicemodel init\n");
ret = platform_driver_register(&devicemodel_driver);
if (ret) {
- printk(KERN_ERR "Unable to register driver\n");
+ pr_err("Unable to register driver\n");
return ret;
}
@@ -5288,7 +5279,7 @@ Up to this point we've seen all kinds of modules doing all kinds of things, but
static void devicemodel_exit(void)
{
- printk("devicemodel exit\n");
+ pr_info("devicemodel exit\n");
platform_driver_unregister(&devicemodel_driver);
}
@@ -5298,17 +5289,17 @@ MODULE_DESCRIPTION("Linux Device Model example")
module_init(devicemodel_init);
module_exit(devicemodel_exit);
-
+
Sometimes you might want your code to run as quickly as possible, especially if it's handling an interrupt or doing something which might cause noticible latency. If your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either true or false, then you can allow the compiler to optimise for this using the likely and unlikely macros.
@@ -5318,13 +5309,13 @@ For example, when allocating memory you're almost always expecting this to succebvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
+bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
if (unlikely(!bvl)) {
mempool_free(bio, bio_pool);
bio = NULL;
goto out;
}
-
+
@@ -5333,35 +5324,35 @@ When the unlikely macro is used the compiler alters its machine instructi
Before I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.
You can't do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms.
You might need to do this for a short time and that is OK, but if you don't enable them afterwards, your system will be stuck and you'll have to power it off.
I probably don't have to warn you about this, but I figured I will anyway, just in case.
@@ -5369,9 +5360,9 @@ I probably don't have to warn you about this, but I figured I will anyway, justI could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there's a need for that – you'd have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven't touched upon, such as bootstrapping or the disk interface.
diff --git a/4.12.12/LKMPG-4.12.12.md b/4.12.12/LKMPG-4.12.12.md index 15c311b..0952202 100644 --- a/4.12.12/LKMPG-4.12.12.md +++ b/4.12.12/LKMPG-4.12.12.md @@ -8,83 +8,83 @@ Table of Contents ----------------- ::: {#text-table-of-contents} -- [Introduction](#org98c97cb) - - [Authorship](#org2782b14) - - [Versioning and Notes](#org0b6d633) - - [Acknowledgements](#orge57cf6b) - - [What Is A Kernel Module?](#org37341bc) - - [Kernel module package](#orge9612fa) - - [What Modules are in my Kernel?](#orgb6ce832) - - [Do I need to download and compile the kernel?](#orge1ec8b5) - - [Before We Begin](#org87661f2) -- [Headers](#org52fbd37) -- [Examples](#org628945f) -- [Hello World](#org0d455c0) - - [The Simplest Module](#orgba22fe1) - - [Hello and Goodbye](#org56fc79a) - - [The \_\_init and \_\_exit Macros](#org86bfdb6) - - [Licensing and Module Documentation](#org11aaf91) - - [Passing Command Line Arguments to a Module](#org9e1dd8d) - - [Modules Spanning Multiple Files](#orgcd10981) - - [Building modules for a precompiled kernel](#orga65faca) -- [Preliminaries](#orgdeef601) - - [How modules begin and end](#orgc8eceb0) - - [Functions available to modules](#org290f3df) - - [User Space vs Kernel Space](#orga7850df) - - [Name Space](#org4b4877b) - - [Code space](#org7e3a491) - - [Device Drivers](#org6c0b122) -- [Character Device drivers](#org016c39a) - - [The file\_operations Structure](#org31d952e) - - [The file structure](#org607b208) - - [Registering A Device](#orgf96ab85) - - [Unregistering A Device](#org452ea75) - - [chardev.c](#orgdd49880) - - [Writing Modules for Multiple Kernel Versions](#org903f5d5) -- [The /proc File System](#org6400501) - - [Read and Write a /proc File](#orga906618) - - [Manage /proc file with standard filesystem](#org561d817) - - [Manage /proc file with seq\_file](#org38ea52f) -- [sysfs: Interacting with your module](#org954957f) -- [Talking To Device Files](#org438f37b) -- [System Calls](#org8de5924) -- [Blocking Processes and threads](#org13e2c0e) - - [Sleep](#org9cbc7d3) - - [Completions](#org89cb410) -- [Avoiding Collisions and Deadlocks](#org949949f) - - [Mutex](#org10f05c2) - - [Spinlocks](#org5d633fc) - - [Read and write locks](#orgaa517c3) - - [Atomic operations](#orgadbf448) -- [Replacing Printks](#org7974c60) - - [Replacing printk](#org1c8b17b) - - [Flashing keyboard LEDs](#org418d823) -- [Scheduling Tasks](#orgf37d73f) - - [Tasklets](#org32525a8) - - [Work queues](#orge8a2d87) -- [Interrupt Handlers](#orgbc0cdf8) - - [Interrupt Handlers](#org93511bb) - - [Detecting button presses](#org77533ca) - - [Bottom Half](#orgdb452ba) -- [Crypto](#org627e987) - - [Hash functions](#org0d560c3) - - [Symmetric key encryption](#org4e331ef) -- [Standardising the interfaces: The Device Model](#org01d6493) -- [Optimisations](#org87293ce) - - [Likely and Unlikely conditions](#org87e8223) -- [Common Pitfalls](#org79dea20) - - [Using standard libraries](#org86275d7) - - [Disabling interrupts](#org8646229) - - [Sticking your head inside a large carnivore](#org58c8bc4) -- [Where To Go From Here?](#org2307e11) +- [Introduction](#orgcfc88e3) + - [Authorship](#orgb35992a) + - [Versioning and Notes](#org1e701d7) + - [Acknowledgements](#orgff412d1) + - [What Is A Kernel Module?](#org85e5d05) + - [Kernel module package](#org8138753) + - [What Modules are in my Kernel?](#org5f1fe9f) + - [Do I need to download and compile the kernel?](#orge267f2b) + - [Before We Begin](#orge21c8f9) +- [Headers](#org020fd9b) +- [Examples](#org3fb7793) +- [Hello World](#org8065caf) + - [The Simplest Module](#orgbda9acd) + - [Hello and Goodbye](#org761c702) + - [The \_\_init and \_\_exit Macros](#orgf583ec5) + - [Licensing and Module Documentation](#orgcf0f915) + - [Passing Command Line Arguments to a Module](#orgc88a626) + - [Modules Spanning Multiple Files](#orgcac6115) + - [Building modules for a precompiled kernel](#orgd8499f9) +- [Preliminaries](#orgb6633e2) + - [How modules begin and end](#org7f4891d) + - [Functions available to modules](#org8021b97) + - [User Space vs Kernel Space](#org2487a6b) + - [Name Space](#orgd5dd329) + - [Code space](#org3cb9562) + - [Device Drivers](#orgb4dc531) +- [Character Device drivers](#org952d427) + - [The file\_operations Structure](#org1f70982) + - [The file structure](#org7c65651) + - [Registering A Device](#org88f75aa) + - [Unregistering A Device](#org33e8c4e) + - [chardev.c](#org4a28a33) + - [Writing Modules for Multiple Kernel Versions](#orgbcf1c83) +- [The /proc File System](#orgf6ba9df) + - [Read and Write a /proc File](#org43d4889) + - [Manage /proc file with standard filesystem](#org1607657) + - [Manage /proc file with seq\_file](#org1f457d2) +- [sysfs: Interacting with your module](#orgf71ef7e) +- [Talking To Device Files](#org18e4279) +- [System Calls](#org57619bf) +- [Blocking Processes and threads](#org2c54a9a) + - [Sleep](#org8e98b07) + - [Completions](#orgc9f3884) +- [Avoiding Collisions and Deadlocks](#orgbc36b97) + - [Mutex](#org08abf74) + - [Spinlocks](#org8abef7b) + - [Read and write locks](#org0a55320) + - [Atomic operations](#org2652f4e) +- [Replacing Print Macros](#orgf928ddc) + - [Replacement](#org79d2e43) + - [Flashing keyboard LEDs](#org006f60c) +- [Scheduling Tasks](#orgcab6a64) + - [Tasklets](#orga758af1) + - [Work queues](#org5e7cad8) +- [Interrupt Handlers](#org991944f) + - [Interrupt Handlers](#orgdc4fa66) + - [Detecting button presses](#org170473f) + - [Bottom Half](#org58210bf) +- [Crypto](#org95671c1) + - [Hash functions](#org5702461) + - [Symmetric key encryption](#orgdca7f0b) +- [Standardising the interfaces: The Device Model](#org7ee71e2) +- [Optimisations](#org6dcd6c8) + - [Likely and Unlikely conditions](#org9398c78) +- [Common Pitfalls](#org7813eb9) + - [Using standard libraries](#orgcbd6cad) + - [Disabling interrupts](#orgf96d0f1) + - [Sticking your head inside a large carnivore](#orga703bab) +- [Where To Go From Here?](#orge615b39) ::: ::: -::: {#outline-container-org98c97cb .outline-2} -Introduction {#org98c97cb} +::: {#outline-container-orgcfc88e3 .outline-2} +Introduction {#orgcfc88e3} ------------ -::: {#text-org98c97cb .outline-text-2} +::: {#text-orgcfc88e3 .outline-text-2} The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 3.0. @@ -116,10 +116,10 @@ LDP. If you have questions or comments, please contact the address above. ::: -::: {#outline-container-org2782b14 .outline-3} -### Authorship {#org2782b14} +::: {#outline-container-orgb35992a .outline-3} +### Authorship {#orgb35992a} -::: {#text-org2782b14 .outline-text-3} +::: {#text-orgb35992a .outline-text-3} 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 @@ -132,10 +132,10 @@ other chapters. ::: ::: -::: {#outline-container-org0b6d633 .outline-3} -### Versioning and Notes {#org0b6d633} +::: {#outline-container-org1e701d7 .outline-3} +### Versioning and Notes {#org1e701d7} -::: {#text-org0b6d633 .outline-text-3} +::: {#text-org1e701d7 .outline-text-3} The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch @@ -150,20 +150,20 @@ I can\'t promise anything. ::: ::: -::: {#outline-container-orge57cf6b .outline-3} -### Acknowledgements {#orge57cf6b} +::: {#outline-container-orgff412d1 .outline-3} +### Acknowledgements {#orgff412d1} -::: {#text-orge57cf6b .outline-text-3} +::: {#text-orgff412d1 .outline-text-3} The following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon, Horst Schirmeier, Bob Mottram and Roman Lakeev. ::: ::: -::: {#outline-container-org37341bc .outline-3} -### What Is A Kernel Module? {#org37341bc} +::: {#outline-container-org85e5d05 .outline-3} +### What Is A Kernel Module? {#org85e5d05} -::: {#text-org37341bc .outline-text-3} +::: {#text-org85e5d05 .outline-text-3} So, you want to write a kernel module. You know C, you\'ve written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your @@ -181,58 +181,68 @@ time we want new functionality. ::: ::: -::: {#outline-container-orge9612fa .outline-3} -### Kernel module package {#orge9612fa} +::: {#outline-container-org8138753 .outline-3} +### Kernel module package {#org8138753} -::: {#text-orge9612fa .outline-text-3} +::: {#text-org8138753 .outline-text-3} Linux distros provide the commands *modprobe*, *insmod* and *depmod* within a package. On Debian: ::: {.org-src-container} - sudo apt-get install build-essential kmod +``` {.src .src-sh} +sudo apt-get install build-essential kmod +``` ::: On Parabola: ::: {.org-src-container} - sudo pacman -S gcc kmod +``` {.src .src-sh} +sudo pacman -S gcc kmod +``` ::: ::: ::: -::: {#outline-container-orgb6ce832 .outline-3} -### What Modules are in my Kernel? {#orgb6ce832} +::: {#outline-container-org5f1fe9f .outline-3} +### What Modules are in my Kernel? {#org5f1fe9f} -::: {#text-orgb6ce832 .outline-text-3} +::: {#text-org5f1fe9f .outline-text-3} To discover what modules are already loaded within your current kernel use the command **lsmod**. ::: {.org-src-container} - sudo lsmod +``` {.src .src-sh} +sudo lsmod +``` ::: Modules are stored within the file /proc/modules, so you can also see them with: ::: {.org-src-container} - sudo cat /proc/modules +``` {.src .src-sh} +sudo cat /proc/modules +``` ::: This can be a long list, and you might prefer to search for something particular. To search for the *fat* module: ::: {.org-src-container} - sudo lsmod | grep fat +``` {.src .src-sh} +sudo lsmod | grep fat +``` ::: ::: ::: -::: {#outline-container-orge1ec8b5 .outline-3} -### Do I need to download and compile the kernel? {#orge1ec8b5} +::: {#outline-container-orge267f2b .outline-3} +### Do I need to download and compile the kernel? {#orge267f2b} -::: {#text-orge1ec8b5 .outline-text-3} +::: {#text-orge267f2b .outline-text-3} For the purposes of following this guide you don\'t necessarily need to do that. However, it would be wise to run the examples within a test distro running on a virtual machine in order to avoid any possibility of @@ -240,10 +250,10 @@ messing up your system. ::: ::: -::: {#outline-container-org87661f2 .outline-3} -### Before We Begin {#org87661f2} +::: {#outline-container-orge21c8f9 .outline-3} +### Before We Begin {#orge21c8f9} -::: {#text-org87661f2 .outline-text-3} +::: {#text-orge21c8f9 .outline-text-3} Before we delve into code, there are a few issues we need to cover. Everyone\'s system is different and everyone has their own groove. Getting your first \"hello world\" program to compile and load correctly @@ -252,8 +262,8 @@ hurdle of doing it for the first time, it will be smooth sailing thereafter. ::: -- []{#org551d822}Modversioning\ - ::: {#text-org551d822 .outline-text-5} +- []{#org8987615}Modversioning\ + ::: {#text-org8987615 .outline-text-5} A module compiled for one kernel won\'t load if you boot a different kernel unless you enable CONFIG\_MODVERSIONS in the kernel. We won\'t go into module versioning until later in this guide. Until we @@ -264,8 +274,8 @@ thereafter. kernel with modversioning turned off. ::: -- []{#orgaf2a17b}Using X\ - ::: {#text-orgaf2a17b .outline-text-5} +- []{#org2132e29}Using X\ + ::: {#text-org2132e29 .outline-text-5} It is highly recommended that you type in, compile and load all the examples this guide discusses. It\'s also highly recommended you do this from a console. You should not be working on this stuff in X. @@ -281,45 +291,53 @@ thereafter. ::: ::: -::: {#outline-container-org52fbd37 .outline-2} -Headers {#org52fbd37} +::: {#outline-container-org020fd9b .outline-2} +Headers {#org020fd9b} ------- -::: {#text-org52fbd37 .outline-text-2} +::: {#text-org020fd9b .outline-text-2} Before you can build anything you\'ll need to install the header files for your kernel. On Parabola GNU/Linux: ::: {.org-src-container} - sudo pacman -S linux-libre-headers +``` {.src .src-sh} +sudo pacman -S linux-libre-headers +``` ::: On Debian: ::: {.org-src-container} - sudo apt-get update - apt-cache search linux-headers-$(uname -r) +``` {.src .src-sh} +sudo apt-get update +apt-cache search linux-headers-$(uname -r) +``` ::: This will tell you what kernel header files are available. Then for example: ::: {.org-src-container} - sudo apt-get install kmod linux-headers-4.12.12-1-amd64 +``` {.src .src-sh} +sudo apt-get install kmod linux-headers-4.12.12-1-amd64 +``` ::: ::: ::: -::: {#outline-container-org628945f .outline-2} -Examples {#org628945f} +::: {#outline-container-org3fb7793 .outline-2} +Examples {#org3fb7793} -------- -::: {#text-org628945f .outline-text-2} +::: {#text-org3fb7793 .outline-text-2} All the examples from this document are available within the *examples* subdirectory. To test that they compile: ::: {.org-src-container} - cd examples - make +``` {.src .src-sh} +cd examples +make +``` ::: If there are any compile errors then you might have a more recent kernel @@ -327,17 +345,17 @@ version or need to install the corresponding kernel header files. ::: ::: -::: {#outline-container-org0d455c0 .outline-2} -Hello World {#org0d455c0} +::: {#outline-container-org8065caf .outline-2} +Hello World {#org8065caf} ----------- -::: {#text-org0d455c0 .outline-text-2} +::: {#text-org8065caf .outline-text-2} ::: -::: {#outline-container-orgba22fe1 .outline-3} -### The Simplest Module {#orgba22fe1} +::: {#outline-container-orgbda9acd .outline-3} +### The Simplest Module {#orgbda9acd} -::: {#text-orgba22fe1 .outline-text-3} +::: {#text-orgbda9acd .outline-text-3} Most people learning programming start out with some sort of \"*hello world*\" example. I don\'t know what happens to people who break with this tradition, but I think it\'s safer not to find out. We\'ll start @@ -349,91 +367,111 @@ Here\'s the simplest module possible. Make a test directory: ::: {.org-src-container} - mkdir -p ~/develop/kernel/hello-1 - cd ~/develop/kernel/hello-1 +``` {.src .src-sh} +mkdir -p ~/develop/kernel/hello-1 +cd ~/develop/kernel/hello-1 +``` ::: Paste this into you favourite editor and save it as **hello-1.c**: ::: {.org-src-container} +``` {.src .src-c} +/* + * hello-1.c - The simplest kernel module. + */ +#include