Writing Your First Kernel Module – Part 2
local graph
Chapter 5 — Writing Your First Kernel Module – Part 2
Section titled “Chapter 5 — Writing Your First Kernel Module – Part 2”This chapter is the second half of our coverage regarding the Loadable Kernel Module (LKM) framework and how to write kernel modules using it.To get the most out of it, I expect you to complete the previous chapter and try out the code and questions/exercises there before tackling this one.
In this chapter, we will continue from the point where we left off in the previous one. Here, we cover making use of a “better” Makefile for LKMs, cross-compiling a kernel module for the ARM platform (as a typical example), what module stacking is and how to do it, and how to set up and use module parameters. Along the way, among several other things, you will learn about the kernel API/ABI stability (or rather, the lack thereof!), the key differences between writing user-space and kernel code, auto-loading a kernel module at system boot, and security concerns and how they can be addressed. We end with information on the kernel documentation (including coding style) and how one gets started on contributing to the mainline kernel.
In brief, we will cover the following topics in this chapter:
- A “better” Makefile template for your kernel modules
- Cross-compiling a kernel module
- Gathering minimal system information
- Licensing kernel modules
- Emulating “library-like” features for kernel modules
- Passing parameters to a kernel module
- Floating point not allowed in the kernel
- Auto-loading modules on system boot
- Kernel modules and security – an overview
- Coding style guidelines for kernel developers
- Contributing to the mainline kernel
Technical requirements
Section titled “Technical requirements”The technical requirements – the software packages required – for this chapter are identical to what was shown in the Technical requirements section in Chapter 4, Writing Your First Kernel Module – Part 1; please refer to it. As always, you can find the source code for this chapter in this book’s GitHub repository. Clone it with the following:
git clone https://github.com/PacktPublishing/Linux-Kernel-Programming_2EThe code displayed in the book is often just a relevant snippet. Follow along with the full source code from the repository.
A “better” Makefile template for your kernel modules
Section titled “A “better” Makefile template for your kernel modules”The preceding chapter introduced you to the Makefile used to generate the kernel module from the source code, to install and clean it up. However, as we briefly mentioned there, I will now introduce what is, in my opinion, a superior, so-called “better” Makefile, and explain how it’s better.
Ultimately, we all must write better and more secure code – both user- and kernel-space. The good news is that there are several tools to help improve your code’s robustness and security posture, static and dynamic analyzers being among them (as several have already been mentioned in Online Chapter, Kernel Workspace Setup, I won’t repeat them here).
I have devised a simple yet useful Makefile “template” of sorts for kernel modules that includes several targets that help you run these tools. These targets allow you to perform valuable checks and analysis very easily; stuff you might otherwise forget, ignore, or put off forever! These targets include the following:
- The “usual” ones – the
build (all),install, andcleantargets (taking into account a “debug” setting, stripping the module if debug is off). - Kernel coding style generation and checking (via
indentand the kernel’scheckpatch.plscript). - Kernel static analysis targets (
sparse,gcc, andflawfinder), with a mention of Coccinelle. - A couple of dummy kernel dynamic analysis targets pointing out how you should invest time in configuring and building a “debug” kernel and using it to catch bugs (via
KASANandLOCKDEP/CONFIG_PROVE_LOCKING; more on this follows shortly) - A simple
tarxz-pkgtarget that tars and compresses the source files into the parent directory. This enables you to transfer the compressedtar-xzfile to any other Linux system, then extract and build the LKM there.
You can find the code (along with a README file as well) in the ch5/lkm_template directory. To help you understand its use and power and get started, the following figure simply shows the output and a screenshot of the output the code produces when you do make <tab><tab> and run make help:
lkm_template $ make <tab><tab>all clean help install sa sa_flawfinder sa_sparsecheckpatch code-style indent nsdeps sa_cppcheck sa_gcc tarxz-pkg
Figure 5.1: The output of the help target from our “better” Makefile
As we can see in Figure 5.1, we type make, immediately followed by pressing the Tab key twice, thus having it display all available targets (you might need the Bash completion package installed for stuff like this to work; it’s usually installed on most distros). Do study this carefully and use it! For example, running make sa (see the sa target in Figure 5.1 along with the other ones) will cause it to run all the static analysis (sa) targets on your code.
Note how the line beginning with FYI: KDIR=… (highlighted) shows the Makefile’s current understanding of various variables and “settings.” We’ve reproduced it here:
FYI: KDIR=/lib/modules/6.1.25-lkp-kernel/build ARCH= CROSS_COMPILE= ccflags-y="-UDEBUG -DDYNAMIC_DEBUG_MODULE" MYDEBUG=n DBG_STRIP=nIn the Makefile, we use a variable named MYDEBUG to determine whether we perform a ‘debug’ build. Clearly, with the MYDEBUG variable being set to n by default, we’re not performing a so-called debug build (the next section delves into what exactly this means).
Also, our variable DBG_STRIP=n essentially says to make : don’t strip the module object of debug ‘symbols.’ Actually, it’s set to y by default; our Makefile has the intelligence to strip debug symbols (don’t ever strip anything more from a module!) only if MYDEBUG is n (off) and if the kernel config is not using the module-signing feature (which needs symbols; we cover this aspect later in this chapter). The KDIR variable is the path to the (limited) kernel source tree, the kernel headers really, and is the usual value; the ARCH and CROSS_COMPILE variables are null by default as we aren’t cross-compiling the module.
Okay, let’s use this “better” Makefile to simply build our “template” module, then insert it, remove it, and see that the kernel printk's do show up (the screenshot in Figure 5.2 reveals the output):

