From dadc4300bfc8dc6409ca81b29d38765e461ca354 Mon Sep 17 00:00:00 2001 From: Bob Mottram Date: Tue, 22 May 2018 13:56:32 +0100 Subject: [PATCH] Update different formats --- 4.15.2/LKMPG-4.15.2.html | 957 +++---- 4.15.2/LKMPG-4.15.2.md | 656 ++--- 4.15.2/LKMPG-4.15.2.rst | 5846 +++++++++++++++++++------------------- 4.15.2/LKMPG-4.15.2.tex | 254 +- 4.15.2/img/seq_file.png | Bin 26202 -> 26089 bytes 5 files changed, 3721 insertions(+), 3992 deletions(-) diff --git a/4.15.2/LKMPG-4.15.2.html b/4.15.2/LKMPG-4.15.2.html index 6a0e4e2..39e3e96 100644 --- a/4.15.2/LKMPG-4.15.2.html +++ b/4.15.2/LKMPG-4.15.2.html @@ -3,33 +3,26 @@ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> - - - The Linux Kernel Module Programming Guide - - - + + + + - + @@ -191,7 +99,7 @@ @licstart The following is the entire license notice for the JavaScript code in this tag. -Copyright (C) 2012-2017 Free Software Foundation, Inc. +Copyright (C) 2012-2013 Free Software Foundation, Inc. The JavaScript code in this tag is free software: you can redistribute it and/or modify it under the terms of the GNU @@ -232,28 +140,48 @@ for the JavaScript code in this tag. } /*]]>*///--> - + -
@@ -265,121 +193,121 @@ for the JavaScript code in this tag.

Table of Contents

-
-

Introduction

-
+
+

Introduction

+

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 +329,18 @@ If you publish or distribute this book commercially, donations, royalties, and/o

-
-

Authorship

-
+
+

Authorship

+

The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels. Bob Mottram updated the examples for 3.8 and later kernels, added the sysfs chapter and modified or updated other chapters.

-
-

Versioning and Notes

-
+
+

Versioning and Notes

+

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 +351,18 @@ The source code and discussions should apply to most architectures, but I can't
-
-

Acknowledgements

-
+
+

Acknowledgements

+

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.

-
-

What Is A Kernel Module?

-
+
+

What Is A Kernel Module?

+

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 +373,9 @@ What exactly is a kernel module? Modules are pieces of code that can be loaded a
-
-

Kernel module package

-
+
+

Kernel module package

+

Linux distros provide the commands modprobe, insmod and depmod within a package.

@@ -457,6 +385,7 @@ On Debian:

+
sudo apt-get install build-essential kmod
 
@@ -466,20 +395,22 @@ On Parabola:

+
sudo pacman -S gcc kmod
 
-
-

What Modules are in my Kernel?

-
+
+

What Modules are in my Kernel?

+

To discover what modules are already loaded within your current kernel use the command lsmod.

+
sudo lsmod
 
@@ -489,6 +420,7 @@ Modules are stored within the file /proc/modules, so you can also see them with:

+
sudo cat /proc/modules
 
@@ -498,39 +430,37 @@ This can be a long list, and you might prefer to search for something particular

+
sudo lsmod | grep fat
 
-
-

Do I need to download and compile the kernel?

-
+
+

Do I need to download and compile the kernel?

+

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 Begin

-
+
+

Before We Begin

+

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.

-
    -
  • Modversioning
    -
    +
    • Modversioning

      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.

    • -
    • Using X
      -
      +
    • Using X

      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.

      @@ -539,19 +469,19 @@ It is highly recommended that you type in, compile and load all the examples thi Modules can't print to the screen like printf() can, but they can log information and warnings, which ends up being printed on your screen, but only on a console. If you insmod a module from an xterm, the information and warnings will be logged, but only to your systemd journal. You won't see it unless you look through your journalctl. To have immediate access to this information, do all your work from the console.

      -
    • -
    +
-
-

Headers

-
+
+

Headers

+

Before 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
 
@@ -561,6 +491,7 @@ On Debian:

+
sudo apt-get update
 apt-cache search linux-headers-$(uname -r)
 
@@ -571,19 +502,21 @@ This will tell you what kernel header files are available. Then for example:

+
sudo apt-get install kmod linux-headers-4.15.2-1-amd64
 
-
-

Examples

-
+
+

Examples

+

All the examples from this document are available within the examples subdirectory. To test that they compile:

+
cd examples
 make
 
@@ -594,13 +527,12 @@ If there are any compile errors then you might have a more recent kernel version

-
-

Hello World

-
-
-
-

The Simplest Module

-
+
+

Hello World

+
+
+

The Simplest Module

+

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,6 +546,7 @@ Make a test directory:

+
mkdir -p ~/develop/kernel/hello-1
 cd ~/develop/kernel/hello-1
 
@@ -624,6 +557,7 @@ Paste this into you favourite editor and save it as hello-1.c:

+
/*
  *  hello-1.c - The simplest kernel module.
  */
@@ -652,6 +586,7 @@ Now you'll need a Makefile. If you copy and paste this change the indentation to
 

+
obj-m += hello-1.o
 
 all:
@@ -667,6 +602,7 @@ And finally just:
 

+
make
 
@@ -676,6 +612,7 @@ If all goes smoothly you should then find that you have a compiled hello-1.ko

+
sudo modinfo hello-1.ko
 
@@ -685,6 +622,7 @@ At this point the command:

+
sudo lsmod | grep hello
 
@@ -694,6 +632,7 @@ should return nothing. You can try loading your shiny new module with:

+
sudo insmod hello-1.ko
 
@@ -703,6 +642,7 @@ The dash character will get converted to an underscore, so when you again try:

+
sudo lsmod | grep hello
 
@@ -712,6 +652,7 @@ you should now see your loaded module. It can be removed again with:

+
sudo rmmod hello_1
 
@@ -721,6 +662,7 @@ Notice that the dash was replaced by an underscore. To see what just happened in

+
journalctl --since "1 hour ago" | grep kernel
 
@@ -743,24 +685,20 @@ Lastly, every kernel module needs to include linux/module.h. We needed to includ

-
    -
  • A point about coding style
    -
    +
    • A point about coding style

      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.

    • -
    • Introducing print macros
      -
      +
    • Introducing print macros

      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.

    • -
    • About Compiling
      -
      +
    • About Compiling

      Kernel modules need to be compiled a bit differently from regular userspace apps. Former kernel versions required us to care much about these settings, which are usually stored in Makefiles. 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.

      @@ -775,18 +713,18 @@ Here's another exercise for the reader. See that comment above the return statem

      -
    • -
    +
-
-

Hello and Goodbye

-
+
+

Hello and Goodbye

+

In 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().
@@ -816,6 +754,7 @@ So now we have two real kernel modules under our belt. Adding another module is
 

+
obj-m += hello-1.o
 obj-m += hello-2.o
 
@@ -833,9 +772,9 @@ Now have a look at linux/drivers/char/Makefile for a real world example. As you
 
-
-

The __init and __exit Macros

-
+
+

The __init and __exit Macros

+

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.

@@ -853,6 +792,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.
  */
@@ -880,14 +820,15 @@ module_exit(hello_3_exit);
 
-
-

Licensing and Module Documentation

-
+
+

Licensing and Module Documentation

+

Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this:

+
# 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
@@ -904,6 +845,7 @@ To reference what license you're using a macro is available called MODULE_LIC
 

+
/*
  *  hello-4.c - Demonstrates module documentation.
  */
@@ -934,9 +876,9 @@ module_exit(cleanup_hello_4);
 
-
-

Passing Command Line Arguments to a Module

-
+
+

Passing Command Line Arguments to a Module

+

Modules can take command line arguments, but not with the argc/argv you might be used to.

@@ -950,6 +892,7 @@ The module_param() macro takes 3 arguments: the name of the variable, its type a

+
int myint = 3;
 module_param(myint, int, 0);
 
@@ -960,12 +903,13 @@ Arrays are supported too, but things are a bit different now than they were in t

+
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 */
+module_param_array(myshortarray, short, &count, 0); /* put count into "count" variable */
 
@@ -978,6 +922,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.
  */
@@ -1056,6 +1001,7 @@ I would recommend playing around with this code:
 

+
# sudo insmod hello-5.ko mystring="bebop" mybyte=255 myintArray=-1
 mybyte is an 8 bit integer: 255
 myshort is a short integer: 1
@@ -1086,9 +1032,9 @@ hello-5.o: invalid argument syntax for mylong: 'h'
 
-
-

Modules Spanning Multiple Files

-
+
+

Modules Spanning Multiple Files

+

Sometimes it makes sense to divide a kernel module between several source files.

@@ -1098,6 +1044,7 @@ Here's an example of such a kernel module.

+
/*
  *  start.c - Illustration of multi filed modules
  */
@@ -1118,6 +1065,7 @@ The next file:
 

+
/*
  *  stop.c - Illustration of multi filed modules
  */
@@ -1137,6 +1085,7 @@ And finally, the makefile:
 

+
obj-m += hello-1.o
 obj-m += hello-2.o
 obj-m += hello-3.o
@@ -1159,9 +1108,9 @@ This is the complete makefile for all the examples we've seen so far. The first
 
-
-

Building modules for a precompiled kernel

-
+
+

Building modules for a precompiled kernel

+

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.

@@ -1175,6 +1124,7 @@ Now, if you just install a kernel source tree, use it to compile your kernel mod

+
insmod: error inserting 'poet_atkm.ko': -1 Invalid module format
 
@@ -1184,6 +1134,7 @@ 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
 REGPARM 4KSTACKS gcc-3.3' should be '2.6.5-1.358 686 REGPARM 4KSTACKS gcc-3.3'
 
@@ -1194,6 +1145,7 @@ In other words, your kernel refuses to accept your module because version string

+
# sudo modinfo hello-4.ko
 license:        GPL
 author:         Bob Mottram <bob@freedombone.net>
@@ -1216,6 +1168,7 @@ Let's focus again on the previous error message: a closer look at the version ma
 

+
VERSION = 4
 PATCHLEVEL = 7
 SUBLEVEL = 4
@@ -1232,6 +1185,7 @@ Now, please run make to update configuration and version headers and objects:
 

+
# make
 CHK     include/linux/version.h
 UPD     include/linux/version.h
@@ -1253,13 +1207,12 @@ If you do not desire to actually compile the kernel, you can interrupt the build
 
-
-

Preliminaries

-
-
-
-

How modules begin and end

-
+
+

Preliminaries

+
+
+

How modules begin and end

+

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.

@@ -1274,9 +1227,9 @@ Every module must have an entry function and an exit function. Since there's mor
-
-

Functions available to modules

-
+
+

Functions available to modules

+

Programmers 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.

@@ -1294,6 +1247,7 @@ Would you like to see what system calls are made by printf()? It's easy! Compile

+
#include <stdio.h>
 
 int main(void)
@@ -1314,9 +1268,9 @@ You can even write modules to replace the kernel's system calls, which we'll do
 
-
-

User Space vs Kernel Space

-
+
+

User Space vs Kernel Space

+

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'.

@@ -1327,9 +1281,9 @@ Recall the discussion about library functions vs system calls. Typically, you us
-
-

Name Space

-
+
+

Name Space

+

When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you'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.

@@ -1344,9 +1298,9 @@ The file /proc/kallsyms holds all the symbols that the kernel knows about
-
-

Code space

-
+
+

Code space

+

Memory 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.

@@ -1360,27 +1314,26 @@ The kernel has its own space of memory as well. Since a module is code which can

-By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't quite the same thing as "building all your modules into the kernel", although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel. +By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't quite the same thing as /"building all your modules into the kernel"/, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel.

-
-

Device Drivers

-
+
+

Device Drivers

+

One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.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.

-
    -
  • Major and Minor Numbers
    -
    +
    • Major and Minor Numbers

      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]
       brw-rw----  1 root  disk  3, 1 Jul  5  2000 /dev/hda1
       brw-rw----  1 root  disk  3, 2 Jul  5  2000 /dev/hda2
      @@ -1401,6 +1354,7 @@ 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-r-----  1 root  dial 4, 65 Nov 17 10:26 /dev/ttyS1
       crw-rw----  1 root  dial 4, 66 Jul  5  2000 /dev/ttyS2
      @@ -1421,10 +1375,11 @@ I would like to make a few last points which are implicit from the above discuss
       

      -By the way, when I say "hardware", I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files: +By the way, when I say /"hardware"/, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files:

      +
      % ls -l /dev/sda /dev/sdb
       brw-rw---- 1 root disk 8,  0 Jan  3 09:02 /dev/sda
       brw-rw---- 1 root disk 8, 16 Jan  3 09:02 /dev/sdb
      @@ -1435,18 +1390,16 @@ brw-rw---- 1 root disk 8, 16 Jan  3 09:02 /dev/sdb
       By now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 8). Sometimes two device files with the same major but different minor number can actually represent the same piece of physical hardware. So just be aware that the word "hardware" in our discussion can mean something very abstract.
       

      -
    • -
    +
-
-

Character Device drivers

-
-
-
-

The file_operations Structure

-
+
+

Character Device drivers

+
+
+

The file_operations Structure

+

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.

@@ -1456,6 +1409,7 @@ For example, every character driver needs to define a function that reads from t

+
struct file_operations {
     struct module *owner;
     loff_t (*llseek) (struct file *, loff_t, int);
@@ -1498,6 +1452,7 @@ There is a gcc extension that makes assigning to this structure more convenient.
 

+
struct file_operations fops = {
         read: device_read,
         write: device_write,
@@ -1512,6 +1467,7 @@ However, there's also a C99 way of assigning to elements of a structure, and thi
 

+
struct file_operations fops = {
         .read = device_read,
         .write = device_write,
@@ -1531,9 +1487,9 @@ An instance of struct file_operations containing pointers to functions that are
 
-
-

The file structure

-
+
+

The file structure

+

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.

@@ -1548,9 +1504,9 @@ Go ahead and look at the definition of file. Most of the entries you see, like s
-
-

Registering A Device

-
+
+

Registering A Device

+

As 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.

@@ -1560,6 +1516,7 @@ Adding a driver to your system means registering it with the kernel. This is syn

+
int register_chrdev(unsigned int major, const char *name, struct file_operations *fops);
 
@@ -1578,9 +1535,9 @@ If you pass a major number of 0 to register_chrdev, the return value will be the
-
-

Unregistering A Device

-
+
+

Unregistering A Device

+

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.

@@ -1590,8 +1547,10 @@ Normally, when you don't want to allow something, you return an error code (a ne

