Copyright (C) 2000-2012 |
Whole document tree 11. Writing Your Own Loadable Kernel ModuleThe Linux Kernel Module Programming Guide by Ori Pomerantz is a complete explanation of writing your own LKM. This book is also available in print. It is, however, a little out of date and contains an error or two. Here are a few things about writing an LKM that aren't in there. 11.1. bug in hello.cThe simple hello.c program has a small bug that causes it to generate a warning about an implicit declaration of printk(). The warning is innocuous. The program is also more complicated than it needs to be with current Linux and depends on your having kernel messaging set up a certain way on your system to see it work. Finally, the program requires to to include -D options on your compile command to work, because it does not define some macros in the source code, where the definition belongs. Here is an improved version of hello.c. Compile this with the simple command
11.2. Rubini: Linux Device DriversThe most popular book on writing device drivers is O'Reilly's Linux Device Drivers by Alessandro Rubini. Even if you're writing an LKM that isn't a device driver, you can learn a lot from this book that will help you. The first edition of this book covers Linux 2.0, with notes about differences in 2.2. The second edition covers Linux 2.4. 11.3. Improving On Use CountsIn the original design, the LKM increments and decrements its use count to tell the module manager whether it is OK to unload it. For example, if it's a filesystem driver, it would increment the use count when someone mounts a filesystem of the type it drives, and decrement it at unmount time. Now, there is a more flexible alternative. Your LKM can register a function that the module manager will call whenever it wants to know if it is OK to unload the module. If the function returns a true value, that means the LKM is busy and cannot be unloaded. If it returns a false value, the LKM is idle and can be unloaded. The module manager holds the big kernel lock from before calling the module-busy function until after its cleanup subroutine returns or sleeps, and unless you've done something odd, that should mean that your LKM cannot become busy between the time that you report "not busy" and the time you clean up. So how do you register the module-busy function? By putting its address in the unfortunately named can_unload field in the module descriptor ("struct module"). The name is truly unfortunate because the boolean value it returns is the exact opposite of what "can unload" means: true if the module manager cannot unload the LKM. The module manager ensures that it does not attempt to unload the module before its initialization subroutine has returned or sleeps, so you are safe in setting the can_unload field anywhere in the initialization subroutine except after a sleep. |