Figure 5.2: Building our lkm_template module with the “better” Makefile and trying it out (on our x86_64 Ubuntu guest)
It’s important to note that to fully exploit this “better” Makefile, you will need to have installed a few packages/apps on the system; these include (for a base Ubuntu system) indent(1), linux-headers-$(uname -r), sparse(1), flawfinder(1), cppcheck(1), and tar(1). (Online Chapter, Kernel Workspace Setup, already specified that these should be installed. Also, running our ch1/pkg_install4ubuntu_lkp.sh script (on Ubuntu) will ensure they’re installed.)
Also, note that the so-called dynamic analysis (da) targets mentioned in the Makefile are merely dummy targets that don’t do anything other than print a message. They are there to remind you to thoroughly test your code by running it on an appropriately configured “debug” kernel!
Speaking of a “debug” kernel, the next section shows you the basics of how to configure one.
Configuring a “debug” kernel
Section titled “Configuring a “debug” kernel”For details on configuring and building the kernel, look back to Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, and Chapter 3, Building the 6.x Linux Kernel from Source – Part 2.
Running your code on a debug kernel can help you uncover hard-to-spot bugs and issues. I highly recommend doing so, typically during development and testing!
In effect, you should have two kernels to run and test your work on: the carefully-configured-for-optimization regular production kernel, as well as a debug kernel, deliberately configured such that many kernel debug options are enabled (perhaps unoptimized but the idea is to use it to catch bugs).
Here, I minimally expect you to configure your custom 6.1 kernel to have the following kernel debug config options turned on (that is, set to y; you’ll find them within the make menuconfig UI, and you will find most of them under the Kernel Hacking sub-menu; the following list is with respect to Linux 6.1.25):
CONFIG_DEBUG_KERNELandCONFIG_DEBUG_INFOCONFIG_DEBUG_MISC- Generic kernel debugging instruments:
CONFIG_MAGIC_SYSRQ(the magic SysRq hotkeys feature)CONFIG_DEBUG_FS(thedebugfspseudo filesystem)CONFIG_KGDB(kernel GDB; optional, recommended)CONFIG_UBSAN(the undefined behaviour sanity checker)CONFIG_KCSAN(the dynamic data race detector)
- Memory debugging:
CONFIG_SLUB_DEBUGCONFIG_DEBUG_MEMORY_INITCONFIG_KASAN: The powerful Kernel Address Sanitizer (KASAN) memory checker
CONFIG_DEBUG_SHIRQCONFIG_SCHED_STACK_END_CHECKCONFIG_DEBUG_PREEMPT- Lock debugging:
CONFIG_PROVE_LOCKING: The very powerfullockdepfeature to catch locking bugs! This turns on several other lock debug configs as well, explained in Chapter 13, Kernel Synchronization – Part 2.CONFIG_LOCK_STAT.CONFIG_DEBUG_ATOMIC_SLEEP.
CONFIG_BUG_ON_DATA_CORRUPTIONCONFIG_STACKTRACECONFIG_DEBUG_BUGVERBOSECONFIG_FTRACE(ftrace: Within its sub-menu, turn on at least a couple of “tracers,” including the ‘Kernel Function [Graph] Tracer’)CONFIG_BUG_ON_DATA_CORRUPTIONArch-specific(shows up under “x86 Debugging” on the x86):CONFIG_EARLY_PRINTK(arch-specific)CONFIG_DEBUG_BOOT_PARAMSCONFIG_UNWINDER_FRAME_POINTER(selectsFRAME_POINTERandCONFIG_STACK_VALIDATION)
A few things to note:
a) Don’t worry too much right now if you don’t get what all the previously mentioned kernel debug config options do; by the time you’re done with this book, many of them will be clear.
b) Turning on some Ftrace tracers (or plugins), such as CONFIG_IRQSOFF_TRACER, would be useful as we actually make use of them in our Linux Kernel Programming – Part 2 companion volume book in the Handling Hardware Interrupts chapter (note that while Ftrace itself may be enabled by default, all its tracers aren’t).
c) Detailed coverage on tuning and building a debug kernel can be found in the Linux Kernel Debugging book.
Note that turning on these config options does entail a performance hit, but that’s okay. We’re running a “debug” kernel of this sort for the express purpose of catching errors and bugs (especially the hard-to-uncover kind!). It can indeed be a life-saver! On your project, your workflow should involve your code being tested and run on both of the following:
- The debug kernel system, where all required kernel debug config options are turned on (as previously shown minimally)
- The production kernel system (where perhaps most of the preceding kernel debug options will be turned off; note that having a few so-called “debug” kernel configs enabled even in production can be extremely helpful).
Needless to say, we will be using the preceding “better” Makefile in all the subsequent LKM code in this book.
Alright, now that you’re all set, let’s dive into an interesting and practical scenario – compiling your kernel module(s) for another target (typically ARM).
Cross-compiling a kernel module
Section titled “Cross-compiling a kernel module”In Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, in the Kernel build for the Raspberry Pi section,we showed you how we can cross-compile the Linux kernel for a “foreign” target architecture (such as ARM[64], PowerPC, MIPS, and so on). Essentially, the same can be done for a kernel module as well; you can easily cross-compile a kernel module by setting up a cross-toolchain as well as the “special” ARCH and CROSS_COMPILE environment variables appropriately.
For example, let’s imagine we are working on an embedded Linux product; the target device on which our code will run has an AArch64 (ARM-64) CPU. Why not take an actual example: let’s cross-compile our ch5/lkm_template kernel module for the Raspberry Pi 4 Single-Board Computer (SBC)!
This is interesting. You will find that although it appears simple and straightforward, we will end up taking four iterations before we succeed. Why? Read on to find out.
FYI, I have summarized what you’ll learn in the following sections during four attempts to cross-build and load the kernel module in the upcoming section Summarizing what went wrong with the module cross-build/load and how it was fixed. (I do suggest that, at least on first reading, you first read the full notes to understand the details before looking at the summary).
First, though, we definitely require an appropriate cross-toolchain setup, so let’s cover that now.
Setting up the system for cross-compilation
Section titled “Setting up the system for cross-compilation”The prerequisites to cross-compile a kernel module are quite clear:
- We need the kernel source tree for the target system installed as part of the workspace on our host system, typically an x86_64 desktop (for our example, using the Raspberry Pi as a target; please refer to the official Raspberry Pi documentation here: https://www.raspberrypi.org/documentation/linux/kernel/building.md).
- We now need a cross toolchain (host-to-target). Typically, the host system is an x86_64 and here, as the target is an ARM-64, we will need an x86_64-to-ARM64 cross toolchain. Again, as is clearly mentioned in Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, in the Kernel build for the Raspberry Pi section, you must install the Raspberry Pi-specific x86_64-to-ARM toolchain as part of the host system workspace (if you haven’t already set up the toolchain, refer to the just-mentioned location to learn how to install it).
Quick tip: If you haven’t already, install the aarch64-linux-gnu cross-compiler with sudo apt install gcc-aarch64-linux-gnu binutils-aarch64-linux-gnu.
Okay, from this point on, I will assume that you have these prerequisites among the things we covered in Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, in the section Kernel build for the Raspberry Pi: you have the Raspberry Pi 6.1.34 kernel source tree and an x86_64-to-ARM64 cross toolchain installed. Thus, I shall also assume the toolchain prefix is aarch64-linux-gnu; we can quickly check that the toolchain is installed and its binaries added to the path by trying to invoke the gcc cross-compiler:
$ aarch64-linux-gnu-gccaarch64-linux-gnu-gcc: fatal error: no input filescompilation terminated.It works – it’s just that we have not passed any C program as a parameter to compile, hence it complains.
You can certainly look up the compiler version as well, with the aarch64-linux-gnu-gcc --version command (and more with the -v option switch). As an aside, a modern alternative to GCC is the Clang toolchain; it’s quite heavily used these days (including by Android AOSP) and is even superior to GCC in some respects (see the Further reading section for more on cross-compilation with Clang). Here, we continue to use GCC, native and cross, compilers.
Okay, let’s now dive into cross-compiling our module for the Raspberry Pi device!
Attempt 1 – setting the ARCH and CROSS_COMPILE environment variables
Section titled “Attempt 1 – setting the ARCH and CROSS_COMPILE environment variables”Cross-compiling the kernel module is very easy (or so we think!). First, ensure that you set the “special” ARCH and CROSS_COMPILE environment variables appropriately. Follow along with these steps:
- Let’s re-build our just discussed
lkm_templatekernel module for the Raspberry Pi target; this also has the advantage of employing the so-called “better” Makefile. Here’s how to build it:
To do so without corrupting the original code, make a new folder called cross with a copy of the code to begin with. (BTW, the codebase already has it set up, here: ch5/cross.)
cd <book-dir>/ch5; mkdir cross ; cd crosscp ../lkm_template/lkm_template.c ../lkm_template/Makefile .Here, <book-dir> is the root of this book’s GitHub source tree.
- Now, run the following command (we assume the cross-compiler tools are in the path):
make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu-
(By the way, the book codebase has a small wrapper script, ch5/cross/buildit, that performs a couple of validity checks and runs this command for you.) But it doesn’t work (or it may work; please see the following materials) straight off the bat. We get compile failures, as seen here:
$ make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu---- Building : KDIR=~/arm64_prj/kernel/linux ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- ccflags-y="-UDEBUG -DDYNAMIC_DEBUG_MODULE" MYDEBUG=n ---aarch64-linux-gnu-gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0make -C ~/arm64_prj/kernel/linux M=/home/c2kp/Linux-Kernel-Programming_2E/ch5/cross modulesmake[1]: *** /home/c2kp/arm64_prj/kernel/linux: No such file or directory. Stop.make: *** [Makefile:93: all] Error 2$(Notice how, this time, the ARCH and CROSS_COMPILE environment variables are correctly defined.) Why did it fail?
The clue as to why the preceding cross-compilation attempt failed lies in the fact that it is attempting to use – build against – the kernel source tree of the current host system and not the target’s kernel source tree. So, we need to modify the Makefile to point it to the correct kernel source tree, the one for the target. It’s quite easy to do so. In the following code, we see the typical way that the (corrected) Makefile code is written:
# ch5/cross/Makefile:# To support cross-compiling for kernel modules:# For architecture (cpu) 'arch', invoke make as:# make ARCH=<arch> CROSS_COMPILE=<cross-compiler-prefix>[ ... ]else ifeq ($(ARCH),arm64) # *UPDATE* 'KDIR' below to point to the ARM64 (Aarch64) Linux kernel source # tree on your box #KDIR ?= ~/arm64_prj/kernel/linux KDIR ?= ~/rpi_work/kernel_rpi/linuxelse ifeq ($(ARCH),powerpc) [ ... ]else [ … ]endif[ ... ]# IMPORTANT :: Set FNAME_C to the kernel module name source filename (without .c)FNAME_C := lkm_templatePWD := $(shell pwd)obj-m += ${FNAME_C}.o[ ... ]all: @echo @echo '--- Building : KDIR=${KDIR} ARCH=${ARCH} CROSS_COMPILE=${CROSS_COMPILE} ccflags-y="${ccflags-y}" MYDEBUG=${MYDEBUG} DBG_STRIP=${DBG_STRIP} ---' @echo make -C $(KDIR) M=$(PWD) modules[...]Look carefully at the (new and “better,” as explained in the preceding section) Makefile and you will see how it works:
- Most importantly, we conditionally set the
KDIRvariable to point to the correct kernel source tree, depending on the value of theARCHenvironment variable (of course, I’ve used a sample pathname to kernel source trees for the ARM-32 and PowerPC as examples; do substitute the pathname with the actual path to your kernel source trees). - As usual, we set
obj-mto the object filename. - You can set the variable
ccflags-y(CFLAGS_EXTRAis considered deprecated) to add theDEBUGsymbol (so that theDEBUGsymbol is defined in our LKM and thepr_debug()/dev_dbg()macros work). The ‘debug’ build’s off by default. - The
@echo '<...>'lines are equivalent to the shell’sechocommand; it just emits some useful information while building (the@prefix hides the echo statement itself from displaying). - Finally, we have the “usual” Makefile targets:
all,install, andclean.Pay attention to how, within them, when invokingmake, we ensure we change directory via the-Cswitch to the value ofKDIR! - Though not shown in the preceding code, this “better” Makefile – at the risk of repetition – has several additional useful targets. You should definitely take the time to explore and use them (as explained in the preceding section; to start, simply type
make help, study the output, and try things out).
Having done this, let’s retry the module cross-compile with this version and see how it goes.
Attempt 2 – pointing the Makefile to the correct kernel source tree for the target
Section titled “Attempt 2 – pointing the Makefile to the correct kernel source tree for the target”So now, with the enhanced and fixed Makefile described in the previous section, it should work. In our new directory where we will try this out – cross (as we’re cross-compiling, not that we’re angry!) – follow along with these steps:
- Attempt the build (for a second time) with the
makecommand appropriate for cross-compilation:$ make ARCH=arm CROSS_COMPILE=arm-linux-gnueabihf-[ ... ]CC [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/lkm_template.oMODPOST /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/Module.symversERROR: modpost: "_printk" [/home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/lkm_template.ko] undefined!make[2]: *** [scripts/Makefile.modpost:126: /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/Module.symvers] Error 1[ ... ]
Oops. This time we have a modpost error. In this module build stage, MODPOST, the build system must be able to access and check all exported kernel symbols. This very information is stored in the file Module.symvers (in the root of the kernel source tree). It’s typically generated just after the modules are built (during the kernel build procedure). We can get this modpost failure – as we just did – when this file isn’t present. So, to fix this in one shot, I simply cleaned up my (Raspberry Pi) kernel source tree (with make mrproper) and then rebuilt it; the Module.symvers file now did indeed turn up and the build went through:
[ … ]rpi $ make ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu---- Building : KDIR=~/rpi_work/kernel_rpi/linux ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- ccflags-y="-UDEBUG -DDYNAMIC_DEBUG_MODULE" MYDEBUG=n ---aarch64-linux-gnu-gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0make -C ~/rpi_work/kernel_rpi/linux M=/home/c2kp/Linux-Kernel-Programming_2E/ch5/cross modulesmake[1]: Entering directory '/home/c2kp/rpi_work/kernel_rpi/linux' CC [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/lkm_template.o MODPOST /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/Module.symvers CC [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/lkm_template.mod.o LD [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/cross/lkm_template.komake[1]: Leaving directory '/home/c2kp/rpi_work/kernel_rpi/linux'if [ "n" != "y" ]; then \ sudo aarch64-linux-gnu-strip --strip-debug lkm_template.ko ; \fi- Ah, the cross-compile build did work! Let’s see the freshly built module:
$ ls -l ./lkm_template.ko-rw-rw-r-- 1 c2kp c2kp [ … ] ./lkm_template.ko$ file ./lkm_template.ko./lkm_template.ko: ELF 64-bit LSB relocatable, ARM aarch64, version 1 (SYSV), BuildID[sha1]=03<...>4, not stripped
The reality of course is that the build might fail for several reasons, not just the ones that happen to be seen here… In another instance, it failed as the target kernel source tree that we’re compiling our kernel module against was still in a “virgin” state. It perhaps does not even have the .config file present (as well as other required headers) in its root directory, which it requires to (at least) be configured. To fix this, you’ll have to configure and cross-compile the kernel in the usual manner, then retry the module build.
Attempt 3 – cross-compiling our kernel module
Section titled “Attempt 3 – cross-compiling our kernel module”Now that we have generated the cross-compiled kernel module using a properly configured Raspberry Pi kernel source tree (on the host system with the Module.symvers file present; see the Attempt 2 – pointing the Makefile to the correct kernel source tree for the target section), it should work on the board (hey, we’re optimists).
Of course, the proof of the pudding is in the eating. So, we fire up our Raspberry Pi, scp across our cross-compiled kernel module object file to it, and as follows (within an ssh session on the Raspberry Pi), try it out (the following output is directly from the device):
$ sudo insmod ./lkm_template.koinsmod: ERROR: could not insert module ./lkm_template.ko: Invalid module formatClearly, the insmod has failed! It’s important to understand why. It’s because there is a mismatch between the kernel version that we’re attempting to load the module on and the kernel version the module has been compiled against.
While logged in to the Raspberry Pi, let’s print out the current Raspberry Pi kernel version we’re running on and use the modinfo utility to print out details regarding the kernel module itself:
rpi $ cat /proc/versionLinux version 6.1.21-v8+ (dom@buildbot) (aarch64-linux-gnu-gcc-8 (Ubuntu/Linaro 8.4.0-3ubuntu1) 8.4.0, GNU ld (GNU Binutils for Ubuntu) 2.34) #1642 SMP PREEMPT Mon Apr 3 17:24:16 BST 2023rpi $ modinfo ./lkm_template.kofilename: /home/pi/lkp2e/ch5/cross/./lkm_template.koversion: 0.2license: Dual MIT/GPLdescription: a simple LKM template; do refer to the (better) Makefile as wellauthor: Kaiwan N Billimoriasrcversion: 606276CA0788B10170FC6D5depends:name: lkm_templatevermagic: 6.1.34-v8+ SMP preempt mod_unload modversions aarch64rpi $From the preceding output, clearly, on the ARM64 Raspberry Pi board here, we’re running the 6.1.21-v8+ kernel. This, in fact, is the kernel I inherited when I installed the default Raspberry Pi OS on the device’s microSD card (it’s a deliberate scenario introduced here, at first not using the 6.1 kernel we built earlier for the Raspberry Pi). The kernel module, on the other hand, reveals that it’s been compiled against the 6.1.34-v8+ Linux kernel (the vermagic string from modinfo(8) reveals this). Clearly, there’s a mismatch. Well, so what? Read on, the next section reveals this.
Examining Linux kernel ABI compatibility issues
Section titled “Examining Linux kernel ABI compatibility issues”The Linux kernel has a rule, part of the kernel Application Binary Interface (ABI): it will only ever insert a kernel module into kernel memory if that kernel module has been built against it – the precise kernel version, build flags, and even the kernel configuration options matter!
The built-against kernel is the kernel whose source location you specified in the Makefile (we did so via the KDIR variable previously).
In other words, kernel modules are not binary-compatible with kernels other than the one they have been built against. For example, if we build a kernel module on, say, an x86_64 Ubuntu 22.04 LTS box, then it will only work on a system running this precise environment (hardware, libraries, and kernel)! It will not work (load) on a Fedora 38 or an RHEL 8.x, a Raspberry Pi, and so on, or even an x86_64 Ubuntu 22.04 box running a different kernel.
Now, importantly – and again, think about this – this does not mean that kernel modules are completely incompatible and non-portable. No, they are source-compatible across different architectures (at least they can or should be written that way). So, assuming you have the source code, you can always rebuild a kernel module on a given system and then it will work on that system. It’s just that the binary image (the .ko file) is incompatible with kernels other than the precise one it’s built against. (On some versions of the kernel, the kernel log will spell this out.) So, now it’s clear; here, there is a mismatch – between the binary module and the kernel it’s built against, and the kernel we’re attempting to run (load) it on – and hence the failure to insert the kernel module.
Though we don’t use this approach here, there is a way to ensure the successful build and deployment of third-party out-of-tree kernel modules (if their source code is available), via a framework called DKMS (Dynamic Kernel Module Support). The following is a quote directly from it:
Dynamic Kernel Module Support (DKMS) is a program/framework that enables generating Linux kernel modules whose sources generally reside outside the kernel source tree. The concept is to have DKMS modules automatically rebuilt when a new kernel is installed.
Note well: the key phrase is “… to have DKMS modules automatically rebuilt when a new kernel is installed,” which proves the point: kernel modules need to be built against precisely the kernel on which they will be deployed. As an example of DKMS usage, the Oracle VirtualBox hypervisor (when running on a Linux host) uses DKMS to auto-build and keep up to date its kernel modules.
By the way, what if you don’t have a Raspberry Pi handy to try out these experiments? No worries, you can use other ARM-based boards or even virtualization! (FYI, the SEALS project mentioned back in Chapter 1 allows very simple virtualization of an ARM-32, ARM-64, and x86_64 PC via QEMU.)
Attempt 4 – cross-compiling our kernel module
Section titled “Attempt 4 – cross-compiling our kernel module”So, now that we have understood the binary compatibility issue, there are a few possible solutions:
- We must configure, (cross) build, and boot the device with the required custom kernel for the product and build all our kernel modules against that kernel source tree.
- Use the DKMS approach.
- Alternatively, we could rebuild the kernel module to match the current kernel the Raspberry Pi device happens to be running.
Now, in typical embedded Linux projects, you will almost certainly have a custom-configured kernel for the target device, one that you must work with. All kernel modules for the product will/must be built against it. Thus, we follow the first approach – we must boot the device with our custom-configured and built (6.1.34) kernel, and since our kernel module is built against it, it should certainly work now.
We covered the kernel build for the Raspberry Pi in Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, in the Kernel build for the Raspberry Pi section*.* Refer back there for the details if required.
Okay, I will have to assume that you’ve followed the steps (covered in Chapter 3, Building the 6.x Linux Kernel from Source – Part 2,in the Kernel build for the Raspberry Pi section) and have by now configured and built a 6.x kernel for the Raspberry Pi. The nitty-gritty details regarding how to copy our custom kernel image, DTB, and module files onto the microSD card of the device and so on isn’t covered; I refer you to the official Raspberry Pi documentation here: https://www.raspberrypi.org/documentation/linux/kernel/building.md.
Nevertheless, we will point out a convenient way to switch between kernels on the device (here, I assume the device is a Raspberry Pi 4B running a 64-bit kernel):
- Copy your custom-built
Imagekernel binary into the device’s microSD card’s/bootpartition askernel8.img. (For safety, first ensure you save the original (default) Raspberry Pi kernel image askernel8.img.orig). - Copy (
scp) the just-cross-compiled kernel module (lkm_template.kofor ARM64, built in the previous section) from your host system onto the microSD card (into/home/piis fine). - [Optional] On the Raspberry Pi boards, you can specify the kernel to boot with as follows; this is not required in our case: the bootloader will automatically pick the file
kernel8.imgas the kernel to boot by default. If you’d like to specify a different kernel to boot with, on the device’s microSD card, edit the/boot/config.txtfile, setting the kernel image to boot via thekernel=xxxline. - Once saved and rebooted, we log in to the device and retry our kernel module. Figure 5.3 is a screenshot showing the just-cross-compiled
lkm_template.koLKM being used on the Raspberry Pi 4 B device:
Figure 5.3: The cross-compiled LKM being used on a Raspberry Pi 4B; see how the kernel versions, the hardware, and kernel config perfectly match
Ah, it worked! Notice how, this time, the current kernel version running on the board (6.1.34-v8+) precisely matches that of the kernel the module was built against – in the modinfo output’s vermagic line, we can see it’s 6.1.34-v8+. Whew, finally, it’s done.
If you do see an issue with rmmod throwing a non-fatal error (though the cleanup hook is still called), the reason is that you haven’t yet fully set up the newly built kernel on the device. You will have to copy in all the kernel modules (under /lib/modules/<kernel-ver>/) and run the depmod(8) utility there (as root). Here, we will not delve further into these details – as mentioned before, the official documentation for the Raspberry Pi covers all these steps.
Of course, the Raspberry Pi board is a pretty powerful system; you can install the (default) Raspberry Pi OS (a Debian derivative) along with development tools and kernel headers and thus compile kernel modules on the board itself! (No cross-compile required.) Here, though, we have followed the cross-compile approach as this is typical and required when working on embedded Linux projects.
A summary of what we’ve just learned with regard to cross-compiling kernel modules follows.
Summarizing what went wrong with the module cross-buildd/load and how it was fixed
Section titled “Summarizing what went wrong with the module cross-buildd/load and how it was fixed”Let’s summarize what we learned in this interesting section on cross-compiling a kernel module:
| Attempt # | Cause of failure to cross-compile or run | Fix |
|---|---|---|
| 1 | Module build failed because we were attempting to build the target kernel module against the kernel source tree of the current host (x86_64) system (or an invalid path specified) and not against the target’s kernel source tree. KDIR ?= /lib/modules/$(shell uname -r)/build | Modify the module Makefile to point the KDIR variable to the correct kernel source tree, that of the target system’s: KDIR ?= ~/rpi_work/kernel_rpi/linux |
| 2 | Module build failed in the MODPOST stage (due to the absence of the Module.symvers file in the target’s kernel source tree). | Implies the target kernel tree hasn’t been configured and/or built; so do so… then this file appears and it (cross) builds the module. |
| 3 | Cross-compiled module fails to load on the device (the Raspberry Pi) with the kernel citing an “Invalid module format” error. | This is due to the kernel ABI rule: the kernel will only ever insert a kernel module into kernel memory if that kernel module has been built against it. So modules have no binary compatibility across systems but can be written to be source portable. (Attempt #4 fixes it.) |
| 4 | <Same as above, Attempt #3> | The fix: we boot the device with our custom 6.1 kernel AND cross-compile our module against the same kernel (referencing it via the KDIR Makefile variable), copy the binary module onto the target’s root filesystem, and then insmod it. It works! |
Table 5.1: Summary of our attempts to cross-compile and run a kernel module from an x86_64 host to an AArch64 (Raspberry Pi 4) target
Done.
The LKM framework is a rather large piece of work. Plenty more remains to be explored. Let’s get to it. In the next section, we will examine how you can obtain some minimal system information from within a kernel module.
Gathering minimal system information
Section titled “Gathering minimal system information”At times, especially when writing a module that’s meant to be portable across various architectures (CPUs), we need to conditionally perform work based on the actual processor family we’re running upon. The kernel provides a few macros and ways to figure this out; here, we build a simple demo module (ch5/min_sysinfo/min_sysinfo.c) that, though still quite simplistic, shows a few ways to “detect” some system details (such as the CPU family, bit-width, and endian-ness). In the following code snippet, we show only the relevant function:
[ ... ]void llkd_sysinfo(void){ char msg[128]; memset(msg, 0, 128); my_snprintf_lkp(msg, 47, "%s(): minimal Platform Info:\nCPU: ", __func__); /* Strictly speaking, all this #if...#endif is considered ugly and should be * isolated as far as is possible */#ifdef CONFIG_X86#if(BITS_PER_LONG == 32) strncat(msg, "x86-32, ", 9);#else strncat(msg, "x86_64, ", 9);#endif#endif#ifdef CONFIG_ARM strncat(msg, "AArch32 (ARM-32), ", 19);#endif#ifdef CONFIG_ARM64 strncat(msg, "AArch64 (ARM-64), ", 19);#endif#ifdef CONFIG_MIPS strncat(msg, "MIPS, ", 7);#endif#ifdef CONFIG_PPC strncat(msg, "PowerPC, ", 10);#endif#ifdef CONFIG_S390 strncat(msg, "IBM S390, ", 11);#endif#ifdef __BIG_ENDIAN strncat(msg, "big-endian; ", 13);#else strncat(msg, "little-endian; ", 16);#endif#if(BITS_PER_LONG == 32) strncat(msg, "32-bit OS.\n", 12);#elif(BITS_PER_LONG == 64) strncat(msg, "64-bit OS.\n", 12);#endif pr_info("%s", msg); show_sizeof(); /* Word ranges: min & max: defines are in include/linux/limits.h */ [ ... ]}EXPORT_SYMBOL(llkd_sysinfo);Additional details that this LKM shows you – like the size of various primitive data types plus word ranges – are not shown here; please do refer to the source code from our GitHub repository and try it out for yourself.
The preceding kernel module code is instructive as it helps demonstrate how you can write portable code. Remember, the kernel module itself is a binary non-portable object file, but its source code could (perhaps, should, depending on your project) be written in such a manner so that it’s portable across various architectures. A simple build on (or for) the target architecture would then have it ready for deployment.
For now, please ignore the EXPORT_SYMBOL() macro used here. We will cover its usage shortly. Also, my_snprintf_lkp() is a simple wrapper over snprintf(), for better security, and is, for now, simply defined in the current source file (min_sysinfo.c; do check it out. FYI, once we cover more on emulating ‘library-like’ functionality, we shall define the snprintf_lkp() wrapper elsewhere; don’t worry about it now). The next section delves more into the security aspect, as do several places in the book.
Building and running it on our now familiar x86_64 Ubuntu 22.04 LTS guest, we get this output (from the sudo dmesg command onward):

Figure 5.4: Kernel output from our simple yet interesting min_sysinfo module (on our x86_64 guest)
The output from the llkd_sysinfo() function that we just saw is highlighted in a rectangle in Figure 5.4. It’s followed by the output of our llkd_sysinfo2() function (which is the same of course; its just more security-conscious, the next section covers it). It goes on to use the sizeof() operator to show the byte size of various data types; finally, our module shows the word ranges for that architecture (for all unsigned and signed 8, 16, 32, and 64 bit words).
Great! Similarly (as demonstrated earlier), we can cross-compile this kernel module for an AArch64 target, then transfer (scp) the cross-compiled kernel module and run it there (the following output is from a Raspberry Pi 4B running our custom 64-bit 6.1.34-v8+ kernel):
$ sudo insmod ./min_sysinfo.komin_sysinfo:min_sysinfo_init(): insertedmin_sysinfo:llkd_sysinfo(): llkd_sysinfo(): minimal Platform Info: CPU: AArch64 (ARM-64), little-endian; 64-bit OS.min_sysinfo:llkd_sysinfo2(): llkd_sysinfo2(): minimal Platform Info: CPU: AArch64 (ARM-64), little-endian; 64-bit OS.min_sysinfo:show_sizeof(): sizeof: (bytes) char = 1 short int = 2 int = 4 long = 8 long long = 8 void * = 8 float = 4 double = 8 long double = 16min_sysinfo:llkd_sysinfo2(): Word [U|S][8|16|32|64] ranges: unsigned max, signed max, signed min: U8_MAX = 255 = 0x ff, S8_MAX = 127 = 0x 7f, S8_MIN = -128 = 0x ffffff80 U16_MAX = 65535 = 0x ffff, S16_MAX = 32767 = 0x 7fff, S16_MIN = -32768 = 0x ffff8000 U32_MAX = 4294967295 = 0x ffffffff, S32_MAX = 2147483647 = 0x 7fffffff, S32_MIN = -2147483648 = 0x 80000000 U64_MAX = 18446744073709551615 = 0xffffffffffffffff, S64_MAX = 9223372036854775807 = 0x7fffffffffffffff, S64_MIN = -9223372036854775808 = 0x8000000000000000 PHYS_ADDR_MAX = 18446744073709551615 = 0xffffffffffffffffAgain, we can see the details this time, relevant to the AArch64 platform!
FYI, the powerful Yocto Project (https://www.yoctoproject.org/) is one (industry-standard) way to generate a complete embedded Linux BSP for the Raspberry Pi. Alternatively (and much easier to quickly try), Ubuntu provides a custom Ubuntu 64-bit kernel and root filesystem for the device (https://wiki.ubuntu.com/ARM/RaspberryPi).
I urge you to go through the code and try out this module for yourself.
Being a bit more security-aware
Section titled “Being a bit more security-aware”Security, of course, is a key concern these days. Professional developers are expected to write secure code. In recent years, there have been many known exploits against the Linux kernel (see the Further reading section for more on this). In parallel, many efforts toward improving Linux kernel security are in place.
In our preceding kernel module (ch5/min_sysinfo/min_sysinfo.c), be wary of using older-style routines (like the sprintf, strlen, and so on; yes, they’re present within the kernel)! Static analyzers can greatly aid in catching potential security-related and other bugs; we highly recommend you use them. Online Chapter, Kernel Workspace Setup, mentions several useful static analysis tools for the kernel. In the following output block, we use one of the sa targets within our “better” Makefile to run a relatively simple static analyzer: flawfinder (written by David Wheeler) against the source code in the ch5/min_sysinfo/ folder:
$ make [tab][tab]all clean help install sa sa_flawfinder sa_sparsecheckpatch code-style indent nsdeps sa_cppcheck sa_gcc tarxz-pkg$ make sa_flawfindermake cleanmake[1]: Entering directory '<...>/Linux-Kernel-Programming_2E/ch5/min_sysinfo'--- cleaning ---[...]--- static analysis with flawfinder ---flawfinder *.[ch]Flawfinder version 2.0.19, (C) 2001-2019 David A. Wheeler.Number of rules (primarily dangerous function names) in C/C++ ruleset: 222Examining min_sysinfo.cFINAL RESULTS:min_sysinfo.c:54: [2] (buffer) char: Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues (CWE-119!/CWE-120). Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length.[ … ]min_sysinfo.c:136: [1] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum size to add) [MS-banned] (CWE-120). Consider strcat_s, strlcat, snprintf, or automatically resizing strings. Risk is low because the source is a constant string.min_sysinfo.c:138: [1] (buffer) strncat: Easily used incorrectly (e.g., incorrectly computing the correct maximum[ ... ]Look carefully at the above warning emitted by flawfinder regarding the strncat() function (among the many it generates!). Following it’s advice, we use the strlcat() in its place, rewriting the code of the llkd_sysinfo() function as llkd_sysinfo2() (but why exactly? It’s written to be safer, more secure; look up the details on its man page: https://linux.die.net/man/3/strlcat). Similarly, actually leveraging the power of the snprintf() API requires checking it’s return value to see whether a (possible) buffer overflow occurred (the root cause of many vulnerabilities!); hence (as already mentioned), I wrote a simple wrapper over it, my_snprintf_lkp().
The output of flawfinder often mentions the CWE number (here, CWE-119/120) of the generalized class of security issue that is being seen here (do Google it and you will see the details). In this instance, CWE-120 represents the ‘Buffer Copy without Checking Size of Input (‘Classic Buffer Overflow’): https://cwe.mitre.org/data/definitions/120.html. As you’ll realize, Buffer Overflow defects form one of the largest classes of vulnerabilities that are frequently the target of hacking attacks (yes, even on the kernel!).
We also add a few lines of code to show the range (min, max) of both unsigned and signed variables on the platform (in both base 10 and 16). We leave it to you to read through. As a simple assignment, run this kernel module on your Linux box(es) and verify the output.
There’s much more, of course, to Linux kernel security and hardening techniques. I have spoken about these concerns and possible kernel hardening mitigations here: Mitigating Hackers with Hardening on Linux – An Overview for Developers, Focus on BoF, Kaiwan Billimoria (for the Embedded IOT Summit, Prague, June 2023): https://www.youtube.com/watch?v=KQa_XEiLGMc.
The upcoming Kernel modules and security – an overview section has some coverage on this topic. Besides, be sure to check out the numerous resources in the Further reading section of this chapter (under the Linux Kernel Security heading).
Now, let’s move on to discuss a little bit regarding the licensing of the Linux kernel and kernel module code.
Licensing kernel modules
Section titled “Licensing kernel modules”As is well known, the Linux kernel code base itself is licensed under the GNU GPL v2 (aka GPL-2.0; GPL stands for General Public License), and as far as most people are concerned will remain that way. As briefly mentioned before, in Chapter 4, Writing Your First Kernel Module – Part 1, licensing your kernel code is required and important. Let’s split up this short discussion on licensing into two portions: one, as it applies to inline kernel code (or the mainline kernel), and two, as it applies to writing third-party out-of-tree kernel modules (as many of us do).
Licensing of inline kernel code
Section titled “Licensing of inline kernel code”We begin with the first, that is, inline kernel code. A key point with regard to licensing here: if your intention is to directly use Linux kernel code and/or contribute your code upstream into the mainline kernel (we cover more on this in an upcoming section), you must release the code under the same license that the Linux kernel is released under: the GNU GPL-2.0. The details are well documented; see the official take here: https://docs.kernel.org/process/license-rules.html#linux-kernel-licensing-rules.
When new to licensing, the plethora of open-source licenses, along with their do’s and dont’s, can be perplexing, no doubt. Do check out this site to help clear up the fog: https://choosealicense.com/. Also Bootlin’s coverage on open-source licensing in their guide Embedded Linux system development training under the section Open source licenses and compliance is excellent (https://bootlin.com/doc/training/embedded-linux/embedded-linux-slides.pdf).
In order to be consistent, recent kernels have a rule: every single source file’s first line must be an SPDX (Software Package Data Exchange) license identifier (see https://spdx.org/ for details), a shorthand and concise format for expressing the license the code is released under. (Of course, scripts will require the first line to specify the interpreter.) Thus, the very first line of most C source files in the kernel is a comment regarding the SPDX license:
Licensing of out-of-tree kernel modules
Section titled “Licensing of out-of-tree kernel modules”For an out-of-tree kernel module, the situation is still a bit “fluid,” shall we say. No matter, to engage the kernel community and have them help (a huge plus), you should, or are expected to, release the code under the GNU GPL-2.0 license (though dual licensing is certainly possible and acceptable).
The license(s) that a kernel module is released under is specified in two ways:
- Via the SPDX-License-Identifier tag as (a comment in) the very first source line. This strictly applies to modules within the source tree, not always to out-of-tree modules.
- Via the
MODULE_LICENSE()macro. Do note what the official kernel documentation clearly states (https://docs.kernel.org/process/license-rules.html#id1): “ Loadable kernel modules also require a MODULE_LICENSE() tag. This tag is neither a replacement for proper source code license information (SPDX-License-Identifier) nor in any way relevant for expressing or determining the exact license under which the source code of the module is provided.”
The sole purpose of this tag is to provide sufficient information whether the module is free software or proprietary for the kernel module loader and for user space tools.
The following comment, reproduced from the include/linux/module.h kernel header, clearly shows what license “idents” are acceptable (notice the dual licensing). Obviously, the kernel community would highly recommend releasing your kernel module under the GPL-2.0 (GPL v2) and/or another similar one, such as BSD/MIT/MPL. If you are intending to contribute code upstream to the kernel mainline, it goes without saying that the GPL-2.0 alone is the license to release under:
[...]/* * The following license idents are currently accepted as indicating free * software modules * * "GPL" [GNU Public License v2 or later] * "GPL v2" [GNU Public License v2] * "GPL and additional rights" [GNU Public License v2 rights and more] * "Dual BSD/GPL" [GNU Public License v2 * or BSD license choice] * "Dual MIT/GPL" [GNU Public License v2 * or MIT license choice] * "Dual MPL/GPL" [GNU Public License v2 * or Mozilla license choice] * * The following other idents are available * * "Proprietary" [Non free products] [ ... ]It goes on to say that the usage of MODULE_LICENSE () is largely a historic and failed attempt to convey more information in the MODULE_LICENSE string. It’s main purpose now is to be able to check for and flag Proprietary modules, thus restricting their usage of symbols exported under the GPL (we’ll get to this). It also helps the community, end users, and vendors of modules to quickly vet whether the codebase is open-source or not.
FYI, the kernel source tree has a LICENSES/ directory under which you will find detailed information on relevant licenses; a quick ls on this folder reveals the sub-folders therein:
$ ls <...>/linux-6.1.25/LICENSES/deprecated/ dual/ exceptions/ preferred/We’ll leave it to you to take a look, and with this, we will leave the discussion on licensing at that; the reality is that it’s a complex topic requiring legal knowledge. You would be well advised to consult specialist legal staff (lawyers) within your company (or hire them) regarding getting the legal angle right for your product or service.
FYI, some answers to FAQs on the GPL license are addressed here: https://www.gnu.org/licenses/gpl-faq.html.
More on licensing models, not abusing the MODULE_LICENSE macro, and particularly the multi-licensing/dual-licensing one, can be found in references provided in the Further reading section of this chapter.
Now, let’s get back to the technical stuff. The next section explains how you can effectively emulate a library-like feature in kernel space.
Emulating “library-like” features for kernel modules
Section titled “Emulating “library-like” features for kernel modules”One of the major differences between user-mode and kernel-mode programming is the complete absence of the familiar “library” concept in the latter. Libraries are essentially a collection or archive of APIs, conveniently allowing developers to meet these important goals: do not reinvent the wheel, software reuse, modularity, portability and the like. But within the Linux kernel, libraries – in the traditional sense of the word – just do not exist. Having said that, the lib/ folder within the kernel source tree contains library-like routines, several of which get built into the kernel image and are thus available to kernel/module developers at runtime.
The good news is that, broadly speaking, there are two techniques by which you can achieve “library-like” functionality in kernel space for your kernel modules:
- The first technique is by explicitly “linking in” multiple source files, including the so-called “library” code, to your kernel module object.
- The second is a technique called module stacking.
Do read on as we discuss these techniques in more detail. A spoiler, perhaps, but useful to know, is that the first of the preceding techniques is often superior to the second. Then again, it does depend on the project. Do read the details in the coming sections; we list out some pros and cons as we go along.
Performing library emulation via linking multiple source files
Section titled “Performing library emulation via linking multiple source files”So far, we have dealt with very simple kernel modules that have had exactly one C source file. What about the (quite typical) real-world situation where there is more than one C source file for a single kernel module? All source files will have to be compiled and then linked together as a single .ko binary object.
For example, say we’re building a kernel module project called projx. It consists of three C source files: prj1.c, prj2.c, and prj3.c. We want the final kernel module to be called projx.ko. The Makefile is where you specify these relationships, as shown:
obj-m := projx.oprojx-objs := prj1.o prj2.o prj3.oIn the preceding code, note how the projx label has been used after the obj-m directive and as the prefix for the -objs directive on the next line. Of course, you can use any label in place of projx. Our preceding example Makefile will have the kernel build system first compile the three individual C source files into individual object (.o) files, and then link them all together to form the final binary kernel module object file, projx.ko, just as we desire.
Indeed, we leverage precisely this mechanism to build a small “library” of routines within our book’s source tree (the source files for this ‘kernel library’ are in the root of this book’s source tree here: klib.h and klib.c). The idea, of course, is that other kernel modules can use the functions within here by linking into them! For example, in the upcoming Chapter 8, Kernel Memory Allocation for Module Authors – Part 1, we have our ch8/lowlevel_mem/lowlevel_mem.c kernel module code invoke a function that resides in our library code, at this relative path from it: ../../klib.c. This “linking into” our so-called library code is achieved by putting the following into the lowlevel_mem kernel module’s Makefile (with the prefix highlighted in bold):
FNAME_C := lowlevel_mem[ … ]PWD := $(shell pwd)obj-m += ${FNAME_C}_lkm.olowlevel_mem_lkm-objs := ${FNAME_C}.o ../../klib.oThe last line above specifies the source files to build (into object files); they are the code of the lowlevel_mem.c kernel module and the ../../klib.c library code. Then, the build system links both into a single binary kernel module, lowlevel_mem_lkm.ko, achieving our objective. (Why not work on Assignment 5.1 specified in the Questions section at the end of this chapter to better understand this approach?)
Next, let’s understand something fundamental – the scope of functions and variables within a kernel module.
Understanding function and variable scope in a kernel module
Section titled “Understanding function and variable scope in a kernel module”Before delving further, a quick re-look at some basics is a good idea. When programming with C, you will understand the following:
- Variables declared locally within a function are obviously local to it and only have scope within that function (local variables ‘disappear’ when the function returns, hence they’re referred to as “automatic.” A common bug is to try and refer to a local or automatic variable outside its scope; this is often called the Use After Scope (UAS) or Use After Return (UAR) defect).
- Variables and functions prefixed with the
staticqualifier have scope only within the current “unit”; effectively, the file they have been declared within. This is good as it helps reduce namespace pollution. Static data variables declared within a function retain their value across function calls..
Prior to 2.6 Linux (that is, <= 2.4.x, ancient history now), kernel module static and global variables, as well as all functions, were automatically visible throughout the kernel. This was, in retrospect, obviously not a great idea. The decision was reversed from 2.5 (and thus 2.6 onward, modern Linux): all kernel module variables (static and global data) and functions are by default scoped to be private to that kernel module only and are thus invisible outside it. So, if two kernel modules, lkmA and lkmB, have a global (or static) variable named maya, it’s unique to each of them; there is no clash.
To change the scope, the LKM framework provides the EXPORT_SYMBOL() macro. Using it, you can declare a data item or function to be global in scope – in effect, visible to any and all other kernel modules.
Let’s take a simple example. We have a kernel module called prj_core that contains a global and a function:
static int my_glob = 5;static long my_foo(int key){ [...]}Though both the variable my_glob and the function my_foo() are usable within this kernel module itself, neither can be seen outside it. This is intentional. To make them visible outside this kernel module, we can export them:
int my_glob = 5;EXPORT_SYMBOL(my_glob);long my_foo(int key){ [...]}EXPORT_SYMBOL(my_foo);Now, both have scope outside this kernel module (notice how, in the preceding code block, the static keyword has been deliberately removed). Other kernel modules can now “see” and use them. Precisely, this idea is leveraged in two broad ways:
- First, the kernel exports (via the
EXPORT_SYMBOL*()macros) a well-thought-out subset of global variables and functions that form a part of its core functionality, as well as that of other subsystems. Now, these globals and functions are visible and thus usable from kernel modules! We will see some sample uses shortly.- This idea also spawns a very important corollary: out-of-tree kernel modules can only access functions and variables within the kernel that have been explicitly exported.
- Second, kernel module authors (often device drivers) use this very notion to export certain data and/or functionality so that other kernel modules, at a higher abstraction level, perhaps, can leverage this design and use this data and/or functionality – this concept is called module stacking and we will delve into it shortly with an example.
With the first use case, for example, a device driver author might want to handle (trap into) a hardware interrupt from a peripheral device. A common way to do so is via the request_threaded_irq() API:
int request_threaded_irq(unsigned int irq, irq_handler_t handler, irq_handler_t thread_fn, unsigned long irqflags, const char *devname, void *dev_id){ struct irqaction *action;[...] return retval;}EXPORT_SYMBOL(request_threaded_irq);Precisely because the request_threaded_irq() function is exported, can it be called from within a device driver, which is very often written as a (often out-of-tree, as we do) kernel module.
Similarly, module developers often require some “convenience” routines – for example, string processing ones. The Linux kernel, in lib/string.c, provides an implementation of several common string processing functions (that you’d expect to be present): str[n]casecmp(), str[n|l|s]cpy(), str[n|l]cat(), str[n]cmp(), strchr[nul](), str[n|r]chr(), str[n]len(), and so on. Of course, these are all exported via the EXPORT_SYMBOL() macro so as to make them visible and thus available to module authors.
Here, we used the str[n|l|s]cpy() notation to imply that the kernel provides the four functions: strcpy(), strncpy(), strlcpy(), and strscpy(). Note that some interfaces may be deprecated (strcpy(), strncpy(), and strlcpy()). In general, always avoid using deprecated stuff documented here: Deprecated Interfaces, Language Features, Attributes, and Conventions (https://www.kernel.org/doc/html/latest/process/deprecated.html#deprecated-interfaces-language-features-attributes-and-conventions).
On the other hand, let’s glance at a (tiny) bit of the core CFS (Completely Fair Scheduler) CPU scheduling code deep within the kernel core. Here, the pick_next_task_fair() function is the one invoked by the scheduling code when we need to find another task to context-switch to:
static struct task_struct *pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf){ struct cfs_rq *cfs_rq = &rq->cfs;[...] update_idle_rq_clock_pelt(rq); return NULL;}We don’t really want to study scheduling here (Chapter 10, The CPU Scheduler – Part 1, and Chapter 11, The CPU Scheduler – Part 2, will take care of it!); the point here is this: as the preceding function is not marked with any of the EXPORT_SYMBOL*() macros, it cannot ever be invoked by a kernel module. It remains private to the core kernel; this is, of course, a deliberate design decision.
You can also mark data structures as exported with the same macro(s). Also, it should be obvious that only globally scoped data – not local variables – can be marked as exported. (FYI, if you want to see how the EXPORT_SYMBOL() macro works, please refer to the Further reading section of this chapter.)
Recall our brief discussion on the licensing of kernel modules. The Linux kernel has a, shall we say, interesting,proposition: there is also a macro called EXPORT_SYMBOL_GPL(). It’s just like its cousin, the EXPORT_SYMBOL() macro, except that the function or data item exported will only be visible to those kernel modules that include the word GPL within their MODULE_LICENSE() macro! Ah, the sweet revenge of the kernel community. It is indeed used in several places in the kernel code base. (I’ll leave it as an exercise for you to find occurrences of this macro in the code; on the 6.1.25 kernel, a quick search with cscope revealed “just” 17,000-odd usage instances!)
To view all exported symbols, navigate to the root of your kernel source tree and issue the make export_report command. Note though that this works only upon a kernel tree that has been configured and built.
Let’s now look at another key approach to realizing a library-like kernel feature: module stacking.
Understanding module stacking
Section titled “Understanding module stacking”The second important idea here – module stacking – is what we will now delve further into.
Module stacking is a concept that, to a degree, provides a “library-like” feature to kernel module authors. Here, we typically architect our project or product design in such a manner that we have one or more “core” kernel modules, whose job is to act as a library of sorts. It will include the data structures and functionality (functions/APIs) that will be exported to other kernel modules in the project (and to anyone else who wants to use them; the preceding section discussed this).
To better understand this concept, let’s look at a couple of real examples. To begin with, on my host system, an Ubuntu 22.04.3 LTS native Linux system, I ran a guest VM(s) over the Oracle VirtualBox 7.0 hypervisor application*.* Okay, performing a quick lsmod on the host system while filtering for the string vbox reveals the following:
$ lsmod | grep vboxvboxnetadp 28672 0vboxnetflt 28672 1vboxdrv 614400 3 vboxnetadp,vboxnetfltRecall from our earlier discussion that, of the four columns seen, the third column is the usage count. It’s 0 in the first row but has a value of 3 in the third row. Not only that, the vboxdrv kernel module has two kernel modules listed to its right (after the usage count column). If any kernel modules show up after the third column, they represent module dependencies; read it this way:the kernel modules displayed on the right depend on the kernel module on the left.
So, in the preceding example, the vboxnetadp and vboxnetflt kernel modules depend on the vboxdrv kernel module. Depend on it in what way? They call functions (APIs) and/or use data structures that reside within the vboxdrv core kernel module, of course! In general, kernel modules showing up on the right of the third column imply they are calling one or more functions and/or using data structures of the kernel module on the left (leading to an increment in the usage count; this usage count is a good example of a reference counter (here, it’s actually a 32-bit atomic variable), something we delve into in the last chapter). In effect, the vboxdrv kernel module is akin to a “library” (in a limited sense, with none of the usual user - space connotations associated with user-mode libraries except that it provides modular functionality). You can see that, in this snapshot, its usage count is 3 and the kernel modules that depend on it are stacked on top of it – literally! (You can see them in the preceding two lines of lsmod output.) Also, notice that the vboxnetflt kernel module has a positive usage count (1) but no kernel modules show up on its right; this still implies that something is using it at the moment, typically a process or thread.
FYI, the Oracle VirtualBox kernel modules we see in this example are actually the implementation of the VirtualBox Guest Additions. They are essentially a para-virtualization construct, helping to accelerate the working of the guest VM. Oracle VirtualBox provides similar functionality for Windows and macOS hosts as well (as do all the major virtualization vendors).
Another example of module stacking, as promised: the kernel has a generic core HID (Human Interface Device) driver, often run as a module; it has several other drivers that ‘depend’ on it that are stacked above it, leveraging precisely the “library-like” feature we have been discussing here; the screenshot makes it clear:

Figure 5.5: A screenshot showing how the kernel “hid” module has several other HID-related drivers depending upon it, demonstrating the “module-stacking” approach
Here’s some quick scripting magic to see all kernel modules whose usage count is non-zero (they often – but not always – have some dependent kernel modules show up on their right; we further numerically sort the output in ascending order by usage count):
lsmod | awk '$3 > 0 {print $0}' | sort -k3nAn implication of module stacking: you can only successfully rmmod a kernel module if its usage count is 0; that is, it is not in use. Thus, for the preceding first example, we can only remove the vboxdrv kernel module after removing the two dependent kernel modules that are stacked on it (thus getting the usage count down to 0).
Trying out module stacking
Section titled “Trying out module stacking”Let’s architect some very simple proof-of-concept code for module stacking. To do so, we will build two kernel modules:
- The first we will call
core_lkm; its job is to act as a ‘library’ of sorts, making available to the kernel and other modules a couple of functions (we think of them as APIs provided by this ‘core’ module). - Our second kernel module,
user_lkm, is the ‘user’ (or consumer/client) of the ‘library.’ It will simply invoke the functions (and use some data) residing within the first.
To do so, our pair of kernel modules will need to do the following:
- The ‘core’ kernel module must use the
EXPORT_SYMBOL()macro to mark some data and functions as being exported (you could use theEXPORT_SYMBOL_GPL()macro as well if you choose to). - The ‘user’ kernel module must declare the data and/or functions that it expects to use as being external to it, via the C
externkeyword (remember, exporting data or functionality merely sets up the appropriate linkage; the compiler still needs to know about the data and/or functions being invoked). - With recent toolchains, marking the exported function(s) and data items as
staticis allowed. As this results in a compiler warning, we don’t use thestatickeyword for exported symbols. - Edit the custom Makefile to build both kernel modules.
The sample ‘core’ module – the ‘library’
Section titled “The sample ‘core’ module – the ‘library’”The code follows; first, the core or library kernel module. To (hopefully) make this more interesting, we will copy the code of one of our previous module’s functions – ch5/min_sysinfo/min_sysinfo.c:llkd_sysinfo2() – into this kernel module and export it, thus making it visible to our second “user” LKM, which will invoke that function.
Here, we do not show the full code; you can refer to the book’s GitHub repo for it:
#define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__#include <linux/init.h>#include <linux/module.h>#define THE_ONE 0xfedfaceMODULE_LICENSE("Dual MIT/GPL");int exp_int = 200;EXPORT_SYMBOL_GPL(exp_int);/* Functions to be called from other LKMs */void llkd_sysinfo2(void){[...]}EXPORT_SYMBOL(llkd_sysinfo2);#if(BITS_PER_LONG == 32)u32 get_skey(int p)#else // 64-bitu64 get_skey(int p)#endif{#if(BITS_PER_LONG == 32) u32 secret = 0x567def;#else // 64-bit u64 secret = 0x123abc567def;#endif if (p == THE_ONE) return secret; return 0;}EXPORT_SYMBOL(get_skey);[...]The sample ‘user’ module – the ‘library’ client
Section titled “The sample ‘user’ module – the ‘library’ client”Next is the user_lkm kernel module, the one “stacked” on top of the core_lkm kernel module, the ‘user’ or client of the core or ‘library’ module:
#define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__#if 1MODULE_LICENSE("Dual MIT/GPL");#elseMODULE_LICENSE("MIT");#endifextern void llkd_sysinfo2(void);extern long get_skey(int);extern int exp_int;/* Call some functions within the 'core' module */static int __init user_lkm_init(void){#define THE_ONE 0xfedface pr_info("inserted\n"); u64 sk = get_skey(THE_ONE); pr_debug("Called get_skey(), ret = 0x%llx = %llu\n", sk, sk); pr_debug("exp_int = %d\n", exp_int); llkd_sysinfo2(); return 0;}static void __exit user_lkm_exit(void){ pr_info("bids you adieu\n");}module_init(user_lkm_init);module_exit(user_lkm_exit);Trying them out
Section titled “Trying them out”The Makefile remains largely identical to our earlier kernel modules, except that this time we need two kernel module objects (that are within the same directory) to be built, as follows:
obj-m := core_lkm.oobj-m += user_lkm.oOkay, let’s try it out:
- First, build the kernel modules:
$ make--- Building : KDIR=/lib/modules/6.1.25-lkp-kernel/build ARCH= CROSS_COMPILE= ccflags-y="-DDEBUG -g -ggdb -gdwarf-4 -Wall -fno-omit-frame-pointer -fvar-tracking-assignments -DDYNAMIC_DEBUG_MODULE" MYDEBUG=y ---gcc (Ubuntu 11.3.0-1ubuntu1~22.04.1) 11.3.0make -C /lib/modules/6.1.25-lkp-kernel/build M=/home/c2kp/Linux-Kernel-Programming_2E/ch5/modstacking modules[ … ]LD [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/modstacking/core_lkm.koCC [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/modstacking/user_lkm.mod.oLD [M] /home/c2kp/Linux-Kernel-Programming_2E/ch5/modstacking/user_lkm.ko[ … ]$ ls *.kocore_lkm.ko user_lkm.ko
- Now, let’s perform a quick series of tests to demonstrate the module-stacking proof of concept. Let’s first do it wrongly: we will first attempt to insert the
user_lkmkernel module before inserting thecore_lkmmodule.
This will fail – why? You will realize that the exported functionality (and data) that the user_lkm kernel module depends on is not (yet) available within the kernel. More technically, the symbols will not be located within the kernel’s symbol table as the core_lkm kernel module that has them hasn’t been inserted yet:
$ sudo dmesg -C$ sudo insmod ./user_lkm.koinsmod: ERROR: could not insert module ./user_lkm.ko: Unknown symbol in module$ sudo dmesg[13204.476455] user_lkm: Unknown symbol exp_int (err -2)[13204.476493] user_lkm: Unknown symbol get_skey (err -2)[13204.476531] user_lkm: Unknown symbol llkd_sysinfo2 (err -2)As expected, as the required symbols are unavailable, insmod fails (the precise error message you see in the kernel log may vary slightly depending on the kernel version and debug config options set).
- Now, let’s do it right:

Figure 5.6: Screenshot showing running the module-stacking proof-of-concept demo: the top window is the shell where we’re doing the insmod, and the bottom one is running journalctl -k -f to continually show the kernel log “live”
Study Figure 5.6; yes, now it works as expected!
Notice how, for the core_lkm kernel module, the usage countcolumn has incremented to 1 and we can now see that the user_lkm kernel module appears on its right indicating that it depends upon the core_lkm one. (Recall that the kernel module(s) displayed in the extreme-right columns of lsmod ‘s output depend on the one in the extreme-left column.)
- Now, let’s remove the kernel modules. Removing the kernel modules has an ordering dependency as well (just as with insertion). Attempting to remove the
core_lkmone first fails, as, obviously, there is another module still in the kernel memory relying upon its code/data; in other words, it’s still in use:$ sudo rmmod core_lkmrmmod: ERROR: Module core_lkm is in use by: user_lkm
Note that if the modules are installed on the system, then you could use the modprobe -r <modules...> command to remove all related modules; we cover module installation in the Auto-loading modules on system boot section.
- The preceding
rmmodfailure message is self-explanatory. So, let’s do it right:$ sudo rmmod user_lkm core_lkm$ dmesg[...]CPU: x86_64, little-endian; 64-bit OS.[13889.717265] user_lkm:user_lkm_exit(): bids you adieu[13889.732018] core_lkm:core_lkm_exit(): bids you adieu
There, done!
Next, you will notice that in the code of the user_lkm kernel module, the license we release it under is in a conditional #if statement:
#if 1MODULE_LICENSE("Dual MIT/GPL");#elseMODULE_LICENSE("MIT");#endifWe can see that it’s released (by default) under the Dual MIT/GPL license; well, so what? Think about it; in the code of the core_lkm kernel module, we have the following:
int exp_int = 200;EXPORT_SYMBOL_GPL(exp_int);The exp_int integer is only visible to those kernel modules that run under a GPL license. So, an exercise for you: change the #if 1 statement in core_lkm.c to #if 0, thus now releasing it under an MIT-only license. Now, rebuild and retry. It fails at the build stage itself:
$ make[...] MODPOST /home/c2kp/Linux-Kernel-Programming_2E/ch5/modstacking/Module.symversERROR: modpost: GPL-incompatible module user_lkm.ko uses GPL-only symbol 'exp_int'[...]Read the error message; the license does matter!
Did you notice that, in our module-stacking demo (under the ch5/modstacking folder), both the “core” and “user” modules’ code were in the same directory, thus easing the Makefile rules and the build. What if this isn’t the case? No problem; consider they’re in different folders, something like this:
modstacking2├── core_module└── user_moduleEverything remains the same except for the Makefile of course:
- For the “core” module’s Makefile, we now only require one module to be built, the core one:
obj-m := core_module.o
- For the “user” module’s Makefile, we of course require it to refer to both it andthe core module, as before; it’s just that, this time, we have to specify the correct (relative) path to the core module. Thus it becomes:
obj-m := user_module.oobj-m += ../core_module/core_module.o
Build both, insert them into the kernel in the correct order, and it all works. (We leave actually doing this as an assignment for you.)
Before we wind up this section, here’s a quick list of things that can go wrong with module stacking; that is, things to check:
- Trying to insert/remove kernel modules in the wrong order.
- Attempting to insert an exported routine that is already in kernel memory – a namespace collision issue. Here’s an example:
$ cd <book_src>/ch5/min_sysinfo ; make && sudo insmod ./min_sysinfo.ko[...]$ cd ../modstacking ; sudo insmod ./core_lkm.koinsmod: ERROR: could not insert module ./core_lkm.ko: Invalid module format$ sudo dmesg[...][335.823472] core_lkm: exports duplicate symbol llkd_sysinfo2 (owned by min_sysinfo)$ sudo rmmod min_sysinfo$ sudo insmod ./core_lkm.ko # now it's ok
- License issues caused by the usage of the
EXPORT_SYMBOL_GPL()macro.
Tip: Always look up the kernel log (with dmesg or journalctl). It often helps to show what actually went awry.
Emulating ‘library-like’ features – summary and conclusions
Section titled “Emulating ‘library-like’ features – summary and conclusions”So, let’s briefly summarize the key points we learned for emulating library-like features within the kernel module space. We explored two techniques:
- The first technique we used works by linking multiple source files together into a single kernel module.
- This is as opposed to the module-stacking technique, where we actually build multiple kernel modules and “stack” them on top of each other.
Not only does the first technique work well, it also has these advantages:
- We do not have to explicitly mark (via
EXPORT_SYMBOL()) every function and/or data item that we use as exported. - The functions and data are only available to the kernel module to which they are actually linked (and not to any and all other modules). This is a good thing! All this at the cost of slightly tweaking the Makefile – well worth it.
A downside to the “linking” (first) approach: when linking multiple files, the size of the kernel module can grow to be quite large.
This concludes your learning about a powerful feature of kernel programming – the ability to link multiple source files together to form one kernel module, and/or leveraging the module-stacking design, both allowing you to develop more sophisticated kernel projects. (Do work on the sample code and the suggested assignments before moving on to the next topic area.)
Now, can one pass parameters to a kernel module? The following section shows you how to!
Passing parameters to a kernel module
Section titled “Passing parameters to a kernel module”A common debugging technique is to instrument your code; that is, insert prints at appropriate points such that you can follow the path the code takes. Within a kernel module, of course, we would use the versatile printk (and friends) functions for this purpose. So, let’s say we do something like the following (pseudo-code):
#define pr_fmt(fmt) "%s:%s():%d: " fmt, KBUILD_MODNAME, __func__, __LINE__[ ... ]func_x() { pr_debug("At 1\n"); [...] while (<cond>) { pr_debug("At 2: j=0x%x\n", j); [...] } [...]}Okay, great. But, hey, we don’t want the debug prints to appear in a production (or release) version. That’s precisely why we’re using pr_debug(): it emits a printk only when the DEBUG symbol is defined! Indeed, but what if, interestingly, our customer is an engineering customer and wants to dynamically turn on or turn off these debug prints? There are several approaches you might take to make this happen; one is as in the following pseudo-code:
static int debug_level; /* will be init to zero */func_x() { if (debug_level >= 1) pr_debug("At 1\n"); [...] while (<cond>) { if (debug_level >= 2) pr_debug("At 2: j=0x%x\n", j); [...] } [...]}Ah, that’s nice. So, what we’re getting at really is this: what if we can make the debug_level variable a parameter to our kernel module? Then – a powerful thing – the user of your kernel module has control over which debug messages appear and which do not.
This, being a contrived example, is fine… But, realistically, you can always – even in production! – use the easier and more powerful dynamic debug framework of the kernel to see debug prints whenever you’d like to. Recall we covered this key topic in brief in Chapter 4, Writing Your First Kernel Module – Part 1, in the An introduction to the kernel’s powerful dynamic debug feature section.
Besides debug instrumentation, there are many more cases where module parameters prove invaluable (think: setting the initial volume level for an audio driver, the brightness level on a camera driver, and so on). So let’s now jump into learning about the usage of module parameters.
Declaring and using module parameters
Section titled “Declaring and using module parameters”Module parameters are passed to a kernel module as name-value pairs at module insertion (insmod/modprobe) time.
For example, assume we have a module parameter named mp_debug_level; then, we could pass its value at insmod time, like this:
sudo insmod ./modparams1.ko mp_debug_level=2Here, the mp prefix stands for module parameter. It’s not required to name it that way, of course; it is pedantic, but consistently following such conventions helps by making the reading of large codebases a bit more intuitive.
That would be quite powerful. Now, the end user can decide at exactly what verbosity they want debug-level messages to be emitted at. We can easily arrange for the default value to be 0 and thus the module emits no debug messages by default.
You might wonder how it works: kernel modules have no main() function and hence no conventional (argc, argv) parameter list, so how exactly, then, do you pass parameters along? It’s simply a bit of linker trickery… Just do this: declare your intended module parameter as a global (static) variable, then specify to the build system that it’s to be treated as a module parameter by employing the module_param() macro.
This is easy to see with our first module parameter’s demo kernel module (as usual, the full source code and Makefile can be found in the book’s GitHub repo):
[ ... ]/* Module parameters */static int mp_debug_level;module_param(mp_debug_level, int, 0660);MODULE_PARM_DESC(mp_debug_level,"Debug level [0-2]; 0 => no debug messages, 2 => high verbosity");static char *mp_strparam = "My string param";module_param(mp_strparam, charp, 0660);MODULE_PARM_DESC(mp_strparam, "A demo string parameter");An aside: in the static int mp_debug_level; statement above, there is no harm in changing it to static int mp_debug_level = 0;, thus explicitly initializing the variable to 0, right? Well, no: the kernel’s scripts/checkpatch.pl script output reveals that this is not considered a good coding style by the kernel community; if you do so, it triggers this “error”:
ERROR: do not initialise statics to 0
#28: FILE: modparams1.c:28:
+static int mp_debug_level = 0;
In the preceding code block, we have declared two variables to be module parameters via the module_param() macro. The module_param() macro itself takes three parameters:
- The first parameter: The variable in our code that we would like to be treated as a module parameter. This should be declared using the
staticqualifier. - The second parameter: Its data type.
- The third parameter: Permissions (really, its visibility via
sysfs; this is explained shortly).
Next, the MODULE_PARM_DESC() macro allows us to “describe” what the parameter represents. Think about it: this is how you inform the end user of the kernel module (or driver) regarding what parameters are actually available. The lookup is performed via the modinfo(8) utility. Furthermore, you can specifically print only the information on parameters to a module by using the -p option switch, as shown:
$ cd <booksrc>/ch5/modparams/modparams1 ; make[ … ]$ modinfo -p ./modparams1.koparm: mp_debug_level:Debug level [0-2]; 0 => no debug messages, 2 => high verbosity (int)parm: mp_strparam:A demo string parameter (charp)The modinfo output displays available module parameters, if any. Here, we can see that our modparams1.ko kernel module has two parameters: their name, description, and data type (the last component, within parentheses; BTW, charp is “character pointer,” a string) is then displayed.
Right, let’s now give our demo kernel module a quick spin:
$ sudo dmesg -C$ sudo insmod ./modparams1.ko$ sudo dmesg[630238.316261] modparams1:modparams1_init(): inserted[630238.316685] modparams1:modparams1_init(): module parameters passed: mp_debug_level=0 mp_strparam=My string paramHere, we see from the dmesg output that, as we did not explicitly pass any kernel module parameters, the module variables obviously retain their default (original) values. Let’s redo this, this time passing explicit values to the module parameters:
sudo rmmod modparams1sudo insmod ./modparams1.ko mp_debug_level=2 mp_strparam=\"Hello modparams1\"sudo dmesg[...][630359.270765] modparams1:modparams1_exit(): removed[630373.572641] modparams1:modparams1_init(): inserted[630373.573096] modparams1:modparams1_init(): module parameters passed: mp_debug_level=2 mp_strparam=Hello modparams1It works as expected. Isn’t it interesting: the (parameter) variables have now been modified in kernel memory with the new values we passed from user space!
Now that we’ve seen how to declare and pass along some parameters to a kernel module, let’s look at retrieving and even modifying them at runtime.
Getting/setting module parameters after insertion
Section titled “Getting/setting module parameters after insertion”Let’s look carefully at the module_param() macro usage in our preceding modparams1.c source file again:
module_param(mp_debug_level, int, 0660);Notice the third parameter, the permissions (or mode): it’s 0660 (which, of course, is an octal number, implying read-write access for the owner and group and no access for others). It’s a bit confusing until you realize that if this permissions (or mode) parameter is specified as non-zero, a pseudofile(s) gets created under the sysfs filesystem, representing the kernel module parameter(s), here: /sys/module/<module-name>/parameters/:
sysfs is usually mounted under /sys. Also, by default, all pseudofiles under it will have the owner and group as root.
- So, for our
modparams1kernel module (first ensure youinsmodit into kernel memory!), let’s look them up:$ ls /sys/module/modparams1/coresize holders/ initsize initstate notes/ parameters/ refcnt sections/ srcversion taint uevent version$ ls -l /sys/module/modparams1/parameters/total 0-rw-rw---- 1 root root 4096 Oct 11 17:09 mp_debug_level-rw-rw---- 1 root root 4096 Oct 11 17:09 mp_strparam$
Indeed, there they are! Not only that, but the real beauty of it is also that these “parameters” can now be read and written at will, at any time (though, here, only with root permission, of course)!
- Check it out; let’s look up the current value of the
mp_debug_levelmodule parameter:$ cat /sys/module/modparams1/parameters/mp_debug_levelcat: /sys/module/modparams1/parameters/mp_debug_level: Permission denied$ sudo cat /sys/module/modparams1/parameters/mp_debug_level[sudo] password for c2kp:2
The current value of our mp_debug_level kernel module parameter is indeed 2 (as this is precisely the value we assigned to it when we did the insmod).
- Now let’s dynamically change it to
0by writing into it (as root), implying that no “debug” messages will be emitted by themodparams1kernel module:$ sudo sh -c "echo 0 > /sys/module/modparams1/parameters/mp_debug_level"$ sudo cat /sys/module/modparams1/parameters/mp_debug_level0
Voilà – done. You can similarly get and/or set the mp_strparam parameter; we will leave it to you to try this as a simple exercise. Do dwell on this concept. It’s quite powerful stuff: you could write simple scripts to control a device’s (or whatever’s) behavior via kernel module parameters, get (or cut off) debug info, and anything else; the possibilities are quite endless.
Actually, coding the third parameter to module_param() as a literal octal number (such as 0660) is not considered the best programming practice in some circles. Specify the permissions of the sysfs pseudofile via appropriate macros (specified in include/uapi/linux/stat.h), for example:
module_param(mp_debug_level, int, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);However, having said this, our “better” Makefile’s checkpatch target (which, of course, invokes the kernel’s scripts/checkpatch.pl “coding-style” Perl script checker) politely informs us that simply using octal permissions is better:
$ make checkpatch[ ... ]checkpatch.pl: /lib/modules/<ver>/build//scripts/checkpatch.pl --no-tree -f *.[ch][ ... ]WARNING: Symbolic permissions 'S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP' are not preferred. Consider using octal permissions '0660'. #32: FILE: modparams1.c:32: +module_param(mp_debug_level, int, S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP);So, the kernel community disagrees. Hence, we will just use the “usual” octal number notation of 0660. (Interestingly and FYI, here’s a recent (6.3) commit that fixes precisely this for some drivers: dm: avoid using symbolic permissions: https://github.com/torvalds/linux/commit/6a808034724b5a36f8e0b712427bfbe9e667d296.)
Again, repeated for emphasis, a useful tip: from what we learned, for the purpose of providing “dynamic” debug instrumentation, using a debug_level type of module parameter seems to be a good approach. I’d argue, though, that the Linux kernel’s built-in dynamic debug feature is much superior (CONFIG_DYNAMIC_DEBUG)! We did briefly cover this key topic in Chapter 4, Writing Your First Kernel Module – Part 1, in the An introduction to the kernel’s powerful dynamic debug feature section. You can learn more about it from the official kernel documentation here (https://www.kernel.org/doc/html/v6.1/admin-guide/dynamic-debug-howto.html) and from my Linux Kernel Debugging book’s third chapter.
Learning module parameter data types and validation
Section titled “Learning module parameter data types and validation”In our preceding simple kernel module, we set up two parameters of the integer (int) and string data types (charp). What other data types can be used for module parameters? Several, as it turns out: the moduleparam.h include file reveals all (within a comment, duplicated as follows):
[...] * Standard types are: * byte, hexint, short, ushort, int, uint, long, ulong * charp: a character pointer * bool: a bool, values 0/1, y/n, Y/N. * invbool: the above, only sense-reversed (N = true).All right, that’s pretty comprehensive. You can even define your own data types if required. Usually, though, the standard types more than suffice.
Validating kernel module parameters
Section titled “Validating kernel module parameters”All kernel module parameters are optional by default; the user may or may not explicitly pass them. But what if our project requires thatthe user must explicitly pass a value for a given kernel module parameter? We address this here: let’s enhance our previous kernel module, creating another (ch5/modparams/modparams2), the key difference being that we set up an additional parameter called control_freak. Here, let’s say we require that the user must mandatorily pass this parameter along at module insertion time:
- Let’s set up the new module parameter in code:
static int control_freak;module_param(control_freak, int, 0660);MODULE_PARM_DESC(control_freak, "Set to the project's control level [1-5]. MANDATORY");
- How can we achieve this “mandatory parameter passing”? Well, it’s a bit of a hack really: at insertion time, just check whether the (parameter) variable value is the default (
0, here). If so, it of course implies that the end user hasn’t overridden it by explicitly passing it; so abort with an appropriate message (we also do a simple validity check to ensure that the integer passed is within a given range). Here’s theinitcode ofch5/modparams/modparams2/modparams2.c:static int __init modparams2_init(void){pr_info("inserted\n");if (mp_debug_level > 0)pr_info("module parameters passed: ""mp_debug_level=%d mp_strparam=%s\n control_freak=%d\n",mp_debug_level, mp_strparam, control_freak);/* param 'control_freak': if it hasn't been passed (implicit guess),* or is the same old value, or isn't within the right range,* it's Unacceptable! :-)*/if ((control_freak < 1) || (control_freak > 5)) {pr_warn("I'm a control freak; thus, you *Must* pass along module parameter 'control_freak', value in the range [1-5]; aborting...\n");return -EINVAL;}return 0; /* success */}
So let’s do the unthinkable and load up this module without passing the control_freak parameter (shudder)!
$ sudo dmesg -C[sudo] password for c2kp:$ sudo insmod ./modparams2.koinsmod: ERROR: could not insert module ./modparams2.ko: Invalid parameters$ sudo dmesg[ … ]kern :info : [632275.085408] modparams2:modparams2_init(): insertedkern :warn : [632275.085866] modparams2:modparams2_init(): I'm a control freak; thus, you *Must* pass along module parameter 'control_freak', value in the range [1-5]; aborting...$It works as designed, aborting the module (by returning a negative errno, -EINVAL here) as the parameter’s not explicitly passed.
- Also, as a quick demo, notice how we emit a printk, showing the module parameter values only if
mp_debug_levelis positive. - Finally, on this topic, the kernel framework provides a more rigorous way to “get/set” kernel (module) parameters and perform validity checking on them via the
module_param_cb()macro (cbfor callbacks). We will not delve into this here; I refer you to a blog article mentioned in the Further reading section for details on using it.
Now, let’s move on to how (and why) we can override a module parameter’s name.
Overriding the module parameter’s name
Section titled “Overriding the module parameter’s name”To explain this feature, let’s take an example from the (6.1.25) kernel source tree: the direct mapping buffered I/O library driver, drivers/md/dm-bufio.c, has a need to use (as one example) the dm_bufio_current_allocated variable as a module parameter. However, this name is really that of an internal variable and is not highly intuitive to a user of this driver. The authors of this driver would therefore much prefer to use another more intuitive and meaningful name for the parameter – current_allocated_bytes – as an alias or name override. Precisely this can be achieved via the module_param_named() macro, overriding and completely equivalent to the internal variable name, as follows:
module_param_named(current_allocated_bytes, dm_bufio_current_allocated, ulong, S_IRUGO);MODULE_PARM_DESC(current_allocated_bytes, "Memory currently used by the cache");You can look this up, and several similar usages of the module_param_named() macro at the end of this file, here: https://elixir.bootlin.com/linux/v6.1.25/source/drivers/md/dm-bufio.c#L2169.
So, when the user performs insmod on this driver, they can do stuff like the following:
sudo insmod <path/to/>dm-bufio.ko current_allocated_bytes=4096 ...Internally, the actual variable, dm_bufio_current_allocated, will now be assigned the value 4096.
Hardware-related kernel parameters
Section titled “Hardware-related kernel parameters”For security reasons, module or kernel parameters that specify hardware-specific values have a separate macro: module_param_hw[_named|array](). David Howells submitted a patch series for these new hardware parameters’ kernel support on 1 December 2016. The patch email (https://lwn.net/Articles/708274/) mentions the following:
Provided an annotation for module parameters that specify hardwareparameters (such as io ports, iomem addresses, irqs, dma channels, fixeddma buffers and other types).This will enable such parameters to be locked down in the core parameterparser for secure boot support. [...]This concludes our discussion on kernel module parameters. Let’s now move on to a slightly peculiar aspect of writing kernel code – that of floating-point usage within the kernel.
Floating point not allowed in the kernel
Section titled “Floating point not allowed in the kernel”Years ago, a young and relatively inexperienced lad working on a temperature sensor device driver (me) had an amusing experience (though it wasn’t quite so amusing at the time). Attempting to express a temperature value in millidegrees Celsius as a “regular” temperature value in degrees Celsius correct to three decimal places, he did something like the following:
int temperature;double temperature_fp; [... processing …]temperature_fp = temperature / 1000.0;printk(KERN_INFO "temperature is %.3f degrees C\n", temperature_fp);It all went downhill from there!
The venerable LDD (Linux Device Drivers, by Corbet, Rubini, and Kroah-Hartman) book pointed out my error – floating-point (FP) arithmetic is not allowed in kernel space! It’s a conscious design decision; saving processor (FP) state, turning on the FP unit, working on it, then turning off and restoring the FP state is just not considered a worthwhile thing to do while in the kernel. The kernel (or driver) developer is well advised to just not attempt to perform FP work while in kernel space.
Well, then, you ask, how can you do the (as in my example) temperature conversion? Simple: pass the integer millidegrees Celsius value to user space and perform the FP work there!
In quite a few cases, it’s just plain wrong to perform certain kinds of work in the kernel; user space is the right place for such work (there are a few exceptions, as with every rule). This includes performing floating-point arithmetic, file I/O (yes, do not try doing file reading and writing within the kernel via system call-like code paths), and running applications, though the kernel does provide the (fairly surprising but very useful at times) ability to do so via the UMH (user-mode helper) APIs like the call_usermodehelper*() ones (use with caution!), and so on.
Forcing FP in the kernel
Section titled “Forcing FP in the kernel”While we said that FP isn’t allowed in kernel space, there does exist a way to force the kernel to perform floating point arithmetic: put your floating-point code between the kernel_fpu_begin() and kernel_fpu_end() macros. There are a few places where precisely this technique is used within the kernel code base (typically, some code paths covering crypto/AES, CRC, and so on).
The recommendation is clear: the typical module (or driver) developer should perform only integer arithmetic within the kernel.
Nevertheless, to test this whole scenario (always remember, the empirical approach – actually trying things out – is the only realistic way forward!), we write a simple kernel module that attempts to perform some FP work. The key part of the code is shown here:
static double num = 22.0, den = 7.0, mypi;static int __init fp_in_lkm_init(void){ [...] kernel_fpu_begin(); mypi = num/den; kernel_fpu_end();#if 1 pr_info("%s: PI = %.4f = %.4f\n", OURMODNAME, mypi, num/den);#endif return 0; /* success */}It actually works, until we attempt to display the FP value via printk()! At that point, it goes quite berserk. See the following screenshot:

Figure 5.7: The output of WARN_ONCE() when we try and print an FP number in kernel space
The key line here is Please remove unsupported %f in format string.
This tells us the story. The system does not actually crash or panic as this is a mere WARNING, spat out to the kernel log via the WARN_ONCE() macro. Do realize, though, that on a production system, the /proc/sys/kernel/panic_on_warn sysctl (pseudofile) will, perhaps, be set to the value 1, causing the kernel to (quite rightly) panic.
Though not visible in the preceding screenshot (Figure 5.7), further down, the section beginning with Call Trace: is, of course, a peek into the current state of the kernel-mode stack of the process or thread that was “caught” in the preceding WARN_ONCE() code path (hang on, you will learn key details regarding the user- and kernel-mode stacks and so on in Chapter 6, Kernel Internals Essentials – Processes and Threads).
One can interpret the kernel stack by reading it in a bottom-up fashion, greatly aiding the debug effort. FYI, here’s a truncated portion of the Call Trace: output (continuing the output from Figure 5.7):
[ … ][633848.592829] CR2: 000056086ea0dbd8 CR3: 0000000775ed8003 CR4: 00000000007706e0[633848.593607] PKRU: 55555554[633848.593889] Call Trace:[633848.594148] <TASK>[633848.594374] vsnprintf+0x71/0x560[633848.594717] vprintk_store+0x19a/0x5a0[633848.595101] vprintk_emit+0x8e/0x1f0[633848.595468] ? 0xffffffffc0a33000[633848.595811] vprintk_default+0x1d/0x30[633848.596194] vprintk+0x67/0xb0[633848.596587] ? 0xffffffffc0a33000[633848.596927] _printk+0x58/0x81[633848.597246] fp_in_lkm_init+0x62/0x1000 [fp_in_lkm][633848.597735] do_one_initcall+0x46/0x230[633848.598163] ? kmem_cache_alloc_trace+0x1a6/0x330[633848.598638] do_init_module+0x52/0x220[633848.599022] load_module+0xb56/0xd40[633848.599388] ? security_kernel_post_read_file+0x5c/0x80[ … ]Here, following along, reading it from the bottom up, we can see the do_one_initcall() function called fp_in_lkm_init() (which belongs to the kernel module in square brackets, [fp_in_lkm_init], our kernel module of course), which then calls [_]printk(), which then ends up causing all kinds of trouble as it attempts to print an FP quantity! (By the way, simply ignore any call frames beginning with the ? symbol.)
The moral here is clear: as far as possible, avoid using floating-point math within kernel space.
Exercise: What if the offending printk() is removed? Will it then work? Try it.
Let’s now move on to the practical topic of how you can install and auto-load kernel modules on system startup.
Auto-loading modules on system boot
Section titled “Auto-loading modules on system boot”Until now, we have written simple “out-of-tree” kernel modules that reside in their own private directories and have to be manually loaded up, typically via the insmod or modprobe(8) utilities. In most real-world projects and products, you will require your out-of-tree kernel module(s) to be auto-loaded at boot. This section covers how you can achieve this.
Consider we have a kernel module named foo.ko. We assume we have access to its source code and Makefile. In order to have it auto-load on system boot, you need to first install the kernel module to a known location on the system. To do so, we expect that the Makefile for the module contains an install target, typically:
install: make -C $(KDIR) M=$(PWD) modules_installThis is not something new; we have been placing the install target within the Makefile s of our demo kernel modules. Further, as it writes into a root-owned directory, we can always modify the rule to run via sudo to ensure it succeeds (or, the user must invoke it via sudo, either way):
install: sudo make -C $(KDIR) M=$(PWD) modules_installTo demonstrate this “auto-load” procedure, we have shown the set of steps to follow in order to install and auto-load on boot our ch5/min_sysinfo kernel module:
- First, change directory to the module’s source directory:
cd <book_src>/ch5/min_sysinfo
- Next, it’s important to first build the kernel module (with
make), and, on success, install it (as you’ll soon see, our “better” Makefile makes the process simpler by guaranteeing that the build is done first, followed by theinstalland thedepmod):make && sudo make install
Assuming it builds successfully, the sudo make install command then installs the kernel module here: /lib/modules/<kernel-ver>/extra/ as is expected (do see the following info box and tips as well). Let’s give it a shot:
$ cd <book_src>/ch5/min_sysinfo$ make # <-- ensure it's first built 'locally' # generating the min_sysinfo.ko kernel module object[...]$ sudo make install[sudo] password for c2kp:--- installing --- [First, invoking the 'make' ]make[ … ] [Now for the 'sudo make install' ]sudo make -C /lib/modules/6.1.25-lkp-kernel/build M=/home/c2kp/Linux-Kernel-Programming_2E/ch5/min_sysinfo modules_installmake: Entering directory '/home/c2kp/kernels/linux-6.1.25' INSTALL /lib/modules/6.1.25-lkp-kernel/extra/min_sysinfo.ko SIGN /lib/modules/6.1.25-lkp-kernel/extra/min_sysinfo.ko DEPMOD /lib/modules/6.1.25-lkp-kernelmake: Leaving directory '/home/c2kp/kernels/linux-6.1.25'sudo depmod [If !debug, stripping debug info from /lib/modules/6.1.25-lkp-kernel/extra/min_sysinfo.ko]if [ "n" != "y" ]; then \ sudo strip --strip-debug /lib/modules/6.1.25-lkp-kernel/extra/min_sysinfo.ko ; \fi$ ls -l /lib/modules/6.1.25-lkp-kernel/extra/total 16-rw-r--r-- 1 root root <...> min_sysinfo.ko$For now, simply ignore the SIGN line; it’s saying that the module has been “signed” by the kernel, a security feature that we’ll cover shortly.
During sudo make install, it’s possible you might see (non-fatal) errors regarding SSL; they can be safely ignored. They indicate that the system failed to “sign” the kernel module (here, it worked). More on this in the upcoming section on security.
Also, just in case you find that sudo make install fails, try the following approaches:
a) Switch to a root shell (sudo -s) and, within it, run the make ; make install commands.
b) A useful reference: Makefile: installing external Linux kernel module, Stack Overflow, June 2016 (https://unix.stackexchange.com/questions/288540/makefile-installing-external-linux-kernel-module).
- Another module utility, called
depmod(8), is then typically invoked by default within thesudo make install(as can be seen from the preceding output). Just in case (for whatever reason) this has not occurred, you can always manually invokedepmod(which our Makefile does); its job is essentially to resolve module dependencies (see its man page for details):sudo depmod. Once you install the kernel module, you can see the effect ofdepmodwith its--dry-runoption switch:$ sudo depmod --dry-run | grep min_sysinfoextra/min_sysinfo.ko:alias symbol:llkd_sysinfo min_sysinfoalias symbol:llkd_sysinfo2 min_sysinfo - Ensure the just-installed module is auto-loaded on boot. One way to do so is to create the
/etc/modules-load.d/<foo>.confconfig file (where <foo> is the name of the module. Of course, you will need root access to create this file). The simple case is really simple: just put the kernel module’s name inside the file and that’s it. Any line starting with a#character is treated as a comment and ignored. For ourmin_sysinfoexample, we have the following:$ sudo vim /etc/modules-load.d/min_sysinfo.conf# Auto load kernel module demo for the LKP2E book: ch5/min_sysinfomin_sysinfo<save & exit>$ cat /etc/modules-load.d/min_sysinfo.conf# Auto load kernel module demo for the LKP2E book: ch5/min_sysinfomin_sysinfo$
On modern Linux, the de facto initialization framework is systemd. An (even simpler) way to autoload your module at boot is to inform systemd to load it up: simply enter the name of the (already installed) module into the (pre-existing) /etc/modules-load.d/modules.conf file.
- Reboot the system with
sync; sudo reboot.
Once the system is up, use lsmod to spot the module and look up the kernel log (with dmesg or journalctl). You should see relevant info pertaining to the kernel module loading up (in our example, min_sysinfo):
[... system boots up, we log in and check …]
Figure 5.8: Screenshot showing our min_sysinfo module has been auto-loaded into kernel memory at boot
There, it’s done: our min_sysinfo kernel module has indeed been auto-loaded into kernel space on boot! (The “platform details” – the output of our module – do indeed follow in the kernel log; it’s just that all output lines aren’t matched here via the grep we did.)
Remember, you must first build your kernel module and then perform the install; to help automate this, our “better” Makefile has the following in its module installation install target:
// ch5/min_sysinfo/Makefile[ ... ]install: @echo @echo "--- installing ---" @echo " [First, invoking the 'make' ]" make @echo @echo " [Now for the 'sudo make install' ]" sudo make -C $(KDIR) M=$(PWD) modules_install sudo depmod @echo " [If !debug and !(module signing), stripping debug info from ${KMODDIR}/extra/${FNAME_C}.ko]" if [ "${DBG_STRIP}" = "y" ]; then \ sudo ${STRIP} --strip-debug ${KMODDIR}/extra/${FNAME_C}.ko ; \ fiIt ensures that, first, the build is done, followed by the install and (explicitly) the depmod. (Our Makefile also has the intelligence to strip the module of debug symbols if it’s built as a release binary and if module signing (coming up) isn’t enabled.)
An alternate way to auto-load your module at boot is to “manually” load it via a startup script that invokes the modprobe(8) utility, a more intelligent version of insmod (more on this in the following section).
What if your auto-loaded kernel module requires some (module) parameters passed at load time? There are two ways to ensure that this happens: via a so-called modprobe config file (under /etc/modprobe.d/) or, if the module’s built into the kernel, via the kernel command line.
Here we’ll show the first way: simply set up your modprobe configuration file (as an example here, we use the name mykmod as the name of our LKM; again, you require root access to create this file): /etc/modprobe.d/mykmod.conf; in it, you can pass parameters like this:
options <module-name> <parameter-name>=<value>As an example, the /etc/modprobe.d/alsa-base.conf modprobe config file on my x86_64 Ubuntu 22.04 LTS system contains the lines (among several others):
# Ubuntu #62691, enable MPU for snd-cmipcioptions snd-cmipci mpu_port=0x330 fm_port=0x388Here, we understand it as: if the snd-cmipci module is required, it’s loaded into kernel memory along with the module parameters mpu_port=0x330 fm_port=0x388. A few more points on kernel module auto-loading-related items follow.
Module auto-loading – additional details
Section titled “Module auto-loading – additional details”Once a kernel module has been installed on a system (via sudo make install, as shown previously), you can also insert it into the kernel interactively (or via a script) simply by using a “smarter” version of the insmod utility, called modprobe(8). For our example, we could first rmmod the module and then do the following:
sudo modprobe min_sysinfoAs an interesting aside, consider the following. In cases where there are several kernel module objects to load (for example, with the module-stacking design), the modprobe utility has the intelligence to load them up in the right order (we covered the need for this in the section Understanding module stacking) so that module dependencies are served and it all just works!
How does modprobe know the right order in which to load up kernel modules? When performing a build locally, the build process generates a file called modules.order. It tells utilities such as modprobe the order in which to load up kernel modules such that all dependencies are resolved. When kernel modules are installed into the kernel (that is, into the /lib/modules/$(uname -r)/extra/, or a similar, location), the depmod utility generates a /lib/modules/$(uname -r)/modules.dep file. This contains the dependency information – it specifies whether a kernel module depends on another. Using this information, modprobe then loads them up in the required order. To flesh this out, let’s install our module-stacking example modules:
$ cd <...>/ch5/modstacking$ sudo make install[ ... ] INSTALL /lib/modules/6.1.25-lkp-kernel/extra/core_lkm.ko SIGN /lib/modules/6.1.25-lkp-kernel/extra/core_lkm.ko INSTALL /lib/modules/6.1.25-lkp-kernel/extra/user_lkm.ko SIGN /lib/modules/6.1.25-lkp-kernel/extra/user_lkm.ko DEPMOD /lib/modules/6.1.25-lkp-kernelmake: Leaving directory '/home/c2kp/kernels/linux-6.1.25'sudo depmod[ ... ]$ ls -l /lib/modules/6.1.25-lkp-kernel/extra/total 248-rw-r--r-- 1 root root 118377 Oct 12 16:37 core_lkm.ko-rw-r--r-- 1 root root 12672 Oct 12 15:51 min_sysinfo.ko-rw-r--r-- 1 root root 117097 Oct 12 16:37 user_lkm.koClearly, the two kernel modules from our module-stacking example (core_lkm.ko and user_lkm.ko) are now installed under the expected location, /lib/modules/$(uname -r)/extra/ (and we can see that depmod was run).
Now, check this out:
$ grep user_lkm /lib/modules/6.1.25-lkp-kernel/* 2>/dev/null/lib/modules/6.1.25-lkp-kernel/modules.dep:extra/user_lkm.ko: extra/core_lkm.ko$Aha, depmod has arranged for the modules.dep file to include the dependency! It shows that the extra/user_lkm.ko kernel module (this time, the one on the left) depends on the extra/core_lkm.ko kernel module (via the <k1.ko>: <k2.ko>... notation, implying that the k1.ko module depends on the k2.ko module).
Thus, modprobe, parsing the /lib/modules/$(uname -r)/modules.order file, notices this and thus loads them in the required order, avoiding any issues.
FYI, while on this topic, the generated /lib/modules/$(uname -r)/modules.symbols file has information on all exported module symbols. Similarly, within the module directory, the Module.symvers file contains the same. (As well, all symbols in the kernel symbol table – exported and private – along with their (virtual) addresses, can be seen via the /proc/kallsyms pseudofile (as root; see the man page on nm(1) to understand the notation)).
Next, on modern Linux systems, it’s actually systemd that takes care of auto-loading kernel modules at system boot, by parsing the content of files such as /etc/modules-load.d/* (the systemd service responsible for this is systemd-modules-load.service(8) – for details, refer to the man page on modules-load.d(5)).
Conversely, you might sometimes find that a certain auto-loaded kernel module is misbehaving – causing lockups or delays, or it simply doesn’t work – and so you want to disableit being auto-loaded at boot. This can be done by blacklisting the module. You can specify this either on the kernel command line (convenient when all else fails!) or within the (previously mentioned) /etc/modules-load.d/<foo>.conf config file. On the kernel command line, via module_blacklist=mod1,mod2,..., the kernel docs shows us the syntax/explanation:
module_blacklist= [KNL] Do not load a comma-separated list of modules. Useful for debugging problem modules.You can look up the current kernel command line by doing cat /proc/cmdline.
While on the topic of the kernel command line, several other useful options exist, enabling us to use the kernel’s help for debugging issues concerned with kernel initialization. As a few examples, among several others, the kernel provides the following parameters in this regard (sourced from the official kernel docs here: https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html):
debug [KNL] Enable kernel debugging (events log level).[...]initcall_debug [KNL] Trace initcalls as they are executed. Useful for working out where the kernel is dying during startup.[...]ignore_loglevel [KNL] Ignore loglevel setting - this will print /all/ kernel messages to the console. Useful for debugging. We also add it as printk module parameter, so users could change it dynamically, usually by /sys/module/printk/parameters/ignore_loglevel.Fastboot! Also, the initcall_debug kernel parameter can help you pinpoint kernel functionality that’s taking a long time to run during boot; this is a part of getting the system to “fast boot,” a requirement for some kinds of projects. (On this note, be sure to check out systemd-analyze, the Perl script in the kernel tree scripts/bootgraph.pl, and more. See the Further reading section for more.)
FYI, and as mentioned earlier in this chapter, there is an alternate framework for third-party kernel module auto-rebuilding, called Dynamic Kernel Module Support (DKMS). The Further reading document for this chapter also provides some helpful links. In conclusion, auto-loading kernel modules into memory on system startup is a useful and often required functionality in a product.
Building high-quality products requires a keen understanding of – and the knowledge to build in – security; that’s the focus of the next section.
Kernel modules and security – an overview
Section titled “Kernel modules and security – an overview”An ironic reality is that enormous efforts spent on improving user-space security considerations have resulted in a large payoff over recent years. A malicious user performing a Buffer Overflow (BoF) attack was relatively straightforward a couple of decades back, but today it is really hard to pull off well. Why? Because there are many layers of beefed-up security mechanisms to prevent many of these attack classes.
To quickly name a few countermeasures: compiler protections (-fstack-protector[...], -Wformat-security, -D_FORTIFY_SOURCE=3), partial/full RELRO, better sanity and security checker tools (checksec.sh, address sanitizers, PaxTest, static analysis tools, and so on), secure libraries, hardware-level protection mechanisms (NX, SMEP, SMAP, and so on), [K]ASLR, better testing (fuzzing), and so on. Whew.
The irony is that kernel-space attacks have become increasingly common over the last several years! It has been demonstrated that revealing even a single valid kernel (virtual) address (and its corresponding symbol) to a clever attacker can allow them to figure out the location of some key internal kernel structures, paving the way to carry out all kinds of privilege escalation (privesc) attacks. Coming up, we will enumerate and briefly describe a few security/hardening features that the Linux kernel provides. However, ultimately, as a kernel developer – you have a large role to play: writing secure code, to begin with! Using our “better” Makefile is a great way to get started – several targets within it are concerned with security (all the static analysis ones, for example). Within this section on security and kernel modules, we’ll cover a few pertinent topics; let’s begin with looking at some key proc-based sysctl.
Proc filesystem tunables affecting the system log
Section titled “Proc filesystem tunables affecting the system log”We directly refer you to the man page on proc(5) – very valuable! – to glean information on these two security-related tunables or sysctl (Link: https://man7.org/linux/man-pages/man5/proc.5.html):
dmesg_restrictkptr_restrict
A quick word on the dmesg_restrict sysctl
Section titled “A quick word on the dmesg_restrict sysctl”The dmesg_restrict sysctl is a means to determine what minimal privileges are required to look up the kernel log. Recall that even something as seemingly innocent as this is actually valuable information to a determined hacker! The relevant entry for it within the man page on proc(5) is as follows:
dmesg_restrict/proc/sys/kernel/dmesg_restrict (since Linux 2.6.37)The value in this file determines who can see kernel syslog contents. A value of 0 in this file imposes no restrictions. If the value is 1, only privileged users can read the kernel syslog. (See syslog(2) for more details.) Since Linux 3.4, only users with the CAP_SYS_ADMIN capability may change the value in this file.(Recall that a “ CAP_SYS_ADMIN capability” user is equivalent to root.) The default values of the dmesg_restrict tunable on (x86_64):
- Ubuntu 22.04 (running a 5.19-based kernel) is 1. That’s good; until the 20.04 release, Ubuntu had the default value as 0 (weaker).
- Fedora 38 (running a 6.2-based kernel) is 0.
How can I see the current value on my Linux box? Easy; here are two ways to do so:
$ cat /proc/sys/kernel/dmesg_restrict0$ sysctl -a 2>/dev/null |grep -w dmesg_restrictkernel.dmesg_restrict = 0Clearly, it’s 0, implying there aren’t any restrictions (this is on a Fedora 39 workstation; recent Ubuntu distros set it to 1).
FYI, Linux kernels use the powerful fine-granularity POSIX capabilities model. The CAP_SYS_ADMIN capability essentially is a catch-all for what is traditionally root (superuser/sysadmin) access. The CAP_SYSLOG capability gives the process (or thread) the capability to perform privileged syslog(2) operations.
A quick word on the kptr_restrict sysctl
Section titled “A quick word on the kptr_restrict sysctl”As already mentioned, “leaking” a kernel address and the symbol it’s associated with might result in an info-leak-based attack. To help prevent these, kernel and module authors are advised to, firstly, simply avoid printing kernel addresses. If you must print them, then always use a new-ish (and kernel-specific) printf -style format: instead of the familiar %p or %px to print a kernel (virtual) address, you should use the %pK format specifier for printing an address. Using the %px format specifier ensures the actual address is printed; while perhaps useful for debugging, you’ll definitely want to avoid this in production. How do these this printk format specifiers help? Read on…
The kptr_restrict sysctl (2.6.38 onward) affects the printk() output when printing kernel addresses; doing printk("&var = %pK\n", &var);and not the good old printk("&var = %p\n", &var); is considered a security best practice. Understanding how exactly the kptr_restrict tunable works is key to this:
kptr_restrict/proc/sys/kernel/kptr_restrict (since Linux 2.6.38)The value in this file determines whether kernel addresses are exposed via /proc files and other interfaces. A value of 0 in this file imposes no restrictions. If the value is 1, kernel pointers printed using the %pK format specifier will be replaced with zeros unless the user has the CAP_SYSLOG capability. If the value is 2, kernel pointers printed using the %pK format specifier will be replaced with zeros regardless of the user's capabilities. The initial default value for this file was 1, but the default was changed to 0 in Linux 2.6.39. Since Linux 3.4, only users with the CAP_SYS_ADMIN capability can change the value in this file.Again, the default values of this sysctl on our recent-enough Ubuntu and Fedora platforms are 1 and 0 respectively. You can leverage the sysctl utility to see (and, as root, change) kernel sysctls; on our Ubuntu 22.04 VM:
$ sysctl kernel.dmesg_restrict kernel.kptr_restrictkernel.dmesg_restrict = 1kernel.kptr_restrict = 1Here’s a table summarizing how the kptr_restrict sysctl behaves:
kptr_restrict value | Unprivileged user and printk uses %pK | Privileged user (root) and printk uses %pK |
0 | No restrictions (kernel addresses are exposed) | |
1 | Kernel addresses replaced with zeroes (unless the caller has | No restrictions (kernel addresses are exposed) |
2 | Kernel addresses replaced with zeroes | |
Table 5.2: A summary of how the kptr_restrict sysctl’s value affects the display of kernel addresses in different circumstances
You can – rather, must – change these sysctls on production systems to a secure value (1 or 2), a best practice for security.
a) As procfs is, of course, a volatile filesystem, you can always make the changes permanent by using the sysctl(8) utility with the -w option switch (or by directly updating the /etc/sysctl.conf file).
b) For the purpose of debugging, if you must print an actual kernel (unmodified) address, you’re advised to use the %px format specifier; do remove these prints on production systems!
c) Detailed kernel documentation on printk format specifiers can be found at https://www.kernel.org/doc/html/latest/core-api/printk-formats.html#how-to-get-printk-format-specifiers-right; do browse through it.
Of course, security measures only work when developers make use of them; as of the 6.1.25 kernel source tree, there is an approximate total of 87,000-odd uses of the printk () (~ 33k) and friends (pr_*(): ~ 54k) routines. Of these, a measly 24 employ the security-aware %pK format specifier! (To find out, I grepped the kernel source tree’s *.[ch] files with the regular expressions printk\(.*\%pK and pr_.*\(.*\%pK. Though unlikely to be perfect, this gives a decent approximation. The first edition of this book found just 14 users of the %pK format specifier in the 5.4.0 kernel source tree; so, it’s improving, slowly.)
With the advent of hardware-level defects in early 2018 (the now well-known Meltdown, Spectre, and other processor speculation security issues), there was a sense of renewed urgency in detecting information leakage, thus enabling developers and administrators to block it off.
A useful Perl script, scripts/leaking_addresses.pl, was released in mainline in 4.14 (in November 2017; I am happy to have lent a hand in this important work: https://github.com/torvalds/linux/commit/1410fe4eea22959bd31c05e4c1846f1718300bde), with more checks being made for detecting leaking kernel addresses.
Let’s now look at an exciting and powerful security feature, especially for module authors!
Understanding the cryptographic signing of kernel modules
Section titled “Understanding the cryptographic signing of kernel modules”Once a malicious attacker gets a foothold on a system, they will typically attempt some kind of privesc vector in order to gain root access. Once this is achieved, the typical next step is to install a rootkit: essentially, a collection of scripts and kernel modules that will pretty much take over the system in a stealthy manner (by “hijacking” system calls, setting up backdoors, keyloggers, and so on) so that the attacker can reenter the system at will.
Of course, it’s not easy – the security posture of a modern production-quality Linux system, replete with Linux Security Modules (LSMs) and various user/kernel hardening features, means it’s not at all a trivial thing to do, but for a skilled and motivated attacker, anything’s possible (for sensitive installations, that’s the right mindset to have). Assuming they have a sufficiently sophisticated rootkit installed, the system is now considered compromised.
An interesting idea is this: even with root access, do not allow anything – the insmod (or modprobe, or even the underlying [f]init_module() system calls) – to insert kernel modules into kernel address space unless they are cryptographically signed with a security key that is in the kernel’s keyring*.* This powerful security feature was introduced with the 3.7 kernel, over a decade back! (The relevant initia commit is here: https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=106a4ee258d14818467829bf0e12aeae14c16cd7.)
A few relevant kernel configuration options concerned with this feature are CONFIG_MODULE_SIG, CONFIG_MODULE_SIG_FORCE, CONFIG_MODULE_SIG_ALL, and so on. You can see and set them up from the usual make menuconfig UI: navigate to Enable loadable module support > Module signature verification. Most are off by default; I turned Module signature verification on first. A partial screenshot showing these options follows:

Figure 5.9: Partial screenshot showing the various module signature options (among others)
So, now we understand better: when installing modules, we can arrange appropriate kernel configs so that:
- Installed modules can be signed (
CONFIG_MODULE_SIG=y). - All installed modules will always be signed (
CONFIG_MODULE_SIG_ALL=y). - Installed modules will not be loaded into kernel memory unless they are signed (aka “sig force” (
CONFIG_MODULE_SIG_FORCE=y)! - Modules are (also) compressed when being installed (
CONFIG_MODULE_COMPRESS_XZ=y, among others).
To help understand what exactly the first one, CONFIG_MODULE_SIG=y, means, let’s see its Kconfig file’s “ help ” section, as follows (from init/Kconfig):
config MODULE_SIG bool "Module signature verification" depends on MODULES select SYSTEM_DATA_VERIFICATION help Check modules for valid signatures upon load: the signature is simply appended to the module. For more information see <file:Documentation/admin-guide/module-signing.rst>. Note that this option adds the OpenSSL development packages as a kernel build dependency so that the signing tool can use its crypto library. You should enable this option if you wish to use either CONFIG_SECURITY_LOCKDOWN_LSM or lockdown functionality imposed via another LSM - otherwise unsigned modules will be loadable regardless of the lockdown policy. !!!WARNING!!! If you enable this option, you MUST make sure that the module DOES NOT get stripped after being signed. This includes the debuginfo strip done by some packagers (such as rpmbuild) and inclusion into an initramfs that wants the module size reduced.Do read the above Help screen carefully. Our “better” Makefile takes this warning seriously and does not strip (debug) symbols if any of the CONFIG_MODULE_SIG* kernel configs are on.
The two module-signing modes
Section titled “The two module-signing modes”Module signing works in two possible modes:
- Permissive (the default): When
CONFIG_MODULE_SIG_FORCEis off. Allows modules that aren’t signed (or where the key isn’t available) to be loaded. As a side effect, the kernel is marked as being “tainted” (with the E bit being set for it and the concerned module). This setting – permissive – tends to be the default on a typical modern Linux distribution. - Restrictive: When
CONFIG_MODULE_SIG_FORCEis on (set toy, or the kernel command line includesmodule.sig_enforce=1). Now only valid signed modules (which are verified by a key in the kernel) will be allowed to load. Further, any modules with a signature block that can’t be parsed by the kernel or is mismatched will refuse to be loaded. This is good for added security. (Recall, though, that the module(s) must not be stripped in any manner.) Tainted kernel: The word “tainted” means polluted or dirtied… the kernel is marked as tainted in some situations (like an Oops, a proprietary or unsigned module being loaded, and several more). The kernel maintains a tainted bitmask; it has no material effect, but it can help when investigating what happened. See details here: https://docs.kernel.org/admin-guide/tainted-kernels.html.
In the following output block, I look up these kernel configs on my x86_64 Fedora 38 system (running a recent 6.5-based distro kernel):
$ grep MODULE_SIG /boot/config-6.5.6-200.fc38.x86_64CONFIG_MODULE_SIG_FORMAT=yCONFIG_MODULE_SIG=y# CONFIG_MODULE_SIG_FORCE is not setCONFIG_MODULE_SIG_ALL=y[ ... ]The CONFIG_MODULE_SIG_ALL being set to y ensures that all kernel modules, when installed, are signed! (Using module signing does imply that the OpenSSL developer packages must be installed on the system, as it has the tool that performs the signing.) This being the default setting seems to be good for security. However, precisely for security, it’s then also definitely recommended that the keypair (public/private) being used should be one other than the kernel default (these are configurable via the certs/x509.genkey, which will be generated as required). Thus, it’s recommended you explicitly set up this file and don’t use the kernel defaults.
It’s also possible to manually sign your kernel modules by leveraging the scripts/sign-file program (which gets built from its C source file). All of this, and more, is very well documented in the official kernel documentation: https://www.kernel.org/doc/html/v6.1/admin-guide/module-signing.html; do refer to it. (FYI, Ubuntu has its own kernel module-signing tool, kmodsign.)
Thus, the cryptographic signing and load-only-if-signed behavior of kernel modules is encouraged on production systems (in recent years, with (I)IoT edge devices becoming more prevalent, security is a key concern).
Disabling kernel modules altogether
Section titled “Disabling kernel modules altogether”Paranoid folks might want to completely disable the loading of kernel modules. Rather drastic, but hey, this way you can completely lock down the kernel space of a system (as well as render any rootkits pretty much harmless). This can be achieved in two broad ways:
- First, while configuring your kernel, set the
CONFIG_MODULESkernel config to off (it’s on, of course, by default). Doing this is pretty drastic – it makes the decision a permanent one! - Second, assuming
CONFIG_MODULESis turned on, module loading can be dynamically turned off at runtime via themodules_disabled sysctl; take a look at this:$ cat /proc/sys/kernel/modules_disabled0
It’s off (0) by default, of course. As usual, the man page on proc(5) tells us the story:
/proc/sys/kernel/modules_disabled (since Linux 2.6.31)A toggle value indicates if modules are allowed to be loaded in an otherwise modular kernel. This toggle defaults to off (0), but can be set true (1).Once true, modules can be neither loaded nor unloaded, and the toggle cannot be set back to false. The file is present only if the kernel is built with the CONFIG_MODULES option enabled.The kernel lockdown LSM – an introduction
Section titled “The kernel lockdown LSM – an introduction”An even more powerful kernel hardening feature is a relatively recent (from 5.4) one, an LSM (Linux Security Module) named lockdown; it can be quite strict and invasive and is thus disabled by default. In short, it disables user-mode apps/scripts from making modifications to the running kernel (via its so-called Integrity mode). An even more strict lockdown mode, Confidential, in addition, prevents the extraction of kernel information considered to be confidential (thus helping prevent info leaks and more).
Note that the lockdown feature can be auto-enabled when using Secure Boot mode on (U)EFI x86 or AArch64! This, in turn, can lead to your modules failing to load (it happened to me once). Security can – and does – tend to be a double-edged sword.
More on the lockdown LSMcan be found in the Further reading section.
In conclusion, of course, kernel security hardening and malicious attacks are a cat-and-mouse game. For example, a security hardening measure called (K)ASLR (we talk about what (K)ASLR means in the chapters to come on Linux memory management) is quite regularly defeated. Also, see this article – Effectively bypassing kptr_restrict on Android: http://bits-please.blogspot.com/2015/08/effectively-bypassing-kptrrestrict-on.html. Security is not easy; it’s always a work in progress. It (almost) goes without saying: developers – in both user and kernel space – need to be clued into the required and actual security posture of the system and must write code that is security-aware, using tools and testing to verify it on a continuous basis. (More work, but hey, we have to do it.)
Let’s complete this chapter with a bit on the kernel community – coding style guidelines, and quick how-to-style pointers on upstream contribution.
Coding style guidelines for kernel developers
Section titled “Coding style guidelines for kernel developers”Many large projects specify their own set of coding guidelines; so does the Linux kernel community. Adhering to the Linux kernel coding style guidelines is a really good idea when writing kernel and/or kernel module code. You can see the style guidelines officially documented here: https://www.kernel.org/doc/html/latest/process/coding-style.html (please do read them!).
Furthermore, as part of the (quite exhaustive) code-submission checklist(s) for developers like you wanting to upstream your code, you are expected to run your patch through a Perl script that checks your code for congruence with the Linux kernel coding style: scripts/checkpatch.pl.
By default, this script only runs on a well-formatted git patch. It’s possible to run it against standalone C code (as in your out-of-tree kernel module code), as follows (as our “better” Makefile indeed does):
<kernel-src>/scripts/checkpatch.pl --no-tree -f <filename>.cDoing this as a habit with your kernel code is helpful, enabling you to catch those annoying little issues – plus more serious ones! – that might otherwise hold your patch up. Again, we’ll remind you: our “better” Makefile’s indent and checkpatch targets are geared toward this.
Exercise: cd to your module directory (the one that has the “better” Makefile) and do this: make checkpatch. This will, via the Makefile, have the checkpatch target execute on your code, which in turn invokes the kernel’s checkpatch.pl script on it. Carefully read any warnings and errors generated, fix them, and repeat. (Note: Typically, the first warning emitted can be ignored as it pertains to specifying the “SPDX-License” tag as the first line.)
Besides coding style guidelines, you will find that every now and then, you need to dig into the elaborate and useful kernel documentation. A gentle reminder: we covered locating and using the kernel documentation in Online Chapter, Kernel Workspace Setup, under the Locating and using the Linux kernel documentation section. It pays to get yourself familiar with the kernel documentation.
We will now complete this chapter by making a brief mention of how you can get started on a noble objective: contributing code to the mainline Linux kernel project.
Contributing to the mainline kernel
Section titled “Contributing to the mainline kernel”In this book, we typically perform kernel development outside the kernel source tree, via the LKM framework. What if you are writing code within the kernel tree, with the explicit goal of upstreaming your code to the mainline kernel? This is a laudable goal indeed – the whole basis of open source stems from the community’s willingness to put in work and contribute upstream to the project.
Getting started with contributing to the kernel
Section titled “Getting started with contributing to the kernel”The most frequently asked question, of course, is how do I get started?To help you precisely with this, a long and detailed answer lies within the official kernel documentation here: HOWTO do Linux kernel development: https://www.kernel.org/doc/html/latest/process/howto.html#howto-do-linux-kernel-development.
As a matter of fact, you can generate the full Linux kernel documentation (via the make pdfdocs command, in the root of the kernel source tree); once successful, you will find this PDF document – the same HOWTO do Linux kernel development one –here: <root-of-kernel-source-tree>/Documentation/output/latex/development-process.pdf.
It is a very detailed guide to the Linux kernel development process, including guidelines for code submission. A cropped screenshot of this document is shown here:

Graphical user interface, text, application, email Description automatically generated
Figure 5.10: (Partial) screenshot of the kernel development docs just generated
As a part of the kernel development process, and to maintain quality standards, a rigorous, must-be-followed checklist – a long recipe of sorts! – is very much a part of the kernel patch submission process (the current latest version of this checklist has 24 points, no less). The official checklist resides here: Linux Kernel patch submission checklist: https://www.kernel.org/doc/html/latest/process/submit-checklist.html#linux-kernel-patch-submission-checklist.
Though it may seem an onerous task for a kernel newbie, carefully following this checklist lends both rigor and credibility to your work and ultimately results in superior code. I strongly encourage you to read through the kernel patch submission checklist and try out the procedures mentioned therein.
Is there a practical hands-on tip, an almost guaranteed way, to become a kernel hacker? Of course, keep reading this book! Ha ha, yes, besides that, do partake in the simply awesome Eudyptula Challenge (http://www.eudyptula-challenge.org/) Oh, hang on, it’s – very unfortunately, and as of the time of writing – closed down.
Fear not; here’s a site with all the challenges (and solutions, but don’t cheat!) posted. Do check it out and try the challenges. This will greatly accelerate your kernel hacking skills: https://github.com/agelastic/eudyptula.
Summary
Section titled “Summary”In this chapter, the second one on writing kernel modules via the LKM framework, we covered several (remaining) areas pertaining to this important topic: among them, using a “better” Makefile for your kernel module, tips on configuring a debug kernel (it’s very important!), cross-compiling a kernel module, gathering some minimal platform information from within a kernel module, and even a bit on the licensing of kernel modules. We also looked at emulating library-like features with two different approaches (first – the typically preferred one, which is the linking approach, and second, the module-stacking approach), using module parameters, avoiding floating-point arithmetic, the auto-loading of your kernel modules at boot, and so on. Security concerns, especially regarding modules and how they can be addressed, are important and have been covered. Finally, we wrapped up this chapter by covering kernel coding style guidelines, and how you can get started with contributing to the mainline kernel. So, congratulations! You now know how to develop a kernel module and can even get started on the journey to kernel upstream contribution.
In the next chapter (the first of our Part 2 – Understanding and Working with the Kernel, topics), we will delve into an interesting and necessary topic. We will begin our exploration in some depth into the internals of the Linux kernel, with respect to its architecture, how it encapsulates processes and threads, and more.
Questions
Section titled “Questions”As we conclude, here is a list of questions for you to test your knowledge regarding this chapter’s material: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/questions/ch5_qs_assignments.txt. You will find some of the questions answered in the book’s GitHub repo: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/tree/main/solutions_to_assgn.
Further reading
Section titled “Further reading”To aid you in delving deeper into the subject with useful materials, we provide a rather detailed list of online references and links (and at times even books) in a Further reading markdown document – organized by chapter – in this book’s GitHub repository. The Further reading document is available here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/Further_Reading.md.
Get This Book’s PDF Version and Exclusive Extras
|