    -
  • try_module_get(THIS_MODULE): Increment the use count.
  • -
  • module_put(THIS_MODULE): Decrement the use count.
  • +
  • try_module_get(THIS_MODULE): Increment the use count. +
  • +
  • module_put(THIS_MODULE): Decrement the use count. +

@@ -1600,14 +1559,15 @@ It's important to keep the counter accurate; if you ever do lose track of the co

-
-

chardev.c

-
+
+

chardev.c

+

The next code sample creates a char driver named chardev. You can cat its device file.

+
cat /proc/devices
 
@@ -1617,6 +1577,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
@@ -1803,9 +1764,9 @@ The next code sample creates a char driver named chardev. You can cat its device
 
-
-

Writing Modules for Multiple Kernel Versions

-
+
+

Writing Modules for Multiple Kernel Versions

+

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.

@@ -1829,9 +1790,9 @@ You might already have noticed that recent kernels look different. In case you h
-
-

The /proc File System

-
+
+

The /proc File System

+

In 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.

@@ -1861,12 +1822,14 @@ Each time, everytime the file /proc/helloworld is read, the function p

+
# cat /proc/helloworld
 HelloWorld!
 
+
/*
  procfs1.c
 */
@@ -1921,9 +1884,9 @@ HelloWorld!
 
-
-

Read and Write a /proc File

-
+
+

Read and Write a /proc File

+

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)

@@ -1937,6 +1900,7 @@ The only memory segment accessible to a process is its own, so when writing regu

+
/**
  *  procfs2.c -  create a "file" in /proc
  *
@@ -2040,9 +2004,9 @@ The only memory segment accessible to a process is its own, so when writing regu
 
-
-

Manage /proc file with standard filesystem

-
+
+

Manage /proc file with standard filesystem

+

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.

@@ -2068,6 +2032,7 @@ It's important to note that the standard roles of read and write are reversed in

+
/*
     procfs3.c
 */
@@ -2160,9 +2125,9 @@ Still hungry for procfs examples? Well, first of all keep in mind, there are rum
 
-
-

Manage /proc file with seq_file

-
+
+

Manage /proc file with seq_file

+

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 @@ -2197,6 +2162,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.
@@ -2339,9 +2305,11 @@ If you want more information, you can read this web page:
 

@@ -2352,14 +2320,15 @@ You can also read the code of fs/seq_file.c in the linux kernel.
-
-

sysfs: Interacting with your module

-
+
+

sysfs: Interacting with your module

+

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
 
@@ -2369,73 +2338,8 @@ 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/kobject.h>
-#include <linux/sysfs.h>
-#include <linux/init.h>
-#include <linux/fs.h>
-#include <linux/string.h>
-
-MODULE_LICENSE("GPL");
-MODULE_AUTHOR("Bob Mottram");
-
-static struct kobject *mymodule;
-
-/* the variable you want to be able to change */
-static int myvariable = 0;
-
-static ssize_t myvariable_show(struct kobject *kobj,
-                               struct kobj_attribute *attr,
-                               char *buf)
-{
-    return sprintf(buf, "%d\n", myvariable);
-}
-
-static ssize_t myvariable_store(struct kobject *kobj,
-                                struct kobj_attribute *attr,
-                                char *buf, size_t count)
-{
-    sscanf(buf, "%du", &myvariable);
-    return count;
-}
-
-
-static struct kobj_attribute myvariable_attribute =
-    __ATTR(myvariable, 0660, myvariable_show,
-           (void*)myvariable_store);
-
-static int __init mymodule_init (void)
-{
-    int error = 0;
-
-    pr_info("mymodule: initialised\n");
-
-    mymodule =
-        kobject_create_and_add("mymodule", kernel_kobj);
-    if (!mymodule)
-        return -ENOMEM;
-
-    error = sysfs_create_file(mymodule, &myvariable_attribute.attr);
-    if (error) {
-        pr_info("failed to create the myvariable file " \
-               "in /sys/kernel/mymodule\n");
-    }
-
-    return error;
-}
-
-static void __exit mymodule_exit (void)
-{
-    pr_info("mymodule: Exit success\n");
-    kobject_put(mymodule);
-}
-
-module_init(mymodule_init);
-module_exit(mymodule_exit);
+
"hello-sysfs.c"body
 
@@ -2444,6 +2348,7 @@ Make and install the module:

+
make
 sudo insmod hello-sysfs.ko
 
@@ -2454,6 +2359,7 @@ Check that it exists:

+
sudo lsmod | grep hello_sysfs
 
@@ -2463,6 +2369,7 @@ What is the current value of myvariable ?

+
cat /sys/kernel/mymodule/myvariable
 
@@ -2472,6 +2379,7 @@ Set the value of myvariable and check that it changed.

+
echo "32" > /sys/kernel/mymodule/myvariable
 cat /sys/kernel/mymodule/myvariable
 
@@ -2482,15 +2390,16 @@ Finally, remove the test module:

+
sudo rmmod hello_sysfs
 
-
-

Talking To Device Files

-
+
+

Talking To Device Files

+

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.

@@ -2516,6 +2425,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
  */
@@ -2807,6 +2717,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
 
+
/*
  *  chardev.h - the header file with the ioctl definitions.
  *
@@ -2877,6 +2788,7 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
 
+
/*
  *  ioctl.c - the process to use ioctl's to control the kernel module
  *
@@ -2986,9 +2898,9 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o
 
-
-

System Calls

-
+
+

System Calls

+

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.

@@ -3034,6 +2946,7 @@ Note that all the related problems make syscall stealing unfeasiable for product

+
/*
  *  syscall.c
  *
@@ -3194,13 +3107,12 @@ MODULE_LICENSE("GPL");
 
-
-

Blocking Processes and threads

-
-
-
-

Sleep

-
+
+

Blocking Processes and threads

+
+
+

Sleep

+

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).

@@ -3210,6 +3122,7 @@ This kernel module is an example of this. The file (called /proc/sleep) c

+
tail -f
 
@@ -3247,6 +3160,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# cat_noblock /proc/sleep
 Last input:
@@ -3271,6 +3185,7 @@ 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
@@ -3540,6 +3455,7 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
 
+
/* cat_noblock.c - open a file and display its contents, but exit rather than
  * wait for input */
 /* Copyright (C) 1998 by Ori Pomerantz */
@@ -3610,9 +3526,9 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);
 
-
-

Completions

-
+
+

Completions

+

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.

@@ -3622,6 +3538,7 @@ In the following example two threads are started, but one needs to start before

+
#include <linux/init.h>
 #include <linux/module.h>
 #include <linux/kernel.h>
@@ -3717,21 +3634,22 @@ There are other variations upon the wait_for_completion function, which i
 
-
-

Avoiding Collisions and Deadlocks

-
+
+

Avoiding Collisions and Deadlocks

+

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.

-
-

Mutex

-
+
+

Mutex

+

You can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland. This may be all that's needed to avoid collisions in most cases.

+
#include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/init.h>
@@ -3776,18 +3694,19 @@ MODULE_LICENSE("GPL");
 
-
-

Spinlocks

-
+
+

Spinlocks

+

As the name suggests, spinlocks lock up the CPU that the code is running on, taking 100% of its resources. Because of this you should only use the spinlock mechanism around code which is likely to take no more than a few milliseconds to run and so won't noticably slow anything down from the user's point of view.

-The example here is "irq safe" in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the flags variable to retain their state. +The example here is /"irq safe"/ in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the flags variable to retain their state.

+
#include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/init.h>
@@ -3856,14 +3775,15 @@ MODULE_LICENSE("GPL");
 
-
-

Read and write locks

-
+
+

Read and write locks

+

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/module.h>
 #include <linux/interrupt.h>
@@ -3925,14 +3845,15 @@ Of course if you know for sure that there are no functions triggered by irqs whi
 

-
-

Atomic operations

-
+
+

Atomic operations

+

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/module.h>
 #include <linux/interrupt.h>
@@ -4014,13 +3935,12 @@ MODULE_LICENSE("GPL");
 
-
-

Replacing Print Macros

-
-
-
-

Replacement

-
+
+

Replacing Print Macros

+
+
+

Replacement

+

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.

@@ -4034,6 +3954,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
@@ -4147,9 +4068,9 @@ module_exit(print_string_exit);
 
-
-

Flashing keyboard LEDs

-
+
+

Flashing keyboard LEDs

+

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.

@@ -4159,6 +4080,7 @@ The following source code illustrates a minimal kernel module which, when loaded

+
/*
  *  kbleds.c - Blink keyboard leds until the module is unloaded.
  */
@@ -4266,22 +4188,23 @@ While you have seen lots of stuff that can be used to aid debugging here, there
 
-
-

Scheduling Tasks

-
+
+

Scheduling Tasks

+

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.

-
-

Tasklets

-
+
+

Tasklets

+

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/module.h>
 #include <linux/delay.h>
@@ -4325,6 +4248,7 @@ So with this example loaded dmesg should show:
 

+
tasklet example init
 Example tasklet starts
 Example tasklet init continues...
@@ -4333,14 +4257,15 @@ Example tasklet ends
 
-
-

Work queues

-
+
+

Work queues

+

To add a task to the scheduler we can use a workqueue. The kernel then uses the Completely Fair Scheduler (CFS) to execute work within the queue.

+
#include <linux/module.h>
 #include <linux/init.h>
 #include <linux/workqueue.h>
@@ -4377,13 +4302,12 @@ MODULE_DESCRIPTION("Workqueue example");
 
-
-

Interrupt Handlers

-
-
-
-

Interrupt Handlers

-
+
+

Interrupt Handlers

+
+
+

Interrupt Handlers

+

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.

@@ -4414,9 +4338,9 @@ This function receives the IRQ number, the name of the function, flags, a name f
-
-

Detecting button presses

-
+
+

Detecting button presses

+

Many 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.

@@ -4426,6 +4350,7 @@ Here's an example where buttons are connected to GPIO numbers 17 and 18 and an L

+
/*
  *  intrpt.c - Handling GPIO with interrupts
  *
@@ -4582,9 +4507,9 @@ MODULE_DESCRIPTION("Handle some GPIO interrupts"
 
-
-

Bottom Half

-
+
+

Bottom Half

+

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.

@@ -4594,6 +4519,7 @@ The example below modifies the previous example to also run an additional task w

+
/*
  * bottomhalf.c - Top and bottom half interrupt handling
  *
@@ -4764,22 +4690,23 @@ MODULE_DESCRIPTION("Interrupt with top and bottom half"
 
-
-

Crypto

-
+
+

Crypto

+

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.

-
-

Hash functions

-
+
+

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 <crypto/internal/hash.h>
 
@@ -4852,6 +4779,7 @@ Make and install the module:
 

+
make
 sudo insmod cryptosha256.ko
 dmesg
@@ -4867,19 +4795,21 @@ Finally, remove the test module:
 

+
sudo rmmod cryptosha256
 
-
-

Symmetric key encryption

-
+
+

Symmetric key encryption

+

Here is an example of symmetrically encrypting a string using the AES algorithm and a password.

+
#include <crypto/internal/skcipher.h>
 #include <linux/module.h>
 #include <linux/crypto.h>
@@ -5065,14 +4995,15 @@ MODULE_LICENSE("GPL");
 
-
-

Standardising the interfaces: The Device Model

-
+
+

Standardising the interfaces: The Device Model

+

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/module.h>
 #include <linux/platform_device.h>
@@ -5173,13 +5104,12 @@ module_exit(devicemodel_exit);
 
-
-

Optimisations

-
-
-
-

Likely and Unlikely conditions

-
+
+

Optimisations

+
+
+

Likely and Unlikely conditions

+

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.

@@ -5189,6 +5119,7 @@ For example, when allocating memory you're almost always expecting this to succe

+
bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx);
 if (unlikely(!bvl)) {
   mempool_free(bio, bio_pool);
@@ -5204,35 +5135,35 @@ When the unlikely macro is used the compiler alters its machine instructi
 
-
-

Common Pitfalls

-
+
+

Common Pitfalls

+

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.

-
-

Using standard libraries

-
+
+

Using standard libraries

+

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.

-
-

Disabling interrupts

-
+
+

Disabling interrupts

+

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.

-
-

Sticking your head inside a large carnivore

-
+
+

Sticking your head inside a large carnivore

+

I probably don't have to warn you about this, but I figured I will anyway, just in case.

@@ -5240,9 +5171,9 @@ I probably don't have to warn you about this, but I figured I will anyway, just
-
-

Where To Go From Here?

-
+
+

Where To Go From Here?

+

I 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.15.2/LKMPG-4.15.2.md b/4.15.2/LKMPG-4.15.2.md index eb1259e..f7d8ef6 100644 --- a/4.15.2/LKMPG-4.15.2.md +++ b/4.15.2/LKMPG-4.15.2.md @@ -8,83 +8,83 @@ Table of Contents ----------------- ::: {#text-table-of-contents} -- [Introduction](#org1785162) - - [Authorship](#org63a1b37) - - [Versioning and Notes](#org10863e7) - - [Acknowledgements](#org49d4e59) - - [What Is A Kernel Module?](#org0a5ce13) - - [Kernel module package](#org1cb0938) - - [What Modules are in my Kernel?](#org878e43e) - - [Do I need to download and compile the kernel?](#orgb530dfd) - - [Before We Begin](#org2583533) -- [Headers](#org46d2b5f) -- [Examples](#orgdd7dd5d) -- [Hello World](#org92f8539) - - [The Simplest Module](#org5ae5562) - - [Hello and Goodbye](#org5c5dd06) - - [The \_\_init and \_\_exit Macros](#org7fd362f) - - [Licensing and Module Documentation](#orga52c864) - - [Passing Command Line Arguments to a Module](#org6976bc8) - - [Modules Spanning Multiple Files](#org5a97220) - - [Building modules for a precompiled kernel](#org65d6819) -- [Preliminaries](#orgb5adf2b) - - [How modules begin and end](#org4cf9365) - - [Functions available to modules](#orgcb5e2da) - - [User Space vs Kernel Space](#orgab9f1d1) - - [Name Space](#org9d3f3fc) - - [Code space](#orga3691e9) - - [Device Drivers](#org382352c) -- [Character Device drivers](#orgf1744e4) - - [The file\_operations Structure](#org07ed5b3) - - [The file structure](#orgf283636) - - [Registering A Device](#orgab1c63f) - - [Unregistering A Device](#org85bc5ea) - - [chardev.c](#orgdbd100e) - - [Writing Modules for Multiple Kernel Versions](#org130321b) -- [The /proc File System](#org44e86f2) - - [Read and Write a /proc File](#org330f61f) - - [Manage /proc file with standard filesystem](#orgaae8b16) - - [Manage /proc file with seq\_file](#org688df35) -- [sysfs: Interacting with your module](#orgbd8ce69) -- [Talking To Device Files](#orga1b8e31) -- [System Calls](#orgdf0ab54) -- [Blocking Processes and threads](#org83613ec) - - [Sleep](#org36ce43a) - - [Completions](#orgcfa6577) -- [Avoiding Collisions and Deadlocks](#org3ffdc76) - - [Mutex](#org89ec2e6) - - [Spinlocks](#org9889db8) - - [Read and write locks](#orge2dc3e1) - - [Atomic operations](#org1316854) -- [Replacing Print Macros](#orgbdec3ca) - - [Replacement](#org4579c68) - - [Flashing keyboard LEDs](#orgc9bd69e) -- [Scheduling Tasks](#orgf1f1faf) - - [Tasklets](#orgd815b3b) - - [Work queues](#org9b5b18e) -- [Interrupt Handlers](#org1cdf533) - - [Interrupt Handlers](#org5db45ad) - - [Detecting button presses](#org9ca1a6c) - - [Bottom Half](#org575eebf) -- [Crypto](#org004956f) - - [Hash functions](#org8f45455) - - [Symmetric key encryption](#orgcf62e2d) -- [Standardising the interfaces: The Device Model](#org161334f) -- [Optimisations](#org8639895) - - [Likely and Unlikely conditions](#orgb775e92) -- [Common Pitfalls](#org1cf3372) - - [Using standard libraries](#org8e71ecd) - - [Disabling interrupts](#org9ff7def) - - [Sticking your head inside a large carnivore](#orgdd651cd) -- [Where To Go From Here?](#orgcf6e3aa) +- [Introduction](#sec-1) + - [Authorship](#sec-1-1) + - [Versioning and Notes](#sec-1-2) + - [Acknowledgements](#sec-1-3) + - [What Is A Kernel Module?](#sec-1-4) + - [Kernel module package](#sec-1-5) + - [What Modules are in my Kernel?](#sec-1-6) + - [Do I need to download and compile the kernel?](#sec-1-7) + - [Before We Begin](#sec-1-8) +- [Headers](#sec-2) +- [Examples](#sec-3) +- [Hello World](#sec-4) + - [The Simplest Module](#sec-4-1) + - [Hello and Goodbye](#sec-4-2) + - [The \_\_init and \_\_exit Macros](#sec-4-3) + - [Licensing and Module Documentation](#sec-4-4) + - [Passing Command Line Arguments to a Module](#sec-4-5) + - [Modules Spanning Multiple Files](#sec-4-6) + - [Building modules for a precompiled kernel](#sec-4-7) +- [Preliminaries](#sec-5) + - [How modules begin and end](#sec-5-1) + - [Functions available to modules](#sec-5-2) + - [User Space vs Kernel Space](#sec-5-3) + - [Name Space](#sec-5-4) + - [Code space](#sec-5-5) + - [Device Drivers](#sec-5-6) +- [Character Device drivers](#sec-6) + - [The file\_operations Structure](#sec-6-1) + - [The file structure](#sec-6-2) + - [Registering A Device](#sec-6-3) + - [Unregistering A Device](#sec-6-4) + - [chardev.c](#sec-6-5) + - [Writing Modules for Multiple Kernel Versions](#sec-6-6) +- [The /proc File System](#sec-7) + - [Read and Write a /proc File](#sec-7-1) + - [Manage /proc file with standard filesystem](#sec-7-2) + - [Manage /proc file with seq\_file](#sec-7-3) +- [sysfs: Interacting with your module](#sec-8) +- [Talking To Device Files](#sec-9) +- [System Calls](#sec-10) +- [Blocking Processes and threads](#sec-11) + - [Sleep](#sec-11-1) + - [Completions](#sec-11-2) +- [Avoiding Collisions and Deadlocks](#sec-12) + - [Mutex](#sec-12-1) + - [Spinlocks](#sec-12-2) + - [Read and write locks](#sec-12-3) + - [Atomic operations](#sec-12-4) +- [Replacing Print Macros](#sec-13) + - [Replacement](#sec-13-1) + - [Flashing keyboard LEDs](#sec-13-2) +- [Scheduling Tasks](#sec-14) + - [Tasklets](#sec-14-1) + - [Work queues](#sec-14-2) +- [Interrupt Handlers](#sec-15) + - [Interrupt Handlers](#sec-15-1) + - [Detecting button presses](#sec-15-2) + - [Bottom Half](#sec-15-3) +- [Crypto](#sec-16) + - [Hash functions](#sec-16-1) + - [Symmetric key encryption](#sec-16-2) +- [Standardising the interfaces: The Device Model](#sec-17) +- [Optimisations](#sec-18) + - [Likely and Unlikely conditions](#sec-18-1) +- [Common Pitfalls](#sec-19) + - [Using standard libraries](#sec-19-1) + - [Disabling interrupts](#sec-19-2) + - [Sticking your head inside a large carnivore](#sec-19-3) +- [Where To Go From Here?](#sec-20) ::: ::: -::: {#outline-container-org1785162 .outline-2} -Introduction {#org1785162} +::: {#outline-container-sec-1 .outline-2} +Introduction {#sec-1} ------------ -::: {#text-org1785162 .outline-text-2} +::: {#text-1 .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. @@ -105,7 +105,7 @@ the Open Software License, and the original copyright notice must remain intact. If you have contributed new material to this book, you must make the material and source code available for your revisions. Please make revisions and updates available directly to the document maintainer, -Peter Jay Salzman \. This will allow for the merging of +Peter Jay Salzman \. This will allow for the merging of updates and provide consistent revisions to the Linux community. If you publish or distribute this book commercially, donations, @@ -116,10 +116,10 @@ LDP. If you have questions or comments, please contact the address above. ::: -::: {#outline-container-org63a1b37 .outline-3} -### Authorship {#org63a1b37} +::: {#outline-container-sec-1-1 .outline-3} +### Authorship {#sec-1-1} -::: {#text-org63a1b37 .outline-text-3} +::: {#text-1-1 .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-org10863e7 .outline-3} -### Versioning and Notes {#org10863e7} +::: {#outline-container-sec-1-2 .outline-3} +### Versioning and Notes {#sec-1-2} -::: {#text-org10863e7 .outline-text-3} +::: {#text-1-2 .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-org49d4e59 .outline-3} -### Acknowledgements {#org49d4e59} +::: {#outline-container-sec-1-3 .outline-3} +### Acknowledgements {#sec-1-3} -::: {#text-org49d4e59 .outline-text-3} +::: {#text-1-3 .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-org0a5ce13 .outline-3} -### What Is A Kernel Module? {#org0a5ce13} +::: {#outline-container-sec-1-4 .outline-3} +### What Is A Kernel Module? {#sec-1-4} -::: {#text-org0a5ce13 .outline-text-3} +::: {#text-1-4 .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,10 +181,10 @@ time we want new functionality. ::: ::: -::: {#outline-container-org1cb0938 .outline-3} -### Kernel module package {#org1cb0938} +::: {#outline-container-sec-1-5 .outline-3} +### Kernel module package {#sec-1-5} -::: {#text-org1cb0938 .outline-text-3} +::: {#text-1-5 .outline-text-3} Linux distros provide the commands *modprobe*, *insmod* and *depmod* within a package. @@ -206,10 +206,10 @@ sudo pacman -S gcc kmod ::: ::: -::: {#outline-container-org878e43e .outline-3} -### What Modules are in my Kernel? {#org878e43e} +::: {#outline-container-sec-1-6 .outline-3} +### What Modules are in my Kernel? {#sec-1-6} -::: {#text-org878e43e .outline-text-3} +::: {#text-1-6 .outline-text-3} To discover what modules are already loaded within your current kernel use the command **lsmod**. @@ -239,10 +239,10 @@ sudo lsmod | grep fat ::: ::: -::: {#outline-container-orgb530dfd .outline-3} -### Do I need to download and compile the kernel? {#orgb530dfd} +::: {#outline-container-sec-1-7 .outline-3} +### Do I need to download and compile the kernel? {#sec-1-7} -::: {#text-orgb530dfd .outline-text-3} +::: {#text-1-7 .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 @@ -250,10 +250,10 @@ messing up your system. ::: ::: -::: {#outline-container-org2583533 .outline-3} -### Before We Begin {#org2583533} +::: {#outline-container-sec-1-8 .outline-3} +### Before We Begin {#sec-1-8} -::: {#text-org2583533 .outline-text-3} +::: {#text-1-8 .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 @@ -262,8 +262,8 @@ hurdle of doing it for the first time, it will be smooth sailing thereafter. ::: -- []{#org4517450}Modversioning\ - ::: {#text-org4517450 .outline-text-5} +- []{#sec-1-8-0-1}Modversioning\ + ::: {#text-1-8-0-1 .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 @@ -274,8 +274,8 @@ thereafter. kernel with modversioning turned off. ::: -- []{#orgdc404d5}Using X\ - ::: {#text-orgdc404d5 .outline-text-5} +- []{#sec-1-8-0-2}Using X\ + ::: {#text-1-8-0-2 .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. @@ -291,11 +291,11 @@ thereafter. ::: ::: -::: {#outline-container-org46d2b5f .outline-2} -Headers {#org46d2b5f} +::: {#outline-container-sec-2 .outline-2} +Headers {#sec-2} ------- -::: {#text-org46d2b5f .outline-text-2} +::: {#text-2 .outline-text-2} Before you can build anything you\'ll need to install the header files for your kernel. On Parabola GNU/Linux: @@ -325,11 +325,11 @@ sudo apt-get install kmod linux-headers-4.15.2-1-amd64 ::: ::: -::: {#outline-container-orgdd7dd5d .outline-2} -Examples {#orgdd7dd5d} +::: {#outline-container-sec-3 .outline-2} +Examples {#sec-3} -------- -::: {#text-orgdd7dd5d .outline-text-2} +::: {#text-3 .outline-text-2} All the examples from this document are available within the *examples* subdirectory. To test that they compile: @@ -345,17 +345,17 @@ version or need to install the corresponding kernel header files. ::: ::: -::: {#outline-container-org92f8539 .outline-2} -Hello World {#org92f8539} +::: {#outline-container-sec-4 .outline-2} +Hello World {#sec-4} ----------- -::: {#text-org92f8539 .outline-text-2} +::: {#text-4 .outline-text-2} ::: -::: {#outline-container-org5ae5562 .outline-3} -### The Simplest Module {#org5ae5562} +::: {#outline-container-sec-4-1 .outline-3} +### The Simplest Module {#sec-4-1} -::: {#text-org5ae5562 .outline-text-3} +::: {#text-4-1 .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 @@ -498,8 +498,8 @@ 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. ::: -- []{#org8e886ba}A point about coding style\ - ::: {#text-org8e886ba .outline-text-5} +- []{#sec-4-1-0-1}A point about coding style\ + ::: {#text-4-1-0-1 .outline-text-5} 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 @@ -507,8 +507,8 @@ pr\_alert() log level, which you\'ll learn about in Section 2.1.1. get used to it if you ever submit a patch upstream. ::: -- []{#org912c90e}Introducing print macros\ - ::: {#text-org912c90e .outline-text-5} +- []{#sec-4-1-0-2}Introducing print macros\ + ::: {#text-4-1-0-2 .outline-text-5} 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, @@ -518,8 +518,8 @@ pr\_alert() log level, which you\'ll learn about in Section 2.1.1. priority macros. ::: -- []{#org9ba89c7}About Compiling\ - ::: {#text-org9ba89c7 .outline-text-5} +- []{#sec-4-1-0-3}About Compiling\ + ::: {#text-4-1-0-3 .outline-text-5} 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. @@ -545,10 +545,10 @@ pr\_alert() log level, which you\'ll learn about in Section 2.1.1. ::: ::: -::: {#outline-container-org5c5dd06 .outline-3} -### Hello and Goodbye {#org5c5dd06} +::: {#outline-container-sec-4-2 .outline-3} +### Hello and Goodbye {#sec-4-2} -::: {#text-org5c5dd06 .outline-text-3} +::: {#text-4-2 .outline-text-3} In 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 @@ -611,10 +611,10 @@ something like that. ::: ::: -::: {#outline-container-org7fd362f .outline-3} -### The \_\_init and \_\_exit Macros {#org7fd362f} +::: {#outline-container-sec-4-3 .outline-3} +### The \_\_init and \_\_exit Macros {#sec-4-3} -::: {#text-org7fd362f .outline-text-3} +::: {#text-4-3 .outline-text-3} 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 @@ -664,10 +664,10 @@ module_exit(hello_3_exit); ::: ::: -::: {#outline-container-orga52c864 .outline-3} -### Licensing and Module Documentation {#orga52c864} +::: {#outline-container-sec-4-4 .outline-3} +### Licensing and Module Documentation {#sec-4-4} -::: {#text-orga52c864 .outline-text-3} +::: {#text-4-4 .outline-text-3} Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this: @@ -721,10 +721,10 @@ module_exit(cleanup_hello_4); ::: ::: -::: {#outline-container-org6976bc8 .outline-3} -### Passing Command Line Arguments to a Module {#org6976bc8} +::: {#outline-container-sec-4-5 .outline-3} +### Passing Command Line Arguments to a Module {#sec-4-5} -::: {#text-org6976bc8 .outline-text-3} +::: {#text-4-5 .outline-text-3} Modules can take command line arguments, but not with the argc/argv you might be used to. @@ -763,7 +763,7 @@ 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 */ +module_param_array(myshortarray, short, &count, 0); /* put count into "count" variable */ ``` ::: @@ -886,10 +886,10 @@ hello-5.o: invalid argument syntax for mylong: 'h' ::: ::: -::: {#outline-container-org5a97220 .outline-3} -### Modules Spanning Multiple Files {#org5a97220} +::: {#outline-container-sec-4-6 .outline-3} +### Modules Spanning Multiple Files {#sec-4-6} -::: {#text-org5a97220 .outline-text-3} +::: {#text-4-6 .outline-text-3} Sometimes it makes sense to divide a kernel module between several source files. @@ -957,10 +957,10 @@ module, second we tell make what object files are part of that module. ::: ::: -::: {#outline-container-org65d6819 .outline-3} -### Building modules for a precompiled kernel {#org65d6819} +::: {#outline-container-sec-4-7 .outline-3} +### Building modules for a precompiled kernel {#sec-4-7} -::: {#text-org65d6819 .outline-text-3} +::: {#text-4-7 .outline-text-3} 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 @@ -1094,17 +1094,17 @@ any errors. ::: ::: -::: {#outline-container-orgb5adf2b .outline-2} -Preliminaries {#orgb5adf2b} +::: {#outline-container-sec-5 .outline-2} +Preliminaries {#sec-5} ------------- -::: {#text-orgb5adf2b .outline-text-2} +::: {#text-5 .outline-text-2} ::: -::: {#outline-container-org4cf9365 .outline-3} -### How modules begin and end {#org4cf9365} +::: {#outline-container-sec-5-1 .outline-3} +### How modules begin and end {#sec-5-1} -::: {#text-org4cf9365 .outline-text-3} +::: {#text-5-1 .outline-text-3} 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 @@ -1128,10 +1128,10 @@ cleanup\_module, I think you\'ll know what I mean. ::: ::: -::: {#outline-container-orgcb5e2da .outline-3} -### Functions available to modules {#orgcb5e2da} +::: {#outline-container-sec-5-2 .outline-3} +### Functions available to modules {#sec-5-2} -::: {#text-orgcb5e2da .outline-text-3} +::: {#text-5-2 .outline-text-3} Programmers 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 @@ -1196,10 +1196,10 @@ everytime someone tries to delete a file on your system. ::: ::: -::: {#outline-container-orgab9f1d1 .outline-3} -### User Space vs Kernel Space {#orgab9f1d1} +::: {#outline-container-sec-5-3 .outline-3} +### User Space vs Kernel Space {#sec-5-3} -::: {#text-orgab9f1d1 .outline-text-3} +::: {#text-5-3 .outline-text-3} 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 @@ -1222,10 +1222,10 @@ returns and execution gets transfered back to user mode. ::: ::: -::: {#outline-container-org9d3f3fc .outline-3} -### Name Space {#org9d3f3fc} +::: {#outline-container-sec-5-4 .outline-3} +### Name Space {#sec-5-4} -::: {#text-org9d3f3fc .outline-text-3} +::: {#text-5-4 .outline-text-3} When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you\'re writing routines which will be part of a bigger problem, any global variables @@ -1250,10 +1250,10 @@ share the kernel\'s codespace. ::: ::: -::: {#outline-container-orga3691e9 .outline-3} -### Code space {#orga3691e9} +::: {#outline-container-sec-5-5 .outline-3} +### Code space {#sec-5-5} -::: {#text-orga3691e9 .outline-text-3} +::: {#text-5-5 .outline-text-3} Memory 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 @@ -1285,17 +1285,17 @@ worse than it sounds, so try your best to be careful. By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn\'t -quite the same thing as *\"building all your modules into the kernel\"*, +quite the same thing as /\"building all your modules into the kernel\"/, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel. ::: ::: -::: {#outline-container-org382352c .outline-3} -### Device Drivers {#org382352c} +::: {#outline-container-sec-5-6 .outline-3} +### Device Drivers {#sec-5-6} -::: {#text-org382352c .outline-text-3} +::: {#text-5-6 .outline-text-3} One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides @@ -1306,8 +1306,8 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed. ::: -- []{#org4e199a6}Major and Minor Numbers\ - ::: {#text-org4e199a6 .outline-text-5} +- []{#sec-5-6-0-1}Major and Minor Numbers\ + ::: {#text-5-6-0-1 .outline-text-5} Let\'s look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive: @@ -1384,7 +1384,7 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use thing that cares about the minor number. It uses the minor number to distinguish between different pieces of hardware. - By the way, when I say *\"hardware\"*, I mean something a bit more + By the way, when I say /\"hardware\"/, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files: @@ -1406,17 +1406,17 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use ::: ::: -::: {#outline-container-orgf1744e4 .outline-2} -Character Device drivers {#orgf1744e4} +::: {#outline-container-sec-6 .outline-2} +Character Device drivers {#sec-6} ------------------------ -::: {#text-orgf1744e4 .outline-text-2} +::: {#text-6 .outline-text-2} ::: -::: {#outline-container-org07ed5b3 .outline-3} -### The file\_operations Structure {#org07ed5b3} +::: {#outline-container-sec-6-1 .outline-3} +### The file\_operations Structure {#sec-6-1} -::: {#text-org07ed5b3 .outline-text-3} +::: {#text-6-1 .outline-text-3} 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 @@ -1511,10 +1511,10 @@ named fops. ::: ::: -::: {#outline-container-orgf283636 .outline-3} -### The file structure {#orgf283636} +::: {#outline-container-sec-6-2 .outline-3} +### The file structure {#sec-6-2} -::: {#text-orgf283636 .outline-text-3} +::: {#text-6-2 .outline-text-3} 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 @@ -1533,10 +1533,10 @@ only use structures contained in file which are created elsewhere. ::: ::: -::: {#outline-container-orgab1c63f .outline-3} -### Registering A Device {#orgab1c63f} +::: {#outline-container-sec-6-3 .outline-3} +### Registering A Device {#sec-6-3} -::: {#text-orgab1c63f .outline-text-3} +::: {#text-6-3 .outline-text-3} As 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 @@ -1585,10 +1585,10 @@ registration and **device\_destroy** during the call to cleanup\_module. ::: ::: -::: {#outline-container-org85bc5ea .outline-3} -### Unregistering A Device {#org85bc5ea} +::: {#outline-container-sec-6-4 .outline-3} +### Unregistering A Device {#sec-6-4} -::: {#text-org85bc5ea .outline-text-3} +::: {#text-6-4 .outline-text-3} 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 @@ -1622,10 +1622,10 @@ sooner or later during a module\'s development. ::: ::: -::: {#outline-container-orgdbd100e .outline-3} -### chardev.c {#orgdbd100e} +::: {#outline-container-sec-6-5 .outline-3} +### chardev.c {#sec-6-5} -::: {#text-orgdbd100e .outline-text-3} +::: {#text-6-5 .outline-text-3} The next code sample creates a char driver named chardev. You can cat its device file. @@ -1831,10 +1831,10 @@ static ssize_t device_write(struct file *filp, ::: ::: -::: {#outline-container-org130321b .outline-3} -### Writing Modules for Multiple Kernel Versions {#org130321b} +::: {#outline-container-sec-6-6 .outline-3} +### Writing Modules for Multiple Kernel Versions {#sec-6-6} -::: {#text-org130321b .outline-text-3} +::: {#text-6-6 .outline-text-3} 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 @@ -1882,11 +1882,11 @@ archives if you\'re interested in the full story. ::: ::: -::: {#outline-container-org44e86f2 .outline-2} -The /proc File System {#org44e86f2} +::: {#outline-container-sec-7 .outline-2} +The /proc File System {#sec-7} --------------------- -::: {#text-org44e86f2 .outline-text-2} +::: {#text-7 .outline-text-2} In 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 @@ -1999,10 +1999,10 @@ void cleanup_module() ::: ::: -::: {#outline-container-org330f61f .outline-3} -### Read and Write a /proc File {#org330f61f} +::: {#outline-container-sec-7-1 .outline-3} +### Read and Write a /proc File {#sec-7-1} -::: {#text-org330f61f .outline-text-3} +::: {#text-7-1 .outline-text-3} 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 @@ -2136,10 +2136,10 @@ void cleanup_module() ::: ::: -::: {#outline-container-orgaae8b16 .outline-3} -### Manage /proc file with standard filesystem {#orgaae8b16} +::: {#outline-container-sec-7-2 .outline-3} +### Manage /proc file with standard filesystem {#sec-7-2} -::: {#text-orgaae8b16 .outline-text-3} +::: {#text-7-2 .outline-text-3} 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. @@ -2276,10 +2276,10 @@ you want to document something kernel related yourself. ::: ::: -::: {#outline-container-org688df35 .outline-3} -### Manage /proc file with seq\_file {#org688df35} +::: {#outline-container-sec-7-3 .outline-3} +### Manage /proc file with seq\_file {#sec-7-3} -::: {#text-org688df35 .outline-text-3} +::: {#text-7-3 .outline-text-3} 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 formating a /proc file for output. It\'s based on sequence, which @@ -2456,11 +2456,11 @@ You can also read the code of fs/seq\_file.c in the linux kernel. ::: ::: -::: {#outline-container-orgbd8ce69 .outline-2} -sysfs: Interacting with your module {#orgbd8ce69} +::: {#outline-container-sec-8 .outline-2} +sysfs: Interacting with your module {#sec-8} ----------------------------------- -::: {#text-orgbd8ce69 .outline-text-2} +::: {#text-8 .outline-text-2} *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. @@ -2477,74 +2477,8 @@ An example of a hello world module which includes the creation of a variable accessible via sysfs is given below. ::: {.org-src-container} -``` {.src .src-c} -/* - * hello-sysfs.c sysfs example - */ - -#include -#include -#include -#include -#include -#include - -MODULE_LICENSE("GPL"); -MODULE_AUTHOR("Bob Mottram"); - -static struct kobject *mymodule; - -/* the variable you want to be able to change */ -static int myvariable = 0; - -static ssize_t myvariable_show(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf) -{ - return sprintf(buf, "%d\n", myvariable); -} - -static ssize_t myvariable_store(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf, size_t count) -{ - sscanf(buf, "%du", &myvariable); - return count; -} - - -static struct kobj_attribute myvariable_attribute = - __ATTR(myvariable, 0660, myvariable_show, - (void*)myvariable_store); - -static int __init mymodule_init (void) -{ - int error = 0; - - pr_info("mymodule: initialised\n"); - - mymodule = - kobject_create_and_add("mymodule", kernel_kobj); - if (!mymodule) - return -ENOMEM; - - error = sysfs_create_file(mymodule, &myvariable_attribute.attr); - if (error) { - pr_info("failed to create the myvariable file " \ - "in /sys/kernel/mymodule\n"); - } - - return error; -} - -static void __exit mymodule_exit (void) -{ - pr_info("mymodule: Exit success\n"); - kobject_put(mymodule); -} - -module_init(mymodule_init); -module_exit(mymodule_exit); +``` {.src .src- hello-sysfs.c"lang"hello-sysfs.c"switches"hello-sysfs.c"flags"=""} +"hello-sysfs.c"body ``` ::: @@ -2592,11 +2526,11 @@ sudo rmmod hello_sysfs ::: ::: -::: {#outline-container-orga1b8e31 .outline-2} -Talking To Device Files {#orga1b8e31} +::: {#outline-container-sec-9 .outline-2} +Talking To Device Files {#sec-9} ----------------------- -::: {#text-orga1b8e31 .outline-text-2} +::: {#text-9 .outline-text-2} 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 @@ -3118,11 +3052,11 @@ int main() ::: ::: -::: {#outline-container-orgdf0ab54 .outline-2} -System Calls {#orgdf0ab54} +::: {#outline-container-sec-10 .outline-2} +System Calls {#sec-10} ------------ -::: {#text-orgdf0ab54 .outline-text-2} +::: {#text-10 .outline-text-2} 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, @@ -3396,17 +3330,17 @@ MODULE_LICENSE("GPL"); ::: ::: -::: {#outline-container-org83613ec .outline-2} -Blocking Processes and threads {#org83613ec} +::: {#outline-container-sec-11 .outline-2} +Blocking Processes and threads {#sec-11} ------------------------------ -::: {#text-org83613ec .outline-text-2} +::: {#text-11 .outline-text-2} ::: -::: {#outline-container-org36ce43a .outline-3} -### Sleep {#org36ce43a} +::: {#outline-container-sec-11-1 .outline-3} +### Sleep {#sec-11-1} -::: {#text-org36ce43a .outline-text-3} +::: {#text-11-1 .outline-text-3} 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!*\". @@ -3850,10 +3784,10 @@ int main(int argc, char *argv[]) ::: ::: -::: {#outline-container-orgcfa6577 .outline-3} -### Completions {#orgcfa6577} +::: {#outline-container-sec-11-2 .outline-3} +### Completions {#sec-11-2} -::: {#text-orgcfa6577 .outline-text-3} +::: {#text-11-2 .outline-text-3} 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 @@ -3960,11 +3894,11 @@ enough for many common situations without adding a lot of complexity. ::: ::: -::: {#outline-container-org3ffdc76 .outline-2} -Avoiding Collisions and Deadlocks {#org3ffdc76} +::: {#outline-container-sec-12 .outline-2} +Avoiding Collisions and Deadlocks {#sec-12} --------------------------------- -::: {#text-org3ffdc76 .outline-text-2} +::: {#text-12 .outline-text-2} 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 @@ -3973,10 +3907,10 @@ code is \"locked\" or \"unlocked\" so that simultaneous attempts to run it can\'t happen. ::: -::: {#outline-container-org89ec2e6 .outline-3} -### Mutex {#org89ec2e6} +::: {#outline-container-sec-12-1 .outline-3} +### Mutex {#sec-12-1} -::: {#text-org89ec2e6 .outline-text-3} +::: {#text-12-1 .outline-text-3} 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. @@ -4028,17 +3962,17 @@ MODULE_LICENSE("GPL"); ::: ::: -::: {#outline-container-org9889db8 .outline-3} -### Spinlocks {#org9889db8} +::: {#outline-container-sec-12-2 .outline-3} +### Spinlocks {#sec-12-2} -::: {#text-org9889db8 .outline-text-3} +::: {#text-12-2 .outline-text-3} 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. -The example here is *\"irq safe\"* in that if interrupts happen during +The example here is /\"irq safe\"/ in that if interrupts happen during the lock then they won\'t be forgotten and will activate when the unlock happens, using the *flags* variable to retain their state. @@ -4112,10 +4046,10 @@ MODULE_LICENSE("GPL"); ::: ::: -::: {#outline-container-orge2dc3e1 .outline-3} -### Read and write locks {#orge2dc3e1} +::: {#outline-container-sec-12-3 .outline-3} +### Read and write locks {#sec-12-3} -::: {#text-orge2dc3e1 .outline-text-3} +::: {#text-12-3 .outline-text-3} 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 @@ -4190,10 +4124,10 @@ corresponding write functions. ::: ::: -::: {#outline-container-org1316854 .outline-3} -### Atomic operations {#org1316854} +::: {#outline-container-sec-12-4 .outline-3} +### Atomic operations {#sec-12-4} -::: {#text-org1316854 .outline-text-3} +::: {#text-12-4 .outline-text-3} 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 @@ -4285,17 +4219,17 @@ MODULE_LICENSE("GPL"); ::: ::: -::: {#outline-container-orgbdec3ca .outline-2} -Replacing Print Macros {#orgbdec3ca} +::: {#outline-container-sec-13 .outline-2} +Replacing Print Macros {#sec-13} ---------------------- -::: {#text-orgbdec3ca .outline-text-2} +::: {#text-13 .outline-text-2} ::: -::: {#outline-container-org4579c68 .outline-3} -### Replacement {#org4579c68} +::: {#outline-container-sec-13-1 .outline-3} +### Replacement {#sec-13-1} -::: {#text-org4579c68 .outline-text-3} +::: {#text-13-1 .outline-text-3} 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 @@ -4427,10 +4361,10 @@ module_exit(print_string_exit); ::: ::: -::: {#outline-container-orgc9bd69e .outline-3} -### Flashing keyboard LEDs {#orgc9bd69e} +::: {#outline-container-sec-13-2 .outline-3} +### Flashing keyboard LEDs {#sec-13-2} -::: {#text-orgc9bd69e .outline-text-3} +::: {#text-13-2 .outline-text-3} 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 @@ -4559,11 +4493,11 @@ minimum and make sure it does not show up in production code. ::: ::: -::: {#outline-container-orgf1f1faf .outline-2} -Scheduling Tasks {#orgf1f1faf} +::: {#outline-container-sec-14 .outline-2} +Scheduling Tasks {#sec-14} ---------------- -::: {#text-orgf1f1faf .outline-text-2} +::: {#text-14 .outline-text-2} 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 @@ -4571,10 +4505,10 @@ are more complicated but also better suited to running multiple things in a sequence. ::: -::: {#outline-container-orgd815b3b .outline-3} -### Tasklets {#orgd815b3b} +::: {#outline-container-sec-14-1 .outline-3} +### Tasklets {#sec-14-1} -::: {#text-orgd815b3b .outline-text-3} +::: {#text-14-1 .outline-text-3} 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. @@ -4632,10 +4566,10 @@ Example tasklet ends ::: ::: -::: {#outline-container-org9b5b18e .outline-3} -### Work queues {#org9b5b18e} +::: {#outline-container-sec-14-2 .outline-3} +### Work queues {#sec-14-2} -::: {#text-org9b5b18e .outline-text-3} +::: {#text-14-2 .outline-text-3} To add a task to the scheduler we can use a workqueue. The kernel then uses the Completely Fair Scheduler (CFS) to execute work within the queue. @@ -4678,17 +4612,17 @@ MODULE_DESCRIPTION("Workqueue example"); ::: ::: -::: {#outline-container-org1cdf533 .outline-2} -Interrupt Handlers {#org1cdf533} +::: {#outline-container-sec-15 .outline-2} +Interrupt Handlers {#sec-15} ------------------ -::: {#text-org1cdf533 .outline-text-2} +::: {#text-15 .outline-text-2} ::: -::: {#outline-container-org5db45ad .outline-3} -### Interrupt Handlers {#org5db45ad} +::: {#outline-container-sec-15-1 .outline-3} +### Interrupt Handlers {#sec-15-1} -::: {#text-org5db45ad .outline-text-3} +::: {#text-15-1 .outline-text-3} 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 @@ -4755,10 +4689,10 @@ you\'re both willing to share. ::: ::: -::: {#outline-container-org9ca1a6c .outline-3} -### Detecting button presses {#org9ca1a6c} +::: {#outline-container-sec-15-2 .outline-3} +### Detecting button presses {#sec-15-2} -::: {#text-org9ca1a6c .outline-text-3} +::: {#text-15-2 .outline-text-3} Many 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 @@ -4929,10 +4863,10 @@ MODULE_DESCRIPTION("Handle some GPIO interrupts"); ::: ::: -::: {#outline-container-org575eebf .outline-3} -### Bottom Half {#org575eebf} +::: {#outline-container-sec-15-3 .outline-3} +### Bottom Half {#sec-15-3} -::: {#text-org575eebf .outline-text-3} +::: {#text-15-3 .outline-text-3} 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 @@ -5114,11 +5048,11 @@ MODULE_DESCRIPTION("Interrupt with top and bottom half"); ::: ::: -::: {#outline-container-org004956f .outline-2} -Crypto {#org004956f} +::: {#outline-container-sec-16 .outline-2} +Crypto {#sec-16} ------ -::: {#text-org004956f .outline-text-2} +::: {#text-16 .outline-text-2} 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 @@ -5128,10 +5062,10 @@ enabling common methods of encryption, decryption and your favourite hash functions. ::: -::: {#outline-container-org8f45455 .outline-3} -### Hash functions {#org8f45455} +::: {#outline-container-sec-16-1 .outline-3} +### Hash functions {#sec-16-1} -::: {#text-org8f45455 .outline-text-3} +::: {#text-16-1 .outline-text-3} 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. @@ -5227,10 +5161,10 @@ sudo rmmod cryptosha256 ::: ::: -::: {#outline-container-orgcf62e2d .outline-3} -### Symmetric key encryption {#orgcf62e2d} +::: {#outline-container-sec-16-2 .outline-3} +### Symmetric key encryption {#sec-16-2} -::: {#text-orgcf62e2d .outline-text-3} +::: {#text-16-2 .outline-text-3} Here is an example of symmetrically encrypting a string using the AES algorithm and a password. @@ -5422,11 +5356,11 @@ MODULE_LICENSE("GPL"); ::: ::: -::: {#outline-container-org161334f .outline-2} -Standardising the interfaces: The Device Model {#org161334f} +::: {#outline-container-sec-17 .outline-2} +Standardising the interfaces: The Device Model {#sec-17} ---------------------------------------------- -::: {#text-org161334f .outline-text-2} +::: {#text-17 .outline-text-2} 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 @@ -5537,17 +5471,17 @@ module_exit(devicemodel_exit); ::: ::: -::: {#outline-container-org8639895 .outline-2} -Optimisations {#org8639895} +::: {#outline-container-sec-18 .outline-2} +Optimisations {#sec-18} ------------- -::: {#text-org8639895 .outline-text-2} +::: {#text-18 .outline-text-2} ::: -::: {#outline-container-orgb775e92 .outline-3} -### Likely and Unlikely conditions {#orgb775e92} +::: {#outline-container-sec-18-1 .outline-3} +### Likely and Unlikely conditions {#sec-18-1} -::: {#text-orgb775e92 .outline-text-3} +::: {#text-18-1 .outline-text-3} 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 @@ -5577,51 +5511,51 @@ pipeline. The opposite happens if you use the *likely* macro. ::: ::: -::: {#outline-container-org1cf3372 .outline-2} -Common Pitfalls {#org1cf3372} +::: {#outline-container-sec-19 .outline-2} +Common Pitfalls {#sec-19} --------------- -::: {#text-org1cf3372 .outline-text-2} +::: {#text-19 .outline-text-2} 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. ::: -::: {#outline-container-org8e71ecd .outline-3} -### Using standard libraries {#org8e71ecd} +::: {#outline-container-sec-19-1 .outline-3} +### Using standard libraries {#sec-19-1} -::: {#text-org8e71ecd .outline-text-3} +::: {#text-19-1 .outline-text-3} 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. ::: ::: -::: {#outline-container-org9ff7def .outline-3} -### Disabling interrupts {#org9ff7def} +::: {#outline-container-sec-19-2 .outline-3} +### Disabling interrupts {#sec-19-2} -::: {#text-org9ff7def .outline-text-3} +::: {#text-19-2 .outline-text-3} 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. ::: ::: -::: {#outline-container-orgdd651cd .outline-3} -### Sticking your head inside a large carnivore {#orgdd651cd} +::: {#outline-container-sec-19-3 .outline-3} +### Sticking your head inside a large carnivore {#sec-19-3} -::: {#text-orgdd651cd .outline-text-3} +::: {#text-19-3 .outline-text-3} I probably don\'t have to warn you about this, but I figured I will anyway, just in case. ::: ::: ::: -::: {#outline-container-orgcf6e3aa .outline-2} -Where To Go From Here? {#orgcf6e3aa} +::: {#outline-container-sec-20 .outline-2} +Where To Go From Here? {#sec-20} ---------------------- -::: {#text-orgcf6e3aa .outline-text-2} +::: {#text-20 .outline-text-2} I 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 diff --git a/4.15.2/LKMPG-4.15.2.rst b/4.15.2/LKMPG-4.15.2.rst index 69adb40..27a0d4d 100644 --- a/4.15.2/LKMPG-4.15.2.rst +++ b/4.15.2/LKMPG-4.15.2.rst @@ -21,101 +21,101 @@
-- `Introduction <#org1785162>`__ +- `Introduction <#sec-1>`__ - - `Authorship <#org63a1b37>`__ - - `Versioning and Notes <#org10863e7>`__ - - `Acknowledgements <#org49d4e59>`__ - - `What Is A Kernel Module? <#org0a5ce13>`__ - - `Kernel module package <#org1cb0938>`__ - - `What Modules are in my Kernel? <#org878e43e>`__ - - `Do I need to download and compile the kernel? <#orgb530dfd>`__ - - `Before We Begin <#org2583533>`__ + - `Authorship <#sec-1-1>`__ + - `Versioning and Notes <#sec-1-2>`__ + - `Acknowledgements <#sec-1-3>`__ + - `What Is A Kernel Module? <#sec-1-4>`__ + - `Kernel module package <#sec-1-5>`__ + - `What Modules are in my Kernel? <#sec-1-6>`__ + - `Do I need to download and compile the kernel? <#sec-1-7>`__ + - `Before We Begin <#sec-1-8>`__ -- `Headers <#org46d2b5f>`__ -- `Examples <#orgdd7dd5d>`__ -- `Hello World <#org92f8539>`__ +- `Headers <#sec-2>`__ +- `Examples <#sec-3>`__ +- `Hello World <#sec-4>`__ - - `The Simplest Module <#org5ae5562>`__ - - `Hello and Goodbye <#org5c5dd06>`__ - - `The \__init and \__exit Macros <#org7fd362f>`__ - - `Licensing and Module Documentation <#orga52c864>`__ - - `Passing Command Line Arguments to a Module <#org6976bc8>`__ - - `Modules Spanning Multiple Files <#org5a97220>`__ - - `Building modules for a precompiled kernel <#org65d6819>`__ + - `The Simplest Module <#sec-4-1>`__ + - `Hello and Goodbye <#sec-4-2>`__ + - `The \__init and \__exit Macros <#sec-4-3>`__ + - `Licensing and Module Documentation <#sec-4-4>`__ + - `Passing Command Line Arguments to a Module <#sec-4-5>`__ + - `Modules Spanning Multiple Files <#sec-4-6>`__ + - `Building modules for a precompiled kernel <#sec-4-7>`__ -- `Preliminaries <#orgb5adf2b>`__ +- `Preliminaries <#sec-5>`__ - - `How modules begin and end <#org4cf9365>`__ - - `Functions available to modules <#orgcb5e2da>`__ - - `User Space vs Kernel Space <#orgab9f1d1>`__ - - `Name Space <#org9d3f3fc>`__ - - `Code space <#orga3691e9>`__ - - `Device Drivers <#org382352c>`__ + - `How modules begin and end <#sec-5-1>`__ + - `Functions available to modules <#sec-5-2>`__ + - `User Space vs Kernel Space <#sec-5-3>`__ + - `Name Space <#sec-5-4>`__ + - `Code space <#sec-5-5>`__ + - `Device Drivers <#sec-5-6>`__ -- `Character Device drivers <#orgf1744e4>`__ +- `Character Device drivers <#sec-6>`__ - - `The file_operations Structure <#org07ed5b3>`__ - - `The file structure <#orgf283636>`__ - - `Registering A Device <#orgab1c63f>`__ - - `Unregistering A Device <#org85bc5ea>`__ - - `chardev.c <#orgdbd100e>`__ - - `Writing Modules for Multiple Kernel Versions <#org130321b>`__ + - `The file_operations Structure <#sec-6-1>`__ + - `The file structure <#sec-6-2>`__ + - `Registering A Device <#sec-6-3>`__ + - `Unregistering A Device <#sec-6-4>`__ + - `chardev.c <#sec-6-5>`__ + - `Writing Modules for Multiple Kernel Versions <#sec-6-6>`__ -- `The /proc File System <#org44e86f2>`__ +- `The /proc File System <#sec-7>`__ - - `Read and Write a /proc File <#org330f61f>`__ - - `Manage /proc file with standard filesystem <#orgaae8b16>`__ - - `Manage /proc file with seq_file <#org688df35>`__ + - `Read and Write a /proc File <#sec-7-1>`__ + - `Manage /proc file with standard filesystem <#sec-7-2>`__ + - `Manage /proc file with seq_file <#sec-7-3>`__ -- `sysfs: Interacting with your module <#orgbd8ce69>`__ -- `Talking To Device Files <#orga1b8e31>`__ -- `System Calls <#orgdf0ab54>`__ -- `Blocking Processes and threads <#org83613ec>`__ +- `sysfs: Interacting with your module <#sec-8>`__ +- `Talking To Device Files <#sec-9>`__ +- `System Calls <#sec-10>`__ +- `Blocking Processes and threads <#sec-11>`__ - - `Sleep <#org36ce43a>`__ - - `Completions <#orgcfa6577>`__ + - `Sleep <#sec-11-1>`__ + - `Completions <#sec-11-2>`__ -- `Avoiding Collisions and Deadlocks <#org3ffdc76>`__ +- `Avoiding Collisions and Deadlocks <#sec-12>`__ - - `Mutex <#org89ec2e6>`__ - - `Spinlocks <#org9889db8>`__ - - `Read and write locks <#orge2dc3e1>`__ - - `Atomic operations <#org1316854>`__ + - `Mutex <#sec-12-1>`__ + - `Spinlocks <#sec-12-2>`__ + - `Read and write locks <#sec-12-3>`__ + - `Atomic operations <#sec-12-4>`__ -- `Replacing Print Macros <#orgbdec3ca>`__ +- `Replacing Print Macros <#sec-13>`__ - - `Replacement <#org4579c68>`__ - - `Flashing keyboard LEDs <#orgc9bd69e>`__ + - `Replacement <#sec-13-1>`__ + - `Flashing keyboard LEDs <#sec-13-2>`__ -- `Scheduling Tasks <#orgf1f1faf>`__ +- `Scheduling Tasks <#sec-14>`__ - - `Tasklets <#orgd815b3b>`__ - - `Work queues <#org9b5b18e>`__ + - `Tasklets <#sec-14-1>`__ + - `Work queues <#sec-14-2>`__ -- `Interrupt Handlers <#org1cdf533>`__ +- `Interrupt Handlers <#sec-15>`__ - - `Interrupt Handlers <#org5db45ad>`__ - - `Detecting button presses <#org9ca1a6c>`__ - - `Bottom Half <#org575eebf>`__ + - `Interrupt Handlers <#sec-15-1>`__ + - `Detecting button presses <#sec-15-2>`__ + - `Bottom Half <#sec-15-3>`__ -- `Crypto <#org004956f>`__ +- `Crypto <#sec-16>`__ - - `Hash functions <#org8f45455>`__ - - `Symmetric key encryption <#orgcf62e2d>`__ + - `Hash functions <#sec-16-1>`__ + - `Symmetric key encryption <#sec-16-2>`__ -- `Standardising the interfaces: The Device Model <#org161334f>`__ -- `Optimisations <#org8639895>`__ +- `Standardising the interfaces: The Device Model <#sec-17>`__ +- `Optimisations <#sec-18>`__ - - `Likely and Unlikely conditions <#orgb775e92>`__ + - `Likely and Unlikely conditions <#sec-18-1>`__ -- `Common Pitfalls <#org1cf3372>`__ +- `Common Pitfalls <#sec-19>`__ - - `Using standard libraries <#org8e71ecd>`__ - - `Disabling interrupts <#org9ff7def>`__ - - `Sticking your head inside a large carnivore <#orgdd651cd>`__ + - `Using standard libraries <#sec-19-1>`__ + - `Disabling interrupts <#sec-19-2>`__ + - `Sticking your head inside a large carnivore <#sec-19-3>`__ -- `Where To Go From Here? <#orgcf6e3aa>`__ +- `Where To Go From Here? <#sec-20>`__ .. raw:: html @@ -127,14 +127,14 @@ .. raw:: html -
+
.. rubric:: Introduction - :name: org1785162 + :name: sec-1 .. raw:: html -
+
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, @@ -172,14 +172,14 @@ above. .. raw:: html -
+
.. rubric:: Authorship - :name: org63a1b37 + :name: sec-1-1 .. raw:: html -
+
The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to @@ -201,14 +201,14 @@ other chapters. .. raw:: html -
+
.. rubric:: Versioning and Notes - :name: org10863e7 + :name: sec-1-2 .. raw:: html -
+
The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around @@ -232,14 +232,14 @@ I can't promise anything. .. raw:: html -
+
.. rubric:: Acknowledgements - :name: org49d4e59 + :name: sec-1-3 .. raw:: html -
+
The following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, @@ -255,14 +255,14 @@ Francois Audeon, Horst Schirmeier, Bob Mottram and Roman Lakeev. .. raw:: html -
+
.. rubric:: What Is A Kernel Module? - :name: org0a5ce13 + :name: sec-1-4 .. raw:: html -
+
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 @@ -289,14 +289,14 @@ time we want new functionality. .. raw:: html -
+
.. rubric:: Kernel module package - :name: org1cb0938 + :name: sec-1-5 .. raw:: html -
+
Linux distros provide the commands *modprobe*, *insmod* and *depmod* within a package. @@ -309,7 +309,7 @@ On Debian: .. code:: src - sudo apt-get install build-essential kmod + sudo apt-get install build-essential kmod .. raw:: html @@ -323,7 +323,7 @@ On Parabola: .. code:: src - sudo pacman -S gcc kmod + sudo pacman -S gcc kmod .. raw:: html @@ -339,14 +339,14 @@ On Parabola: .. raw:: html -
+
.. rubric:: What Modules are in my Kernel? - :name: org878e43e + :name: sec-1-6 .. raw:: html -
+
To discover what modules are already loaded within your current kernel use the command **lsmod**. @@ -357,7 +357,7 @@ use the command **lsmod**. .. code:: src - sudo lsmod + sudo lsmod .. raw:: html @@ -372,7 +372,7 @@ them with: .. code:: src - sudo cat /proc/modules + sudo cat /proc/modules .. raw:: html @@ -387,7 +387,7 @@ particular. To search for the *fat* module: .. code:: src - sudo lsmod | grep fat + sudo lsmod | grep fat .. raw:: html @@ -403,14 +403,14 @@ particular. To search for the *fat* module: .. raw:: html -
+
.. rubric:: Do I need to download and compile the kernel? - :name: orgb530dfd + :name: sec-1-7 .. raw:: html -
+
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 @@ -427,14 +427,14 @@ messing up your system. .. raw:: html -
+
.. rubric:: Before We Begin - :name: org2583533 + :name: sec-1-8 .. raw:: html -
+
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. @@ -448,7 +448,7 @@ thereafter.
- | Modversioning - | ::: {#text-org4517450 .outline-text-5} A module compiled for one + | ::: {#text-1-8-0-1 .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 cover modversions, @@ -461,8 +461,8 @@ thereafter. ::: - | Using X - | ::: {#text-orgdc404d5 .outline-text-5} It is highly recommended - that you type in, compile and load all the examples this guide + | ::: {#text-1-8-0-2 .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. @@ -486,14 +486,14 @@ thereafter. .. raw:: html -
+
.. rubric:: Headers - :name: org46d2b5f + :name: sec-2 .. raw:: html -
+
Before you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux: @@ -504,7 +504,7 @@ for your kernel. On Parabola GNU/Linux: .. code:: src - sudo pacman -S linux-libre-headers + sudo pacman -S linux-libre-headers .. raw:: html @@ -518,8 +518,8 @@ On Debian: .. code:: src - sudo apt-get update - apt-cache search linux-headers-$(uname -r) + sudo apt-get update + apt-cache search linux-headers-$(uname -r) .. raw:: html @@ -534,7 +534,7 @@ example: .. code:: src - sudo apt-get install kmod linux-headers-4.15.2-1-amd64 + sudo apt-get install kmod linux-headers-4.15.2-1-amd64 .. raw:: html @@ -550,14 +550,14 @@ example: .. raw:: html -
+
.. rubric:: Examples - :name: orgdd7dd5d + :name: sec-3 .. raw:: html -
+
All the examples from this document are available within the *examples* subdirectory. To test that they compile: @@ -568,8 +568,8 @@ subdirectory. To test that they compile: .. code:: src - cd examples - make + cd examples + make .. raw:: html @@ -588,14 +588,14 @@ version or need to install the corresponding kernel header files. .. raw:: html -
+
.. rubric:: Hello World - :name: org92f8539 + :name: sec-4 .. raw:: html -
+
.. raw:: html @@ -603,14 +603,14 @@ version or need to install the corresponding kernel header files. .. raw:: html -
+
.. rubric:: The Simplest Module - :name: org5ae5562 + :name: sec-4-1 .. raw:: html -
+
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 @@ -628,8 +628,8 @@ Make a test directory: .. code:: src - mkdir -p ~/develop/kernel/hello-1 - cd ~/develop/kernel/hello-1 + mkdir -p ~/develop/kernel/hello-1 + cd ~/develop/kernel/hello-1 .. raw:: html @@ -643,26 +643,26 @@ Paste this into you favourite editor and save it as **hello-1.c**: .. code:: src - /* - * hello-1.c - The simplest kernel module. - */ - #include /* Needed by all modules */ - #include /* Needed for KERN_INFO */ + /* + * hello-1.c - The simplest kernel module. + */ + #include /* Needed by all modules */ + #include /* Needed for KERN_INFO */ - int init_module(void) - { - pr_info("Hello world 1.\n"); + int init_module(void) + { + pr_info("Hello world 1.\n"); - /* - * A non 0 return means init_module failed; module can't be loaded. - */ - return 0; - } + /* + * A non 0 return means init_module failed; module can't be loaded. + */ + return 0; + } - void cleanup_module(void) - { - pr_info("Goodbye world 1.\n"); - } + void cleanup_module(void) + { + pr_info("Goodbye world 1.\n"); + } .. raw:: html @@ -677,13 +677,13 @@ indentation to use tabs, not spaces. .. code:: src - obj-m += hello-1.o + obj-m += hello-1.o - all: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + all: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules - clean: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean + clean: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean .. raw:: html @@ -697,7 +697,7 @@ And finally just: .. code:: src - make + make .. raw:: html @@ -712,7 +712,7 @@ If all goes smoothly you should then find that you have a compiled .. code:: src - sudo modinfo hello-1.ko + sudo modinfo hello-1.ko .. raw:: html @@ -726,7 +726,7 @@ At this point the command: .. code:: src - sudo lsmod | grep hello + sudo lsmod | grep hello .. raw:: html @@ -740,7 +740,7 @@ should return nothing. You can try loading your shiny new module with: .. code:: src - sudo insmod hello-1.ko + sudo insmod hello-1.ko .. raw:: html @@ -755,7 +755,7 @@ again try: .. code:: src - sudo lsmod | grep hello + sudo lsmod | grep hello .. raw:: html @@ -769,7 +769,7 @@ you should now see your loaded module. It can be removed again with: .. code:: src - sudo rmmod hello_1 + sudo rmmod hello_1 .. raw:: html @@ -784,7 +784,7 @@ happened in the logs: .. code:: src - journalctl --since "1 hour ago" | grep kernel + journalctl --since "1 hour ago" | grep kernel .. raw:: html @@ -818,8 +818,8 @@ pr_alert() log level, which you'll learn about in Section 2.1.1.
- | A point about coding style - | ::: {#text-org8e886ba .outline-text-5} Another thing which may not - be immediately obvious to anyone getting started with kernel + | ::: {#text-4-1-0-1 .outline-text-5} 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 @@ -828,7 +828,7 @@ pr_alert() log level, which you'll learn about in Section 2.1.1. ::: - | Introducing print macros - | ::: {#text-org912c90e .outline-text-5} In the beginning there was + | ::: {#text-4-1-0-2 .outline-text-5} 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 @@ -839,7 +839,7 @@ pr_alert() log level, which you'll learn about in Section 2.1.1. ::: - | About Compiling - | ::: {#text-org9ba89c7 .outline-text-5} Kernel modules need to be + | ::: {#text-4-1-0-3 .outline-text-5} 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 @@ -857,10 +857,10 @@ pr_alert() log level, which you'll learn about in Section 2.1.1. and the related files before starting to hack Makefiles. It'll probably save you lots of work. - Here's another exercise for the reader. See that comment above - the return statement in init_module()? Change the return value to - something negative, recompile and load the module again. What - happens? + Here's another exercise for the reader. See that comment above the + return statement in init_module()? Change the return value to + something negative, recompile and load the module again. What + happens? ::: @@ -870,14 +870,14 @@ pr_alert() log level, which you'll learn about in Section 2.1.1. .. raw:: html -
+
.. rubric:: Hello and Goodbye - :name: org5c5dd06 + :name: sec-4-2 .. raw:: html -
+
In early kernel versions you had to use the **init_module** and **cleanup_module** functions, as in the first hello world example, but @@ -893,27 +893,27 @@ you'll get compilation errors. Here's an example of this technique: .. code:: src - /* - * hello-2.c - Demonstrating the module_init() and module_exit() macros. - * This is preferred over using init_module() and cleanup_module(). - */ - #include /* Needed by all modules */ - #include /* Needed for KERN_INFO */ - #include /* Needed for the macros */ + /* + * hello-2.c - Demonstrating the module_init() and module_exit() macros. + * This is preferred over using init_module() and cleanup_module(). + */ + #include /* Needed by all modules */ + #include /* Needed for KERN_INFO */ + #include /* Needed for the macros */ - static int __init hello_2_init(void) - { - pr_info("Hello, world 2\n"); - return 0; - } + static int __init hello_2_init(void) + { + pr_info("Hello, world 2\n"); + return 0; + } - static void __exit hello_2_exit(void) - { - pr_info("Goodbye, world 2\n"); - } + static void __exit hello_2_exit(void) + { + pr_info("Goodbye, world 2\n"); + } - module_init(hello_2_init); - module_exit(hello_2_exit); + module_init(hello_2_init); + module_exit(hello_2_exit); .. raw:: html @@ -928,14 +928,14 @@ module is as simple as this: .. code:: src - obj-m += hello-1.o - obj-m += hello-2.o + obj-m += hello-1.o + obj-m += hello-2.o - all: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + all: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules - clean: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean + clean: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean .. raw:: html @@ -961,14 +961,14 @@ something like that. .. raw:: html -
+
.. rubric:: The \__init and \__exit Macros - :name: org7fd362f + :name: sec-4-3 .. raw:: html -
+
This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The **\__init** @@ -996,28 +996,28 @@ kernel memory: 236k freed, this is precisely what the kernel is freeing. .. code:: src - /* - * hello-3.c - Illustrating the __init, __initdata and __exit macros. - */ - #include /* Needed by all modules */ - #include /* Needed for KERN_INFO */ - #include /* Needed for the macros */ + /* + * hello-3.c - Illustrating the __init, __initdata and __exit macros. + */ + #include /* Needed by all modules */ + #include /* Needed for KERN_INFO */ + #include /* Needed for the macros */ - static int hello3_data __initdata = 3; + static int hello3_data __initdata = 3; - static int __init hello_3_init(void) - { - pr_info("Hello, world %d\n", hello3_data); - return 0; - } + static int __init hello_3_init(void) + { + pr_info("Hello, world %d\n", hello3_data); + return 0; + } - static void __exit hello_3_exit(void) - { - pr_info("Goodbye, world 3\n"); - } + static void __exit hello_3_exit(void) + { + pr_info("Goodbye, world 3\n"); + } - module_init(hello_3_init); - module_exit(hello_3_exit); + module_init(hello_3_init); + module_exit(hello_3_exit); .. raw:: html @@ -1033,14 +1033,14 @@ kernel memory: 236k freed, this is precisely what the kernel is freeing. .. raw:: html -
+
.. rubric:: Licensing and Module Documentation - :name: orga52c864 + :name: sec-4-4 .. raw:: html -
+
Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this: @@ -1051,10 +1051,10 @@ then you might have seen something like this: .. code:: src - # 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 + # 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 .. raw:: html @@ -1075,31 +1075,31 @@ are illustrated in the below example. .. code:: src - /* - * hello-4.c - Demonstrates module documentation. - */ - #include /* Needed by all modules */ - #include /* Needed for KERN_INFO */ - #include /* Needed for the macros */ + /* + * hello-4.c - Demonstrates module documentation. + */ + #include /* Needed by all modules */ + #include /* Needed for KERN_INFO */ + #include /* Needed for the macros */ - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("A sample driver"); - MODULE_SUPPORTED_DEVICE("testdevice"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("A sample driver"); + MODULE_SUPPORTED_DEVICE("testdevice"); - static int __init init_hello_4(void) - { - pr_info("Hello, world 4\n"); - return 0; - } + static int __init init_hello_4(void) + { + pr_info("Hello, world 4\n"); + return 0; + } - static void __exit cleanup_hello_4(void) - { - pr_info("Goodbye, world 4\n"); - } + static void __exit cleanup_hello_4(void) + { + pr_info("Goodbye, world 4\n"); + } - module_init(init_hello_4); - module_exit(cleanup_hello_4); + module_init(init_hello_4); + module_exit(cleanup_hello_4); .. raw:: html @@ -1115,14 +1115,14 @@ are illustrated in the below example. .. raw:: html -
+
.. rubric:: Passing Command Line Arguments to a Module - :name: org6976bc8 + :name: sec-4-5 .. raw:: html -
+
Modules can take command line arguments, but not with the argc/argv you might be used to. @@ -1147,8 +1147,8 @@ integers or strings see module_param_array() and module_param_string(). .. code:: src - int myint = 3; - module_param(myint, int, 0); + int myint = 3; + module_param(myint, int, 0); .. raw:: html @@ -1166,12 +1166,12 @@ both possibilities here: .. code:: src - int myintarray[2]; - module_param_array(myintarray, int, NULL, 0); /* not interested in count */ + 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 */ + short myshortarray[4]; + int count; + module_param_array(myshortarray, short, &count, 0); /* put count into "count" variable */ .. raw:: html @@ -1192,76 +1192,76 @@ a variable name and a free form string describing that variable. .. code:: src - /* - * hello-5.c - Demonstrates command line argument passing to a module. - */ - #include - #include - #include - #include - #include + /* + * hello-5.c - Demonstrates command line argument passing to a module. + */ + #include + #include + #include + #include + #include - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Peter Jay Salzman"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Peter Jay Salzman"); - static short int myshort = 1; - static int myint = 420; - static long int mylong = 9999; - static char *mystring = "blah"; - static int myintArray[2] = { -1, -1 }; - static int arr_argc = 0; + static short int myshort = 1; + static int myint = 420; + static long int mylong = 9999; + static char *mystring = "blah"; + static int myintArray[2] = { -1, -1 }; + static int arr_argc = 0; - /* - * module_param(foo, int, 0000) - * The first param is the parameters name - * The second param is it's data type - * The final argument is the permissions bits, - * for exposing parameters in sysfs (if non-zero) at a later stage. - */ + /* + * module_param(foo, int, 0000) + * The first param is the parameters name + * The second param is it's data type + * The final argument is the permissions bits, + * for exposing parameters in sysfs (if non-zero) at a later stage. + */ - module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); - MODULE_PARM_DESC(myshort, "A short integer"); - module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); - MODULE_PARM_DESC(myint, "An integer"); - module_param(mylong, long, S_IRUSR); - MODULE_PARM_DESC(mylong, "A long integer"); - module_param(mystring, charp, 0000); - MODULE_PARM_DESC(mystring, "A character string"); + module_param(myshort, short, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); + MODULE_PARM_DESC(myshort, "A short integer"); + module_param(myint, int, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); + MODULE_PARM_DESC(myint, "An integer"); + module_param(mylong, long, S_IRUSR); + MODULE_PARM_DESC(mylong, "A long integer"); + module_param(mystring, charp, 0000); + MODULE_PARM_DESC(mystring, "A character string"); - /* - * module_param_array(name, type, num, perm); - * The first param is the parameter's (in this case the array's) name - * The second param is the data type of the elements of the array - * The third argument is a pointer to the variable that will store the number - * of elements of the array initialized by the user at module loading time - * The fourth argument is the permission bits - */ - module_param_array(myintArray, int, &arr_argc, 0000); - MODULE_PARM_DESC(myintArray, "An array of integers"); + /* + * module_param_array(name, type, num, perm); + * The first param is the parameter's (in this case the array's) name + * The second param is the data type of the elements of the array + * The third argument is a pointer to the variable that will store the number + * of elements of the array initialized by the user at module loading time + * The fourth argument is the permission bits + */ + module_param_array(myintArray, int, &arr_argc, 0000); + MODULE_PARM_DESC(myintArray, "An array of integers"); - static int __init hello_5_init(void) - { - int i; - 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++) - { - pr_info("myintArray[%d] = %d\n", i, myintArray[i]); - } - pr_info("got %d arguments for myintArray.\n", arr_argc); - return 0; - } + static int __init hello_5_init(void) + { + int i; + 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++) + { + pr_info("myintArray[%d] = %d\n", i, myintArray[i]); + } + pr_info("got %d arguments for myintArray.\n", arr_argc); + return 0; + } - static void __exit hello_5_exit(void) - { - pr_info("Goodbye, world 5\n"); - } + static void __exit hello_5_exit(void) + { + pr_info("Goodbye, world 5\n"); + } - module_init(hello_5_init); - module_exit(hello_5_exit); + module_init(hello_5_init); + module_exit(hello_5_exit); .. raw:: html @@ -1275,31 +1275,31 @@ I would recommend playing around with this code: .. code:: src - # 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 - mylong is a long integer: 9999 - mystring is a string: bebop - myintArray is -1 and 420 + # 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 + mylong is a long integer: 9999 + mystring is a string: bebop + myintArray is -1 and 420 - # rmmod hello-5 - Goodbye, world 5 + # rmmod hello-5 + Goodbye, world 5 - # sudo insmod hello-5.ko mystring="supercalifragilisticexpialidocious" \ - > mybyte=256 myintArray=-1,-1 - mybyte is an 8 bit integer: 0 - myshort is a short integer: 1 - myint is an integer: 20 - mylong is a long integer: 9999 - mystring is a string: supercalifragilisticexpialidocious - myintArray is -1 and -1 + # sudo insmod hello-5.ko mystring="supercalifragilisticexpialidocious" \ + > mybyte=256 myintArray=-1,-1 + mybyte is an 8 bit integer: 0 + myshort is a short integer: 1 + myint is an integer: 20 + mylong is a long integer: 9999 + mystring is a string: supercalifragilisticexpialidocious + myintArray is -1 and -1 - # rmmod hello-5 - Goodbye, world 5 + # rmmod hello-5 + Goodbye, world 5 - # sudo insmod hello-5.ko mylong=hello - hello-5.o: invalid argument syntax for mylong: 'h' + # sudo insmod hello-5.ko mylong=hello + hello-5.o: invalid argument syntax for mylong: 'h' .. raw:: html @@ -1315,14 +1315,14 @@ I would recommend playing around with this code: .. raw:: html -
+
.. rubric:: Modules Spanning Multiple Files - :name: org5a97220 + :name: sec-4-6 .. raw:: html -
+
Sometimes it makes sense to divide a kernel module between several source files. @@ -1335,18 +1335,18 @@ Here's an example of such a kernel module. .. code:: src - /* - * start.c - Illustration of multi filed modules - */ + /* + * start.c - Illustration of multi filed modules + */ - #include /* We're doing kernel work */ - #include /* Specifically, a module */ + #include /* We're doing kernel work */ + #include /* Specifically, a module */ - int init_module(void) - { - pr_info("Hello, world - this is the kernel speaking\n"); - return 0; - } + int init_module(void) + { + pr_info("Hello, world - this is the kernel speaking\n"); + return 0; + } .. raw:: html @@ -1360,17 +1360,17 @@ The next file: .. code:: src - /* - * stop.c - Illustration of multi filed modules - */ + /* + * stop.c - Illustration of multi filed modules + */ - #include /* We're doing kernel work */ - #include /* Specifically, a module */ + #include /* We're doing kernel work */ + #include /* Specifically, a module */ - void cleanup_module() - { - pr_info("Short is the life of a kernel module\n"); - } + void cleanup_module() + { + pr_info("Short is the life of a kernel module\n"); + } .. raw:: html @@ -1384,19 +1384,19 @@ And finally, the makefile: .. code:: src - obj-m += hello-1.o - obj-m += hello-2.o - obj-m += hello-3.o - obj-m += hello-4.o - obj-m += hello-5.o - obj-m += startstop.o - startstop-objs := start.o stop.o + obj-m += hello-1.o + obj-m += hello-2.o + obj-m += hello-3.o + obj-m += hello-4.o + obj-m += hello-5.o + obj-m += startstop.o + startstop-objs := start.o stop.o - all: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules + all: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules - clean: - make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean + clean: + make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean .. raw:: html @@ -1417,14 +1417,14 @@ second we tell make what object files are part of that module. .. raw:: html -
+
.. rubric:: Building modules for a precompiled kernel - :name: org65d6819 + :name: sec-4-7 .. raw:: html -
+
Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features, such as forced module @@ -1455,7 +1455,7 @@ cases you would obtain an error as follows: .. code:: src - insmod: error inserting 'poet_atkm.ko': -1 Invalid module format + insmod: error inserting 'poet_atkm.ko': -1 Invalid module format .. raw:: html @@ -1469,8 +1469,8 @@ Less cryptical information are logged to the systemd journal: .. code:: src - 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' + 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' .. raw:: html @@ -1490,12 +1490,12 @@ issue the modinfo module.ko command: .. code:: src - # sudo modinfo hello-4.ko - license: GPL - author: Bob Mottram - description: A sample driver - vermagic: 4.15.2-1.358 amd64 REGPARM 4KSTACKS gcc-4.9.2 - depends: + # sudo modinfo hello-4.ko + license: GPL + author: Bob Mottram + description: A sample driver + vermagic: 4.15.2-1.358 amd64 REGPARM 4KSTACKS gcc-4.9.2 + depends: .. raw:: html @@ -1533,10 +1533,10 @@ example, you makefile could start as follows: .. code:: src - VERSION = 4 - PATCHLEVEL = 7 - SUBLEVEL = 4 - EXTRAVERSION = -1.358custom + VERSION = 4 + PATCHLEVEL = 7 + SUBLEVEL = 4 + EXTRAVERSION = -1.358custom .. raw:: html @@ -1562,17 +1562,17 @@ objects: .. code:: src - # make - CHK include/linux/version.h - UPD include/linux/version.h - SYMLINK include/asm -> include/asm-i386 - SPLIT include/linux/autoconf.h -> include/config/* - HOSTCC scripts/basic/fixdep - HOSTCC scripts/basic/split-include - HOSTCC scripts/basic/docproc - HOSTCC scripts/conmakehash - HOSTCC scripts/kallsyms - CC scripts/empty.o + # make + CHK include/linux/version.h + UPD include/linux/version.h + SYMLINK include/asm -> include/asm-i386 + SPLIT include/linux/autoconf.h -> include/config/* + HOSTCC scripts/basic/fixdep + HOSTCC scripts/basic/split-include + HOSTCC scripts/basic/docproc + HOSTCC scripts/conmakehash + HOSTCC scripts/kallsyms + CC scripts/empty.o .. raw:: html @@ -1599,14 +1599,14 @@ any errors. .. raw:: html -
+
.. rubric:: Preliminaries - :name: orgb5adf2b + :name: sec-5 .. raw:: html -
+
.. raw:: html @@ -1614,14 +1614,14 @@ any errors. .. raw:: html -
+
.. rubric:: How modules begin and end - :name: org4cf9365 + :name: sec-5-1 .. raw:: html -
+
A program usually begins with a **main()** function, executes a bunch of instructions and terminates upon completion of those instructions. @@ -1654,14 +1654,14 @@ think you'll know what I mean. .. raw:: html -
+
.. rubric:: Functions available to modules - :name: orgcb5e2da + :name: sec-5-2 .. raw:: html -
+
Programmers use functions they don't define all the time. A prime example of this is **printf()**. You use these library functions which @@ -1698,13 +1698,13 @@ Compile the following program: .. code:: src - #include + #include - int main(void) - { - printf("hello"); - return 0; - } + int main(void) + { + printf("hello"); + return 0; + } .. raw:: html @@ -1741,14 +1741,14 @@ everytime someone tries to delete a file on your system. .. raw:: html -
+
.. rubric:: User Space vs Kernel Space - :name: orgab9f1d1 + :name: sec-5-3 .. raw:: html -
+
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. @@ -1780,14 +1780,14 @@ returns and execution gets transfered back to user mode. .. raw:: html -
+
.. rubric:: Name Space - :name: org9d3f3fc + :name: sec-5-4 .. raw:: html -
+
When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you're writing @@ -1821,14 +1821,14 @@ share the kernel's codespace. .. raw:: html -
+
.. rubric:: Code space - :name: orga3691e9 + :name: sec-5-5 .. raw:: html -
+
Memory management is a very complicated subject and the majority of O'Reilly's "*Understanding The Linux Kernel*" exclusively covers memory @@ -1861,7 +1861,7 @@ worse than it sounds, so try your best to be careful. By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't -quite the same thing as *"building all your modules into the kernel"*, +quite the same thing as /"building all your modules into the kernel"/, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel. @@ -1876,14 +1876,14 @@ Magenta kernel of Google Fuchsia are two examples of a microkernel. .. raw:: html -
+
.. rubric:: Device Drivers - :name: org382352c + :name: sec-5-6 .. raw:: html -
+
One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is @@ -1899,7 +1899,7 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use
- | Major and Minor Numbers - | ::: {#text-org4e199a6 .outline-text-5} Let's look at some device + | ::: {#text-5-6-0-1 .outline-text-5} Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive: @@ -1909,10 +1909,10 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use .. code:: src - # 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 + # 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 .. raw:: html @@ -1955,10 +1955,10 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use .. code:: src - 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 + 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 .. raw:: html @@ -1986,7 +1986,7 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use cares about the minor number. It uses the minor number to distinguish between different pieces of hardware. - By the way, when I say *"hardware"*, I mean something a bit more + By the way, when I say /"hardware"/, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files: @@ -1996,9 +1996,9 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use .. code:: src - % ls -l /dev/sda /dev/sdb - brw-rw---- 1 root disk 8, 0 Jan 3 09:02 /dev/sda - brw-rw---- 1 root disk 8, 16 Jan 3 09:02 /dev/sdb + % ls -l /dev/sda /dev/sdb + brw-rw---- 1 root disk 8, 0 Jan 3 09:02 /dev/sda + brw-rw---- 1 root disk 8, 16 Jan 3 09:02 /dev/sdb .. raw:: html @@ -2023,14 +2023,14 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use .. raw:: html -
+
.. rubric:: Character Device drivers - :name: orgf1744e4 + :name: sec-6 .. raw:: html -
+
.. raw:: html @@ -2038,14 +2038,14 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use .. raw:: html -
+
.. rubric:: The file_operations Structure - :name: org07ed5b3 + :name: sec-6-1 .. raw:: html -
+
The file_operations structure is defined in **/usr/include/linux/fs.h**, and holds pointers to functions defined by the driver that perform @@ -2064,36 +2064,36 @@ definition looks like for kernel 3.0: .. code:: src - struct file_operations { - struct module *owner; - loff_t (*llseek) (struct file *, loff_t, int); - ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); - ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); - ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); - ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); - int (*iterate) (struct file *, struct dir_context *); - unsigned int (*poll) (struct file *, struct poll_table_struct *); - long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); - long (*compat_ioctl) (struct file *, unsigned int, unsigned long); - int (*mmap) (struct file *, struct vm_area_struct *); - int (*open) (struct inode *, struct file *); - int (*flush) (struct file *, fl_owner_t id); - int (*release) (struct inode *, struct file *); - int (*fsync) (struct file *, loff_t, loff_t, int datasync); - int (*aio_fsync) (struct kiocb *, int datasync); - int (*fasync) (int, struct file *, int); - int (*lock) (struct file *, int, struct file_lock *); - ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); - unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); - int (*check_flags)(int); - int (*flock) (struct file *, int, struct file_lock *); - ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); - ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); - int (*setlease)(struct file *, long, struct file_lock **); - long (*fallocate)(struct file *file, int mode, loff_t offset, - loff_t len); - int (*show_fdinfo)(struct seq_file *m, struct file *f); - }; + struct file_operations { + struct module *owner; + loff_t (*llseek) (struct file *, loff_t, int); + ssize_t (*read) (struct file *, char __user *, size_t, loff_t *); + ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *); + ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t); + ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t); + int (*iterate) (struct file *, struct dir_context *); + unsigned int (*poll) (struct file *, struct poll_table_struct *); + long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long); + long (*compat_ioctl) (struct file *, unsigned int, unsigned long); + int (*mmap) (struct file *, struct vm_area_struct *); + int (*open) (struct inode *, struct file *); + int (*flush) (struct file *, fl_owner_t id); + int (*release) (struct inode *, struct file *); + int (*fsync) (struct file *, loff_t, loff_t, int datasync); + int (*aio_fsync) (struct kiocb *, int datasync); + int (*fasync) (int, struct file *, int); + int (*lock) (struct file *, int, struct file_lock *); + ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int); + unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long); + int (*check_flags)(int); + int (*flock) (struct file *, int, struct file_lock *); + ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int); + ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int); + int (*setlease)(struct file *, long, struct file_lock **); + long (*fallocate)(struct file *file, int mode, loff_t offset, + loff_t len); + int (*show_fdinfo)(struct seq_file *m, struct file *f); + }; .. raw:: html @@ -2115,12 +2115,12 @@ like: .. code:: src - struct file_operations fops = { - read: device_read, - write: device_write, - open: device_open, - release: device_release - }; + struct file_operations fops = { + read: device_read, + write: device_write, + open: device_open, + release: device_release + }; .. raw:: html @@ -2138,12 +2138,12 @@ your driver. It will help with compatibility: .. code:: src - struct file_operations fops = { - .read = device_read, - .write = device_write, - .open = device_open, - .release = device_release - }; + struct file_operations fops = { + .read = device_read, + .write = device_write, + .open = device_open, + .release = device_release + }; .. raw:: html @@ -2167,14 +2167,14 @@ named fops. .. raw:: html -
+
.. rubric:: The file structure - :name: orgf283636 + :name: sec-6-2 .. raw:: html -
+
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 @@ -2202,14 +2202,14 @@ use structures contained in file which are created elsewhere. .. raw:: html -
+
.. rubric:: Registering A Device - :name: orgab1c63f + :name: sec-6-3 .. raw:: html -
+
As discussed earlier, char devices are accessed through device files, usually located in /dev. This is by convention. When writing a driver, @@ -2230,7 +2230,7 @@ defined by linux/fs.h. .. code:: src - int 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); .. raw:: html @@ -2273,14 +2273,14 @@ the **device_create** function after a successful registration and .. raw:: html -
+
.. rubric:: Unregistering A Device - :name: org85bc5ea + :name: sec-6-4 .. raw:: html -
+
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 @@ -2322,14 +2322,14 @@ sooner or later during a module's development. .. raw:: html -
+
.. rubric:: chardev.c - :name: orgdbd100e + :name: sec-6-5 .. raw:: html -
+
The next code sample creates a char driver named chardev. You can cat its device file. @@ -2340,7 +2340,7 @@ its device file. .. code:: src - cat /proc/devices + cat /proc/devices .. raw:: html @@ -2360,187 +2360,187 @@ acknowledging that we received it. .. code:: src - /* - * chardev.c: Creates a read-only char device that says how many times - * you've read from the dev file - */ + /* + * chardev.c: Creates a read-only char device that says how many times + * you've read from the dev file + */ - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include - /* - * Prototypes - this would normally go in a .h file - */ - int init_module(void); - void cleanup_module(void); - static int device_open(struct inode *, struct file *); - static int device_release(struct inode *, struct file *); - static ssize_t device_read(struct file *, char *, size_t, loff_t *); - static ssize_t device_write(struct file *, const char *, size_t, loff_t *); + /* + * Prototypes - this would normally go in a .h file + */ + int init_module(void); + void cleanup_module(void); + static int device_open(struct inode *, struct file *); + static int device_release(struct inode *, struct file *); + static ssize_t device_read(struct file *, char *, size_t, loff_t *); + static ssize_t device_write(struct file *, const char *, size_t, loff_t *); - #define SUCCESS 0 - #define DEVICE_NAME "chardev" /* Dev name as it appears in /proc/devices */ - #define BUF_LEN 80 /* Max length of the message from the device */ + #define SUCCESS 0 + #define DEVICE_NAME "chardev" /* Dev name as it appears in /proc/devices */ + #define BUF_LEN 80 /* Max length of the message from the device */ - /* - * Global variables are declared as static, so are global within the file. - */ + /* + * Global variables are declared as static, so are global within the file. + */ - static int Major; /* Major number assigned to our device driver */ - static int Device_Open = 0; /* Is device open? - * Used to prevent multiple access to device */ - static char msg[BUF_LEN]; /* The msg the device will give when asked */ - static char *msg_Ptr; + static int Major; /* Major number assigned to our device driver */ + static int Device_Open = 0; /* Is device open? + * Used to prevent multiple access to device */ + static char msg[BUF_LEN]; /* The msg the device will give when asked */ + static char *msg_Ptr; - static struct class *cls; + static struct class *cls; - static struct file_operations chardev_fops = { - .read = device_read, - .write = device_write, - .open = device_open, - .release = device_release - }; + static struct file_operations chardev_fops = { + .read = device_read, + .write = device_write, + .open = device_open, + .release = device_release + }; - /* - * This function is called when the module is loaded - */ - int init_module(void) - { - Major = register_chrdev(0, DEVICE_NAME, &chardev_fops); + /* + * This function is called when the module is loaded + */ + int init_module(void) + { + Major = register_chrdev(0, DEVICE_NAME, &chardev_fops); - if (Major < 0) { - pr_alert("Registering char device failed with %d\n", Major); - return Major; - } + if (Major < 0) { + pr_alert("Registering char device failed with %d\n", Major); + return Major; + } - pr_info("I was assigned major number %d.\n", Major); + pr_info("I was assigned major number %d.\n", Major); - cls = class_create(THIS_MODULE, DEVICE_NAME); - device_create(cls, NULL, MKDEV(Major, 0), NULL, DEVICE_NAME); + cls = class_create(THIS_MODULE, DEVICE_NAME); + device_create(cls, NULL, MKDEV(Major, 0), NULL, DEVICE_NAME); - pr_info("Device created on /dev/%s\n", DEVICE_NAME); + pr_info("Device created on /dev/%s\n", DEVICE_NAME); - return SUCCESS; - } + return SUCCESS; + } - /* - * This function is called when the module is unloaded - */ - void cleanup_module(void) - { - device_destroy(cls, MKDEV(Major, 0)); - class_destroy(cls); + /* + * This function is called when the module is unloaded + */ + void cleanup_module(void) + { + device_destroy(cls, MKDEV(Major, 0)); + class_destroy(cls); - /* - * Unregister the device - */ - unregister_chrdev(Major, DEVICE_NAME); - } + /* + * Unregister the device + */ + unregister_chrdev(Major, DEVICE_NAME); + } - /* - * Methods - */ + /* + * Methods + */ - /* - * Called when a process tries to open the device file, like - * "cat /dev/mycharfile" - */ - static int device_open(struct inode *inode, struct file *file) - { - static int counter = 0; + /* + * Called when a process tries to open the device file, like + * "cat /dev/mycharfile" + */ + static int device_open(struct inode *inode, struct file *file) + { + static int counter = 0; - if (Device_Open) - return -EBUSY; + if (Device_Open) + return -EBUSY; - Device_Open++; - sprintf(msg, "I already told you %d times Hello world!\n", counter++); - msg_Ptr = msg; - try_module_get(THIS_MODULE); + Device_Open++; + sprintf(msg, "I already told you %d times Hello world!\n", counter++); + msg_Ptr = msg; + try_module_get(THIS_MODULE); - return SUCCESS; - } + return SUCCESS; + } - /* - * Called when a process closes the device file. - */ - static int device_release(struct inode *inode, struct file *file) - { - Device_Open--; /* We're now ready for our next caller */ + /* + * Called when a process closes the device file. + */ + static int device_release(struct inode *inode, struct file *file) + { + Device_Open--; /* We're now ready for our next caller */ - /* - * Decrement the usage count, or else once you opened the file, you'll - * never get get rid of the module. - */ - module_put(THIS_MODULE); + /* + * Decrement the usage count, or else once you opened the file, you'll + * never get get rid of the module. + */ + module_put(THIS_MODULE); - return SUCCESS; - } + return SUCCESS; + } - /* - * Called when a process, which already opened the dev file, attempts to - * read from it. - */ - static ssize_t device_read(struct file *filp, /* see include/linux/fs.h */ - char *buffer, /* buffer to fill with data */ - size_t length, /* length of the buffer */ - loff_t * offset) - { - /* - * Number of bytes actually written to the buffer - */ - int bytes_read = 0; + /* + * Called when a process, which already opened the dev file, attempts to + * read from it. + */ + static ssize_t device_read(struct file *filp, /* see include/linux/fs.h */ + char *buffer, /* buffer to fill with data */ + size_t length, /* length of the buffer */ + loff_t * offset) + { + /* + * Number of bytes actually written to the buffer + */ + int bytes_read = 0; - /* - * If we're at the end of the message, - * return 0 signifying end of file - */ - if (*msg_Ptr == 0) - return 0; + /* + * If we're at the end of the message, + * return 0 signifying end of file + */ + if (*msg_Ptr == 0) + return 0; - /* - * Actually put the data into the buffer - */ - while (length && *msg_Ptr) { + /* + * Actually put the data into the buffer + */ + while (length && *msg_Ptr) { - /* - * The buffer is in the user data segment, not the kernel - * segment so "*" assignment won't work. We have to use - * put_user which copies data from the kernel data segment to - * the user data segment. - */ - put_user(*(msg_Ptr++), buffer++); + /* + * The buffer is in the user data segment, not the kernel + * segment so "*" assignment won't work. We have to use + * put_user which copies data from the kernel data segment to + * the user data segment. + */ + put_user(*(msg_Ptr++), buffer++); - length--; - bytes_read++; - } + length--; + bytes_read++; + } - /* - * Most read functions return the number of bytes put into the buffer - */ - return bytes_read; - } + /* + * Most read functions return the number of bytes put into the buffer + */ + return bytes_read; + } - /* - * Called when a process writes to dev file: echo "hi" > /dev/hello - */ - static ssize_t device_write(struct file *filp, - const char *buff, - size_t len, - loff_t * off) - { - pr_alert("Sorry, this operation isn't supported.\n"); - return -EINVAL; - } + /* + * Called when a process writes to dev file: echo "hi" > /dev/hello + */ + static ssize_t device_write(struct file *filp, + const char *buff, + size_t len, + loff_t * off) + { + pr_alert("Sorry, this operation isn't supported.\n"); + return -EINVAL; + } .. raw:: html @@ -2556,14 +2556,14 @@ acknowledging that we received it. .. raw:: html -
+
.. rubric:: Writing Modules for Multiple Kernel Versions - :name: org130321b + :name: sec-6-6 .. raw:: html -
+
The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call @@ -2621,14 +2621,14 @@ archives if you're interested in the full story. .. raw:: html -
+
.. rubric:: The /proc File System - :name: org44e86f2 + :name: sec-7 .. raw:: html -
+
In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the **/proc** file system. @@ -2659,8 +2659,8 @@ to avoid the consequences. Here a simple example showing how to use a **/proc** file. This is the HelloWorld for the **/proc** filesystem. There are three parts: create -the file ***proc* helloworld** in the function init_module, return a -value (and a buffer) when the file **/proc/helloworld** is read in the +the file **proc helloworld** in the function init_module, return a value +(and a buffer) when the file **/proc/helloworld** is read in the callback function **procfile_read**, and delete the file **/proc/helloworld** in the function cleanup_module. @@ -2685,8 +2685,8 @@ it never returns zero, the read function is called endlessly. .. code:: src - # cat /proc/helloworld - HelloWorld! + # cat /proc/helloworld + HelloWorld! .. raw:: html @@ -2698,56 +2698,56 @@ it never returns zero, the read function is called endlessly. .. code:: src - /* - procfs1.c - */ + /* + procfs1.c + */ - #include - #include - #include - #include + #include + #include + #include + #include - #define procfs_name "helloworld" + #define procfs_name "helloworld" - struct proc_dir_entry *Our_Proc_File; + struct proc_dir_entry *Our_Proc_File; - ssize_t procfile_read(struct file *filePointer,char *buffer, - size_t buffer_length, loff_t * offset) - { - int ret=0; - if(strlen(buffer) ==0) { - 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"); - } - return ret; + ssize_t procfile_read(struct file *filePointer,char *buffer, + size_t buffer_length, loff_t * offset) + { + int ret=0; + if(strlen(buffer) ==0) { + 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"); + } + return ret; - } + } - static const struct file_operations proc_file_fops = { - .owner = THIS_MODULE, - .read = procfile_read, - }; + static const struct file_operations proc_file_fops = { + .owner = THIS_MODULE, + .read = procfile_read, + }; - int init_module() - { - Our_Proc_File = proc_create(procfs_name,0644,NULL,&proc_file_fops); - if(NULL==Our_Proc_File) { - proc_remove(Our_Proc_File); - pr_alert("Error:Could not initialize /proc/%s\n",procfs_name); - return -ENOMEM; - } + int init_module() + { + Our_Proc_File = proc_create(procfs_name,0644,NULL,&proc_file_fops); + if(NULL==Our_Proc_File) { + proc_remove(Our_Proc_File); + pr_alert("Error:Could not initialize /proc/%s\n",procfs_name); + return -ENOMEM; + } - pr_info("/proc/%s created\n", procfs_name); - return 0; - } + pr_info("/proc/%s created\n", procfs_name); + return 0; + } - void cleanup_module() - { - proc_remove(Our_Proc_File); - pr_info("/proc/%s removed\n", procfs_name); - } + void cleanup_module() + { + proc_remove(Our_Proc_File); + pr_info("/proc/%s removed\n", procfs_name); + } .. raw:: html @@ -2759,14 +2759,14 @@ it never returns zero, the read function is called endlessly. .. raw:: html -
+
.. rubric:: Read and Write a /proc File - :name: org330f61f + :name: sec-7-1 .. raw:: html -
+
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. @@ -2802,104 +2802,104 @@ function because data is already in kernel space. .. code:: src - /** - * procfs2.c - create a "file" in /proc - * - */ + /** + * procfs2.c - create a "file" in /proc + * + */ - #include /* Specifically, a module */ - #include /* We're doing kernel work */ - #include /* Necessary because we use the proc fs */ - #include /* for copy_from_user */ + #include /* Specifically, a module */ + #include /* We're doing kernel work */ + #include /* Necessary because we use the proc fs */ + #include /* for copy_from_user */ - #define PROCFS_MAX_SIZE 1024 - #define PROCFS_NAME "buffer1k" + #define PROCFS_MAX_SIZE 1024 + #define PROCFS_NAME "buffer1k" - /** - * This structure hold information about the /proc file - * - */ - static struct proc_dir_entry *Our_Proc_File; + /** + * This structure hold information about the /proc file + * + */ + static struct proc_dir_entry *Our_Proc_File; - /** - * The buffer used to store character for this module - * - */ - static char procfs_buffer[PROCFS_MAX_SIZE]; + /** + * The buffer used to store character for this module + * + */ + static char procfs_buffer[PROCFS_MAX_SIZE]; - /** - * The size of the buffer - * - */ - static unsigned long procfs_buffer_size = 0; + /** + * The size of the buffer + * + */ + static unsigned long procfs_buffer_size = 0; - /** - * This function is called then the /proc file is read - * - */ - ssize_t procfile_read(struct file *filePointer,char *buffer, - size_t buffer_length, loff_t * offset) - { - int ret=0; - if(strlen(buffer) ==0) { - 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"); - } - return ret; - } + /** + * This function is called then the /proc file is read + * + */ + ssize_t procfile_read(struct file *filePointer,char *buffer, + size_t buffer_length, loff_t * offset) + { + int ret=0; + if(strlen(buffer) ==0) { + 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"); + } + return ret; + } - /** - * This function is called with the /proc file is written - * - */ - static ssize_t procfile_write(struct file *file, const char *buff, - size_t len, loff_t *off) - { - procfs_buffer_size = len; - if (procfs_buffer_size > PROCFS_MAX_SIZE) - procfs_buffer_size = PROCFS_MAX_SIZE; + /** + * This function is called with the /proc file is written + * + */ + static ssize_t procfile_write(struct file *file, const char *buff, + size_t len, loff_t *off) + { + procfs_buffer_size = len; + if (procfs_buffer_size > PROCFS_MAX_SIZE) + procfs_buffer_size = PROCFS_MAX_SIZE; - if (copy_from_user(procfs_buffer, buff, procfs_buffer_size)) - return -EFAULT; + if (copy_from_user(procfs_buffer, buff, procfs_buffer_size)) + return -EFAULT; - procfs_buffer[procfs_buffer_size] = '\0'; - return procfs_buffer_size; - } + procfs_buffer[procfs_buffer_size] = '\0'; + return procfs_buffer_size; + } - static const struct file_operations proc_file_fops = { - .owner = THIS_MODULE, - .read = procfile_read, - .write = procfile_write, - }; + static const struct file_operations proc_file_fops = { + .owner = THIS_MODULE, + .read = procfile_read, + .write = procfile_write, + }; - /** - *This function is called when the module is loaded - * - */ - int init_module() - { - Our_Proc_File = proc_create(PROCFS_NAME,0644,NULL,&proc_file_fops); - if(NULL==Our_Proc_File) { - proc_remove(Our_Proc_File); - pr_alert("Error:Could not initialize /proc/%s\n",PROCFS_NAME); - return -ENOMEM; - } + /** + *This function is called when the module is loaded + * + */ + int init_module() + { + Our_Proc_File = proc_create(PROCFS_NAME,0644,NULL,&proc_file_fops); + if(NULL==Our_Proc_File) { + proc_remove(Our_Proc_File); + pr_alert("Error:Could not initialize /proc/%s\n",PROCFS_NAME); + return -ENOMEM; + } - pr_info("/proc/%s created\n", PROCFS_NAME); - return 0; - } + pr_info("/proc/%s created\n", PROCFS_NAME); + return 0; + } - /** - *This function is called when the module is unloaded - * - */ - void cleanup_module() - { - proc_remove(Our_Proc_File); - pr_info("/proc/%s removed\n", PROCFS_NAME); - } + /** + *This function is called when the module is unloaded + * + */ + void cleanup_module() + { + proc_remove(Our_Proc_File); + pr_info("/proc/%s removed\n", PROCFS_NAME); + } .. raw:: html @@ -2915,14 +2915,14 @@ function because data is already in kernel space. .. raw:: html -
+
.. rubric:: Manage /proc file with standard filesystem - :name: orgaae8b16 + :name: sec-7-2 .. raw:: html -
+
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 @@ -2966,89 +2966,89 @@ writes something to the kernel, then the kernel receives it as input. .. code:: src - /* - procfs3.c - */ + /* + procfs3.c + */ - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include - #define PROCFS_MAX_SIZE 2048 - #define PROCFS_ENTRY_FILENAME "buffer2k" + #define PROCFS_MAX_SIZE 2048 + #define PROCFS_ENTRY_FILENAME "buffer2k" - struct proc_dir_entry *Our_Proc_File; - static char procfs_buffer[PROCFS_MAX_SIZE]; - static unsigned long procfs_buffer_size = 0; + struct proc_dir_entry *Our_Proc_File; + static char procfs_buffer[PROCFS_MAX_SIZE]; + static unsigned long procfs_buffer_size = 0; - static ssize_t procfs_read(struct file *filp, char *buffer, - size_t length, loff_t *offset) - { - static int finished = 0; - if(finished) - { - pr_debug("procfs_read: END\n"); - finished = 0; - return 0; - } - finished = 1; - if(copy_to_user(buffer, procfs_buffer, procfs_buffer_size)) - return -EFAULT; - 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, - size_t len, loff_t *off) - { - if(len>PROCFS_MAX_SIZE) - procfs_buffer_size = PROCFS_MAX_SIZE; - else - procfs_buffer_size = len; - if(copy_from_user(procfs_buffer, buffer, procfs_buffer_size)) - return -EFAULT; - pr_debug("procfs_write: write %lu bytes\n", procfs_buffer_size); - return procfs_buffer_size; - } - int procfs_open(struct inode *inode, struct file *file) - { - try_module_get(THIS_MODULE); - return 0; - } - int procfs_close(struct inode *inode, struct file *file) - { - module_put(THIS_MODULE); - return 0; - } + static ssize_t procfs_read(struct file *filp, char *buffer, + size_t length, loff_t *offset) + { + static int finished = 0; + if(finished) + { + pr_debug("procfs_read: END\n"); + finished = 0; + return 0; + } + finished = 1; + if(copy_to_user(buffer, procfs_buffer, procfs_buffer_size)) + return -EFAULT; + 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, + size_t len, loff_t *off) + { + if(len>PROCFS_MAX_SIZE) + procfs_buffer_size = PROCFS_MAX_SIZE; + else + procfs_buffer_size = len; + if(copy_from_user(procfs_buffer, buffer, procfs_buffer_size)) + return -EFAULT; + pr_debug("procfs_write: write %lu bytes\n", procfs_buffer_size); + return procfs_buffer_size; + } + int procfs_open(struct inode *inode, struct file *file) + { + try_module_get(THIS_MODULE); + return 0; + } + int procfs_close(struct inode *inode, struct file *file) + { + module_put(THIS_MODULE); + return 0; + } - static struct file_operations File_Ops_4_Our_Proc_File = { - .read = procfs_read, - .write = procfs_write, - .open = procfs_open, - .release = procfs_close, - }; + static struct file_operations File_Ops_4_Our_Proc_File = { + .read = procfs_read, + .write = procfs_write, + .open = procfs_open, + .release = procfs_close, + }; - int init_module() - { - Our_Proc_File = proc_create(PROCFS_ENTRY_FILENAME, 0644, NULL,&File_Ops_4_Our_Proc_File); - if(Our_Proc_File == NULL) - { - remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); - 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); + int init_module() + { + Our_Proc_File = proc_create(PROCFS_ENTRY_FILENAME, 0644, NULL,&File_Ops_4_Our_Proc_File); + if(Our_Proc_File == NULL) + { + remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); + 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); - pr_debug("/proc/%s created\n", PROCFS_ENTRY_FILENAME); - return 0; - } - void cleanup_module() - { - remove_proc_entry(PROCFS_ENTRY_FILENAME, NULL); - pr_debug("/proc/%s removed\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); + pr_debug("/proc/%s removed\n", PROCFS_ENTRY_FILENAME); + } .. raw:: html @@ -3073,14 +3073,14 @@ you want to document something kernel related yourself. .. raw:: html -
+
.. rubric:: Manage /proc file with seq_file - :name: org688df35 + :name: sec-7-3 .. raw:: html -
+
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 @@ -3124,140 +3124,140 @@ course, you can still use the same way as in the previous example. .. code:: src - /** - * procfs4.c - create a "file" in /proc - * This program uses the seq_file library to manage the /proc file. - * - */ + /** + * procfs4.c - create a "file" in /proc + * This program uses the seq_file library to manage the /proc file. + * + */ - #include /* We're doing kernel work */ - #include /* Specifically, a module */ - #include /* Necessary because we use proc fs */ - #include /* for seq_file */ + #include /* We're doing kernel work */ + #include /* Specifically, a module */ + #include /* Necessary because we use proc fs */ + #include /* for seq_file */ - #define PROC_NAME "iter" + #define PROC_NAME "iter" - MODULE_AUTHOR("Philippe Reynes"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Philippe Reynes"); + MODULE_LICENSE("GPL"); - /** - * This function is called at the beginning of a sequence. - * ie, when: - * - the /proc file is read (first time) - * - after the function stop (end of sequence) - * - */ - static void *my_seq_start(struct seq_file *s, loff_t *pos) - { - static unsigned long counter = 0; + /** + * This function is called at the beginning of a sequence. + * ie, when: + * - the /proc file is read (first time) + * - after the function stop (end of sequence) + * + */ + static void *my_seq_start(struct seq_file *s, loff_t *pos) + { + static unsigned long counter = 0; - /* beginning a new sequence ? */ - if ( *pos == 0 ) { - /* yes => return a non null value to begin the sequence */ - return &counter; - } - else { - /* no => it's the end of the sequence, return end to stop reading */ - *pos = 0; - return NULL; - } - } + /* beginning a new sequence ? */ + if ( *pos == 0 ) { + /* yes => return a non null value to begin the sequence */ + return &counter; + } + else { + /* no => it's the end of the sequence, return end to stop reading */ + *pos = 0; + return NULL; + } + } - /** - * This function is called after the beginning of a sequence. - * It's called untill the return is NULL (this ends the sequence). - * - */ - static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos) - { - unsigned long *tmp_v = (unsigned long *)v; - (*tmp_v)++; - (*pos)++; - return NULL; - } + /** + * This function is called after the beginning of a sequence. + * It's called untill the return is NULL (this ends the sequence). + * + */ + static void *my_seq_next(struct seq_file *s, void *v, loff_t *pos) + { + unsigned long *tmp_v = (unsigned long *)v; + (*tmp_v)++; + (*pos)++; + return NULL; + } - /** - * This function is called at the end of a sequence - * - */ - static void my_seq_stop(struct seq_file *s, void *v) - { - /* nothing to do, we use a static value in start() */ - } + /** + * This function is called at the end of a sequence + * + */ + static void my_seq_stop(struct seq_file *s, void *v) + { + /* nothing to do, we use a static value in start() */ + } - /** - * This function is called for each "step" of a sequence - * - */ - static int my_seq_show(struct seq_file *s, void *v) - { - loff_t *spos = (loff_t *) v; + /** + * This function is called for each "step" of a sequence + * + */ + static int my_seq_show(struct seq_file *s, void *v) + { + loff_t *spos = (loff_t *) v; - seq_printf(s, "%Ld\n", *spos); - return 0; - } + seq_printf(s, "%Ld\n", *spos); + return 0; + } - /** - * This structure gather "function" to manage the sequence - * - */ - static struct seq_operations my_seq_ops = { - .start = my_seq_start, - .next = my_seq_next, - .stop = my_seq_stop, - .show = my_seq_show - }; + /** + * This structure gather "function" to manage the sequence + * + */ + static struct seq_operations my_seq_ops = { + .start = my_seq_start, + .next = my_seq_next, + .stop = my_seq_stop, + .show = my_seq_show + }; - /** - * This function is called when the /proc file is open. - * - */ - static int my_open(struct inode *inode, struct file *file) - { - return seq_open(file, &my_seq_ops); - }; + /** + * This function is called when the /proc file is open. + * + */ + static int my_open(struct inode *inode, struct file *file) + { + return seq_open(file, &my_seq_ops); + }; - /** - * This structure gather "function" that manage the /proc file - * - */ - static struct file_operations my_file_ops = { - .owner = THIS_MODULE, - .open = my_open, - .read = seq_read, - .llseek = seq_lseek, - .release = seq_release - }; + /** + * This structure gather "function" that manage the /proc file + * + */ + static struct file_operations my_file_ops = { + .owner = THIS_MODULE, + .open = my_open, + .read = seq_read, + .llseek = seq_lseek, + .release = seq_release + }; - /** - * This function is called when the module is loaded - * - */ - int init_module(void) - { - struct proc_dir_entry *entry; + /** + * This function is called when the module is loaded + * + */ + int init_module(void) + { + struct proc_dir_entry *entry; - entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops); - if(entry == NULL) - { - remove_proc_entry(PROC_NAME, NULL); - pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME); - return -ENOMEM; - } + entry = proc_create(PROC_NAME, 0, NULL, &my_file_ops); + if(entry == NULL) + { + remove_proc_entry(PROC_NAME, NULL); + pr_debug("Error: Could not initialize /proc/%s\n", PROC_NAME); + return -ENOMEM; + } - return 0; - } + return 0; + } - /** - * This function is called when the module is unloaded. - * - */ - void cleanup_module(void) - { - remove_proc_entry(PROC_NAME, NULL); - pr_debug("/proc/%s removed\n", PROC_NAME); - } + /** + * This function is called when the module is unloaded. + * + */ + void cleanup_module(void) + { + remove_proc_entry(PROC_NAME, NULL); + pr_debug("/proc/%s removed\n", PROC_NAME); + } .. raw:: html @@ -3284,14 +3284,14 @@ You can also read the code of fs/seq_file.c in the linux kernel. .. raw:: html -
+
.. rubric:: sysfs: Interacting with your module - :name: orgbd8ce69 + :name: sec-8 .. raw:: html -
+
*sysfs* allows you to interact with the running kernel from userspace by reading or setting variables inside of modules. This can be useful for @@ -3305,7 +3305,7 @@ your system. .. code:: src - ls -l /sys + ls -l /sys .. raw:: html @@ -3318,75 +3318,7 @@ variable accessible via sysfs is given below.
-.. code:: src - - /* - * hello-sysfs.c sysfs example - */ - - #include - #include - #include - #include - #include - #include - - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - - static struct kobject *mymodule; - - /* the variable you want to be able to change */ - static int myvariable = 0; - - static ssize_t myvariable_show(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf) - { - return sprintf(buf, "%d\n", myvariable); - } - - static ssize_t myvariable_store(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf, size_t count) - { - sscanf(buf, "%du", &myvariable); - return count; - } - - - static struct kobj_attribute myvariable_attribute = - __ATTR(myvariable, 0660, myvariable_show, - (void*)myvariable_store); - - static int __init mymodule_init (void) - { - int error = 0; - - pr_info("mymodule: initialised\n"); - - mymodule = - kobject_create_and_add("mymodule", kernel_kobj); - if (!mymodule) - return -ENOMEM; - - error = sysfs_create_file(mymodule, &myvariable_attribute.attr); - if (error) { - pr_info("failed to create the myvariable file " \ - "in /sys/kernel/mymodule\n"); - } - - return error; - } - - static void __exit mymodule_exit (void) - { - pr_info("mymodule: Exit success\n"); - kobject_put(mymodule); - } - - module_init(mymodule_init); - module_exit(mymodule_exit); +``{.src .src- hello-sysfs.c"lang"hello-sysfs.c"switches"hello-sysfs.c"flags"=""} "hello-sysfs.c"body`` .. raw:: html @@ -3400,8 +3332,8 @@ Make and install the module: .. code:: src - make - sudo insmod hello-sysfs.ko + make + sudo insmod hello-sysfs.ko .. raw:: html @@ -3415,7 +3347,7 @@ Check that it exists: .. code:: src - sudo lsmod | grep hello_sysfs + sudo lsmod | grep hello_sysfs .. raw:: html @@ -3429,7 +3361,7 @@ What is the current value of *myvariable* ? .. code:: src - cat /sys/kernel/mymodule/myvariable + cat /sys/kernel/mymodule/myvariable .. raw:: html @@ -3443,8 +3375,8 @@ Set the value of *myvariable* and check that it changed. .. code:: src - echo "32" > /sys/kernel/mymodule/myvariable - cat /sys/kernel/mymodule/myvariable + echo "32" > /sys/kernel/mymodule/myvariable + cat /sys/kernel/mymodule/myvariable .. raw:: html @@ -3458,7 +3390,7 @@ Finally, remove the test module: .. code:: src - sudo rmmod hello_sysfs + sudo rmmod hello_sysfs .. raw:: html @@ -3474,14 +3406,14 @@ Finally, remove the test module: .. raw:: html -
+
.. rubric:: Talking To Device Files - :name: orga1b8e31 + :name: sec-9 .. raw:: html -
+
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 @@ -3536,293 +3468,293 @@ Documentation/ioctl-number.txt. .. code:: src - /* - * chardev2.c - Create an input/output character device - */ + /* + * chardev2.c - Create an input/output character device + */ - #include /* We're doing kernel work */ - #include /* Specifically, a module */ - #include - #include - #include - #include - #include - #include - #include - #include - #include - #include + #include /* We're doing kernel work */ + #include /* Specifically, a module */ + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include - #include "chardev.h" - #define SUCCESS 0 - #define DEVICE_NAME "char_dev" - #define BUF_LEN 80 + #include "chardev.h" + #define SUCCESS 0 + #define DEVICE_NAME "char_dev" + #define BUF_LEN 80 - /* - * Is the device open right now? Used to prevent - * concurent access into the same device - */ - static int Device_Open = 0; + /* + * Is the device open right now? Used to prevent + * concurent access into the same device + */ + static int Device_Open = 0; - /* - * The message the device will give when asked - */ - static char Message[BUF_LEN]; + /* + * The message the device will give when asked + */ + static char Message[BUF_LEN]; - /* - * How far did the process reading the message get? - * Useful if the message is larger than the size of the - * buffer we get to fill in device_read. - */ - static char *Message_Ptr; + /* + * How far did the process reading the message get? + * Useful if the message is larger than the size of the + * buffer we get to fill in device_read. + */ + static char *Message_Ptr; - static int Major; /* Major number assigned to our device driver */ - static struct class *cls; + static int Major; /* Major number assigned to our device driver */ + static struct class *cls; - /* - * This is called whenever a process attempts to open the device file - */ - static int device_open(struct inode *inode, struct file *file) - { - #ifdef DEBUG - pr_info("device_open(%p)\n", file); - #endif + /* + * This is called whenever a process attempts to open the device file + */ + static int device_open(struct inode *inode, struct file *file) + { + #ifdef DEBUG + pr_info("device_open(%p)\n", file); + #endif - /* - * We don't want to talk to two processes at the same time - */ - if (Device_Open) - return -EBUSY; + /* + * We don't want to talk to two processes at the same time + */ + if (Device_Open) + return -EBUSY; - Device_Open++; - /* - * Initialize the message - */ - Message_Ptr = Message; - try_module_get(THIS_MODULE); - return SUCCESS; - } + Device_Open++; + /* + * Initialize the message + */ + Message_Ptr = Message; + try_module_get(THIS_MODULE); + return SUCCESS; + } - static int device_release(struct inode *inode, struct file *file) - { - #ifdef DEBUG - pr_info("device_release(%p,%p)\n", inode, file); - #endif + static int device_release(struct inode *inode, struct file *file) + { + #ifdef DEBUG + pr_info("device_release(%p,%p)\n", inode, file); + #endif - /* - * We're now ready for our next caller - */ - Device_Open--; + /* + * We're now ready for our next caller + */ + Device_Open--; - module_put(THIS_MODULE); - return SUCCESS; - } + module_put(THIS_MODULE); + return SUCCESS; + } - /* - * This function is called whenever a process which has already opened the - * device file attempts to read from it. - */ - static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ - char __user * buffer, /* buffer to be - * filled with data */ - size_t length, /* length of the buffer */ - loff_t * offset) - { - /* - * Number of bytes actually written to the buffer - */ - int bytes_read = 0; + /* + * This function is called whenever a process which has already opened the + * device file attempts to read from it. + */ + static ssize_t device_read(struct file *file, /* see include/linux/fs.h */ + char __user * buffer, /* buffer to be + * filled with data */ + size_t length, /* length of the buffer */ + loff_t * offset) + { + /* + * Number of bytes actually written to the buffer + */ + int bytes_read = 0; - #ifdef DEBUG - pr_info("device_read(%p,%p,%d)\n", file, buffer, length); - #endif + #ifdef DEBUG + pr_info("device_read(%p,%p,%d)\n", file, buffer, length); + #endif - /* - * If we're at the end of the message, return 0 - * (which signifies end of file) - */ - if (*Message_Ptr == 0) - return 0; + /* + * If we're at the end of the message, return 0 + * (which signifies end of file) + */ + if (*Message_Ptr == 0) + return 0; - /* - * Actually put the data into the buffer - */ - while (length && *Message_Ptr) { + /* + * Actually put the data into the buffer + */ + while (length && *Message_Ptr) { - /* - * Because the buffer is in the user data segment, - * not the kernel data segment, assignment wouldn't - * work. Instead, we have to use put_user which - * copies data from the kernel data segment to the - * user data segment. - */ - put_user(*(Message_Ptr++), buffer++); - length--; - bytes_read++; - } + /* + * Because the buffer is in the user data segment, + * not the kernel data segment, assignment wouldn't + * work. Instead, we have to use put_user which + * copies data from the kernel data segment to the + * user data segment. + */ + put_user(*(Message_Ptr++), buffer++); + length--; + bytes_read++; + } - #ifdef DEBUG - pr_info("Read %d bytes, %d left\n", bytes_read, length); - #endif + #ifdef DEBUG + pr_info("Read %d bytes, %d left\n", bytes_read, length); + #endif - /* - * Read functions are supposed to return the number - * of bytes actually inserted into the buffer - */ - return bytes_read; - } + /* + * Read functions are supposed to return the number + * of bytes actually inserted into the buffer + */ + return bytes_read; + } - /* - * This function is called when somebody tries to - * write into our device file. - */ - static ssize_t - device_write(struct file *file, - const char __user * buffer, size_t length, loff_t * offset) - { - int i; + /* + * This function is called when somebody tries to + * write into our device file. + */ + static ssize_t + device_write(struct file *file, + const char __user * buffer, size_t length, loff_t * offset) + { + int i; - #ifdef DEBUG - pr_info("device_write(%p,%s,%d)", file, buffer, length); - #endif + #ifdef DEBUG + pr_info("device_write(%p,%s,%d)", file, buffer, length); + #endif - for (i = 0; i < length && i < BUF_LEN; i++) - get_user(Message[i], buffer + i); + for (i = 0; i < length && i < BUF_LEN; i++) + get_user(Message[i], buffer + i); - Message_Ptr = Message; + Message_Ptr = Message; - /* - * Again, return the number of input characters used - */ - return i; - } + /* + * Again, return the number of input characters used + */ + return i; + } - /* - * This function is called whenever a process tries to do an ioctl on our - * device file. We get two extra parameters (additional to the inode and file - * structures, which all device functions get): the number of the ioctl called - * and the parameter given to the ioctl function. - * - * If the ioctl is write or read/write (meaning output is returned to the - * calling process), the ioctl call returns the output of this function. - * - */ - long device_ioctl(struct file *file, /* ditto */ - unsigned int ioctl_num, /* number and param for ioctl */ - unsigned long ioctl_param) - { - int i; - char *temp; - char ch; + /* + * This function is called whenever a process tries to do an ioctl on our + * device file. We get two extra parameters (additional to the inode and file + * structures, which all device functions get): the number of the ioctl called + * and the parameter given to the ioctl function. + * + * If the ioctl is write or read/write (meaning output is returned to the + * calling process), the ioctl call returns the output of this function. + * + */ + long device_ioctl(struct file *file, /* ditto */ + unsigned int ioctl_num, /* number and param for ioctl */ + unsigned long ioctl_param) + { + int i; + char *temp; + char ch; - /* - * Switch according to the ioctl called - */ - switch (ioctl_num) { - case IOCTL_SET_MSG: - /* - * Receive a pointer to a message (in user space) and set that - * to be the device's message. Get the parameter given to - * ioctl by the process. - */ - temp = (char *)ioctl_param; - - /* - * Find the length of the message - */ - get_user(ch, temp); - for (i = 0; ch && i < BUF_LEN; i++, temp++) - get_user(ch, temp); - - device_write(file, (char *)ioctl_param, i, 0); - break; - - case IOCTL_GET_MSG: - /* - * Give the current message to the calling process - - * the parameter we got is a pointer, fill it. - */ - i = device_read(file, (char *)ioctl_param, 99, 0); + /* + * Switch according to the ioctl called + */ + switch (ioctl_num) { + case IOCTL_SET_MSG: + /* + * Receive a pointer to a message (in user space) and set that + * to be the device's message. Get the parameter given to + * ioctl by the process. + */ + temp = (char *)ioctl_param; /* - * Put a zero at the end of the buffer, so it will be - * properly terminated + * Find the length of the message */ - put_user('\0', (char *)ioctl_param + i); + get_user(ch, temp); + for (i = 0; ch && i < BUF_LEN; i++, temp++) + get_user(ch, temp); + + device_write(file, (char *)ioctl_param, i, 0); break; - case IOCTL_GET_NTH_BYTE: - /* - * This ioctl is both input (ioctl_param) and - * output (the return value of this function) - */ - return Message[ioctl_param]; - break; - } + case IOCTL_GET_MSG: + /* + * Give the current message to the calling process - + * the parameter we got is a pointer, fill it. + */ + i = device_read(file, (char *)ioctl_param, 99, 0); - return SUCCESS; - } + /* + * Put a zero at the end of the buffer, so it will be + * properly terminated + */ + put_user('\0', (char *)ioctl_param + i); + break; - /* Module Declarations */ + case IOCTL_GET_NTH_BYTE: + /* + * This ioctl is both input (ioctl_param) and + * output (the return value of this function) + */ + return Message[ioctl_param]; + break; + } - /* - * This structure will hold the functions to be called - * when a process does something to the device we - * created. Since a pointer to this structure is kept in - * the devices table, it can't be local to - * init_module. NULL is for unimplemented functions. - */ - struct file_operations Fops = { - .read = device_read, - .write = device_write, - .unlocked_ioctl = device_ioctl, - .open = device_open, - .release = device_release, /* a.k.a. close */ - }; + return SUCCESS; + } - /* - * Initialize the module - Register the character device - */ - int init_module() - { - int ret_val; - /* - * Register the character device (atleast try) - */ - ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops); + /* Module Declarations */ - /* - * Negative values signify an error - */ - if (ret_val < 0) { - pr_alert("%s failed with %d\n", - "Sorry, registering the character device ", ret_val); - return ret_val; - } + /* + * This structure will hold the functions to be called + * when a process does something to the device we + * created. Since a pointer to this structure is kept in + * the devices table, it can't be local to + * init_module. NULL is for unimplemented functions. + */ + struct file_operations Fops = { + .read = device_read, + .write = device_write, + .unlocked_ioctl = device_ioctl, + .open = device_open, + .release = device_release, /* a.k.a. close */ + }; - Major = ret_val; + /* + * Initialize the module - Register the character device + */ + int init_module() + { + int ret_val; + /* + * Register the character device (atleast try) + */ + ret_val = register_chrdev(MAJOR_NUM, DEVICE_NAME, &Fops); - cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); - device_create(cls, NULL, MKDEV(Major, MAJOR_NUM), NULL, DEVICE_FILE_NAME); + /* + * Negative values signify an error + */ + if (ret_val < 0) { + pr_alert("%s failed with %d\n", + "Sorry, registering the character device ", ret_val); + return ret_val; + } - pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); + Major = ret_val; - return 0; - } + cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); + device_create(cls, NULL, MKDEV(Major, MAJOR_NUM), NULL, DEVICE_FILE_NAME); - /* - * Cleanup - unregister the appropriate file from /proc - */ - void cleanup_module() - { - device_destroy(cls, MKDEV(Major, 0)); - class_destroy(cls); + pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); - /* - * Unregister the device - */ - unregister_chrdev(Major, DEVICE_NAME); - } + return 0; + } + + /* + * Cleanup - unregister the appropriate file from /proc + */ + void cleanup_module() + { + device_destroy(cls, MKDEV(Major, 0)); + class_destroy(cls); + + /* + * Unregister the device + */ + unregister_chrdev(Major, DEVICE_NAME); + } .. raw:: html @@ -3834,72 +3766,72 @@ Documentation/ioctl-number.txt. .. code:: src - /* - * chardev.h - the header file with the ioctl definitions. - * - * The declarations here have to be in a header file, because - * they need to be known both to the kernel module - * (in chardev.c) and the process calling ioctl (ioctl.c) - */ + /* + * chardev.h - the header file with the ioctl definitions. + * + * The declarations here have to be in a header file, because + * they need to be known both to the kernel module + * (in chardev.c) and the process calling ioctl (ioctl.c) + */ - #ifndef CHARDEV_H - #define CHARDEV_H + #ifndef CHARDEV_H + #define CHARDEV_H - #include + #include - /* - * The major device number. We can't rely on dynamic - * registration any more, because ioctls need to know - * it. - */ - #define MAJOR_NUM 100 + /* + * The major device number. We can't rely on dynamic + * registration any more, because ioctls need to know + * it. + */ + #define MAJOR_NUM 100 - /* - * Set the message of the device driver - */ - #define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *) - /* - * _IOW means that we're creating an ioctl command - * number for passing information from a user process - * to the kernel module. - * - * The first arguments, MAJOR_NUM, is the major device - * number we're using. - * - * The second argument is the number of the command - * (there could be several with different meanings). - * - * The third argument is the type we want to get from - * the process to the kernel. - */ + /* + * Set the message of the device driver + */ + #define IOCTL_SET_MSG _IOW(MAJOR_NUM, 0, char *) + /* + * _IOW means that we're creating an ioctl command + * number for passing information from a user process + * to the kernel module. + * + * The first arguments, MAJOR_NUM, is the major device + * number we're using. + * + * The second argument is the number of the command + * (there could be several with different meanings). + * + * The third argument is the type we want to get from + * the process to the kernel. + */ - /* - * Get the message of the device driver - */ - #define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) - /* - * This IOCTL is used for output, to get the message - * of the device driver. However, we still need the - * buffer to place the message in to be input, - * as it is allocated by the process. - */ + /* + * Get the message of the device driver + */ + #define IOCTL_GET_MSG _IOR(MAJOR_NUM, 1, char *) + /* + * This IOCTL is used for output, to get the message + * of the device driver. However, we still need the + * buffer to place the message in to be input, + * as it is allocated by the process. + */ - /* - * Get the n'th byte of the message - */ - #define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) - /* - * The IOCTL is used for both input and output. It - * receives from the user a number, n, and returns - * Message[n]. - */ + /* + * Get the n'th byte of the message + */ + #define IOCTL_GET_NTH_BYTE _IOWR(MAJOR_NUM, 2, int) + /* + * The IOCTL is used for both input and output. It + * receives from the user a number, n, and returns + * Message[n]. + */ - /* - * The name of the device file - */ - #define DEVICE_FILE_NAME "char_dev" + /* + * The name of the device file + */ + #define DEVICE_FILE_NAME "char_dev" - #endif + #endif .. raw:: html @@ -3911,110 +3843,110 @@ Documentation/ioctl-number.txt. .. code:: src - /* - * 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 - * we need to do ioctl's, which require writing our own process. - */ + /* + * 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 + * we need to do ioctl's, which require writing our own process. + */ - /* - * device specifics, such as ioctl numbers and the - * major device file. - */ - #include "../chardev.h" + /* + * device specifics, such as ioctl numbers and the + * major device file. + */ + #include "../chardev.h" - #include - #include - #include /* open */ - #include /* exit */ - #include /* ioctl */ + #include + #include + #include /* open */ + #include /* exit */ + #include /* ioctl */ - /* - * Functions for the ioctl calls - */ + /* + * Functions for the ioctl calls + */ - int ioctl_set_msg(int file_desc, char *message) - { - int ret_val; + int ioctl_set_msg(int file_desc, char *message) + { + int ret_val; - ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); + ret_val = ioctl(file_desc, IOCTL_SET_MSG, message); - if (ret_val < 0) { - printf("ioctl_set_msg failed:%d\n", ret_val); - exit(-1); - } - return 0; - } + if (ret_val < 0) { + printf("ioctl_set_msg failed:%d\n", ret_val); + exit(-1); + } + return 0; + } - int ioctl_get_msg(int file_desc) - { - int ret_val; - char message[100]; + int ioctl_get_msg(int file_desc) + { + int ret_val; + char message[100]; - /* - * Warning - this is dangerous because we don't tell - * the kernel how far it's allowed to write, so it - * might overflow the buffer. In a real production - * program, we would have used two ioctls - one to tell - * the kernel the buffer length and another to give - * it the buffer to fill - */ - ret_val = ioctl(file_desc, IOCTL_GET_MSG, message); + /* + * Warning - this is dangerous because we don't tell + * the kernel how far it's allowed to write, so it + * might overflow the buffer. In a real production + * program, we would have used two ioctls - one to tell + * the kernel the buffer length and another to give + * it the buffer to fill + */ + ret_val = ioctl(file_desc, IOCTL_GET_MSG, message); - if (ret_val < 0) { - printf("ioctl_get_msg failed:%d\n", ret_val); - exit(-1); - } + if (ret_val < 0) { + printf("ioctl_get_msg failed:%d\n", ret_val); + exit(-1); + } - printf("get_msg message:%s\n", message); - return 0; - } + printf("get_msg message:%s\n", message); + return 0; + } - int ioctl_get_nth_byte(int file_desc) - { - int i; - char c; + int ioctl_get_nth_byte(int file_desc) + { + int i; + char c; - printf("get_nth_byte message:"); + printf("get_nth_byte message:"); - i = 0; - do { - c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++); + i = 0; + do { + c = ioctl(file_desc, IOCTL_GET_NTH_BYTE, i++); - if (c < 0) { - printf("ioctl_get_nth_byte failed at the %d'th byte:\n", - i); - exit(-1); - } + if (c < 0) { + printf("ioctl_get_nth_byte failed at the %d'th byte:\n", + i); + exit(-1); + } - putchar(c); - } while (c != 0); - putchar('\n'); - return 0; - } + putchar(c); + } while (c != 0); + putchar('\n'); + return 0; + } - /* - * Main - Call the ioctl functions - */ - int main() - { - int file_desc, ret_val; - char *msg = "Message passed by ioctl\n"; + /* + * Main - Call the ioctl functions + */ + int main() + { + int file_desc, ret_val; + char *msg = "Message passed by ioctl\n"; - file_desc = open(DEVICE_FILE_NAME, 0); - if (file_desc < 0) { - printf("Can't open device file: %s\n", DEVICE_FILE_NAME); - exit(-1); - } + file_desc = open(DEVICE_FILE_NAME, 0); + if (file_desc < 0) { + printf("Can't open device file: %s\n", DEVICE_FILE_NAME); + exit(-1); + } - ioctl_get_nth_byte(file_desc); - ioctl_get_msg(file_desc); - ioctl_set_msg(file_desc, msg); + ioctl_get_nth_byte(file_desc); + ioctl_get_msg(file_desc); + ioctl_set_msg(file_desc, msg); - close(file_desc); - return 0; - } + close(file_desc); + return 0; + } .. raw:: html @@ -4030,14 +3962,14 @@ Documentation/ioctl-number.txt. .. raw:: html -
+
.. rubric:: System Calls - :name: orgdf0ab54 + :name: sec-10 .. raw:: html -
+
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 @@ -4156,161 +4088,161 @@ hacker, this would be the first thing he'd try. ;) .. code:: src - /* - * syscall.c - * - * System call "stealing" sample. - * - * Disables page protection at a processor level by - * changing the 16th bit in the cr0 register (could be Intel specific) - * - * Based on example by Peter Jay Salzman and - * https://bbs.archlinux.org/viewtopic.php?id=139406 - */ + /* + * syscall.c + * + * System call "stealing" sample. + * + * Disables page protection at a processor level by + * changing the 16th bit in the cr0 register (could be Intel specific) + * + * Based on example by Peter Jay Salzman and + * https://bbs.archlinux.org/viewtopic.php?id=139406 + */ - #include - #include - #include - #include - #include - #include /* which will have params */ - #include /* The list of system calls */ + #include + #include + #include + #include + #include + #include /* which will have params */ + #include /* The list of system calls */ - /* - * For the current (process) structure, we need - * this to know who the current user is. - */ - #include - #include + /* + * For the current (process) structure, we need + * this to know who the current user is. + */ + #include + #include - unsigned long **sys_call_table; - unsigned long original_cr0; + unsigned long **sys_call_table; + unsigned long original_cr0; - /* - * UID we want to spy on - will be filled from the - * command line - */ - static int uid; - module_param(uid, int, 0644); + /* + * UID we want to spy on - will be filled from the + * command line + */ + static int uid; + module_param(uid, int, 0644); - /* - * A pointer to the original system call. The reason - * we keep this, rather than call the original function - * (sys_open), is because somebody else might have - * replaced the system call before us. Note that this - * is not 100% safe, because if another module - * replaced sys_open before us, then when we're inserted - * we'll call the function in that module - and it - * might be removed before we are. - * - * Another reason for this is that we can't get sys_open. - * It's a static variable, so it is not exported. - */ - asmlinkage int (*original_call) (const char *, int, int); + /* + * A pointer to the original system call. The reason + * we keep this, rather than call the original function + * (sys_open), is because somebody else might have + * replaced the system call before us. Note that this + * is not 100% safe, because if another module + * replaced sys_open before us, then when we're inserted + * we'll call the function in that module - and it + * might be removed before we are. + * + * Another reason for this is that we can't get sys_open. + * It's a static variable, so it is not exported. + */ + asmlinkage int (*original_call) (const char *, int, int); - /* - * The function we'll replace sys_open (the function - * called when you call the open system call) with. To - * find the exact prototype, with the number and type - * of arguments, we find the original function first - * (it's at fs/open.c). - * - * In theory, this means that we're tied to the - * current version of the kernel. In practice, the - * system calls almost never change (it would wreck havoc - * and require programs to be recompiled, since the system - * calls are the interface between the kernel and the - * processes). - */ - asmlinkage int our_sys_open(const char *filename, int flags, int mode) - { - int i = 0; - char ch; + /* + * The function we'll replace sys_open (the function + * called when you call the open system call) with. To + * find the exact prototype, with the number and type + * of arguments, we find the original function first + * (it's at fs/open.c). + * + * In theory, this means that we're tied to the + * current version of the kernel. In practice, the + * system calls almost never change (it would wreck havoc + * and require programs to be recompiled, since the system + * calls are the interface between the kernel and the + * processes). + */ + asmlinkage int our_sys_open(const char *filename, int flags, int mode) + { + int i = 0; + char ch; - /* - * Report the file, if relevant - */ - pr_info("Opened file by %d: ", uid); - do { - get_user(ch, filename + i); - i++; - pr_info("%c", ch); - } while (ch != 0); - pr_info("\n"); + /* + * Report the file, if relevant + */ + pr_info("Opened file by %d: ", uid); + do { + get_user(ch, filename + i); + i++; + pr_info("%c", ch); + } while (ch != 0); + pr_info("\n"); - /* - * Call the original sys_open - otherwise, we lose - * the ability to open files - */ - return original_call(filename, flags, mode); - } + /* + * Call the original sys_open - otherwise, we lose + * the ability to open files + */ + return original_call(filename, flags, mode); + } - static unsigned long **aquire_sys_call_table(void) - { - unsigned long int offset = PAGE_OFFSET; - unsigned long **sct; + static unsigned long **aquire_sys_call_table(void) + { + unsigned long int offset = PAGE_OFFSET; + unsigned long **sct; - while (offset < ULLONG_MAX) { - sct = (unsigned long **)offset; + while (offset < ULLONG_MAX) { + sct = (unsigned long **)offset; - if (sct[__NR_close] == (unsigned long *) sys_close) - return sct; + if (sct[__NR_close] == (unsigned long *) sys_close) + return sct; - offset += sizeof(void *); - } + offset += sizeof(void *); + } - return NULL; - } + return NULL; + } - static int __init syscall_start(void) - { - if(!(sys_call_table = aquire_sys_call_table())) - return -1; + static int __init syscall_start(void) + { + if(!(sys_call_table = aquire_sys_call_table())) + return -1; - original_cr0 = read_cr0(); + original_cr0 = read_cr0(); - write_cr0(original_cr0 & ~0x00010000); + write_cr0(original_cr0 & ~0x00010000); - /* keep track of the original open function */ - original_call = (void*)sys_call_table[__NR_open]; + /* keep track of the original open function */ + original_call = (void*)sys_call_table[__NR_open]; - /* use our open function instead */ - sys_call_table[__NR_open] = (unsigned long *)our_sys_open; + /* use our open function instead */ + sys_call_table[__NR_open] = (unsigned long *)our_sys_open; - write_cr0(original_cr0); + write_cr0(original_cr0); - pr_info("Spying on UID:%d\n", uid); + pr_info("Spying on UID:%d\n", uid); - return 0; - } + return 0; + } - static void __exit syscall_end(void) - { - if(!sys_call_table) { - return; - } + static void __exit syscall_end(void) + { + if(!sys_call_table) { + return; + } - /* - * Return the system call back to normal - */ - if (sys_call_table[__NR_open] != (unsigned long *)our_sys_open) { - 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"); - } + /* + * Return the system call back to normal + */ + if (sys_call_table[__NR_open] != (unsigned long *)our_sys_open) { + 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); - sys_call_table[__NR_open] = (unsigned long *)original_call; - write_cr0(original_cr0); + write_cr0(original_cr0 & ~0x00010000); + sys_call_table[__NR_open] = (unsigned long *)original_call; + write_cr0(original_cr0); - msleep(2000); - } + msleep(2000); + } - module_init(syscall_start); - module_exit(syscall_end); + module_init(syscall_start); + module_exit(syscall_end); - MODULE_LICENSE("GPL"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -4326,14 +4258,14 @@ hacker, this would be the first thing he'd try. ;) .. raw:: html -
+
.. rubric:: Blocking Processes and threads - :name: org83613ec + :name: sec-11 .. raw:: html -
+
.. raw:: html @@ -4341,14 +4273,14 @@ hacker, this would be the first thing he'd try. ;) .. raw:: html -
+
.. rubric:: Sleep - :name: org36ce43a + :name: sec-11-1 .. raw:: html -
+
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 @@ -4371,7 +4303,7 @@ it with: .. code:: src - tail -f + tail -f .. raw:: html @@ -4438,26 +4370,26 @@ a file with **O_NONBLOCK**. .. code:: src - 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 & - Last input: - Last input: - Last input: - Last input: - Last input: - Last input: - Last input: - tail: /proc/sleep: file truncated - [1] 6540 - hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep - Open would block - hostname:~/lkmpg-examples/09-BlockingProcesses# kill %1 - [1]+ Terminated tail -f /proc/sleep - hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep - Last input: - hostname:~/lkmpg-examples/09-BlockingProcesses# + 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 & + Last input: + Last input: + Last input: + Last input: + Last input: + Last input: + Last input: + tail: /proc/sleep: file truncated + [1] 6540 + hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep + Open would block + hostname:~/lkmpg-examples/09-BlockingProcesses# kill %1 + [1]+ Terminated tail -f /proc/sleep + hostname:~/lkmpg-examples/09-BlockingProcesses# cat_noblock /proc/sleep + Last input: + hostname:~/lkmpg-examples/09-BlockingProcesses# .. raw:: html @@ -4469,271 +4401,271 @@ a file with **O_NONBLOCK**. .. code:: src - /* - * sleep.c - create a /proc file, and if several processes try to open it at - * the same time, put all but one to sleep - */ + /* + * sleep.c - create a /proc file, and if several processes try to open it at + * the same time, put all but one to sleep + */ - #include /* We're doing kernel work */ - #include /* Specifically, a module */ - #include /* Necessary because we use proc fs */ - #include /* For putting processes to sleep and - waking them up */ - #include /* for get_user and put_user */ + #include /* We're doing kernel work */ + #include /* Specifically, a module */ + #include /* Necessary because we use proc fs */ + #include /* For putting processes to sleep and + waking them up */ + #include /* for get_user and put_user */ - /* - * The module's file functions - */ + /* + * The module's file functions + */ - /* - * Here we keep the last message received, to prove that we can process our - * input - */ - #define MESSAGE_LENGTH 80 - static char Message[MESSAGE_LENGTH]; + /* + * Here we keep the last message received, to prove that we can process our + * input + */ + #define MESSAGE_LENGTH 80 + static char Message[MESSAGE_LENGTH]; - static struct proc_dir_entry *Our_Proc_File; - #define PROC_ENTRY_FILENAME "sleep" + static struct proc_dir_entry *Our_Proc_File; + #define PROC_ENTRY_FILENAME "sleep" - /* - * Since we use the file operations struct, we can't use the special proc - * output provisions - we have to use a standard read function, which is this - * function - */ - static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ - char *buf, /* The buffer to put data to - (in the user segment) */ - size_t len, /* The length of the buffer */ - loff_t * offset) - { - static int finished = 0; - int i; - char message[MESSAGE_LENGTH + 30]; + /* + * Since we use the file operations struct, we can't use the special proc + * output provisions - we have to use a standard read function, which is this + * function + */ + static ssize_t module_output(struct file *file, /* see include/linux/fs.h */ + char *buf, /* The buffer to put data to + (in the user segment) */ + size_t len, /* The length of the buffer */ + loff_t * offset) + { + static int finished = 0; + int i; + char message[MESSAGE_LENGTH + 30]; - /* - * Return 0 to signify end of file - that we have nothing - * more to say at this point. - */ - if (finished) { - finished = 0; - return 0; - } + /* + * Return 0 to signify end of file - that we have nothing + * more to say at this point. + */ + if (finished) { + finished = 0; + return 0; + } - /* - * If you don't understand this by now, you're hopeless as a kernel - * programmer. - */ - sprintf(message, "Last input:%s\n", Message); - for (i = 0; i < len && message[i]; i++) - put_user(message[i], buf + i); + /* + * If you don't understand this by now, you're hopeless as a kernel + * programmer. + */ + sprintf(message, "Last input:%s\n", Message); + for (i = 0; i < len && message[i]; i++) + put_user(message[i], buf + i); - finished = 1; - return i; /* Return the number of bytes "read" */ - } + finished = 1; + return i; /* Return the number of bytes "read" */ + } - /* - * This function receives input from the user when the user writes to the /proc - * file. - */ - static ssize_t module_input(struct file *file, /* The file itself */ - const char *buf, /* The buffer with input */ - size_t length, /* The buffer's length */ - loff_t * offset) /* offset to file - ignore */ - { - int i; + /* + * This function receives input from the user when the user writes to the /proc + * file. + */ + static ssize_t module_input(struct file *file, /* The file itself */ + const char *buf, /* The buffer with input */ + size_t length, /* The buffer's length */ + loff_t * offset) /* offset to file - ignore */ + { + int i; - /* - * Put the input into Message, where module_output will later be - * able to use it - */ - for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) - get_user(Message[i], buf + i); - /* - * we want a standard, zero terminated string - */ - Message[i] = '\0'; + /* + * Put the input into Message, where module_output will later be + * able to use it + */ + for (i = 0; i < MESSAGE_LENGTH - 1 && i < length; i++) + get_user(Message[i], buf + i); + /* + * we want a standard, zero terminated string + */ + Message[i] = '\0'; - /* - * We need to return the number of input characters used - */ - return i; - } + /* + * We need to return the number of input characters used + */ + return i; + } - /* - * 1 if the file is currently open by somebody - */ - int Already_Open = 0; + /* + * 1 if the file is currently open by somebody + */ + int Already_Open = 0; - /* - * Queue of processes who want our file - */ - DECLARE_WAIT_QUEUE_HEAD(WaitQ); - /* - * Called when the /proc file is opened - */ - static int module_open(struct inode *inode, struct file *file) - { - /* - * If the file's flags include O_NONBLOCK, it means the process doesn't - * want to wait for the file. In this case, if the file is already - * open, we should fail with -EAGAIN, meaning "you'll have to try - * again", instead of blocking a process which would rather stay awake. - */ - if ((file->f_flags & O_NONBLOCK) && Already_Open) - return -EAGAIN; + /* + * Queue of processes who want our file + */ + DECLARE_WAIT_QUEUE_HEAD(WaitQ); + /* + * Called when the /proc file is opened + */ + static int module_open(struct inode *inode, struct file *file) + { + /* + * If the file's flags include O_NONBLOCK, it means the process doesn't + * want to wait for the file. In this case, if the file is already + * open, we should fail with -EAGAIN, meaning "you'll have to try + * again", instead of blocking a process which would rather stay awake. + */ + if ((file->f_flags & O_NONBLOCK) && Already_Open) + return -EAGAIN; - /* - * This is the correct place for try_module_get(THIS_MODULE) because - * if a process is in the loop, which is within the kernel module, - * the kernel module must not be removed. - */ - try_module_get(THIS_MODULE); + /* + * This is the correct place for try_module_get(THIS_MODULE) because + * if a process is in the loop, which is within the kernel module, + * the kernel module must not be removed. + */ + try_module_get(THIS_MODULE); - /* - * If the file is already open, wait until it isn't - */ + /* + * If the file is already open, wait until it isn't + */ - while (Already_Open) { - int i, is_sig = 0; + while (Already_Open) { + int i, is_sig = 0; - /* - * This function puts the current process, including any system - * calls, such as us, to sleep. Execution will be resumed right - * after the function call, either because somebody called - * wake_up(&WaitQ) (only module_close does that, when the file - * is closed) or when a signal, such as Ctrl-C, is sent - * to the process - */ - wait_event_interruptible(WaitQ, !Already_Open); + /* + * This function puts the current process, including any system + * calls, such as us, to sleep. Execution will be resumed right + * after the function call, either because somebody called + * wake_up(&WaitQ) (only module_close does that, when the file + * is closed) or when a signal, such as Ctrl-C, is sent + * to the process + */ + wait_event_interruptible(WaitQ, !Already_Open); - /* - * If we woke up because we got a signal we're not blocking, - * return -EINTR (fail the system call). This allows processes - * to be killed or stopped. - */ + /* + * If we woke up because we got a signal we're not blocking, + * return -EINTR (fail the system call). This allows processes + * to be killed or stopped. + */ - /* - * Emmanuel Papirakis: - * - * This is a little update to work with 2.2.*. Signals now are contained in - * two words (64 bits) and are stored in a structure that contains an array of - * two unsigned longs. We now have to make 2 checks in our if. - * - * Ori Pomerantz: - * - * Nobody promised me they'll never use more than 64 bits, or that this book - * won't be used for a version of Linux with a word size of 16 bits. This code - * would work in any case. - */ - for (i = 0; i < _NSIG_WORDS && !is_sig; i++) - is_sig = - current->pending.signal.sig[i] & ~current-> - blocked.sig[i]; + /* + * Emmanuel Papirakis: + * + * This is a little update to work with 2.2.*. Signals now are contained in + * two words (64 bits) and are stored in a structure that contains an array of + * two unsigned longs. We now have to make 2 checks in our if. + * + * Ori Pomerantz: + * + * Nobody promised me they'll never use more than 64 bits, or that this book + * won't be used for a version of Linux with a word size of 16 bits. This code + * would work in any case. + */ + for (i = 0; i < _NSIG_WORDS && !is_sig; i++) + is_sig = + current->pending.signal.sig[i] & ~current-> + blocked.sig[i]; - if (is_sig) { - /* - * It's important to put module_put(THIS_MODULE) here, - * because for processes where the open is interrupted - * there will never be a corresponding close. If we - * don't decrement the usage count here, we will be - * left with a positive usage count which we'll have no - * way to bring down to zero, giving us an immortal - * module, which can only be killed by rebooting - * the machine. - */ - module_put(THIS_MODULE); - return -EINTR; - } - } + if (is_sig) { + /* + * It's important to put module_put(THIS_MODULE) here, + * because for processes where the open is interrupted + * there will never be a corresponding close. If we + * don't decrement the usage count here, we will be + * left with a positive usage count which we'll have no + * way to bring down to zero, giving us an immortal + * module, which can only be killed by rebooting + * the machine. + */ + module_put(THIS_MODULE); + return -EINTR; + } + } - /* - * If we got here, Already_Open must be zero - */ + /* + * If we got here, Already_Open must be zero + */ - /* - * Open the file - */ - Already_Open = 1; - return 0; /* Allow the access */ - } + /* + * Open the file + */ + Already_Open = 1; + return 0; /* Allow the access */ + } - /* - * Called when the /proc file is closed - */ - int module_close(struct inode *inode, struct file *file) - { - /* - * Set Already_Open to zero, so one of the processes in the WaitQ will - * be able to set Already_Open back to one and to open the file. All - * the other processes will be called when Already_Open is back to one, - * so they'll go back to sleep. - */ - Already_Open = 0; + /* + * Called when the /proc file is closed + */ + int module_close(struct inode *inode, struct file *file) + { + /* + * Set Already_Open to zero, so one of the processes in the WaitQ will + * be able to set Already_Open back to one and to open the file. All + * the other processes will be called when Already_Open is back to one, + * so they'll go back to sleep. + */ + Already_Open = 0; - /* - * Wake up all the processes in WaitQ, so if anybody is waiting for the - * file, they can have it. - */ - wake_up(&WaitQ); + /* + * Wake up all the processes in WaitQ, so if anybody is waiting for the + * file, they can have it. + */ + wake_up(&WaitQ); - module_put(THIS_MODULE); + module_put(THIS_MODULE); - return 0; /* success */ - } + return 0; /* success */ + } - /* - * Structures to register as the /proc file, with pointers to all the relevant - * functions. - */ + /* + * Structures to register as the /proc file, with pointers to all the relevant + * functions. + */ - /* - * File operations for our proc file. This is where we place pointers to all - * the functions called when somebody tries to do something to our file. NULL - * means we don't want to deal with something. - */ - static struct file_operations File_Ops_4_Our_Proc_File = { - .read = module_output, /* "read" from the file */ - .write = module_input, /* "write" to the file */ - .open = module_open, /* called when the /proc file is opened */ - .release = module_close, /* called when it's closed */ - }; + /* + * File operations for our proc file. This is where we place pointers to all + * the functions called when somebody tries to do something to our file. NULL + * means we don't want to deal with something. + */ + static struct file_operations File_Ops_4_Our_Proc_File = { + .read = module_output, /* "read" from the file */ + .write = module_input, /* "write" to the file */ + .open = module_open, /* called when the /proc file is opened */ + .release = module_close, /* called when it's closed */ + }; - /* - * Module initialization and cleanup - */ + /* + * Module initialization and cleanup + */ - /* - * Initialize the module - register the proc file - */ + /* + * Initialize the module - register the proc file + */ - int init_module() - { - Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File); - if(Our_Proc_File == NULL) - { - remove_proc_entry(PROC_ENTRY_FILENAME, NULL); - 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); + int init_module() + { + Our_Proc_File = proc_create(PROC_ENTRY_FILENAME, 0644, NULL, &File_Ops_4_Our_Proc_File); + if(Our_Proc_File == NULL) + { + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + 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); - pr_info("/proc/test created\n"); + pr_info("/proc/test created\n"); - return 0; - } + return 0; + } - /* - * Cleanup - unregister our file from /proc. This could get dangerous if - * there are still processes waiting in WaitQ, because they are inside our - * open function, which will get unloaded. I'll explain how to avoid removal - * of a kernel module in such a case in chapter 10. - */ - void cleanup_module() - { - remove_proc_entry(PROC_ENTRY_FILENAME, NULL); - pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME); - } + /* + * Cleanup - unregister our file from /proc. This could get dangerous if + * there are still processes waiting in WaitQ, because they are inside our + * open function, which will get unloaded. I'll explain how to avoid removal + * of a kernel module in such a case in chapter 10. + */ + void cleanup_module() + { + remove_proc_entry(PROC_ENTRY_FILENAME, NULL); + pr_debug("/proc/%s removed\n", PROC_ENTRY_FILENAME); + } .. raw:: html @@ -4745,71 +4677,71 @@ a file with **O_NONBLOCK**. .. code:: src - /* cat_noblock.c - open a file and display its contents, but exit rather than - * wait for input */ - /* Copyright (C) 1998 by Ori Pomerantz */ + /* cat_noblock.c - open a file and display its contents, but exit rather than + * wait for input */ + /* Copyright (C) 1998 by Ori Pomerantz */ - #include /* standard I/O */ - #include /* for open */ - #include /* for read */ - #include /* for exit */ - #include /* for errno */ + #include /* standard I/O */ + #include /* for open */ + #include /* for read */ + #include /* for exit */ + #include /* for errno */ - #define MAX_BYTES 1024*4 + #define MAX_BYTES 1024*4 - int main(int argc, char *argv[]) - { - int fd; /* The file descriptor for the file to read */ - size_t bytes; /* The number of bytes read */ - char buffer[MAX_BYTES]; /* The buffer for the bytes */ + int main(int argc, char *argv[]) + { + int fd; /* The file descriptor for the file to read */ + size_t bytes; /* The number of bytes read */ + char buffer[MAX_BYTES]; /* The buffer for the bytes */ - /* Usage */ - if (argc != 2) { - printf("Usage: %s \n", argv[0]); - puts("Reads the content of a file, but doesn't wait for input"); - exit(-1); - } + /* Usage */ + if (argc != 2) { + printf("Usage: %s \n", argv[0]); + puts("Reads the content of a file, but doesn't wait for input"); + exit(-1); + } - /* Open the file for reading in non blocking mode */ - fd = open(argv[1], O_RDONLY | O_NONBLOCK); + /* Open the file for reading in non blocking mode */ + fd = open(argv[1], O_RDONLY | O_NONBLOCK); - /* If open failed */ - if (fd == -1) { - if (errno = EAGAIN) - puts("Open would block"); - else - puts("Open failed"); - exit(-1); - } + /* If open failed */ + if (fd == -1) { + if (errno = EAGAIN) + puts("Open would block"); + else + puts("Open failed"); + exit(-1); + } - /* Read the file and output its contents */ - do { - int i; + /* Read the file and output its contents */ + do { + int i; - /* Read characters from the file */ - bytes = read(fd, buffer, MAX_BYTES); + /* Read characters from the file */ + bytes = read(fd, buffer, MAX_BYTES); - /* If there's an error, report it and die */ - if (bytes == -1) { - if (errno = EAGAIN) - puts("Normally I'd block, but you told me not to"); - else - puts("Another read error"); - exit(-1); - } + /* If there's an error, report it and die */ + if (bytes == -1) { + if (errno = EAGAIN) + puts("Normally I'd block, but you told me not to"); + else + puts("Another read error"); + exit(-1); + } - /* Print the characters */ - if (bytes > 0) { - for(i=0; i 0) { + for(i=0; i 0); - return 0; - } + /* While there are no errors and the file isn't over */ + } while (bytes > 0); + return 0; + } .. raw:: html @@ -4825,14 +4757,14 @@ a file with **O_NONBLOCK**. .. raw:: html -
+
.. rubric:: Completions - :name: orgcfa6577 + :name: sec-11-2 .. raw:: html -
+
Sometimes one thing should happen before another within a module having multiple threads. Rather than using **/proc/sleep** commands the kernel @@ -4848,83 +4780,83 @@ before another. .. code:: src - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include - static struct { - struct completion crank_comp; - struct completion flywheel_comp; - } machine; + static struct { + struct completion crank_comp; + struct completion flywheel_comp; + } machine; - static int machine_crank_thread(void* arg) - { - pr_info("Turn the crank\n"); + static int machine_crank_thread(void* arg) + { + pr_info("Turn the crank\n"); - complete_all(&machine.crank_comp); - complete_and_exit(&machine.crank_comp, 0); - } + complete_all(&machine.crank_comp); + complete_and_exit(&machine.crank_comp, 0); + } - static int machine_flywheel_spinup_thread(void* arg) - { - wait_for_completion(&machine.crank_comp); + static int machine_flywheel_spinup_thread(void* arg) + { + wait_for_completion(&machine.crank_comp); - pr_info("Flywheel spins up\n"); + pr_info("Flywheel spins up\n"); - complete_all(&machine.flywheel_comp); - complete_and_exit(&machine.flywheel_comp, 0); - } + complete_all(&machine.flywheel_comp); + complete_and_exit(&machine.flywheel_comp, 0); + } - static int completions_init(void) - { - struct task_struct* crank_thread; - struct task_struct* flywheel_thread; + static int completions_init(void) + { + struct task_struct* crank_thread; + struct task_struct* flywheel_thread; - pr_info("completions example\n"); + pr_info("completions example\n"); - init_completion(&machine.crank_comp); - init_completion(&machine.flywheel_comp); + init_completion(&machine.crank_comp); + init_completion(&machine.flywheel_comp); - crank_thread = - kthread_create(machine_crank_thread, - NULL, "KThread Crank"); - if (IS_ERR(crank_thread)) - goto ERROR_THREAD_1; + crank_thread = + kthread_create(machine_crank_thread, + NULL, "KThread Crank"); + if (IS_ERR(crank_thread)) + goto ERROR_THREAD_1; - flywheel_thread = - kthread_create(machine_flywheel_spinup_thread, - NULL, "KThread Flywheel"); - if (IS_ERR(flywheel_thread)) - goto ERROR_THREAD_2; + flywheel_thread = + kthread_create(machine_flywheel_spinup_thread, + NULL, "KThread Flywheel"); + if (IS_ERR(flywheel_thread)) + goto ERROR_THREAD_2; - wake_up_process(flywheel_thread); - wake_up_process(crank_thread); + wake_up_process(flywheel_thread); + wake_up_process(crank_thread); - return 0; + return 0; - ERROR_THREAD_2: - kthread_stop(crank_thread); - ERROR_THREAD_1: + ERROR_THREAD_2: + kthread_stop(crank_thread); + ERROR_THREAD_1: - return -1; - } + return -1; + } - void completions_exit(void) - { - wait_for_completion(&machine.crank_comp); - wait_for_completion(&machine.flywheel_comp); + void completions_exit(void) + { + wait_for_completion(&machine.crank_comp); + wait_for_completion(&machine.flywheel_comp); - pr_info("completions exit\n"); - } + pr_info("completions exit\n"); + } - module_init(completions_init); - module_exit(completions_exit); + module_init(completions_init); + module_exit(completions_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Completions example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Completions example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -4957,14 +4889,14 @@ enough for many common situations without adding a lot of complexity. .. raw:: html -
+
.. rubric:: Avoiding Collisions and Deadlocks - :name: org3ffdc76 + :name: sec-12 .. raw:: html -
+
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 @@ -4979,14 +4911,14 @@ can't happen. .. raw:: html -
+
.. rubric:: Mutex - :name: org89ec2e6 + :name: sec-12-1 .. raw:: html -
+
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 @@ -4998,46 +4930,46 @@ avoid collisions in most cases. .. code:: src - #include - #include - #include - #include + #include + #include + #include + #include - DEFINE_MUTEX(mymutex); + DEFINE_MUTEX(mymutex); - static int example_mutex_init(void) - { - int ret; + static int example_mutex_init(void) + { + int ret; - pr_info("example_mutex init\n"); + pr_info("example_mutex init\n"); - ret = mutex_trylock(&mymutex); - if (ret != 0) { - pr_info("mutex is locked\n"); + ret = mutex_trylock(&mymutex); + if (ret != 0) { + pr_info("mutex is locked\n"); - if (mutex_is_locked(&mymutex) == 0) - pr_info("The mutex failed to lock!\n"); + if (mutex_is_locked(&mymutex) == 0) + pr_info("The mutex failed to lock!\n"); - mutex_unlock(&mymutex); - pr_info("mutex is unlocked\n"); - } - else - pr_info("Failed to lock\n"); + mutex_unlock(&mymutex); + pr_info("mutex is unlocked\n"); + } + else + pr_info("Failed to lock\n"); - return 0; - } + return 0; + } - static void example_mutex_exit(void) - { - pr_info("example_mutex exit\n"); - } + static void example_mutex_exit(void) + { + pr_info("example_mutex exit\n"); + } - module_init(example_mutex_init); - module_exit(example_mutex_exit); + module_init(example_mutex_init); + module_exit(example_mutex_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Mutex example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Mutex example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -5053,14 +4985,14 @@ avoid collisions in most cases. .. raw:: html -
+
.. rubric:: Spinlocks - :name: org9889db8 + :name: sec-12-2 .. raw:: html -
+
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 @@ -5068,7 +5000,7 @@ 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. -The example here is *"irq safe"* in that if interrupts happen during the +The example here is /"irq safe"/ in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the *flags* variable to retain their state. @@ -5078,69 +5010,69 @@ happens, using the *flags* variable to retain their state. .. code:: src - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include - DEFINE_SPINLOCK(sl_static); - spinlock_t sl_dynamic; + DEFINE_SPINLOCK(sl_static); + spinlock_t sl_dynamic; - static void example_spinlock_static(void) - { - unsigned long flags; + static void example_spinlock_static(void) + { + unsigned long flags; - spin_lock_irqsave(&sl_static, flags); - pr_info("Locked static spinlock\n"); + spin_lock_irqsave(&sl_static, flags); + pr_info("Locked static spinlock\n"); - /* Do something or other safely. - Because this uses 100% CPU time this - code should take no more than a few - milliseconds to run */ + /* Do something or other safely. + Because this uses 100% CPU time this + code should take no more than a few + milliseconds to run */ - spin_unlock_irqrestore(&sl_static, flags); - pr_info("Unlocked static spinlock\n"); - } + spin_unlock_irqrestore(&sl_static, flags); + pr_info("Unlocked static spinlock\n"); + } - static void example_spinlock_dynamic(void) - { - unsigned long flags; + static void example_spinlock_dynamic(void) + { + unsigned long flags; - spin_lock_init(&sl_dynamic); - spin_lock_irqsave(&sl_dynamic, flags); - pr_info("Locked dynamic spinlock\n"); + spin_lock_init(&sl_dynamic); + spin_lock_irqsave(&sl_dynamic, flags); + pr_info("Locked dynamic spinlock\n"); - /* Do something or other safely. - Because this uses 100% CPU time this - code should take no more than a few - milliseconds to run */ + /* Do something or other safely. + Because this uses 100% CPU time this + code should take no more than a few + milliseconds to run */ - spin_unlock_irqrestore(&sl_dynamic, flags); - pr_info("Unlocked dynamic spinlock\n"); - } + spin_unlock_irqrestore(&sl_dynamic, flags); + pr_info("Unlocked dynamic spinlock\n"); + } - static int example_spinlock_init(void) - { - pr_info("example spinlock started\n"); + static int example_spinlock_init(void) + { + pr_info("example spinlock started\n"); - example_spinlock_static(); - example_spinlock_dynamic(); + example_spinlock_static(); + example_spinlock_dynamic(); - return 0; - } + return 0; + } - static void example_spinlock_exit(void) - { - pr_info("example spinlock exit\n"); - } + static void example_spinlock_exit(void) + { + pr_info("example spinlock exit\n"); + } - module_init(example_spinlock_init); - module_exit(example_spinlock_exit); + module_init(example_spinlock_init); + module_exit(example_spinlock_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Spinlock example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Spinlock example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -5156,14 +5088,14 @@ happens, using the *flags* variable to retain their state. .. raw:: html -
+
.. rubric:: Read and write locks - :name: orge2dc3e1 + :name: sec-12-3 .. raw:: html -
+
Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something. Like the earlier @@ -5180,59 +5112,59 @@ users to start revolting against the tyranny of your module. .. code:: src - #include - #include - #include + #include + #include + #include - DEFINE_RWLOCK(myrwlock); + DEFINE_RWLOCK(myrwlock); - static void example_read_lock(void) - { - unsigned long flags; + static void example_read_lock(void) + { + unsigned long flags; - read_lock_irqsave(&myrwlock, flags); - pr_info("Read Locked\n"); + read_lock_irqsave(&myrwlock, flags); + pr_info("Read Locked\n"); - /* Read from something */ + /* Read from something */ - read_unlock_irqrestore(&myrwlock, flags); - pr_info("Read Unlocked\n"); - } + read_unlock_irqrestore(&myrwlock, flags); + pr_info("Read Unlocked\n"); + } - static void example_write_lock(void) - { - unsigned long flags; + static void example_write_lock(void) + { + unsigned long flags; - write_lock_irqsave(&myrwlock, flags); - pr_info("Write Locked\n"); + write_lock_irqsave(&myrwlock, flags); + pr_info("Write Locked\n"); - /* Write to something */ + /* Write to something */ - write_unlock_irqrestore(&myrwlock, flags); - pr_info("Write Unlocked\n"); - } + write_unlock_irqrestore(&myrwlock, flags); + pr_info("Write Unlocked\n"); + } - static int example_rwlock_init(void) - { - pr_info("example_rwlock started\n"); + static int example_rwlock_init(void) + { + pr_info("example_rwlock started\n"); - example_read_lock(); - example_write_lock(); + example_read_lock(); + example_write_lock(); - return 0; - } + return 0; + } - static void example_rwlock_exit(void) - { - pr_info("example_rwlock exit\n"); - } + static void example_rwlock_exit(void) + { + pr_info("example_rwlock exit\n"); + } - module_init(example_rwlock_init); - module_exit(example_rwlock_exit); + module_init(example_rwlock_init); + module_exit(example_rwlock_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Read/Write locks example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Read/Write locks example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -5253,14 +5185,14 @@ corresponding write functions. .. raw:: html -
+
.. rubric:: Atomic operations - :name: org1316854 + :name: sec-12-4 .. raw:: html -
+
If you're doing simple arithmetic: adding, subtracting or bitwise operations then there's another way in the multi-CPU and @@ -5275,82 +5207,82 @@ overwritten by some other shenanigans. An example is shown below. .. code:: src - #include - #include - #include + #include + #include + #include - #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" - #define BYTE_TO_BINARY(byte) \ - (byte & 0x80 ? '1' : '0'), \ - (byte & 0x40 ? '1' : '0'), \ - (byte & 0x20 ? '1' : '0'), \ - (byte & 0x10 ? '1' : '0'), \ - (byte & 0x08 ? '1' : '0'), \ - (byte & 0x04 ? '1' : '0'), \ - (byte & 0x02 ? '1' : '0'), \ - (byte & 0x01 ? '1' : '0') + #define BYTE_TO_BINARY_PATTERN "%c%c%c%c%c%c%c%c" + #define BYTE_TO_BINARY(byte) \ + (byte & 0x80 ? '1' : '0'), \ + (byte & 0x40 ? '1' : '0'), \ + (byte & 0x20 ? '1' : '0'), \ + (byte & 0x10 ? '1' : '0'), \ + (byte & 0x08 ? '1' : '0'), \ + (byte & 0x04 ? '1' : '0'), \ + (byte & 0x02 ? '1' : '0'), \ + (byte & 0x01 ? '1' : '0') - static void atomic_add_subtract(void) - { - atomic_t debbie; - atomic_t chris = ATOMIC_INIT(50); + static void atomic_add_subtract(void) + { + atomic_t debbie; + atomic_t chris = ATOMIC_INIT(50); - atomic_set(&debbie, 45); + atomic_set(&debbie, 45); - /* subtract one */ - atomic_dec(&debbie); + /* subtract one */ + atomic_dec(&debbie); - atomic_add(7, &debbie); + atomic_add(7, &debbie); - /* add one */ - atomic_inc(&debbie); + /* add one */ + atomic_inc(&debbie); - pr_info("chris: %d, debbie: %d\n", - atomic_read(&chris), atomic_read(&debbie)); - } + pr_info("chris: %d, debbie: %d\n", + atomic_read(&chris), atomic_read(&debbie)); + } - static void atomic_bitwise(void) - { - unsigned long word = 0; + static void atomic_bitwise(void) + { + unsigned long word = 0; - pr_info("Bits 0: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - set_bit(3, &word); - set_bit(5, &word); - pr_info("Bits 1: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - clear_bit(5, &word); - pr_info("Bits 2: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - change_bit(3, &word); + pr_info("Bits 0: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); + set_bit(3, &word); + set_bit(5, &word); + pr_info("Bits 1: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); + clear_bit(5, &word); + pr_info("Bits 2: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); + change_bit(3, &word); - pr_info("Bits 3: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - if (test_and_set_bit(3, &word)) - pr_info("wrong\n"); - pr_info("Bits 4: "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)) + pr_info("wrong\n"); + pr_info("Bits 4: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - word = 255; - pr_info("Bits 5: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); - } + word = 255; + pr_info("Bits 5: "BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(word)); + } - static int example_atomic_init(void) - { - pr_info("example_atomic started\n"); + static int example_atomic_init(void) + { + pr_info("example_atomic started\n"); - atomic_add_subtract(); - atomic_bitwise(); + atomic_add_subtract(); + atomic_bitwise(); - return 0; - } + return 0; + } - static void example_atomic_exit(void) - { - pr_info("example_atomic exit\n"); - } + static void example_atomic_exit(void) + { + pr_info("example_atomic exit\n"); + } - module_init(example_atomic_init); - module_exit(example_atomic_exit); + module_init(example_atomic_init); + module_exit(example_atomic_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Atomic operations example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Atomic operations example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -5370,14 +5302,14 @@ overwritten by some other shenanigans. An example is shown below. .. raw:: html -
+
.. rubric:: Replacing Print Macros - :name: orgbdec3ca + :name: sec-13 .. raw:: html -
+
.. raw:: html @@ -5385,14 +5317,14 @@ overwritten by some other shenanigans. An example is shown below. .. raw:: html -
+
.. rubric:: Replacement - :name: org4579c68 + :name: sec-13-1 .. raw:: html -
+
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 @@ -5416,114 +5348,114 @@ which we use to write a string to the tty. .. code:: src - /* - * 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. - */ - #include - #include - #include - #include /* For current */ - #include /* For the tty declarations */ - #include /* For LINUX_VERSION_CODE */ + /* + * 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. + */ + #include + #include + #include + #include /* For current */ + #include /* For the tty declarations */ + #include /* For LINUX_VERSION_CODE */ - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Peter Jay Salzman"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Peter Jay Salzman"); - static void print_string(char *str) - { - struct tty_struct *my_tty; - const struct tty_operations *ttyops; + static void print_string(char *str) + { + struct tty_struct *my_tty; + const struct tty_operations *ttyops; - /* - * tty struct went into signal struct in 2.6.6 - */ - #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,5) ) - /* - * The tty for the current task - */ - my_tty = current->tty; - #else - /* - * The tty for the current task, for 2.6.6+ kernels - */ - my_tty = get_current_tty(); - #endif - ttyops = my_tty->driver->ops; + /* + * tty struct went into signal struct in 2.6.6 + */ + #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,5) ) + /* + * The tty for the current task + */ + my_tty = current->tty; + #else + /* + * The tty for the current task, for 2.6.6+ kernels + */ + my_tty = get_current_tty(); + #endif + ttyops = my_tty->driver->ops; - /* - * If my_tty is NULL, the current task has no tty you can print to - * (ie, if it's a daemon). If so, there's nothing we can do. - */ - if (my_tty != NULL) { + /* + * If my_tty is NULL, the current task has no tty you can print to + * (ie, if it's a daemon). If so, there's nothing we can do. + */ + if (my_tty != NULL) { - /* - * my_tty->driver is a struct which holds the tty's functions, - * one of which (write) is used to write strings to the tty. - * It can be used to take a string either from the user's or - * kernel's memory segment. - * - * The function's 1st parameter is the tty to write to, - * because the same function would normally be used for all - * tty's of a certain type. The 2nd parameter controls - * whether the function receives a string from kernel - * memory (false, 0) or from user memory (true, non zero). - * BTW: this param has been removed in Kernels > 2.6.9 - * The (2nd) 3rd parameter is a pointer to a string. - * The (3rd) 4th parameter is the length of the string. - * - * As you will see below, sometimes it's necessary to use - * preprocessor stuff to create code that works for different - * kernel versions. The (naive) approach we've taken here - * does not scale well. The right way to deal with this - * is described in section 2 of - * linux/Documentation/SubmittingPatches - */ - (ttyops->write) (my_tty, /* The tty itself */ - #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) - 0, /* Don't take the string - from user space */ - #endif - str, /* String */ - strlen(str)); /* Length */ + /* + * my_tty->driver is a struct which holds the tty's functions, + * one of which (write) is used to write strings to the tty. + * It can be used to take a string either from the user's or + * kernel's memory segment. + * + * The function's 1st parameter is the tty to write to, + * because the same function would normally be used for all + * tty's of a certain type. The 2nd parameter controls + * whether the function receives a string from kernel + * memory (false, 0) or from user memory (true, non zero). + * BTW: this param has been removed in Kernels > 2.6.9 + * The (2nd) 3rd parameter is a pointer to a string. + * The (3rd) 4th parameter is the length of the string. + * + * As you will see below, sometimes it's necessary to use + * preprocessor stuff to create code that works for different + * kernel versions. The (naive) approach we've taken here + * does not scale well. The right way to deal with this + * is described in section 2 of + * linux/Documentation/SubmittingPatches + */ + (ttyops->write) (my_tty, /* The tty itself */ + #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) + 0, /* Don't take the string + from user space */ + #endif + str, /* String */ + strlen(str)); /* Length */ - /* - * ttys were originally hardware devices, which (usually) - * strictly followed the ASCII standard. In ASCII, to move to - * a new line you need two characters, a carriage return and a - * line feed. On Unix, the ASCII line feed is used for both - * purposes - so we can't just use \n, because it wouldn't have - * a carriage return and the next line will start at the - * column right after the line feed. - * - * This is why text files are different between Unix and - * MS Windows. In CP/M and derivatives, like MS-DOS and - * MS Windows, the ASCII standard was strictly adhered to, - * and therefore a newline requirs both a LF and a CR. - */ + /* + * ttys were originally hardware devices, which (usually) + * strictly followed the ASCII standard. In ASCII, to move to + * a new line you need two characters, a carriage return and a + * line feed. On Unix, the ASCII line feed is used for both + * purposes - so we can't just use \n, because it wouldn't have + * a carriage return and the next line will start at the + * column right after the line feed. + * + * This is why text files are different between Unix and + * MS Windows. In CP/M and derivatives, like MS-DOS and + * MS Windows, the ASCII standard was strictly adhered to, + * and therefore a newline requirs both a LF and a CR. + */ - #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) - (ttyops->write) (my_tty, 0, "\015\012", 2); - #else - (ttyops->write) (my_tty, "\015\012", 2); - #endif - } - } + #if ( LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,9) ) + (ttyops->write) (my_tty, 0, "\015\012", 2); + #else + (ttyops->write) (my_tty, "\015\012", 2); + #endif + } + } - static int __init print_string_init(void) - { - print_string("The module has been inserted. Hello world!"); - return 0; - } + static int __init print_string_init(void) + { + print_string("The module has been inserted. Hello world!"); + return 0; + } - static void __exit print_string_exit(void) - { - print_string("The module has been removed. Farewell world!"); - } + static void __exit print_string_exit(void) + { + print_string("The module has been removed. Farewell world!"); + } - module_init(print_string_init); - module_exit(print_string_exit); + module_init(print_string_init); + module_exit(print_string_exit); .. raw:: html @@ -5539,14 +5471,14 @@ which we use to write a string to the tty. .. raw:: html -
+
.. rubric:: Flashing keyboard LEDs - :name: orgc9bd69e + :name: sec-13-2 .. raw:: html -
+
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 @@ -5564,99 +5496,99 @@ when loaded, starts blinking the keyboard LEDs until it is unloaded. .. code:: src - /* - * kbleds.c - Blink keyboard leds until the module is unloaded. - */ + /* + * kbleds.c - Blink keyboard leds until the module is unloaded. + */ - #include - #include - #include /* for fg_console */ - #include /* For fg_console, MAX_NR_CONSOLES */ - #include /* For KDSETLED */ - #include - #include /* For vc_cons */ + #include + #include + #include /* for fg_console */ + #include /* For fg_console, MAX_NR_CONSOLES */ + #include /* For KDSETLED */ + #include + #include /* For vc_cons */ - MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); - MODULE_AUTHOR("Daniele Paolo Scarpazza"); - MODULE_LICENSE("GPL"); + MODULE_DESCRIPTION("Example module illustrating the use of Keyboard LEDs."); + MODULE_AUTHOR("Daniele Paolo Scarpazza"); + MODULE_LICENSE("GPL"); - struct timer_list my_timer; - struct tty_driver *my_driver; - char kbledstatus = 0; + struct timer_list my_timer; + struct tty_driver *my_driver; + char kbledstatus = 0; - #define BLINK_DELAY HZ/5 - #define ALL_LEDS_ON 0x07 - #define RESTORE_LEDS 0xFF + #define BLINK_DELAY HZ/5 + #define ALL_LEDS_ON 0x07 + #define RESTORE_LEDS 0xFF - /* - * Function my_timer_func blinks the keyboard LEDs periodically by invoking - * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual - * terminal ioctl operations, please see file: - * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl(). - * - * The argument to KDSETLED is alternatively set to 7 (thus causing the led - * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF - * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus - * the LEDs reflect the actual keyboard status). To learn more on this, - * please see file: - * /usr/src/linux/drivers/char/keyboard.c, function setledstate(). - * - */ + /* + * Function my_timer_func blinks the keyboard LEDs periodically by invoking + * command KDSETLED of ioctl() on the keyboard driver. To learn more on virtual + * terminal ioctl operations, please see file: + * /usr/src/linux/drivers/char/vt_ioctl.c, function vt_ioctl(). + * + * The argument to KDSETLED is alternatively set to 7 (thus causing the led + * mode to be set to LED_SHOW_IOCTL, and all the leds are lit) and to 0xFF + * (any value above 7 switches back the led mode to LED_SHOW_FLAGS, thus + * the LEDs reflect the actual keyboard status). To learn more on this, + * please see file: + * /usr/src/linux/drivers/char/keyboard.c, function setledstate(). + * + */ - static void my_timer_func(unsigned long ptr) - { - unsigned long *pstatus = (unsigned long *)ptr; - struct tty_struct* t = vc_cons[fg_console].d->port.tty; + static void my_timer_func(unsigned long ptr) + { + unsigned long *pstatus = (unsigned long *)ptr; + struct tty_struct* t = vc_cons[fg_console].d->port.tty; - if (*pstatus == ALL_LEDS_ON) - *pstatus = RESTORE_LEDS; - else - *pstatus = ALL_LEDS_ON; + if (*pstatus == ALL_LEDS_ON) + *pstatus = RESTORE_LEDS; + else + *pstatus = ALL_LEDS_ON; - (my_driver->ops->ioctl) (t, KDSETLED, *pstatus); + (my_driver->ops->ioctl) (t, KDSETLED, *pstatus); - my_timer.expires = jiffies + BLINK_DELAY; - add_timer(&my_timer); - } + my_timer.expires = jiffies + BLINK_DELAY; + add_timer(&my_timer); + } - static int __init kbleds_init(void) - { - int i; + static int __init kbleds_init(void) + { + int i; - 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; - 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); - } - pr_info("kbleds: finished scanning consoles\n"); + 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; + 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); + } + pr_info("kbleds: finished scanning consoles\n"); - my_driver = vc_cons[fg_console].d->port.tty->driver; - pr_info("kbleds: tty driver magic %x\n", my_driver->magic); + my_driver = vc_cons[fg_console].d->port.tty->driver; + pr_info("kbleds: tty driver magic %x\n", my_driver->magic); - /* - * Set up the LED blink timer the first time - */ - timer_setup(&my_timer, (void*)&my_timer_func, (unsigned long)&kbledstatus); - my_timer.expires = jiffies + BLINK_DELAY; - add_timer(&my_timer); + /* + * Set up the LED blink timer the first time + */ + timer_setup(&my_timer, (void*)&my_timer_func, (unsigned long)&kbledstatus); + my_timer.expires = jiffies + BLINK_DELAY; + add_timer(&my_timer); - return 0; - } + return 0; + } - static void __exit kbleds_cleanup(void) - { - pr_info("kbleds: unloading...\n"); - del_timer(&my_timer); - (my_driver->ops->ioctl) (vc_cons[fg_console].d->port.tty, - KDSETLED, RESTORE_LEDS); - } + static void __exit kbleds_cleanup(void) + { + pr_info("kbleds: unloading...\n"); + del_timer(&my_timer); + (my_driver->ops->ioctl) (vc_cons[fg_console].d->port.tty, + KDSETLED, RESTORE_LEDS); + } - module_init(kbleds_init); - module_exit(kbleds_cleanup); + module_init(kbleds_init); + module_exit(kbleds_cleanup); .. raw:: html @@ -5693,14 +5625,14 @@ minimum and make sure it does not show up in production code. .. raw:: html -
+
.. rubric:: Scheduling Tasks - :name: orgf1f1faf + :name: sec-14 .. raw:: html -
+
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 @@ -5714,14 +5646,14 @@ in a sequence. .. raw:: html -
+
.. rubric:: Tasklets - :name: orgd815b3b + :name: sec-14-1 .. raw:: html -
+
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* @@ -5733,41 +5665,41 @@ function continues to the exit point. .. code:: src - #include - #include - #include - #include + #include + #include + #include + #include - static void tasklet_fn(unsigned long data) - { - pr_info("Example tasklet starts\n"); - mdelay(5000); - pr_info("Example tasklet ends\n"); - } + static void tasklet_fn(unsigned long data) + { + pr_info("Example tasklet starts\n"); + mdelay(5000); + pr_info("Example tasklet ends\n"); + } - DECLARE_TASKLET(mytask, tasklet_fn, 0L); + DECLARE_TASKLET(mytask, tasklet_fn, 0L); - static int example_tasklet_init(void) - { - pr_info("tasklet example init\n"); - tasklet_schedule(&mytask); - mdelay(200); - pr_info("Example tasklet init continues...\n"); - return 0; - } + static int example_tasklet_init(void) + { + pr_info("tasklet example init\n"); + tasklet_schedule(&mytask); + mdelay(200); + pr_info("Example tasklet init continues...\n"); + return 0; + } - static void example_tasklet_exit(void) - { - pr_info("tasklet example exit\n"); - tasklet_kill(&mytask); - } + static void example_tasklet_exit(void) + { + pr_info("tasklet example exit\n"); + tasklet_kill(&mytask); + } - module_init(example_tasklet_init); - module_exit(example_tasklet_exit); + module_init(example_tasklet_init); + module_exit(example_tasklet_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Tasklet example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Tasklet example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -5781,10 +5713,10 @@ So with this example loaded *dmesg* should show: .. code:: src - tasklet example init - Example tasklet starts - Example tasklet init continues... - Example tasklet ends + tasklet example init + Example tasklet starts + Example tasklet init continues... + Example tasklet ends .. raw:: html @@ -5800,14 +5732,14 @@ So with this example loaded *dmesg* should show: .. raw:: html -
+
.. rubric:: Work queues - :name: org9b5b18e + :name: sec-14-2 .. raw:: html -
+
To add a task to the scheduler we can use a workqueue. The kernel then uses the Completely Fair Scheduler (CFS) to execute work within the @@ -5819,36 +5751,36 @@ queue. .. code:: src - #include - #include - #include + #include + #include + #include - static struct workqueue_struct *queue=NULL; - static struct work_struct work; + static struct workqueue_struct *queue=NULL; + static struct work_struct work; - static void work_handler(struct work_struct *data) - { - pr_info ("work handler function.\n"); - } + static void work_handler(struct work_struct *data) + { + pr_info ("work handler function.\n"); + } - int init_module() - { - queue = alloc_workqueue("HELLOWORLD", WQ_UNBOUND, 1); - INIT_WORK(&work, work_handler); - schedule_work(&work); + int init_module() + { + queue = alloc_workqueue("HELLOWORLD", WQ_UNBOUND, 1); + INIT_WORK(&work, work_handler); + schedule_work(&work); - return 0; + return 0; - } + } - void cleanup_module() - { - destroy_workqueue(queue); - } + void cleanup_module() + { + destroy_workqueue(queue); + } - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Workqueue example"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Workqueue example"); .. raw:: html @@ -5868,14 +5800,14 @@ queue. .. raw:: html -
+
.. rubric:: Interrupt Handlers - :name: org1cdf533 + :name: sec-15 .. raw:: html -
+
.. raw:: html @@ -5883,14 +5815,14 @@ queue. .. raw:: html -
+
.. rubric:: Interrupt Handlers - :name: org5db45ad + :name: sec-15-1 .. raw:: html -
+
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 @@ -5966,14 +5898,14 @@ both willing to share. .. raw:: html -
+
.. rubric:: Detecting button presses - :name: org9ca1a6c + :name: sec-15-2 .. raw:: html -
+
Many popular single board computers, such as Raspberry Pis or Beagleboards, have a bunch of GPIO pins. Attaching buttons to those and @@ -5993,157 +5925,157 @@ whatever is appropriate for your board. .. code:: src - /* - * intrpt.c - Handling GPIO with interrupts - * - * Copyright (C) 2017 by Bob Mottram - * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de) - * from: - * https://github.com/wendlers/rpi-kmod-samples - * - * Press one button to turn on a LED and another to turn it off - */ + /* + * intrpt.c - Handling GPIO with interrupts + * + * Copyright (C) 2017 by Bob Mottram + * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de) + * from: + * https://github.com/wendlers/rpi-kmod-samples + * + * Press one button to turn on a LED and another to turn it off + */ - #include - #include - #include - #include + #include + #include + #include + #include - static int button_irqs[] = { -1, -1 }; + static int button_irqs[] = { -1, -1 }; - /* Define GPIOs for LEDs. - Change the numbers for the GPIO on your board. */ - static struct gpio leds[] = { - { 4, GPIOF_OUT_INIT_LOW, "LED 1" } - }; + /* Define GPIOs for LEDs. + Change the numbers for the GPIO on your board. */ + static struct gpio leds[] = { + { 4, GPIOF_OUT_INIT_LOW, "LED 1" } + }; - /* Define GPIOs for BUTTONS - Change the numbers for the GPIO on your board. */ - static struct gpio buttons[] = { - { 17, GPIOF_IN, "LED 1 ON BUTTON" }, - { 18, GPIOF_IN, "LED 1 OFF BUTTON" } - }; + /* Define GPIOs for BUTTONS + Change the numbers for the GPIO on your board. */ + static struct gpio buttons[] = { + { 17, GPIOF_IN, "LED 1 ON BUTTON" }, + { 18, GPIOF_IN, "LED 1 OFF BUTTON" } + }; - /* - * interrupt function triggered when a button is pressed - */ - static irqreturn_t button_isr(int irq, void *data) - { - /* first button */ - if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) - gpio_set_value(leds[0].gpio, 1); - /* second button */ - else if(irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) - gpio_set_value(leds[0].gpio, 0); + /* + * interrupt function triggered when a button is pressed + */ + static irqreturn_t button_isr(int irq, void *data) + { + /* first button */ + if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) + gpio_set_value(leds[0].gpio, 1); + /* second button */ + else if(irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) + gpio_set_value(leds[0].gpio, 0); - return IRQ_HANDLED; - } + return IRQ_HANDLED; + } - int init_module() - { - int ret = 0; + int init_module() + { + int ret = 0; - pr_info("%s\n", __func__); + pr_info("%s\n", __func__); - /* register LED gpios */ - ret = gpio_request_array(leds, ARRAY_SIZE(leds)); + /* register LED gpios */ + ret = gpio_request_array(leds, ARRAY_SIZE(leds)); - if (ret) { - pr_err("Unable to request GPIOs for LEDs: %d\n", ret); - return ret; - } + if (ret) { + pr_err("Unable to request GPIOs for LEDs: %d\n", ret); + return ret; + } - /* register BUTTON gpios */ - ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); + /* register BUTTON gpios */ + ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); - if (ret) { - pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); - goto fail1; - } + if (ret) { + pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); + goto fail1; + } - pr_info("Current button1 value: %d\n", - gpio_get_value(buttons[0].gpio)); + pr_info("Current button1 value: %d\n", + gpio_get_value(buttons[0].gpio)); - ret = gpio_to_irq(buttons[0].gpio); + ret = gpio_to_irq(buttons[0].gpio); - if (ret < 0) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret < 0) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - button_irqs[0] = ret; + button_irqs[0] = ret; - pr_info("Successfully requested BUTTON1 IRQ # %d\n", - button_irqs[0]); + pr_info("Successfully requested BUTTON1 IRQ # %d\n", + button_irqs[0]); - ret = request_irq(button_irqs[0], button_isr, - IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, - "gpiomod#button1", NULL); + ret = request_irq(button_irqs[0], button_isr, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, + "gpiomod#button1", NULL); - if (ret) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - ret = gpio_to_irq(buttons[1].gpio); + ret = gpio_to_irq(buttons[1].gpio); - if (ret < 0) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret < 0) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - button_irqs[1] = ret; + button_irqs[1] = ret; - pr_info("Successfully requested BUTTON2 IRQ # %d\n", - button_irqs[1]); + pr_info("Successfully requested BUTTON2 IRQ # %d\n", + button_irqs[1]); - ret = request_irq(button_irqs[1], button_isr, - IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, - "gpiomod#button2", NULL); + ret = request_irq(button_irqs[1], button_isr, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, + "gpiomod#button2", NULL); - if (ret) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail3; - } + if (ret) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail3; + } - return 0; + return 0; - /* cleanup what has been setup so far */ - fail3: - free_irq(button_irqs[0], NULL); + /* cleanup what has been setup so far */ + fail3: + free_irq(button_irqs[0], NULL); - fail2: - gpio_free_array(buttons, ARRAY_SIZE(leds)); + fail2: + gpio_free_array(buttons, ARRAY_SIZE(leds)); - fail1: - gpio_free_array(leds, ARRAY_SIZE(leds)); + fail1: + gpio_free_array(leds, ARRAY_SIZE(leds)); - return ret; - } + return ret; + } - void cleanup_module() - { - int i; + void cleanup_module() + { + int i; - pr_info("%s\n", __func__); + pr_info("%s\n", __func__); - /* free irqs */ - free_irq(button_irqs[0], NULL); - free_irq(button_irqs[1], NULL); + /* free irqs */ + free_irq(button_irqs[0], NULL); + free_irq(button_irqs[1], NULL); - /* turn all LEDs off */ - for (i = 0; i < ARRAY_SIZE(leds); i++) - gpio_set_value(leds[i].gpio, 0); + /* turn all LEDs off */ + for (i = 0; i < ARRAY_SIZE(leds); i++) + gpio_set_value(leds[i].gpio, 0); - /* unregister */ - gpio_free_array(leds, ARRAY_SIZE(leds)); - gpio_free_array(buttons, ARRAY_SIZE(buttons)); - } + /* unregister */ + gpio_free_array(leds, ARRAY_SIZE(leds)); + gpio_free_array(buttons, ARRAY_SIZE(buttons)); + } - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Handle some GPIO interrupts"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Handle some GPIO interrupts"); .. raw:: html @@ -6159,14 +6091,14 @@ whatever is appropriate for your board. .. raw:: html -
+
.. rubric:: Bottom Half - :name: org575eebf + :name: sec-15-3 .. raw:: html -
+
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 @@ -6182,171 +6114,171 @@ additional task when an interrupt is triggered. .. code:: src - /* - * bottomhalf.c - Top and bottom half interrupt handling - * - * Copyright (C) 2017 by Bob Mottram - * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de) - * from: - * https://github.com/wendlers/rpi-kmod-samples - * - * Press one button to turn on a LED and another to turn it off - */ + /* + * bottomhalf.c - Top and bottom half interrupt handling + * + * Copyright (C) 2017 by Bob Mottram + * Based upon the Rpi example by Stefan Wendler (devnull@kaltpost.de) + * from: + * https://github.com/wendlers/rpi-kmod-samples + * + * Press one button to turn on a LED and another to turn it off + */ - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include - static int button_irqs[] = { -1, -1 }; + static int button_irqs[] = { -1, -1 }; - /* Define GPIOs for LEDs. - Change the numbers for the GPIO on your board. */ - static struct gpio leds[] = { - { 4, GPIOF_OUT_INIT_LOW, "LED 1" } - }; + /* Define GPIOs for LEDs. + Change the numbers for the GPIO on your board. */ + static struct gpio leds[] = { + { 4, GPIOF_OUT_INIT_LOW, "LED 1" } + }; - /* Define GPIOs for BUTTONS - Change the numbers for the GPIO on your board. */ - static struct gpio buttons[] = { - { 17, GPIOF_IN, "LED 1 ON BUTTON" }, - { 18, GPIOF_IN, "LED 1 OFF BUTTON" } - }; + /* Define GPIOs for BUTTONS + Change the numbers for the GPIO on your board. */ + static struct gpio buttons[] = { + { 17, GPIOF_IN, "LED 1 ON BUTTON" }, + { 18, GPIOF_IN, "LED 1 OFF BUTTON" } + }; - /* Tasklet containing some non-trivial amount of processing */ - static void bottomhalf_tasklet_fn(unsigned long data) - { - pr_info("Bottom half tasklet starts\n"); - /* do something which takes a while */ - mdelay(500); - pr_info("Bottom half tasklet ends\n"); - } + /* Tasklet containing some non-trivial amount of processing */ + static void bottomhalf_tasklet_fn(unsigned long data) + { + pr_info("Bottom half tasklet starts\n"); + /* do something which takes a while */ + mdelay(500); + pr_info("Bottom half tasklet ends\n"); + } - DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L); + DECLARE_TASKLET(buttontask, bottomhalf_tasklet_fn, 0L); - /* - * interrupt function triggered when a button is pressed - */ - static irqreturn_t button_isr(int irq, void *data) - { - /* Do something quickly right now */ - if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) - gpio_set_value(leds[0].gpio, 1); - else if(irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) - gpio_set_value(leds[0].gpio, 0); + /* + * interrupt function triggered when a button is pressed + */ + static irqreturn_t button_isr(int irq, void *data) + { + /* Do something quickly right now */ + if (irq == button_irqs[0] && !gpio_get_value(leds[0].gpio)) + gpio_set_value(leds[0].gpio, 1); + else if(irq == button_irqs[1] && gpio_get_value(leds[0].gpio)) + gpio_set_value(leds[0].gpio, 0); - /* Do the rest at leisure via the scheduler */ - tasklet_schedule(&buttontask); + /* Do the rest at leisure via the scheduler */ + tasklet_schedule(&buttontask); - return IRQ_HANDLED; - } + return IRQ_HANDLED; + } - int init_module() - { - int ret = 0; + int init_module() + { + int ret = 0; - pr_info("%s\n", __func__); + pr_info("%s\n", __func__); - /* register LED gpios */ - ret = gpio_request_array(leds, ARRAY_SIZE(leds)); + /* register LED gpios */ + ret = gpio_request_array(leds, ARRAY_SIZE(leds)); - if (ret) { - pr_err("Unable to request GPIOs for LEDs: %d\n", ret); - return ret; - } + if (ret) { + pr_err("Unable to request GPIOs for LEDs: %d\n", ret); + return ret; + } - /* register BUTTON gpios */ - ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); + /* register BUTTON gpios */ + ret = gpio_request_array(buttons, ARRAY_SIZE(buttons)); - if (ret) { - pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); - goto fail1; - } + if (ret) { + pr_err("Unable to request GPIOs for BUTTONs: %d\n", ret); + goto fail1; + } - pr_info("Current button1 value: %d\n", - gpio_get_value(buttons[0].gpio)); + pr_info("Current button1 value: %d\n", + gpio_get_value(buttons[0].gpio)); - ret = gpio_to_irq(buttons[0].gpio); + ret = gpio_to_irq(buttons[0].gpio); - if (ret < 0) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret < 0) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - button_irqs[0] = ret; + button_irqs[0] = ret; - pr_info("Successfully requested BUTTON1 IRQ # %d\n", - button_irqs[0]); + pr_info("Successfully requested BUTTON1 IRQ # %d\n", + button_irqs[0]); - ret = request_irq(button_irqs[0], button_isr, - IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, - "gpiomod#button1", NULL); + ret = request_irq(button_irqs[0], button_isr, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, + "gpiomod#button1", NULL); - if (ret) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - ret = gpio_to_irq(buttons[1].gpio); + ret = gpio_to_irq(buttons[1].gpio); - if (ret < 0) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail2; - } + if (ret < 0) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail2; + } - button_irqs[1] = ret; + button_irqs[1] = ret; - pr_info("Successfully requested BUTTON2 IRQ # %d\n", - button_irqs[1]); + pr_info("Successfully requested BUTTON2 IRQ # %d\n", + button_irqs[1]); - ret = request_irq(button_irqs[1], button_isr, - IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, - "gpiomod#button2", NULL); + ret = request_irq(button_irqs[1], button_isr, + IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, + "gpiomod#button2", NULL); - if (ret) { - pr_err("Unable to request IRQ: %d\n", ret); - goto fail3; - } + if (ret) { + pr_err("Unable to request IRQ: %d\n", ret); + goto fail3; + } - return 0; + return 0; - /* cleanup what has been setup so far */ - fail3: - free_irq(button_irqs[0], NULL); + /* cleanup what has been setup so far */ + fail3: + free_irq(button_irqs[0], NULL); - fail2: - gpio_free_array(buttons, ARRAY_SIZE(leds)); + fail2: + gpio_free_array(buttons, ARRAY_SIZE(leds)); - fail1: - gpio_free_array(leds, ARRAY_SIZE(leds)); + fail1: + gpio_free_array(leds, ARRAY_SIZE(leds)); - return ret; - } + return ret; + } - void cleanup_module() - { - int i; + void cleanup_module() + { + int i; - pr_info("%s\n", __func__); + pr_info("%s\n", __func__); - /* free irqs */ - free_irq(button_irqs[0], NULL); - free_irq(button_irqs[1], NULL); + /* free irqs */ + free_irq(button_irqs[0], NULL); + free_irq(button_irqs[1], NULL); - /* turn all LEDs off */ - for (i = 0; i < ARRAY_SIZE(leds); i++) - gpio_set_value(leds[i].gpio, 0); + /* turn all LEDs off */ + for (i = 0; i < ARRAY_SIZE(leds); i++) + gpio_set_value(leds[i].gpio, 0); - /* unregister */ - gpio_free_array(leds, ARRAY_SIZE(leds)); - gpio_free_array(buttons, ARRAY_SIZE(buttons)); - } + /* unregister */ + gpio_free_array(leds, ARRAY_SIZE(leds)); + gpio_free_array(buttons, ARRAY_SIZE(buttons)); + } - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Interrupt with top and bottom half"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Interrupt with top and bottom half"); .. raw:: html @@ -6366,14 +6298,14 @@ additional task when an interrupt is triggered. .. raw:: html -
+
.. rubric:: Crypto - :name: org004956f + :name: sec-16 .. raw:: html -
+
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 @@ -6389,14 +6321,14 @@ hash functions. .. raw:: html -
+
.. rubric:: Hash functions - :name: org8f45455 + :name: sec-16-1 .. raw:: html -
+
Calculating and checking the hashes of things is a common operation. Here is a demonstration of how to calculate a sha256 hash within a @@ -6408,70 +6340,70 @@ kernel module. .. code:: src - #include - #include + #include + #include - #define SHA256_LENGTH (256/8) + #define SHA256_LENGTH (256/8) - static void show_hash_result(char * plaintext, char * hash_sha256) - { - int i; - char str[SHA256_LENGTH*2 + 1]; + static void show_hash_result(char * plaintext, char * hash_sha256) + { + int i; + char str[SHA256_LENGTH*2 + 1]; - 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; - pr_info("%s\n", str); - } + 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; + pr_info("%s\n", str); + } - int cryptosha256_init(void) - { - char * plaintext = "This is a test"; - char hash_sha256[SHA256_LENGTH]; - struct crypto_shash *sha256; - struct shash_desc *shash; + int cryptosha256_init(void) + { + char * plaintext = "This is a test"; + char hash_sha256[SHA256_LENGTH]; + struct crypto_shash *sha256; + struct shash_desc *shash; - sha256 = crypto_alloc_shash("sha256", 0, 0); - if (IS_ERR(sha256)) - return -1; + sha256 = crypto_alloc_shash("sha256", 0, 0); + if (IS_ERR(sha256)) + return -1; - shash = - kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256), - GFP_KERNEL); - if (!shash) - return -ENOMEM; + shash = + kmalloc(sizeof(struct shash_desc) + crypto_shash_descsize(sha256), + GFP_KERNEL); + if (!shash) + return -ENOMEM; - shash->tfm = sha256; - shash->flags = 0; + shash->tfm = sha256; + shash->flags = 0; - if (crypto_shash_init(shash)) - return -1; + if (crypto_shash_init(shash)) + return -1; - if (crypto_shash_update(shash, plaintext, strlen(plaintext))) - return -1; + if (crypto_shash_update(shash, plaintext, strlen(plaintext))) + return -1; - if (crypto_shash_final(shash, hash_sha256)) - return -1; + if (crypto_shash_final(shash, hash_sha256)) + return -1; - kfree(shash); - crypto_free_shash(sha256); + kfree(shash); + crypto_free_shash(sha256); - show_hash_result(plaintext, hash_sha256); + show_hash_result(plaintext, hash_sha256); - return 0; - } + return 0; + } - void cryptosha256_exit(void) - { - } + void cryptosha256_exit(void) + { + } - module_init(cryptosha256_init); - module_exit(cryptosha256_exit); + module_init(cryptosha256_init); + module_exit(cryptosha256_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("sha256 hash test"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("sha256 hash test"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -6485,9 +6417,9 @@ Make and install the module: .. code:: src - make - sudo insmod cryptosha256.ko - dmesg + make + sudo insmod cryptosha256.ko + dmesg .. raw:: html @@ -6503,7 +6435,7 @@ Finally, remove the test module: .. code:: src - sudo rmmod cryptosha256 + sudo rmmod cryptosha256 .. raw:: html @@ -6519,14 +6451,14 @@ Finally, remove the test module: .. raw:: html -
+
.. rubric:: Symmetric key encryption - :name: orgcf62e2d + :name: sec-16-2 .. raw:: html -
+
Here is an example of symmetrically encrypting a string using the AES algorithm and a password. @@ -6537,186 +6469,186 @@ algorithm and a password. .. code:: src - #include - #include - #include + #include + #include + #include - #define SYMMETRIC_KEY_LENGTH 32 - #define CIPHER_BLOCK_SIZE 16 + #define SYMMETRIC_KEY_LENGTH 32 + #define CIPHER_BLOCK_SIZE 16 - struct tcrypt_result { - struct completion completion; - int err; - }; + struct tcrypt_result { + struct completion completion; + int err; + }; - struct skcipher_def { - struct scatterlist sg; - struct crypto_skcipher * tfm; - struct skcipher_request * req; - struct tcrypt_result result; - char * scratchpad; - char * ciphertext; - char * ivdata; - }; + struct skcipher_def { + struct scatterlist sg; + struct crypto_skcipher * tfm; + struct skcipher_request * req; + struct tcrypt_result result; + char * scratchpad; + char * ciphertext; + char * ivdata; + }; - static struct skcipher_def sk; + static struct skcipher_def sk; - static void test_skcipher_finish(struct skcipher_def * sk) - { - if (sk->tfm) - crypto_free_skcipher(sk->tfm); - if (sk->req) - skcipher_request_free(sk->req); - if (sk->ivdata) - kfree(sk->ivdata); - if (sk->scratchpad) - kfree(sk->scratchpad); - if (sk->ciphertext) - kfree(sk->ciphertext); - } + static void test_skcipher_finish(struct skcipher_def * sk) + { + if (sk->tfm) + crypto_free_skcipher(sk->tfm); + if (sk->req) + skcipher_request_free(sk->req); + if (sk->ivdata) + kfree(sk->ivdata); + if (sk->scratchpad) + kfree(sk->scratchpad); + if (sk->ciphertext) + kfree(sk->ciphertext); + } - static int test_skcipher_result(struct skcipher_def * sk, int rc) - { - switch (rc) { - case 0: - break; - case -EINPROGRESS: - case -EBUSY: - rc = wait_for_completion_interruptible( - &sk->result.completion); - if (!rc && !sk->result.err) { - reinit_completion(&sk->result.completion); - break; - } - default: - pr_info("skcipher encrypt returned with %d result %d\n", - rc, sk->result.err); - break; - } + static int test_skcipher_result(struct skcipher_def * sk, int rc) + { + switch (rc) { + case 0: + break; + case -EINPROGRESS: + case -EBUSY: + rc = wait_for_completion_interruptible( + &sk->result.completion); + if (!rc && !sk->result.err) { + reinit_completion(&sk->result.completion); + break; + } + default: + pr_info("skcipher encrypt returned with %d result %d\n", + rc, sk->result.err); + break; + } - init_completion(&sk->result.completion); + init_completion(&sk->result.completion); - return rc; - } + return rc; + } - static void test_skcipher_callback(struct crypto_async_request *req, int error) - { - struct tcrypt_result *result = req->data; - int ret; + static void test_skcipher_callback(struct crypto_async_request *req, int error) + { + struct tcrypt_result *result = req->data; + int ret; - if (error == -EINPROGRESS) - return; + if (error == -EINPROGRESS) + return; - result->err = error; - complete(&result->completion); - pr_info("Encryption finished successfully\n"); - } + result->err = error; + complete(&result->completion); + pr_info("Encryption finished successfully\n"); + } - static int test_skcipher_encrypt(char * plaintext, char * password, - struct skcipher_def * sk) - { - int ret = -EFAULT; - unsigned char key[SYMMETRIC_KEY_LENGTH]; + static int test_skcipher_encrypt(char * plaintext, char * password, + struct skcipher_def * sk) + { + int ret = -EFAULT; + unsigned char key[SYMMETRIC_KEY_LENGTH]; - if (!sk->tfm) { - sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0); - if (IS_ERR(sk->tfm)) { - pr_info("could not allocate skcipher handle\n"); - return PTR_ERR(sk->tfm); - } - } + if (!sk->tfm) { + sk->tfm = crypto_alloc_skcipher("cbc-aes-aesni", 0, 0); + if (IS_ERR(sk->tfm)) { + pr_info("could not allocate skcipher handle\n"); + return PTR_ERR(sk->tfm); + } + } - if (!sk->req) { - sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL); - if (!sk->req) { - pr_info("could not allocate skcipher request\n"); - ret = -ENOMEM; - goto out; - } - } + if (!sk->req) { + sk->req = skcipher_request_alloc(sk->tfm, GFP_KERNEL); + if (!sk->req) { + pr_info("could not allocate skcipher request\n"); + ret = -ENOMEM; + goto out; + } + } - skcipher_request_set_callback(sk->req, CRYPTO_TFM_REQ_MAY_BACKLOG, - test_skcipher_callback, - &sk->result); + skcipher_request_set_callback(sk->req, CRYPTO_TFM_REQ_MAY_BACKLOG, + test_skcipher_callback, + &sk->result); - /* clear the key */ - memset((void*)key,'\0',SYMMETRIC_KEY_LENGTH); + /* clear the key */ + memset((void*)key,'\0',SYMMETRIC_KEY_LENGTH); - /* Use the world's favourite password */ - sprintf((char*)key,"%s",password); + /* Use the world's favourite password */ + sprintf((char*)key,"%s",password); - /* AES 256 with given symmetric key */ - if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) { - pr_info("key could not be set\n"); - ret = -EAGAIN; - goto out; - } - pr_info("Symmetric key: %s\n", key); - pr_info("Plaintext: %s\n", plaintext); + /* AES 256 with given symmetric key */ + if (crypto_skcipher_setkey(sk->tfm, key, SYMMETRIC_KEY_LENGTH)) { + pr_info("key could not be set\n"); + ret = -EAGAIN; + goto out; + } + 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) { - pr_info("could not allocate ivdata\n"); - goto out; - } - get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE); - } + if (!sk->ivdata) { + /* see https://en.wikipedia.org/wiki/Initialization_vector */ + sk->ivdata = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL); + if (!sk->ivdata) { + pr_info("could not allocate ivdata\n"); + goto out; + } + get_random_bytes(sk->ivdata, CIPHER_BLOCK_SIZE); + } - if (!sk->scratchpad) { - /* The text to be encrypted */ - sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL); - if (!sk->scratchpad) { - pr_info("could not allocate scratchpad\n"); - goto out; - } - } - sprintf((char*)sk->scratchpad,"%s",plaintext); + if (!sk->scratchpad) { + /* The text to be encrypted */ + sk->scratchpad = kmalloc(CIPHER_BLOCK_SIZE, GFP_KERNEL); + if (!sk->scratchpad) { + pr_info("could not allocate scratchpad\n"); + goto out; + } + } + sprintf((char*)sk->scratchpad,"%s",plaintext); - sg_init_one(&sk->sg, sk->scratchpad, CIPHER_BLOCK_SIZE); - skcipher_request_set_crypt(sk->req, &sk->sg, &sk->sg, - CIPHER_BLOCK_SIZE, sk->ivdata); - init_completion(&sk->result.completion); + sg_init_one(&sk->sg, sk->scratchpad, CIPHER_BLOCK_SIZE); + skcipher_request_set_crypt(sk->req, &sk->sg, &sk->sg, + CIPHER_BLOCK_SIZE, sk->ivdata); + init_completion(&sk->result.completion); - /* encrypt data */ - ret = crypto_skcipher_encrypt(sk->req); - ret = test_skcipher_result(sk, ret); - if (ret) - goto out; + /* encrypt data */ + ret = crypto_skcipher_encrypt(sk->req); + ret = test_skcipher_result(sk, ret); + if (ret) + goto out; - pr_info("Encryption request successful\n"); + pr_info("Encryption request successful\n"); - out: - return ret; - } + out: + return ret; + } - int cryptoapi_init(void) - { - /* The world's favourite password */ - char * password = "password123"; + int cryptoapi_init(void) + { + /* The world's favourite password */ + char * password = "password123"; - sk.tfm = NULL; - sk.req = NULL; - sk.scratchpad = NULL; - sk.ciphertext = NULL; - sk.ivdata = NULL; + sk.tfm = NULL; + sk.req = NULL; + sk.scratchpad = NULL; + sk.ciphertext = NULL; + sk.ivdata = NULL; - test_skcipher_encrypt("Testing", password, &sk); - return 0; - } + test_skcipher_encrypt("Testing", password, &sk); + return 0; + } - void cryptoapi_exit(void) - { - test_skcipher_finish(&sk); - } + void cryptoapi_exit(void) + { + test_skcipher_finish(&sk); + } - module_init(cryptoapi_init); - module_exit(cryptoapi_exit); + module_init(cryptoapi_init); + module_exit(cryptoapi_exit); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Symmetric key encryption example"); - MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Symmetric key encryption example"); + MODULE_LICENSE("GPL"); .. raw:: html @@ -6736,14 +6668,14 @@ algorithm and a password. .. raw:: html -
+
.. rubric:: Standardising the interfaces: The Device Model - :name: org161334f + :name: sec-17 .. raw:: html -
+
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 @@ -6758,102 +6690,102 @@ to add your own suspend, resume or other interface functions. .. code:: src - #include - #include - #include + #include + #include + #include - struct devicemodel_data { - char *greeting; - int number; - }; + struct devicemodel_data { + char *greeting; + int number; + }; - static int devicemodel_probe(struct platform_device *dev) - { - struct devicemodel_data *pd = (struct devicemodel_data *)(dev->dev.platform_data); + static int devicemodel_probe(struct platform_device *dev) + { + struct devicemodel_data *pd = (struct devicemodel_data *)(dev->dev.platform_data); - pr_info("devicemodel probe\n"); - pr_info("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 */ + /* Your device initialisation code */ - return 0; - } + return 0; + } - static int devicemodel_remove(struct platform_device *dev) - { - pr_info("devicemodel example removed\n"); + static int devicemodel_remove(struct platform_device *dev) + { + pr_info("devicemodel example removed\n"); - /* Your device removal code */ + /* Your device removal code */ - return 0; - } + return 0; + } - static int devicemodel_suspend(struct device *dev) - { - pr_info("devicemodel example suspend\n"); + static int devicemodel_suspend(struct device *dev) + { + pr_info("devicemodel example suspend\n"); - /* Your device suspend code */ + /* Your device suspend code */ - return 0; - } + return 0; + } - static int devicemodel_resume(struct device *dev) - { - pr_info("devicemodel example resume\n"); + static int devicemodel_resume(struct device *dev) + { + pr_info("devicemodel example resume\n"); - /* Your device resume code */ + /* Your device resume code */ - return 0; - } + return 0; + } - static const struct dev_pm_ops devicemodel_pm_ops = - { - .suspend = devicemodel_suspend, - .resume = devicemodel_resume, - .poweroff = devicemodel_suspend, - .freeze = devicemodel_suspend, - .thaw = devicemodel_resume, - .restore = devicemodel_resume - }; + static const struct dev_pm_ops devicemodel_pm_ops = + { + .suspend = devicemodel_suspend, + .resume = devicemodel_resume, + .poweroff = devicemodel_suspend, + .freeze = devicemodel_suspend, + .thaw = devicemodel_resume, + .restore = devicemodel_resume + }; - static struct platform_driver devicemodel_driver = { - .driver = { - .name = "devicemodel_example", - .owner = THIS_MODULE, - .pm = &devicemodel_pm_ops, - }, - .probe = devicemodel_probe, - .remove = devicemodel_remove, - }; + static struct platform_driver devicemodel_driver = { + .driver = { + .name = "devicemodel_example", + .owner = THIS_MODULE, + .pm = &devicemodel_pm_ops, + }, + .probe = devicemodel_probe, + .remove = devicemodel_remove, + }; - static int devicemodel_init(void) - { - int ret; + static int devicemodel_init(void) + { + int ret; - pr_info("devicemodel init\n"); + pr_info("devicemodel init\n"); - ret = platform_driver_register(&devicemodel_driver); + ret = platform_driver_register(&devicemodel_driver); - if (ret) { - pr_err("Unable to register driver\n"); - return ret; - } + if (ret) { + pr_err("Unable to register driver\n"); + return ret; + } - return 0; - } + return 0; + } - static void devicemodel_exit(void) - { - pr_info("devicemodel exit\n"); - platform_driver_unregister(&devicemodel_driver); - } + static void devicemodel_exit(void) + { + pr_info("devicemodel exit\n"); + platform_driver_unregister(&devicemodel_driver); + } - MODULE_LICENSE("GPL"); - MODULE_AUTHOR("Bob Mottram"); - MODULE_DESCRIPTION("Linux Device Model example"); + MODULE_LICENSE("GPL"); + MODULE_AUTHOR("Bob Mottram"); + MODULE_DESCRIPTION("Linux Device Model example"); - module_init(devicemodel_init); - module_exit(devicemodel_exit); + module_init(devicemodel_init); + module_exit(devicemodel_exit); .. raw:: html @@ -6869,14 +6801,14 @@ to add your own suspend, resume or other interface functions. .. raw:: html -
+
.. rubric:: Optimisations - :name: org8639895 + :name: sec-18 .. raw:: html -
+
.. raw:: html @@ -6884,14 +6816,14 @@ to add your own suspend, resume or other interface functions. .. raw:: html -
+
.. rubric:: Likely and Unlikely conditions - :name: orgb775e92 + :name: sec-18-1 .. raw:: html -
+
Sometimes you might want your code to run as quickly as possible, especially if it's handling an interrupt or doing something which might @@ -6909,12 +6841,12 @@ to succeed. .. code:: src - bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx); - if (unlikely(!bvl)) { - mempool_free(bio, bio_pool); - bio = NULL; - goto out; - } + bvl = bvec_alloc(gfp_mask, nr_iovecs, &idx); + if (unlikely(!bvl)) { + mempool_free(bio, bio_pool); + bio = NULL; + goto out; + } .. raw:: html @@ -6939,14 +6871,14 @@ pipeline. The opposite happens if you use the *likely* macro. .. raw:: html -
+
.. rubric:: Common Pitfalls - :name: org1cf3372 + :name: sec-19 .. raw:: html -
+
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 @@ -6959,14 +6891,14 @@ a full refund of the amount I was paid for your copy of the book. .. raw:: html -
+
.. rubric:: Using standard libraries - :name: org8e71ecd + :name: sec-19-1 .. raw:: html -
+
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. @@ -6981,14 +6913,14 @@ which are the functions you can see in /proc/kallsyms. .. raw:: html -
+
.. rubric:: Disabling interrupts - :name: org9ff7def + :name: sec-19-2 .. raw:: html -
+
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 @@ -7004,14 +6936,14 @@ to power it off. .. raw:: html -
+
.. rubric:: Sticking your head inside a large carnivore - :name: orgdd651cd + :name: sec-19-3 .. raw:: html -
+
I probably don't have to warn you about this, but I figured I will anyway, just in case. @@ -7030,14 +6962,14 @@ anyway, just in case. .. raw:: html -
+
.. rubric:: Where To Go From Here? - :name: orgcf6e3aa + :name: sec-20 .. raw:: html -
+
I 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 diff --git a/4.15.2/LKMPG-4.15.2.tex b/4.15.2/LKMPG-4.15.2.tex index f51a393..e537802 100644 --- a/4.15.2/LKMPG-4.15.2.tex +++ b/4.15.2/LKMPG-4.15.2.tex @@ -1,29 +1,28 @@ -% Created 2018-02-15 Thu 12:41 -% Intended LaTeX compiler: pdflatex +% Created 2018-05-22 Tue 13:55 \documentclass[11pt]{article} \usepackage[utf8]{inputenc} \usepackage[T1]{fontenc} +\usepackage{fixltx2e} \usepackage{graphicx} -\usepackage{grffile} \usepackage{longtable} +\usepackage{float} \usepackage{wrapfig} \usepackage{rotating} \usepackage[normalem]{ulem} \usepackage{amsmath} \usepackage{textcomp} +\usepackage{marvosym} +\usepackage{wasysym} \usepackage{amssymb} -\usepackage{capt-of} \usepackage{hyperref} +\tolerance=1000 \author{Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram} \date{\today} \title{The Linux Kernel Module Programming Guide} \hypersetup{ - pdfauthor={Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram}, - pdftitle={The Linux Kernel Module Programming Guide}, - pdfkeywords={linux, kernel, kernel module, kernel programming}, - pdfsubject={How to make kernel modules for Linux}, - pdfcreator={Emacs 25.3.1 (Org mode 9.1.5)}, - pdflang={English}} + pdfkeywords={linux, kernel, kernel module, kernel programming}, + pdfsubject={How to make kernel modules for Linux}, + pdfcreator={Emacs 25.3.1 (Org mode 8.2.3c)}} \begin{document} \maketitle @@ -31,7 +30,7 @@ \section*{Introduction} -\label{sec:orgc321dcd} +\label{sec-1} 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. This book is distributed in the hope it will be useful, but without any warranty, without even the implied warranty of merchantability or fitness for a particular purpose. @@ -43,31 +42,31 @@ Derivative works and translations of this document must be placed under the Open If you publish or distribute this book commercially, donations, royalties, and/or printed copies are greatly appreciated by the author and the \href{http://www.tldp.org}{Linux Documentation Project} (LDP). Contributing in this way shows your support for free software and the LDP. If you have questions or comments, please contact the address above. \subsection*{Authorship} -\label{sec:orgb6d5857} +\label{sec-1-1} The Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels. Bob Mottram updated the examples for 3.8 and later kernels, added the sysfs chapter and modified or updated other chapters. \subsection*{Versioning and Notes} -\label{sec:org02b5f61} +\label{sec-1-2} 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. The source code and discussions should apply to most architectures, but I can't promise anything. \subsection*{Acknowledgements} -\label{sec:orgd049ec8} +\label{sec-1-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. \subsection*{What Is A Kernel Module?} -\label{sec:orgbf29314} +\label{sec-1-4} 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. What exactly is a kernel module? Modules are pieces of code that can be loaded and unloaded into the kernel upon demand. They extend the functionality of the kernel without the need to reboot the system. For example, one type of module is the device driver, which allows the kernel to access hardware connected to the system. Without modules, we would have to build monolithic kernels and add new functionality directly into the kernel image. Besides having larger kernels, this has the disadvantage of requiring us to rebuild and reboot the kernel every time we want new functionality. \subsection*{Kernel module package} -\label{sec:orga12b1cc} +\label{sec-1-5} Linux distros provide the commands \emph{modprobe}, \emph{insmod} and \emph{depmod} within a package. @@ -84,7 +83,7 @@ sudo pacman -S gcc kmod \end{verbatim} \subsection*{What Modules are in my Kernel?} -\label{sec:org4043d5d} +\label{sec-1-6} To discover what modules are already loaded within your current kernel use the command \textbf{lsmod}. @@ -105,20 +104,20 @@ sudo lsmod | grep fat \end{verbatim} \subsection*{Do I need to download and compile the kernel?} -\label{sec:org5514142} +\label{sec-1-7} 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. \subsection*{Before We Begin} -\label{sec:org64bf8fe} +\label{sec-1-8} 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. \begin{itemize} \item Modversioning -\label{sec:org626b2a3} +\label{sec-1-8-0-1} 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. \item Using X -\label{sec:org90aa845} +\label{sec-1-8-0-2} 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. @@ -126,7 +125,7 @@ Modules can't print to the screen like printf() can, but they can log informatio \end{itemize} \section*{Headers} -\label{sec:org5433425} +\label{sec-2} Before you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux: \begin{verbatim} @@ -146,7 +145,7 @@ This will tell you what kernel header files are available. Then for example: sudo apt-get install kmod linux-headers-4.15.2-1-amd64 \end{verbatim} \section*{Examples} -\label{sec:org6c6550e} +\label{sec-3} All the examples from this document are available within the \emph{examples} subdirectory. To test that they compile: \begin{verbatim} @@ -156,9 +155,9 @@ make If there are any compile errors then you might have a more recent kernel version or need to install the corresponding kernel header files. \section*{Hello World} -\label{sec:org271d322} +\label{sec-4} \subsection*{The Simplest Module} -\label{sec:orgd17fc17} +\label{sec-4-1} Most people learning programming start out with some sort of "\emph{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. Here's the simplest module possible. @@ -260,15 +259,15 @@ Lastly, every kernel module needs to include linux/module.h. We needed to includ \begin{itemize} \item A point about coding style -\label{sec:org2ebe640} +\label{sec-4-1-0-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 \textbf{tabs} and \textbf{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. \item Introducing print macros -\label{sec:orge74bcce} +\label{sec-4-1-0-2} In the beginning there was \textbf{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 \textbf{pr\_info} and \textbf{pr\_debug}. This just saves some mindless keyboard bashing and looks a bit neater. They can be found within \textbf{linux/printk.h}. Take time to read through the available priority macros. \item About Compiling -\label{sec:org70e2fb5} +\label{sec-4-1-0-3} 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 \textbf{linux/Documentation/kbuild/modules.txt}. @@ -280,7 +279,7 @@ Here's another exercise for the reader. See that comment above the return statem \end{itemize} \subsection*{Hello and Goodbye} -\label{sec:org34d97ca} +\label{sec-4-2} In early kernel versions you had to use the \textbf{init\_module} and \textbf{cleanup\_module} functions, as in the first hello world example, but these days you can name those anything you want by using the \textbf{module\_init} and \textbf{module\_exit} macros. These macros are defined in \textbf{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: \begin{verbatim} @@ -323,7 +322,7 @@ clean: Now have a look at linux/drivers/char/Makefile for a real world example. As you can see, some things get hardwired into the kernel (obj-y) but where are all those obj-m gone? Those familiar with shell scripts will easily be able to spot them. For those not, the obj-\$(CONFIG\_FOO) entries you see everywhere expand into obj-y or obj-m, depending on whether the CONFIG\_FOO variable has been set to y or m. While we are at it, those were exactly the kind of variables that you have set in the linux/.config file, the last time when you said make menuconfig or something like that. \subsection*{The \_\_init and \_\_exit Macros} -\label{sec:org6c778f1} +\label{sec-4-3} This demonstrates a feature of kernel 2.2 and later. Notice the change in the definitions of the init and cleanup functions. The \textbf{\_\_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. There is also an \textbf{\_\_initdata} which works similarly to \textbf{\_\_init} but for init variables rather than functions. @@ -358,7 +357,7 @@ module_exit(hello_3_exit); \end{verbatim} \subsection*{Licensing and Module Documentation} -\label{sec:org21ab1f3} +\label{sec-4-4} Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this: \begin{verbatim} @@ -401,7 +400,7 @@ module_exit(cleanup_hello_4); \end{verbatim} \subsection*{Passing Command Line Arguments to a Module} -\label{sec:org3cd1129} +\label{sec-4-5} Modules can take command line arguments, but not with the argc/argv you might be used to. To allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the module\_param() macro, (defined in linux/moduleparam.h) to set the mechanism up. At runtime, insmod will fill the variables with any command line arguments that are given, like ./insmod mymodule.ko myvariable=5. The variable declarations and macros should be placed at the beginning of the module for clarity. The example code should clear up my admittedly lousy explanation. @@ -421,7 +420,7 @@ 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 */ +module_param_array(myshortarray, short, &count, 0); /* put count into "count" variable */ \end{verbatim} A good use for this is to have the module variable's default values set, like an port or IO address. If the variables contain the default values, then perform autodetection (explained elsewhere). Otherwise, keep the current value. This will be made clear later on. @@ -532,7 +531,7 @@ hello-5.o: invalid argument syntax for mylong: 'h' \end{verbatim} \subsection*{Modules Spanning Multiple Files} -\label{sec:orge26ffb5} +\label{sec-4-6} Sometimes it makes sense to divide a kernel module between several source files. Here's an example of such a kernel module. @@ -589,7 +588,7 @@ clean: This is the complete makefile for all the examples we've seen so far. The first five lines are nothing special, but for the last example we'll need two lines. First we invent an object name for our combined module, second we tell make what object files are part of that module. \subsection*{Building modules for a precompiled kernel} -\label{sec:org9159753} +\label{sec-4-7} 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 (\textbf{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 \textbf{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. There are a number of cases in which you may want to load your module into a precompiled running kernel, such as the ones shipped with common Linux distributions, or a kernel you have compiled in the past. In certain circumstances you could require to compile and insert a module into a running kernel which you are not allowed to recompile, or on a machine that you prefer not to reboot. If you can't think of a case that will force you to use modules for a precompiled kernel you might want to skip this and treat the rest of this chapter as a big footnote. @@ -652,9 +651,9 @@ CC scripts/empty.o If you do not desire to actually compile the kernel, you can interrupt the build process (CTRL-C) just after the SPLIT line, because at that time, the files you need will be are ready. Now you can turn back to the directory of your module and compile it: It will be built exactly according your current kernel settings, and it will load into it without any errors. \section*{Preliminaries} -\label{sec:org71a80b8} +\label{sec-5} \subsection*{How modules begin and end} -\label{sec:orgf6f7093} +\label{sec-5-1} A program usually begins with a \textbf{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. All modules end by calling either \textbf{cleanup\_module} or the function you specify with the \textbf{module\_exit} call. This is the exit function for modules; it undoes whatever entry function did. It unregisters the functionality that the entry function registered. @@ -662,7 +661,7 @@ All modules end by calling either \textbf{cleanup\_module} or the function you s Every module must have an entry function and an exit function. Since there's more than one way to specify entry and exit functions, I'll try my best to use the terms `entry function' and `exit function', but if I slip and simply refer to them as init\_module and cleanup\_module, I think you'll know what I mean. \subsection*{Functions available to modules} -\label{sec:org55630eb} +\label{sec-5-2} Programmers use functions they don't define all the time. A prime example of this is \textbf{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, \textbf{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 \textbf{/proc/kallsyms}. @@ -686,13 +685,13 @@ with \textbf{gcc -Wall -o hello hello.c}. Run the exectable with \textbf{strace You can even write modules to replace the kernel's system calls, which we'll do shortly. Crackers often make use of this sort of thing for backdoors or trojans, but you can write your own modules to do more benign things, like have the kernel write Tee hee, that tickles! everytime someone tries to delete a file on your system. \subsection*{User Space vs Kernel Space} -\label{sec:org65c3b2a} +\label{sec-5-3} 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'. Recall the discussion about library functions vs system calls. Typically, you use a library function in user mode. The library function calls one or more system calls, and these system calls execute on the library function's behalf, but do so in supervisor mode since they are part of the kernel itself. Once the system call completes its task, it returns and execution gets transfered back to user mode. \subsection*{Name Space} -\label{sec:orgc59d839} +\label{sec-5-4} When you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you'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. When writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue. The best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols. By convention, all kernel prefixes are lowercase. If you don't want to declare everything as static, another option is to declare a symbol table and register it with a kernel. We'll get to this later. @@ -700,22 +699,22 @@ When writing kernel code, even the smallest module will be linked against the en The file \textbf{/proc/kallsyms} holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel's codespace. \subsection*{Code space} -\label{sec:orga4e4f07} +\label{sec-5-5} Memory management is a very complicated subject and the majority of O'Reilly's "\emph{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. If you haven't thought about what a segfault really means, you may be surprised to hear that pointers don't actually point to memory locations. Not real ones, anyway. When a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about. This memory begins with 0x00000000 and extends up to whatever it needs to be. Since the memory space for any two processes don't overlap, every process that can access a memory address, say 0xbffff978, would be accessing a different location in real physical memory! The processes would be accessing an index named 0xbffff978 which points to some kind of offset into the region of memory set aside for that particular process. For the most part, a process like our Hello, World program can't access the space of another process, although there are ways which we'll talk about later. The kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel's codespace rather than having its own. Therefore, if your module segfaults, the kernel segfaults. And if you start writing over data because of an off-by-one error, then you're trampling on kernel data (or code). This is even worse than it sounds, so try your best to be careful. -By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't quite the same thing as \emph{"building all your modules into the kernel"}, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel. +By the way, I would like to point out that the above discussion is true for any operating system which uses a monolithic kernel. This isn't quite the same thing as /"building all your modules into the kernel"/, although the idea is the same. There are things called microkernels which have modules which get their own codespace. The GNU Hurd and the Magenta kernel of Google Fuchsia are two examples of a microkernel. \subsection*{Device Drivers} -\label{sec:orgc5d62fb} +\label{sec-5-6} One class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.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. \begin{itemize} \item Major and Minor Numbers -\label{sec:org0b68ce3} +\label{sec-5-6-0-1} Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive: @@ -745,7 +744,7 @@ When the system was installed, all of those device files were created by the mkn I would like to make a few last points which are implicit from the above discussion, but I'd like to make them explicit just in case. When a device file is accessed, the kernel uses the major number of the file to determine which driver should be used to handle the access. This means that the kernel doesn't really need to use or even know about the minor number. The driver itself is the only thing that cares about the minor number. It uses the minor number to distinguish between different pieces of hardware. -By the way, when I say \emph{"hardware"}, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files: +By the way, when I say /"hardware"/, I mean something a bit more abstract than a PCI card that you can hold in your hand. Look at these two device files: \begin{verbatim} % ls -l /dev/sda /dev/sdb @@ -757,9 +756,9 @@ By now you can look at these two device files and know instantly that they are b \end{itemize} \section*{Character Device drivers} -\label{sec:orga656c47} +\label{sec-6} \subsection*{The file\_operations Structure} -\label{sec:org274a1cc} +\label{sec-6-1} The file\_operations structure is defined in \textbf{/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. For example, every character driver needs to define a function that reads from the device. The file\_operations structure holds the address of the module's function that performs that operation. Here is what the definition looks like for kernel 3.0: @@ -826,7 +825,7 @@ The meaning is clear, and you should be aware that any member of the structure w An instance of struct file\_operations containing pointers to functions that are used to implement read, write, open, \ldots{} syscalls is commonly named fops. \subsection*{The file structure} -\label{sec:org098d6fc} +\label{sec-6-2} Each device is represented in the kernel by a file structure, which is defined in \textbf{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 \textbf{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. @@ -835,7 +834,7 @@ An instance of struct file is commonly named filp. You'll also see it refered to Go ahead and look at the definition of file. Most of the entries you see, like struct dentry aren't used by device drivers, and you can ignore them. This is because drivers don't fill file directly; they only use structures contained in file which are created elsewhere. \subsection*{Registering A Device} -\label{sec:org754d088} +\label{sec-6-3} As 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. Adding a driver to your system means registering it with the kernel. This is synonymous with assigning it a major number during the module's initialization. You do this by using the register\_chrdev function, defined by linux/fs.h. @@ -851,7 +850,7 @@ Now the question is, how do you get a major number without hijacking one that's If you pass a major number of 0 to register\_chrdev, the return value will be the dynamically allocated major number. The downside is that you can't make a device file in advance, since you don't know what the major number will be. There are a couple of ways to do this. First, the driver itself can print the newly assigned number and we can make the device file by hand. Second, the newly registered device will have an entry in \textbf{/proc/devices}, and we can either make the device file by hand or write a shell script to read the file in and make the device file. The third method is we can have our driver make the the device file using the \textbf{device\_create} function after a successful registration and \textbf{device\_destroy} during the call to cleanup\_module. \subsection*{Unregistering A Device} -\label{sec:org9b8d9f7} +\label{sec-6-4} 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. Normally, when you don't want to allow something, you return an error code (a negative number) from the function which is supposed to do it. With cleanup\_module that's impossible because it's a void function. However, there's a counter which keeps track of how many processes are using your module. You can see what it's value is by looking at the 3rd field of \textbf{/proc/modules}. If this number isn't zero, rmmod will fail. Note that you don't have to check the counter from within cleanup\_module because the check will be performed for you by the system call sys\_delete\_module, defined in \textbf{linux/module.c}. You shouldn't use this counter directly, but there are functions defined in \textbf{linux/module.h} which let you increase, decrease and display this counter: @@ -864,7 +863,7 @@ Normally, when you don't want to allow something, you return an error code (a ne It's important to keep the counter accurate; if you ever do lose track of the correct usage count, you'll never be able to unload the module; it's now reboot time, boys and girls. This is bound to happen to you sooner or later during a module's development. \subsection*{chardev.c} -\label{sec:org3bbde96} +\label{sec-6-5} The next code sample creates a char driver named chardev. You can cat its device file. \begin{verbatim} @@ -1058,19 +1057,19 @@ static ssize_t device_write(struct file *filp, \end{verbatim} \subsection*{Writing Modules for Multiple Kernel Versions} -\label{sec:orga0aa025} +\label{sec-6-6} 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. -The Linux kernel versions are divided between the stable versions (n.\$<\$even number\(>\).m) and the development versions (n.\$<\$odd number\(>\).m). The development versions include all the cool new ideas, including those which will be considered a mistake, or reimplemented, in the next version. As a result, you can't trust the interface to remain the same in those versions (which is why I don't bother to support them in this book, it's too much work and it would become dated too quickly). In the stable versions, on the other hand, we can expect the interface to remain the same regardless of the bug fix version (the m number). +The Linux kernel versions are divided between the stable versions (n.\$<\$even number$>$.m) and the development versions (n.\$<\$odd number$>$.m). The development versions include all the cool new ideas, including those which will be considered a mistake, or reimplemented, in the next version. As a result, you can't trust the interface to remain the same in those versions (which is why I don't bother to support them in this book, it's too much work and it would become dated too quickly). In the stable versions, on the other hand, we can expect the interface to remain the same regardless of the bug fix version (the m number). -There are differences between different kernel versions, and if you want to support multiple kernel versions, you'll find yourself having to code conditional compilation directives. The way to do this to compare the macro LINUX\_VERSION\_CODE to the macro KERNEL\_VERSION. In version a.b.c of the kernel, the value of this macro would be \(2^{16}a+2^{8}b+c\). +There are differences between different kernel versions, and if you want to support multiple kernel versions, you'll find yourself having to code conditional compilation directives. The way to do this to compare the macro LINUX\_VERSION\_CODE to the macro KERNEL\_VERSION. In version a.b.c of the kernel, the value of this macro would be $2^{16}a+2^{8}b+c$. While previous versions of this guide showed how you can write backward compatible code with such constructs in great detail, we decided to break with this tradition for the better. People interested in doing such might now use a LKMPG with a version matching to their kernel. We decided to version the LKMPG like the kernel, at least as far as major and minor number are concerned. We use the patchlevel for our own versioning so use LKMPG version 2.4.x for kernels 2.4.x, use LKMPG version 2.6.x for kernels 2.6.x and so on. Also make sure that you always use current, up to date versions of both, kernel and guide. You might already have noticed that recent kernels look different. In case you haven't they look like 2.6.x.y now. The meaning of the first three items basically stays the same, but a subpatchlevel has been added and will indicate security fixes till the next stable patchlevel is out. So people can choose between a stable tree with security updates and use the latest kernel as developer tree. Search the kernel mailing list archives if you're interested in the full story. \section*{The /proc File System} -\label{sec:org34d8e48} +\label{sec-7} In Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes --- the \textbf{/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 \textbf{/proc/modules} which provides the list of modules and \textbf{/proc/meminfo} which stats memory usage statistics. The method to use the proc file system is very similar to the one used with device drivers --- a structure is created with all the information needed for the \textbf{/proc} file, including pointers to any handler functions (in our case there is only one, the one called when somebody attempts to read from the \textbf{/proc} file). Then, init\_module registers the structure with the kernel and cleanup\_module unregisters it. @@ -1144,7 +1143,7 @@ void cleanup_module() \end{verbatim} \subsection*{Read and Write a /proc File} -\label{sec:org72592c6} +\label{sec-7-1} 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) The reason for copy\_from\_user or get\_user is that Linux memory (on Intel architecture, it may be different under some other processors) is segmented. This means that a pointer, by itself, does not reference a unique location in memory, only a location in a memory segment, and you need to know which memory segment it is to be able to use it. There is one memory segment for the kernel, and one for each of the processes. @@ -1253,7 +1252,7 @@ void cleanup_module() \end{verbatim} \subsection*{Manage /proc file with standard filesystem} -\label{sec:orgfbdd2bd} +\label{sec-7-2} 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. In Linux, there is a standard mechanism for file system registration. Since every file system has to have its own functions to handle inode and file operations, there is a special structure to hold pointers to all those functions, struct \textbf{inode\_operations}, which includes a pointer to struct file\_operations. @@ -1355,7 +1354,7 @@ void cleanup_module() Still hungry for procfs examples? Well, first of all keep in mind, there are rumors around, claiming that procfs is on it's way out, consider using sysfs instead. Second, if you really can't get enough, there's a highly recommendable bonus level for procfs below linux/Documentation/DocBook/ . Use make help in your toplevel kernel directory for instructions about how to convert it into your favourite format. Example: make htmldocs . Consider using this mechanism, in case you want to document something kernel related yourself. \subsection*{Manage /proc file with seq\_file} -\label{sec:orgd4ccaa0} +\label{sec-7-3} 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 formating a /proc file for output. It's based on sequence, which is composed of 3 functions: start(), next(), and stop(). The seq\_file API starts a sequence when a user read the /proc file. @@ -1365,9 +1364,7 @@ non NULL value, the function next() is called. This function is an iterator, the BE CARREFUL: when a sequence is finished, another one starts. That means that at the end of function stop(), the function start() is called again. This loop finishes when the function start() returns NULL. You can see a scheme of this in the figure "How seq\_file works". -\begin{center} \includegraphics[width=.9\linewidth]{img/seq_file.png} -\end{center} \begin{center} \begin{tabular}{} @@ -1518,14 +1515,14 @@ If you want more information, you can read this web page: \begin{itemize} \item \url{http://lwn.net/Articles/22355/} -\item \url{http://www.kernelnewbies.org/documents/seq\_file\_howto.txt} +\item \url{http://www.kernelnewbies.org/documents/seq_file_howto.txt} \end{itemize} You can also read the code of fs/seq\_file.c in the linux kernel. \section*{sysfs: Interacting with your module} -\label{sec:orga3389e2} +\label{sec-8} \emph{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 \emph{sys} directory on your system. \begin{verbatim} @@ -1535,73 +1532,7 @@ ls -l /sys An example of a hello world module which includes the creation of a variable accessible via sysfs is given below. \begin{verbatim} -/* - * hello-sysfs.c sysfs example - */ - -#include -#include -#include -#include -#include -#include - -MODULE_LICENSE("GPL"); -MODULE_AUTHOR("Bob Mottram"); - -static struct kobject *mymodule; - -/* the variable you want to be able to change */ -static int myvariable = 0; - -static ssize_t myvariable_show(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf) -{ - return sprintf(buf, "%d\n", myvariable); -} - -static ssize_t myvariable_store(struct kobject *kobj, - struct kobj_attribute *attr, - char *buf, size_t count) -{ - sscanf(buf, "%du", &myvariable); - return count; -} - - -static struct kobj_attribute myvariable_attribute = - __ATTR(myvariable, 0660, myvariable_show, - (void*)myvariable_store); - -static int __init mymodule_init (void) -{ - int error = 0; - - pr_info("mymodule: initialised\n"); - - mymodule = - kobject_create_and_add("mymodule", kernel_kobj); - if (!mymodule) - return -ENOMEM; - - error = sysfs_create_file(mymodule, &myvariable_attribute.attr); - if (error) { - pr_info("failed to create the myvariable file " \ - "in /sys/kernel/mymodule\n"); - } - - return error; -} - -static void __exit mymodule_exit (void) -{ - pr_info("mymodule: Exit success\n"); - kobject_put(mymodule); -} - -module_init(mymodule_init); -module_exit(mymodule_exit); +"hello-sysfs.c"body \end{verbatim} Make and install the module: @@ -1637,7 +1568,7 @@ sudo rmmod hello_sysfs \end{verbatim} \section*{Talking To Device Files} -\label{sec:org4dcda87} +\label{sec-9} Device files are supposed to represent physical devices. Most physical devices are used for output as well as input, so there has to be some mechanism for device drivers in the kernel to get the output to send to the device from processes. This is done by opening the device file for output and writing to it, just like writing to a file. In the following example, this is implemented by device\_write. This is not always enough. Imagine you had a serial port connected to a modem (even if you have an internal modem, it is still implemented from the CPU's perspective as a serial port connected to a modem, so you don't have to tax your imagination too hard). The natural thing to do would be to use the device file to write things to the modem (either modem commands or data to be sent through the phone line) and read things from the modem (either responses for commands or the data received through the phone line). However, this leaves open the question of what to do when you need to talk to the serial port itself, for example to send the rate at which data is sent and received. @@ -2117,7 +2048,7 @@ int main() \end{verbatim} \section*{System Calls} -\label{sec:orgb23484f} +\label{sec-10} So far, the only thing we've done was to use well defined kernel mechanisms to register \textbf{/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. If you're not being sensible and using a virtual machine then this is where kernel programming can become hazardous. While writing the example below, I killed the \textbf{open()} system call. This meant I couldn't open any files, I couldn't run any programs, and I couldn't shutdown the system. I had to restart the virtual machine. No important files got anihilated, but if I was doing this on some live mission critical system then that could have been a possible outcome. To ensure you don't lose any files, even within a test environment, please run \textbf{sync} right before you do the \textbf{insmod} and the \textbf{rmmod}. @@ -2299,9 +2230,9 @@ MODULE_LICENSE("GPL"); \end{verbatim} \section*{Blocking Processes and threads} -\label{sec:orge7d633e} +\label{sec-11} \subsection*{Sleep} -\label{sec:orgf09dc03} +\label{sec-11-1} 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: "\emph{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). This kernel module is an example of this. The file (called \textbf{/proc/sleep}) can only be opened by a single process at a time. If the file is already open, the kernel module calls wait\_event\_interruptible. The easiest way to keep a file open is to open it with: @@ -2686,7 +2617,7 @@ int main(int argc, char *argv[]) \end{verbatim} \subsection*{Completions} -\label{sec:org674a879} +\label{sec-11-2} Sometimes one thing should happen before another within a module having multiple threads. Rather than using \textbf{/proc/sleep} commands the kernel has another way to do this which allows timeouts or interrupts to also happen. In the following example two threads are started, but one needs to start before another. @@ -2778,10 +2709,10 @@ So even though \emph{flywheel\_thread} is started first you should notice if you There are other variations upon the \emph{wait\_for\_completion} function, which include timeouts or being interrupted, but this basic mechanism is enough for many common situations without adding a lot of complexity. \section*{Avoiding Collisions and Deadlocks} -\label{sec:org3ee70af} +\label{sec-12} 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. \subsection*{Mutex} -\label{sec:orgb6306b0} +\label{sec-12-1} 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. \begin{verbatim} @@ -2827,10 +2758,10 @@ MODULE_DESCRIPTION("Mutex example"); MODULE_LICENSE("GPL"); \end{verbatim} \subsection*{Spinlocks} -\label{sec:org7588133} +\label{sec-12-2} 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. -The example here is \emph{"irq safe"} in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the \emph{flags} variable to retain their state. +The example here is /"irq safe"/ in that if interrupts happen during the lock then they won't be forgotten and will activate when the unlock happens, using the \emph{flags} variable to retain their state. \begin{verbatim} #include @@ -2899,7 +2830,7 @@ MODULE_LICENSE("GPL"); \end{verbatim} \subsection*{Read and write locks} -\label{sec:org6f1791a} +\label{sec-12-3} 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. \begin{verbatim} @@ -2960,7 +2891,7 @@ MODULE_LICENSE("GPL"); Of course if you know for sure that there are no functions triggered by irqs which could possibly interfere with your logic then you can use the simpler \emph{read\_lock(\&myrwlock)} and \emph{read\_unlock(\&myrwlock)} or the corresponding write functions. \subsection*{Atomic operations} -\label{sec:org18753cc} +\label{sec-12-4} 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. \begin{verbatim} @@ -3042,9 +2973,9 @@ MODULE_DESCRIPTION("Atomic operations example"); MODULE_LICENSE("GPL"); \end{verbatim} \section*{Replacing Print Macros} -\label{sec:org3904545} +\label{sec-13} \subsection*{Replacement} -\label{sec:org8657a17} +\label{sec-13-1} 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. "tty" is an abbreviation of \emph{teletype}: originally a combination keyboard-printer used to communicate with a Unix system, and today an abstraction for the text stream used for a Unix program, whether it's a physical terminal, an xterm on an X display, a network connection used with ssh, etc. @@ -3163,7 +3094,7 @@ module_exit(print_string_exit); \end{verbatim} \subsection*{Flashing keyboard LEDs} -\label{sec:org20e7e12} +\label{sec-13-2} 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. The following source code illustrates a minimal kernel module which, when loaded, starts blinking the keyboard LEDs until it is unloaded. @@ -3269,11 +3200,11 @@ If none of the examples in this chapter fit your debugging needs there might yet While you have seen lots of stuff that can be used to aid debugging here, there are some things to be aware of. Debugging is almost always intrusive. Adding debug code can change the situation enough to make the bug seem to dissappear. Thus you should try to keep debug code to a minimum and make sure it does not show up in production code. \section*{Scheduling Tasks} -\label{sec:org22cd2ac} +\label{sec-14} 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. \subsection*{Tasklets} -\label{sec:org61a92d7} +\label{sec-14-1} Here's an example tasklet module. The \emph{tasklet\_fn} function runs for a few seconds and in the mean time execution of the \emph{example\_tasklet\_init} function continues to the exit point. \begin{verbatim} @@ -3323,7 +3254,7 @@ Example tasklet init continues... Example tasklet ends \end{verbatim} \subsection*{Work queues} -\label{sec:org546f488} +\label{sec-14-2} To add a task to the scheduler we can use a workqueue. The kernel then uses the Completely Fair Scheduler (CFS) to execute work within the queue. \begin{verbatim} @@ -3360,9 +3291,9 @@ MODULE_DESCRIPTION("Workqueue example"); \end{verbatim} \section*{Interrupt Handlers} -\label{sec:org5c07d3a} +\label{sec-15} \subsection*{Interrupt Handlers} -\label{sec:org4f9dad1} +\label{sec-15-1} 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. There are two types of interaction between the CPU and the rest of the computer's hardware. The first type is when the CPU gives orders to the hardware, the other is when the hardware needs to tell the CPU something. The second, called interrupts, is much harder to implement because it has to be dealt with when convenient for the hardware, not the CPU. Hardware devices typically have a very small amount of RAM, and if you don't read their information when available, it is lost. @@ -3378,7 +3309,7 @@ In practice IRQ handling can be a bit more complex. Hardware is often designed i This function receives the IRQ number, the name of the function, flags, a name for /proc/interrupts and a parameter to pass to the interrupt handler. Usually there is a certain number of IRQs available. How many IRQs there are is hardware-dependent. The flags can include SA\_SHIRQ to indicate you're willing to share the IRQ with other interrupt handlers (usually because a number of hardware devices sit on the same IRQ) and SA\_INTERRUPT to indicate this is a fast interrupt. This function will only succeed if there isn't already a handler on this IRQ, or if you're both willing to share. \subsection*{Detecting button presses} -\label{sec:org8aa69b8} +\label{sec-15-2} Many 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. Here's an example where buttons are connected to GPIO numbers 17 and 18 and an LED is connected to GPIO 4. You can change those numbers to whatever is appropriate for your board. @@ -3538,7 +3469,7 @@ MODULE_DESCRIPTION("Handle some GPIO interrupts"); \end{verbatim} \subsection*{Bottom Half} -\label{sec:org23c6161} +\label{sec-15-3} 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. The example below modifies the previous example to also run an additional task when an interrupt is triggered. @@ -3711,11 +3642,11 @@ MODULE_AUTHOR("Bob Mottram"); MODULE_DESCRIPTION("Interrupt with top and bottom half"); \end{verbatim} \section*{Crypto} -\label{sec:org4022507} +\label{sec-16} At the dawn of the internet everybody trusted everybody completely\ldots{}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. \subsection*{Hash functions} -\label{sec:orgc51232f} +\label{sec-16-1} 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. @@ -3802,7 +3733,7 @@ Finally, remove the test module: sudo rmmod cryptosha256 \end{verbatim} \subsection*{Symmetric key encryption} -\label{sec:org68c3780} +\label{sec-16-2} Here is an example of symmetrically encrypting a string using the AES algorithm and a password. \begin{verbatim} @@ -3988,7 +3919,7 @@ MODULE_DESCRIPTION("Symmetric key encryption example"); MODULE_LICENSE("GPL"); \end{verbatim} \section*{Standardising the interfaces: The Device Model} -\label{sec:orgf49b112} +\label{sec-17} 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. \begin{verbatim} @@ -4090,9 +4021,9 @@ module_init(devicemodel_init); module_exit(devicemodel_exit); \end{verbatim} \section*{Optimisations} -\label{sec:orga045cfd} +\label{sec-18} \subsection*{Likely and Unlikely conditions} -\label{sec:org279fdc0} +\label{sec-18-1} 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 \emph{true} or \emph{false}, then you can allow the compiler to optimise for this using the \emph{likely} and \emph{unlikely} macros. For example, when allocating memory you're almost always expecting this to succeed. @@ -4108,23 +4039,23 @@ if (unlikely(!bvl)) { When the \emph{unlikely} macro is used the compiler alters its machine instruction output so that it continues along the false branch and only jumps if the condition is true. That avoids flushing the processor pipeline. The opposite happens if you use the \emph{likely} macro. \section*{Common Pitfalls} -\label{sec:org5911e2e} +\label{sec-19} 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. \subsection*{Using standard libraries} -\label{sec:orgf4b2a9d} +\label{sec-19-1} 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. \subsection*{Disabling interrupts} -\label{sec:org7bc9c92} +\label{sec-19-2} 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. \subsection*{Sticking your head inside a large carnivore} -\label{sec:org5023a68} +\label{sec-19-3} I probably don't have to warn you about this, but I figured I will anyway, just in case. \section*{Where To Go From Here?} -\label{sec:org4bc2277} +\label{sec-20} I 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. However, I chose not to. My purpose in writing this book was to provide initiation into the mysteries of kernel module programming and to teach the common techniques for that purpose. For people seriously interested in kernel programming, I recommend \href{https://kernelnewbies.org}{kernelnewbies.org} and the \emph{Documentation} subdirectory within the kernel source code which isn't always easy to understand but can be a starting point for further investigation. Also, as Linus said, the best way to learn the kernel is to read the source code yourself. @@ -4134,4 +4065,5 @@ If you're interested in more examples of short kernel modules then searching on I hope I have helped you in your quest to become a better programmer, or at least to have fun through technology. And, if you do write useful kernel modules, I hope you publish them under the GPL, so I can use them too. If you'd like to contribute to this guide, notice anything glaringly wrong, or just want to add extra sarcastic remarks perhaps involving monkeys or some other kind of animal then please file an issue or even better submit a pull request at \url{https://github.com/bashrc/LKMPG}. +% Emacs 25.3.1 (Org mode 8.2.3c) \end{document} diff --git a/4.15.2/img/seq_file.png b/4.15.2/img/seq_file.png index 4d15a3a1672be847f9e61c88401235eafbeaebb9..d0d9fdfe057f596f57a42456cc2fc51da8d8a613 100644 GIT binary patch literal 26089 zcmeAS@N?(olHy`uVBq!ia0y~yV0_HLz_^=(je&vT!>YfF7#JAXlDyqr82*Fcg1yTp zGcYJHc)B=-RLpsEw>l!^>OcDr-|y_uR)}*r%6&@pagR8Ct3A=q@ThXY|R3sg--~P|JBL?DZ zDQV1~>umY`&)&*@|M%wOGyl#+RlnVu>cqjQq@*;dC*~DHM@PpS*~x~2f)kI-=;`d} zP+2y`ih-%CtE=F}1;v$z6*jHfn0)-u$&;S13_7AzB-sl*-+y>`xTB+Ef)$U_>Qm>> zyI)@yyOghag=^C39jp&ecHL6?cS9vhV!foWprB{Z$r&9T9!WmOTwGj)l8w}qlqN|a zTXrnP$Hhg(P%T+W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