diff --git a/4.12.12/LKMPG-4.12.12.html b/4.12.12/LKMPG-4.12.12.html index 9207b20..6e4dc02 100644 --- a/4.12.12/LKMPG-4.12.12.html +++ b/4.12.12/LKMPG-4.12.12.html @@ -3,7 +3,7 @@ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
- +The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 3.0.
@@ -401,18 +401,18 @@ If you publish or distribute this book commercially, donations, royalties, and/oThe Linux Kernel Module Programming Guide was originally written for the 2.2 kernels by Ori Pomerantz. Eventually, Ori no longer had time to maintain the document. After all, the Linux kernel is a fast moving target. Peter Jay Salzman took over maintenance and updated it for the 2.4 kernels. Eventually, Peter no longer had time to follow developments with the 2.6 kernel, so Michael Burian became a co-maintainer to update the document for the 2.6 kernels. Bob Mottram updated the examples for 3.8 and later kernels, added the sysfs chapter and modified or updated other chapters.
The Linux kernel is a moving target. There has always been a question whether the LKMPG should remove deprecated information or keep it around for historical sake. Michael Burian and I decided to create a new branch of the LKMPG for each new stable kernel version. So version LKMPG 4.12.x will address Linux kernel 4.12.x and LKMPG 2.6.x will address Linux kernel 2.6. No attempt will be made to archive historical information; a person wishing this information should read the appropriately versioned LKMPG.
@@ -423,18 +423,18 @@ The source code and discussions should apply to most architectures, but I can'tThe following people have contributed corrections or good suggestions: Ignacio Martin, David Porter, Daniele Paolo Scarpazza, Dimo Velev, Francois Audeon, Horst Schirmeier, Bob Mottram and Roman Lakeev.
So, you want to write a kernel module. You know C, you've written a few normal programs to run as processes, and now you want to get to where the real action is, to where a single wild pointer can wipe out your file system and a core dump means a reboot.
@@ -445,9 +445,9 @@ What exactly is a kernel module? Modules are pieces of code that can be loaded aLinux distros provide the commands modprobe, insmod and depmod within a package.
@@ -472,9 +472,9 @@ On Parabola:To discover what modules are already loaded within your current kernel use the command lsmod.
@@ -504,33 +504,33 @@ This can be a long list, and you might prefer to search for something particularFor the purposes of following this guide you don't necessarily need to do that. However, it would be wise to run the examples within a test distro running on a virtual machine in order to avoid any possibility of messing up your system.
Before we delve into code, there are a few issues we need to cover. Everyone's system is different and everyone has their own groove. Getting your first "hello world" program to compile and load correctly can sometimes be a trick. Rest assured, after you get over the initial hurdle of doing it for the first time, it will be smooth sailing thereafter.
A module compiled for one kernel won't load if you boot a different kernel unless you enable CONFIG_MODVERSIONS in the kernel. We won't go into module versioning until later in this guide. Until we cover modversions, the examples in the guide may not work if you're running a kernel with modversioning turned on. However, most stock Linux distro kernels come with it turned on. If you're having trouble loading the modules because of versioning errors, compile a kernel with modversioning turned off.
It is highly recommended that you type in, compile and load all the examples this guide discusses. It's also highly recommended you do this from a console. You should not be working on this stuff in X.
@@ -544,9 +544,9 @@ Modules can't print to the screen like printf() can, but they can log informatioBefore you can build anything you'll need to install the header files for your kernel. On Parabola GNU/Linux:
@@ -576,9 +576,9 @@ This will tell you what kernel header files are available. Then for example:All the examples from this document are available within the examples subdirectory. To test that they compile:
@@ -594,13 +594,13 @@ If there are any compile errors then you might have a more recent kernel versionMost 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.
@@ -744,23 +744,23 @@ Lastly, every kernel module needs to include linux/module.h. We needed to includAnother 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.
In the beginning there was printk, usually followed by a priority such as KERN_INFO or KERN_DEBUG. More recently this can also be expressed in abbreviated form using a set of print macros, such as pr_info and pr_debug. This just saves some mindless keyboard bashing and looks a bit neater. They can be found within linux/printk.h. Take time to read through the available priority macros.
Kernel modules need to be compiled a bit differently from regular userspace apps. Former kernel versions required us to care much about these settings, which are usually stored in Makefiles. Although hierarchically organized, many redundant settings accumulated in sublevel Makefiles and made them large and rather difficult to maintain. Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism. To learn more on how to compile modules which are not part of the official kernel (such as all the examples you'll find in this guide), see file linux/Documentation/kbuild/modules.txt.
@@ -779,9 +779,9 @@ Here's another exercise for the reader. See that comment above the return statemIn early kernel versions you had to use the init_module and cleanup_module functions, as in the first hello world example, but these days you can name those anything you want by using the module_init and module_exit macros. These macros are defined in linux/init.h. The only requirement is that your init and cleanup functions must be defined before calling the those macros, otherwise you'll get compilation errors. Here's an example of this technique:
@@ -833,9 +833,9 @@ Now have a look at linux/drivers/char/Makefile for a real world example. As youThis 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.
@@ -880,9 +880,9 @@ module_exit(hello_3_exit);Honestly, who loads or even cares about proprietary modules? If you do then you might have seen something like this:
@@ -934,9 +934,9 @@ module_exit(cleanup_hello_4);Modules can take command line arguments, but not with the argc/argv you might be used to.
@@ -1086,9 +1086,9 @@ hello-5.o: invalid argument syntax for mylong: 'h'Sometimes it makes sense to divide a kernel module between several source files.
@@ -1159,9 +1159,9 @@ This is the complete makefile for all the examples we've seen so far. The firstObviously, 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.
@@ -1253,13 +1253,13 @@ If you do not desire to actually compile the kernel, you can interrupt the buildA 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 +1274,9 @@ Every module must have an entry function and an exit function. Since there's morProgrammers use functions they don't define all the time. A prime example of this is printf(). You use these library functions which are provided by the standard C library, libc. The definitions for these functions don't actually enter your program until the linking stage, which insures that the code (for printf() for example) is available, and fixes the call instruction to point to that code.
@@ -1314,9 +1314,9 @@ You can even write modules to replace the kernel's system calls, which we'll doA 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 +1327,9 @@ Recall the discussion about library functions vs system calls. Typically, you usWhen you write a small C program, you use variables which are convenient and make sense to the reader. If, on the other hand, you're writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash. When a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution. In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.
@@ -1344,9 +1344,9 @@ The file /proc/kallsyms holds all the symbols that the kernel knows aboutMemory management is a very complicated subject and the majority of O'Reilly's "Understanding The Linux Kernel" exclusively covers memory management! We're not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.
@@ -1365,17 +1365,17 @@ By the way, I would like to point out that the above discussion is true for anyOne class of module is the device driver, which provides functionality for hardware like a serial port. On unix, each piece of hardware is represented by a file located in /dev named a device file which provides the means to communicate with the hardware. The device driver provides the communication on behalf of a user program. So the es1370.o sound card device driver might connect the /dev/sound device file to the Ensoniq IS1370 sound card. A userspace program like mp3blaster can use /dev/sound without ever knowing what kind of sound card is installed.
Let's look at some device files. Here are device files which represent the first three partitions on the primary master IDE hard drive:
@@ -1440,13 +1440,13 @@ By now you can look at these two device files and know instantly that they are bThe 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.
@@ -1531,9 +1531,9 @@ An instance of struct file_operations containing pointers to functions that areEach 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 +1548,9 @@ Go ahead and look at the definition of file. Most of the entries you see, like sAs discussed earlier, char devices are accessed through device files, usually located in /dev. This is by convention. When writing a driver, it's OK to put the device file in your current directory. Just make sure you place it in /dev for a production driver. The major number tells you which driver handles which device file. The minor number is used only by the driver itself to differentiate which device it's operating on, just in case the driver handles more than one device.
@@ -1573,14 +1573,14 @@ 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 /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 mknod system call after a successful registration and rm during the call to cleanup_module. +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 /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 device_create function after a successful registration and device_destroy during the call to cleanup_module.
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.
@@ -1600,9 +1600,9 @@ It's important to keep the counter accurate; if you ever do lose track of the coThe next code sample creates a char driver named chardev. You can cat its device file.
@@ -1625,7 +1625,15 @@ The next code sample creates a char driver named chardev. You can cat its device #include <linux/kernel.h> #include <linux/module.h> #include <linux/fs.h> -#include <linux/uaccess.h> /* for put_user */ +#include <linux/init.h> +#include <linux/delay.h> +#include <linux/device.h> +#include <linux/irq.h> +#include <asm/uaccess.h> +#include <asm/irq.h> +#include <asm/io.h> +#include <linux/poll.h> +#include <linux/cdev.h> /* * Prototypes - this would normally go in a .h file @@ -1651,11 +1659,13 @@ The next code sample creates a char driver named chardev. You can cat its device static char msg[BUF_LEN]; /* The msg the device will give when asked */ static char *msg_Ptr; -static struct file_operations fops = { - .read = device_read, - .write = device_write, - .open = device_open, - .release = device_release +static struct class *cls; + +static struct file_operations chardev_fops = { + .read = device_read, + .write = device_write, + .open = device_open, + .release = device_release }; /* @@ -1663,21 +1673,21 @@ The next code sample creates a char driver named chardev. You can cat its device */ int init_module(void) { - Major = register_chrdev(0, DEVICE_NAME, &fops); + 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. To talk to\n", Major); - pr_info("the driver, create a dev file with\n"); - pr_info("'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major); - pr_info("Try various minor numbers. Try to cat and echo to\n"); - pr_info("the device file.\n"); - pr_info("Remove the device file and module when done.\n"); + pr_info("I was assigned major number %d.\n", Major); - return SUCCESS; + 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); + + return SUCCESS; } /* @@ -1685,10 +1695,13 @@ The next code sample creates a char driver named chardev. You can cat its device */ void cleanup_module(void) { - /* - * Unregister the device - */ - unregister_chrdev(Major, DEVICE_NAME); + device_destroy(cls, MKDEV(Major, 0)); + class_destroy(cls); + + /* + * Unregister the device + */ + unregister_chrdev(Major, DEVICE_NAME); } /* @@ -1701,17 +1714,17 @@ The next code sample creates a char driver named chardev. You can cat its device */ static int device_open(struct inode *inode, struct file *file) { - static int counter = 0; + 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; } /* @@ -1719,15 +1732,15 @@ The next code sample creates a char driver named chardev. You can cat its device */ static int device_release(struct inode *inode, struct file *file) { - Device_Open--; /* We're now ready for our next caller */ + 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; } /* @@ -1739,39 +1752,39 @@ The next code sample creates a char driver named chardev. You can cat its device size_t length, /* length of the buffer */ loff_t * offset) { - /* - * Number of bytes actually written to the buffer - */ - int bytes_read = 0; + /* + * 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; + + /* + * Actually put the data into the buffer + */ + while (length && *msg_Ptr) { /* - * If we're at the end of the message, - * return 0 signifying end of file + * 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. */ - if (*msg_Ptr == 0) - return 0; + put_user(*(msg_Ptr++), buffer++); - /* - * Actually put the data into the buffer - */ - while (length && *msg_Ptr) { + length--; + bytes_read++; + } - /* - * 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++; - } - - /* - * 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; } /* @@ -1779,20 +1792,20 @@ The next code sample creates a char driver named chardev. You can cat its device */ static ssize_t device_write(struct file *filp, const char *buff, - size_t len, - loff_t * off) + size_t len, + loff_t * off) { - pr_alert("Sorry, this operation isn't supported.\n"); - return -EINVAL; + pr_alert("Sorry, this operation isn't supported.\n"); + return -EINVAL; }The system calls, which are the major interface the kernel shows to the processes, generally stay the same across versions. A new system call may be added, but usually the old ones will behave exactly like they used to. This is necessary for backward compatibility – a new kernel version is not supposed to break regular processes. In most cases, the device files will also remain the same. On the other hand, the internal interfaces within the kernel can and do change between versions.
@@ -1816,9 +1829,9 @@ You might already have noticed that recent kernels look different. In case you hIn Linux, there is an additional mechanism for the kernel and kernel modules to send information to processes — the /proc file system. Originally designed to allow easy access to information about processes (hence the name), it is now used by every bit of the kernel which has something interesting to report, such as /proc/modules which provides the list of modules and /proc/meminfo which stats memory usage statistics.
@@ -1908,9 +1921,9 @@ HelloWorld!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)
@@ -2027,9 +2040,9 @@ The only memory segment accessible to a process is its own, so when writing reguWe 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.
@@ -2147,9 +2160,9 @@ Still hungry for procfs examples? Well, first of all keep in mind, there are rumAs 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 @@ -2339,9 +2352,9 @@ You can also read the code of fs/seq_file.c in the linux kernel.
sysfs allows you to interact with the running kernel from userspace by reading or setting variables inside of modules. This can be useful for debugging purposes, or just as an interface for applications or scripts. You can find sysfs directories and files under the sys directory on your system.
@@ -2475,9 +2488,9 @@ Finally, remove the test module: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.
@@ -2510,7 +2523,15 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o #include <linux/kernel.h> /* We're doing kernel work */ #include <linux/module.h> /* Specifically, a module */ #include <linux/fs.h> -#include <linux/uaccess.h> /* for get_user and put_user */ +#include <linux/init.h> +#include <linux/delay.h> +#include <linux/device.h> +#include <linux/irq.h> +#include <asm/uaccess.h> +#include <asm/irq.h> +#include <asm/io.h> +#include <linux/poll.h> +#include <linux/cdev.h> #include "chardev.h" #define SUCCESS 0 @@ -2535,6 +2556,9 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o */ static char *Message_Ptr; +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 */ @@ -2752,19 +2776,16 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o */ if (ret_val < 0) { pr_alert("%s failed with %d\n", - "Sorry, registering the character device ", ret_val); + "Sorry, registering the character device ", ret_val); return ret_val; } - pr_info("%s The major device number is %d.\n", - "Registeration is a success", MAJOR_NUM); - pr_info("If you want to talk to the device driver,\n"); - pr_info("you'll have to create a device file. \n"); - pr_info("We suggest you use:\n"); - pr_info("mknod %s c %d 0\n", DEVICE_FILE_NAME, MAJOR_NUM); - pr_info("The device file name is important, because\n"); - pr_info("the ioctl program assumes that's the\n"); - pr_info("file you'll use.\n"); + Major = ret_val; + + cls = class_create(THIS_MODULE, DEVICE_FILE_NAME); + device_create(cls, NULL, MKDEV(Major, MAJOR_NUM), NULL, DEVICE_FILE_NAME); + + pr_info("Device created on /dev/%s\n", DEVICE_FILE_NAME); return 0; } @@ -2774,10 +2795,13 @@ If you want to use ioctls in your own kernel modules, it is best to receive an o */ void cleanup_module() { + device_destroy(cls, MKDEV(Major, 0)); + class_destroy(cls); + /* * Unregister the device */ - unregister_chrdev(MAJOR_NUM, DEVICE_NAME); + unregister_chrdev(Major, DEVICE_NAME); }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.
@@ -3170,13 +3194,13 @@ MODULE_LICENSE("GPL");What do you do when somebody asks you for something you can't do right away? If you're a human being and you're bothered by a human being, the only thing you can say is: "Not right now, I'm busy. Go away!". But if you're a kernel module and you're bothered by a process, you have another possibility. You can put the process to sleep until you can service it. After all, processes are being put to sleep by the kernel and woken up all the time (that's the way multiple processes appear to run on the same time on a single CPU).
@@ -3586,9 +3610,9 @@ DECLARE_WAIT_QUEUE_HEAD(WaitQ);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.
@@ -3693,16 +3717,16 @@ There are other variations upon the wait_for_completion function, which iIf processes running on different CPUs or in different threads try to access the same memory then it's possible that strange things can happen or your system can lock up. To avoid this various types of mutual exclusion kernel functions are available. These indicate if a section of code is "locked" or "unlocked" so that simultaneous attempts to run it can't happen.
You can use kernel mutexes (mutual exclusions) in much the same manner that you might deploy them in userland. This may be all that's needed to avoid collisions in most cases.
@@ -3752,9 +3776,9 @@ MODULE_LICENSE("GPL");As the name suggests, spinlocks lock up the CPU that the code is running on, taking 100% of its resources. Because of this you should only use the spinlock mechanism around code which is likely to take no more than a few milliseconds to run and so won't noticably slow anything down from the user's point of view.
@@ -3832,9 +3856,9 @@ MODULE_LICENSE("GPL");Read and write locks are specialised kinds of spinlocks so that you can exclusively read from something or write to something. Like the earlier spinlocks example the one below shows an "irq safe" situation in which if other functions were triggered from irqs which might also read and write to whatever you are concerned with then they wouldn't disrupt the logic. As before it's a good idea to keep anything done within the lock as short as possible so that it doesn't hang up the system and cause users to start revolting against the tyranny of your module.
@@ -3901,9 +3925,9 @@ Of course if you know for sure that there are no functions triggered by irqs whiIf 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.
@@ -3990,13 +4014,13 @@ MODULE_LICENSE("GPL");In Section 1.2.1.2, I said that X and kernel module programming don't mix. That's true for developing kernel modules, but in actual use, you want to be able to send messages to whichever tty the command to load the module came from.
@@ -4123,9 +4147,9 @@ module_exit(print_string_exit);In certain conditions, you may desire a simpler and more direct way to communicate to the external world. Flashing keyboard LEDs can be such a solution: It is an immediate way to attract attention or to display a status condition. Keyboard LEDs are present on every hardware, they are always visible, they do not need any setup, and their use is rather simple and non-intrusive, compared to writing to a tty or a file.
@@ -4244,17 +4268,17 @@ While you have seen lots of stuff that can be used to aid debugging here, thereThere are two main ways of running tasks: tasklets and work queues. Tasklets are a quick and easy way of scheduling a single function to be run, for example when triggered from an interrupt, whereas work queues are more complicated but also better suited to running multiple things in a sequence.
Here's an example tasklet module. The tasklet_fn function runs for a few seconds and in the mean time execution of the example_tasklet_init function continues to the exit point.
@@ -4311,9 +4335,9 @@ Example tasklet endsVery often, we have "housekeeping" tasks which have to be done at a certain time, or every so often. If the task is to be done by a process, we do it by putting it in the crontab file. If the task is to be done by a kernel module, we have two possibilities. The first is to put a process in the crontab file which will wake up the module by a system call when necessary, for example by opening a file. This is terribly inefficient, however – we run a new process off of crontab, read a new executable to memory, and all this just to wake up a kernel module which is in memory anyway.
@@ -4497,13 +4521,13 @@ MODULE_LICENSE("GPL");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.
@@ -4534,9 +4558,9 @@ This function receives the IRQ number, the name of the function, flags, a name fMany popular single board computers, such as Raspberry Pis or Beagleboards, have a bunch of GPIO pins. Attaching buttons to those and then having a button press do something is a classic case in which you might need to use interrupts so that instead of having the CPU waste time and battery power polling for a change in input state it's better for the input to trigger the CPU to then run a particular handling function.
@@ -4702,9 +4726,9 @@ MODULE_DESCRIPTION("Handle some GPIO interrupts"Suppose you want to do a bunch of stuff inside of an interrupt routine. A common way to do that without rendering the interrupt unavailable for a significant duration is to combine it with a tasklet. This pushes the bulk of the work off into the scheduler.
@@ -4884,17 +4908,17 @@ MODULE_DESCRIPTION("Interrupt with top and bottom half"At the dawn of the internet everybody trusted everybody completely…but that didn't work out so well. When this guide was originally written it was a more innocent era in which almost nobody actually gave a damn about crypto - least of all kernel developers. That's certainly no longer the case now. To handle crypto stuff the kernel has its own API enabling common methods of encryption, decryption and your favourite hash functions.
Calculating and checking the hashes of things is a common operation. Here is a demonstration of how to calculate a sha256 hash within a kernel module.
@@ -4992,9 +5016,9 @@ Finally, remove the test module:Here is an example of symmetrically encrypting a string using the AES algorithm and a password.
@@ -5185,9 +5209,9 @@ MODULE_LICENSE("GPL");Up to this point we've seen all kinds of modules doing all kinds of things, but there was no consistency in their interfaces with the rest of the kernel. To impose some consistency such that there is at minimum a standardised way to start, suspend and resume a device a device model was added. An example is show below, and you can use this as a template to add your own suspend, resume or other interface functions.
@@ -5293,13 +5317,13 @@ module_exit(devicemodel_exit);Sometimes you might want your code to run as quickly as possible, especially if it's handling an interrupt or doing something which might cause noticible latency. If your code contains boolean conditions and if you know that the conditions are almost always likely to evaluate as either true or false, then you can allow the compiler to optimise for this using the likely and unlikely macros.
@@ -5324,35 +5348,35 @@ When the unlikely macro is used the compiler alters its machine instructiBefore I send you on your way to go out into the world and write kernel modules, there are a few things I need to warn you about. If I fail to warn you and something bad happens, please report the problem to me for a full refund of the amount I was paid for your copy of the book.
You can't do that. In a kernel module you can only use kernel functions, which are the functions you can see in /proc/kallsyms.
You might need to do this for a short time and that is OK, but if you don't enable them afterwards, your system will be stuck and you'll have to power it off.
I probably don't have to warn you about this, but I figured I will anyway, just in case.
@@ -5360,9 +5384,9 @@ I probably don't have to warn you about this, but I figured I will anyway, justI could easily have squeezed a few more chapters into this book. I could have added a chapter about creating new file systems, or about adding new protocol stacks (as if there's a need for that – you'd have to dig underground to find a protocol stack not supported by Linux). I could have added explanations of the kernel mechanisms we haven't touched upon, such as bootstrapping or the disk interface.
diff --git a/4.12.12/LKMPG-4.12.12.md b/4.12.12/LKMPG-4.12.12.md index 01bc439..183fc04 100644 --- a/4.12.12/LKMPG-4.12.12.md +++ b/4.12.12/LKMPG-4.12.12.md @@ -8,83 +8,83 @@ Table of Contents ----------------- ::: {#text-table-of-contents} -- [Introduction](#org32fcb39) - - [Authorship](#org70042fe) - - [Versioning and Notes](#org6bc9d50) - - [Acknowledgements](#orgaf14f92) - - [What Is A Kernel Module?](#orge8302b7) - - [Kernel module package](#org018252e) - - [What Modules are in my Kernel?](#org86a2fb0) - - [Do I need to download and compile the kernel?](#orgab5e696) - - [Before We Begin](#org6362ee1) -- [Headers](#orga551762) -- [Examples](#org9ab6de9) -- [Hello World](#org2bf67ab) - - [The Simplest Module](#orgaf987a8) - - [Hello and Goodbye](#org8ffa823) - - [The \_\_init and \_\_exit Macros](#org11cceb2) - - [Licensing and Module Documentation](#org34d76ad) - - [Passing Command Line Arguments to a Module](#org3605080) - - [Modules Spanning Multiple Files](#orga436d2b) - - [Building modules for a precompiled kernel](#org1f65f5b) -- [Preliminaries](#org6957bc4) - - [How modules begin and end](#org0ed644c) - - [Functions available to modules](#org760b84a) - - [User Space vs Kernel Space](#orgd704758) - - [Name Space](#org361db02) - - [Code space](#org3ce918a) - - [Device Drivers](#org1b87707) -- [Character Device drivers](#org052dca4) - - [The file\_operations Structure](#org0989cfb) - - [The file structure](#org9d35c9c) - - [Registering A Device](#orgc230f23) - - [Unregistering A Device](#org45f597a) - - [chardev.c](#org729a75c) - - [Writing Modules for Multiple Kernel Versions](#org44075a2) -- [The /proc File System](#org53ca54d) - - [Read and Write a /proc File](#orgc55fc6d) - - [Manage /proc file with standard filesystem](#orga012908) - - [Manage /proc file with seq\_file](#org69ee08a) -- [sysfs: Interacting with your module](#orgae3eef1) -- [Talking To Device Files](#orgfeee7e2) -- [System Calls](#orgc32321d) -- [Blocking Processes and threads](#org07d7e8d) - - [Sleep](#org300bd6d) - - [Completions](#org35f83b6) -- [Avoiding Collisions and Deadlocks](#orgb21233a) - - [Mutex](#org17205de) - - [Spinlocks](#orgba24119) - - [Read and write locks](#org64419a2) - - [Atomic operations](#org733e7c8) -- [Replacing Print Macros](#orgf9cdbb8) - - [Replacement](#org5532536) - - [Flashing keyboard LEDs](#org7fd3ed8) -- [Scheduling Tasks](#org69766c1) - - [Tasklets](#orgac851dc) - - [Work queues](#org726ddfc) -- [Interrupt Handlers](#orgee935a8) - - [Interrupt Handlers](#org7540085) - - [Detecting button presses](#org0b9ea11) - - [Bottom Half](#org9238405) -- [Crypto](#org4bb15e9) - - [Hash functions](#org493047f) - - [Symmetric key encryption](#orgfeffc67) -- [Standardising the interfaces: The Device Model](#org928676a) -- [Optimisations](#org794b483) - - [Likely and Unlikely conditions](#org3cf58b1) -- [Common Pitfalls](#org054ce97) - - [Using standard libraries](#org2e88bab) - - [Disabling interrupts](#org5dbf3ea) - - [Sticking your head inside a large carnivore](#org7469865) -- [Where To Go From Here?](#org13b2a09) +- [Introduction](#org8109f2d) + - [Authorship](#org9c42cbd) + - [Versioning and Notes](#orgfb5c10c) + - [Acknowledgements](#org1ca202c) + - [What Is A Kernel Module?](#org5747166) + - [Kernel module package](#org13aaf49) + - [What Modules are in my Kernel?](#org32b9977) + - [Do I need to download and compile the kernel?](#orga73e0f0) + - [Before We Begin](#orgc3985d3) +- [Headers](#org5d1b0d9) +- [Examples](#org0c6dad0) +- [Hello World](#orga94c681) + - [The Simplest Module](#orgf7fef59) + - [Hello and Goodbye](#org92b45d5) + - [The \_\_init and \_\_exit Macros](#org1bfa18e) + - [Licensing and Module Documentation](#org82276f4) + - [Passing Command Line Arguments to a Module](#orge14733b) + - [Modules Spanning Multiple Files](#org15bc43d) + - [Building modules for a precompiled kernel](#orgd5ee25d) +- [Preliminaries](#org93db19c) + - [How modules begin and end](#orgfa2eca4) + - [Functions available to modules](#orgf8a274b) + - [User Space vs Kernel Space](#org6d1a8e2) + - [Name Space](#org6aaf8dd) + - [Code space](#orgbf6043c) + - [Device Drivers](#org35013aa) +- [Character Device drivers](#org95b7e50) + - [The file\_operations Structure](#org912203e) + - [The file structure](#orgc3f437e) + - [Registering A Device](#org2105684) + - [Unregistering A Device](#orgd672b69) + - [chardev.c](#org0fe351e) + - [Writing Modules for Multiple Kernel Versions](#orgaa13723) +- [The /proc File System](#org78194dc) + - [Read and Write a /proc File](#org5d232ad) + - [Manage /proc file with standard filesystem](#orgf918b99) + - [Manage /proc file with seq\_file](#org4c4f646) +- [sysfs: Interacting with your module](#org30eb8bf) +- [Talking To Device Files](#orgb3b5532) +- [System Calls](#org0e1baaf) +- [Blocking Processes and threads](#org06cc64b) + - [Sleep](#org9b512d6) + - [Completions](#orgc330b80) +- [Avoiding Collisions and Deadlocks](#orga6e1dd6) + - [Mutex](#org793fca9) + - [Spinlocks](#org725ffbb) + - [Read and write locks](#org4890337) + - [Atomic operations](#org15ea1f6) +- [Replacing Print Macros](#orgf762ab7) + - [Replacement](#org5681eb9) + - [Flashing keyboard LEDs](#orgd052bde) +- [Scheduling Tasks](#org3320952) + - [Tasklets](#org8743433) + - [Work queues](#org9113631) +- [Interrupt Handlers](#org7ef9562) + - [Interrupt Handlers](#orge6ca883) + - [Detecting button presses](#org5a62636) + - [Bottom Half](#orgb4deed3) +- [Crypto](#orge0e6336) + - [Hash functions](#org0a5ac97) + - [Symmetric key encryption](#org44ee933) +- [Standardising the interfaces: The Device Model](#orga6368a0) +- [Optimisations](#org2933656) + - [Likely and Unlikely conditions](#orgc8b3cae) +- [Common Pitfalls](#org6f5c18d) + - [Using standard libraries](#org1774b47) + - [Disabling interrupts](#org961e759) + - [Sticking your head inside a large carnivore](#org340a748) +- [Where To Go From Here?](#orge4e872f) ::: ::: -::: {#outline-container-org32fcb39 .outline-2} -Introduction {#org32fcb39} +::: {#outline-container-org8109f2d .outline-2} +Introduction {#org8109f2d} ------------ -::: {#text-org32fcb39 .outline-text-2} +::: {#text-org8109f2d .outline-text-2} The Linux Kernel Module Programming Guide is a free book; you may reproduce and/or modify it under the terms of the Open Software License, version 3.0. @@ -116,10 +116,10 @@ LDP. If you have questions or comments, please contact the address above. ::: -::: {#outline-container-org70042fe .outline-3} -### Authorship {#org70042fe} +::: {#outline-container-org9c42cbd .outline-3} +### Authorship {#org9c42cbd} -::: {#text-org70042fe .outline-text-3} +::: {#text-org9c42cbd .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-org6bc9d50 .outline-3} -### Versioning and Notes {#org6bc9d50} +::: {#outline-container-orgfb5c10c .outline-3} +### Versioning and Notes {#orgfb5c10c} -::: {#text-org6bc9d50 .outline-text-3} +::: {#text-orgfb5c10c .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-orgaf14f92 .outline-3} -### Acknowledgements {#orgaf14f92} +::: {#outline-container-org1ca202c .outline-3} +### Acknowledgements {#org1ca202c} -::: {#text-orgaf14f92 .outline-text-3} +::: {#text-org1ca202c .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-orge8302b7 .outline-3} -### What Is A Kernel Module? {#orge8302b7} +::: {#outline-container-org5747166 .outline-3} +### What Is A Kernel Module? {#org5747166} -::: {#text-orge8302b7 .outline-text-3} +::: {#text-org5747166 .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-org018252e .outline-3} -### Kernel module package {#org018252e} +::: {#outline-container-org13aaf49 .outline-3} +### Kernel module package {#org13aaf49} -::: {#text-org018252e .outline-text-3} +::: {#text-org13aaf49 .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-org86a2fb0 .outline-3} -### What Modules are in my Kernel? {#org86a2fb0} +::: {#outline-container-org32b9977 .outline-3} +### What Modules are in my Kernel? {#org32b9977} -::: {#text-org86a2fb0 .outline-text-3} +::: {#text-org32b9977 .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-orgab5e696 .outline-3} -### Do I need to download and compile the kernel? {#orgab5e696} +::: {#outline-container-orga73e0f0 .outline-3} +### Do I need to download and compile the kernel? {#orga73e0f0} -::: {#text-orgab5e696 .outline-text-3} +::: {#text-orga73e0f0 .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-org6362ee1 .outline-3} -### Before We Begin {#org6362ee1} +::: {#outline-container-orgc3985d3 .outline-3} +### Before We Begin {#orgc3985d3} -::: {#text-org6362ee1 .outline-text-3} +::: {#text-orgc3985d3 .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. ::: -- []{#org40a7d83}Modversioning\ - ::: {#text-org40a7d83 .outline-text-5} +- []{#org3d48667}Modversioning\ + ::: {#text-org3d48667 .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. ::: -- []{#org25fc457}Using X\ - ::: {#text-org25fc457 .outline-text-5} +- []{#org75e63eb}Using X\ + ::: {#text-org75e63eb .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-orga551762 .outline-2} -Headers {#orga551762} +::: {#outline-container-org5d1b0d9 .outline-2} +Headers {#org5d1b0d9} ------- -::: {#text-orga551762 .outline-text-2} +::: {#text-org5d1b0d9 .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.12.12-1-amd64 ::: ::: -::: {#outline-container-org9ab6de9 .outline-2} -Examples {#org9ab6de9} +::: {#outline-container-org0c6dad0 .outline-2} +Examples {#org0c6dad0} -------- -::: {#text-org9ab6de9 .outline-text-2} +::: {#text-org0c6dad0 .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-org2bf67ab .outline-2} -Hello World {#org2bf67ab} +::: {#outline-container-orga94c681 .outline-2} +Hello World {#orga94c681} ----------- -::: {#text-org2bf67ab .outline-text-2} +::: {#text-orga94c681 .outline-text-2} ::: -::: {#outline-container-orgaf987a8 .outline-3} -### The Simplest Module {#orgaf987a8} +::: {#outline-container-orgf7fef59 .outline-3} +### The Simplest Module {#orgf7fef59} -::: {#text-orgaf987a8 .outline-text-3} +::: {#text-orgf7fef59 .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. ::: -- []{#org7647c25}A point about coding style\ - ::: {#text-org7647c25 .outline-text-5} +- []{#org8a2027e}A point about coding style\ + ::: {#text-org8a2027e .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. ::: -- []{#org81205a7}Introducing print macros\ - ::: {#text-org81205a7 .outline-text-5} +- []{#orgf86ec38}Introducing print macros\ + ::: {#text-orgf86ec38 .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. ::: -- []{#orgcf4532f}About Compiling\ - ::: {#text-orgcf4532f .outline-text-5} +- []{#org8dfdffe}About Compiling\ + ::: {#text-org8dfdffe .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-org8ffa823 .outline-3} -### Hello and Goodbye {#org8ffa823} +::: {#outline-container-org92b45d5 .outline-3} +### Hello and Goodbye {#org92b45d5} -::: {#text-org8ffa823 .outline-text-3} +::: {#text-org92b45d5 .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-org11cceb2 .outline-3} -### The \_\_init and \_\_exit Macros {#org11cceb2} +::: {#outline-container-org1bfa18e .outline-3} +### The \_\_init and \_\_exit Macros {#org1bfa18e} -::: {#text-org11cceb2 .outline-text-3} +::: {#text-org1bfa18e .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-org34d76ad .outline-3} -### Licensing and Module Documentation {#org34d76ad} +::: {#outline-container-org82276f4 .outline-3} +### Licensing and Module Documentation {#org82276f4} -::: {#text-org34d76ad .outline-text-3} +::: {#text-org82276f4 .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-org3605080 .outline-3} -### Passing Command Line Arguments to a Module {#org3605080} +::: {#outline-container-orge14733b .outline-3} +### Passing Command Line Arguments to a Module {#orge14733b} -::: {#text-org3605080 .outline-text-3} +::: {#text-orge14733b .outline-text-3} Modules can take command line arguments, but not with the argc/argv you might be used to. @@ -886,10 +886,10 @@ hello-5.o: invalid argument syntax for mylong: 'h' ::: ::: -::: {#outline-container-orga436d2b .outline-3} -### Modules Spanning Multiple Files {#orga436d2b} +::: {#outline-container-org15bc43d .outline-3} +### Modules Spanning Multiple Files {#org15bc43d} -::: {#text-orga436d2b .outline-text-3} +::: {#text-org15bc43d .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-org1f65f5b .outline-3} -### Building modules for a precompiled kernel {#org1f65f5b} +::: {#outline-container-orgd5ee25d .outline-3} +### Building modules for a precompiled kernel {#orgd5ee25d} -::: {#text-org1f65f5b .outline-text-3} +::: {#text-orgd5ee25d .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-org6957bc4 .outline-2} -Preliminaries {#org6957bc4} +::: {#outline-container-org93db19c .outline-2} +Preliminaries {#org93db19c} ------------- -::: {#text-org6957bc4 .outline-text-2} +::: {#text-org93db19c .outline-text-2} ::: -::: {#outline-container-org0ed644c .outline-3} -### How modules begin and end {#org0ed644c} +::: {#outline-container-orgfa2eca4 .outline-3} +### How modules begin and end {#orgfa2eca4} -::: {#text-org0ed644c .outline-text-3} +::: {#text-orgfa2eca4 .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-org760b84a .outline-3} -### Functions available to modules {#org760b84a} +::: {#outline-container-orgf8a274b .outline-3} +### Functions available to modules {#orgf8a274b} -::: {#text-org760b84a .outline-text-3} +::: {#text-orgf8a274b .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-orgd704758 .outline-3} -### User Space vs Kernel Space {#orgd704758} +::: {#outline-container-org6d1a8e2 .outline-3} +### User Space vs Kernel Space {#org6d1a8e2} -::: {#text-orgd704758 .outline-text-3} +::: {#text-org6d1a8e2 .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-org361db02 .outline-3} -### Name Space {#org361db02} +::: {#outline-container-org6aaf8dd .outline-3} +### Name Space {#org6aaf8dd} -::: {#text-org361db02 .outline-text-3} +::: {#text-org6aaf8dd .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-org3ce918a .outline-3} -### Code space {#org3ce918a} +::: {#outline-container-orgbf6043c .outline-3} +### Code space {#orgbf6043c} -::: {#text-org3ce918a .outline-text-3} +::: {#text-orgbf6043c .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 @@ -1292,10 +1292,10 @@ Magenta kernel of Google Fuchsia are two examples of a microkernel. ::: ::: -::: {#outline-container-org1b87707 .outline-3} -### Device Drivers {#org1b87707} +::: {#outline-container-org35013aa .outline-3} +### Device Drivers {#org35013aa} -::: {#text-org1b87707 .outline-text-3} +::: {#text-org35013aa .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. ::: -- []{#orge0103b3}Major and Minor Numbers\ - ::: {#text-orge0103b3 .outline-text-5} +- []{#orge66dbba}Major and Minor Numbers\ + ::: {#text-orge66dbba .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: @@ -1411,17 +1411,17 @@ Ensoniq IS1370 sound card. A userspace program like mp3blaster can use ::: ::: -::: {#outline-container-org052dca4 .outline-2} -Character Device drivers {#org052dca4} +::: {#outline-container-org95b7e50 .outline-2} +Character Device drivers {#org95b7e50} ------------------------ -::: {#text-org052dca4 .outline-text-2} +::: {#text-org95b7e50 .outline-text-2} ::: -::: {#outline-container-org0989cfb .outline-3} -### The file\_operations Structure {#org0989cfb} +::: {#outline-container-org912203e .outline-3} +### The file\_operations Structure {#org912203e} -::: {#text-org0989cfb .outline-text-3} +::: {#text-org912203e .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 @@ -1516,10 +1516,10 @@ named fops. ::: ::: -::: {#outline-container-org9d35c9c .outline-3} -### The file structure {#org9d35c9c} +::: {#outline-container-orgc3f437e .outline-3} +### The file structure {#orgc3f437e} -::: {#text-org9d35c9c .outline-text-3} +::: {#text-orgc3f437e .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 @@ -1538,10 +1538,10 @@ only use structures contained in file which are created elsewhere. ::: ::: -::: {#outline-container-orgc230f23 .outline-3} -### Registering A Device {#orgc230f23} +::: {#outline-container-org2105684 .outline-3} +### Registering A Device {#org2105684} -::: {#text-orgc230f23 .outline-text-3} +::: {#text-org2105684 .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,15 +1585,15 @@ device file by hand. Second, the newly registered device will have an entry in **/proc/devices**, and we can either make the device file by hand or write a shell script to read the file in and make the device file. The third method is we can have our driver make the the device -file using the mknod system call after a successful registration and rm -during the call to cleanup\_module. +file using the **device\_create** function after a successful +registration and **device\_destroy** during the call to cleanup\_module. ::: ::: -::: {#outline-container-org45f597a .outline-3} -### Unregistering A Device {#org45f597a} +::: {#outline-container-orgd672b69 .outline-3} +### Unregistering A Device {#orgd672b69} -::: {#text-org45f597a .outline-text-3} +::: {#text-orgd672b69 .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 @@ -1627,10 +1627,10 @@ sooner or later during a module\'s development. ::: ::: -::: {#outline-container-org729a75c .outline-3} -### chardev.c {#org729a75c} +::: {#outline-container-org0fe351e .outline-3} +### chardev.c {#org0fe351e} -::: {#text-org729a75c .outline-text-3} +::: {#text-org0fe351e .outline-text-3} The next code sample creates a char driver named chardev. You can cat its device file. @@ -1658,7 +1658,15 @@ data and print a message acknowledging that we received it. #include