Writing Your First Kernel Module – Part 1
local graph
Chapter 4 — Writing Your First Kernel Module – Part 1
Section titled “Chapter 4 — Writing Your First Kernel Module – Part 1”In the previous two chapters, you have learned the ins and outs of obtaining the kernel source tree and configuring and building it (for the x86). Now, welcome to your journey of learning about a fundamental aspect of Linux kernel development – the Loadable Kernel Module (LKM) framework – and how it is to be used by the module user or module author, who is typically a kernel or device driver programmer. This topic is rather vast and hence is split into two chapters – this one and the next.
In this chapter, we’ll begin by taking a quick look at the basics of the Linux kernel architecture, which will help us understand the LKM framework. Then, we’ll look into why kernel modules are useful and write, build, and run our simple Hello, world LKM. We’ll see how messages are written to the kernel log and understand and make use of the LKM Makefile. By the end of this chapter, you will have learned the basics of Linux kernel architecture and the LKM framework, applying it to write a simple yet complete piece of kernel code.
In this chapter, we will cover the following recipes:
- Understanding the kernel architecture – part 1
- Exploring LKMs
- Writing our very first kernel module
- Common operations on kernel modules
- Understanding kernel logging and printk
- Understanding the basics of a kernel module Makefile
Technical requirements
Section titled “Technical requirements”If you have already carefully followed Online Chapter, Kernel Workspace Setup, then a portion of the technical prerequisites that follow will already be taken care of. (The first chapter also mentions various useful open-source tools and projects; I definitely recommend that you browse through it at least once.) For your convenience, we summarize some key points here.
To build and use an external (or out-of-tree) kernel module on a Linux distribution (or custom system), you need:
- The kernel to be built with module support enabled (
CONFIG_MODULES=y) - At a minimum, the following two components to be installed:
- A toolchain: This includes the compiler, assembler, linker/loader, C library, and various other bits and pieces. If building for the local system, as we assume for now, then any modern Linux distribution will have a native toolchain pre-installed. If not, simply installing the GCC package for your distribution should be sufficient; on an Ubuntu- or Debian-based Linux system, use this:
sudo apt install gcc
- Kernel headers: These headers will be used during the compilation of the LKM. In reality, you install a package geared to not only install the kernel headers but also other required bits and pieces (such as the kernel Makefile) onto the system. Again, any modern Linux distribution will/should have the kernel header pre-installed. If not (you can check using the
dpkgutility, as shown here), simply install the package for your distribution; on an Ubuntu- or Debian-based Linux system, use this:
$ sudo apt install linux-headers-generic$ dpkg -l | grep linux-headers | awk '{print $1, $2}'ii linux-headers-5.19.0-45-genericii linux-headers-generic-hwe-22.04 - Kernel headers: These headers will be used during the compilation of the LKM. In reality, you install a package geared to not only install the kernel headers but also other required bits and pieces (such as the kernel Makefile) onto the system. Again, any modern Linux distribution will/should have the kernel header pre-installed. If not (you can check using the
- A toolchain: This includes the compiler, assembler, linker/loader, C library, and various other bits and pieces. If building for the local system, as we assume for now, then any modern Linux distribution will have a native toolchain pre-installed. If not, simply installing the GCC package for your distribution should be sufficient; on an Ubuntu- or Debian-based Linux system, use this:
Here, the second command using the dpkg utility is simply used to verify that the linux-headers packages are indeed installed.
This package may be named kernel-headers-<ver#> on some distributions. Also, for development directly on a Raspberry Pi, install the relevant kernel headers package named raspberrypi-kernel-headers.
Just in case you can’t build modules, try this: prepare the kernel for external module builds by running make modules_prepare in the root of your kernel source tree. With typical modern distros, you should not need to do this; module building should just work.
The entire source tree for this book is available in its GitHub repository at https://github.com/PacktPublishing/Linux-Kernel-Programming_2E; we expect you to clone it:
git clone \ https://github.com/PacktPublishing/Linux-Kernel-Programming_2E.gitThe code for this chapter is under its directory namesake, chn (where n is the chapter number; so here, it’s under ch4/).
Understanding the kernel architecture – part 1
Section titled “Understanding the kernel architecture – part 1”In this section, we begin to deepen our understanding of the Linux kernel. More specifically, here, we delve into what user and kernel spaces are, and the major subsystems and various components that make up the kernel. This information is dealt with at a higher level of abstraction for now and is deliberately kept brief. We shall delve a lot deeper into understanding the fabric of the kernel in Chapter 6, Kernel Internals Essentials – Processes and Threads.
User space and kernel space
Section titled “User space and kernel space”Modern microprocessors support code execution at a minimum of two privilege levels. As a real-world example, the Intel/AMD x86[-64] family supports four privilege levels (they call them ring levels), the AArch32 (ARM-32) microprocessor family supports up to seven modes (ARM calls them execution modes; six are privileged and one is non-privileged), and the AArch64 (ARM-64/ARMv8) microprocessor family supports four exception levels (EL0 to EL3, with EL0 being the least and EL3 being the most privileged).
The key point here is that for security and stability on the platform, all modern operating systems running on these processors will make use of (at least) two of the privilege levels (or modes) of execution, leading to the separation of the Virtual Address Space (VAS) into two clearly distinguished (virtual) address spaces:
User space: For applications to run in unprivileged user mode. All apps – processes and threads – will execute at this privilege in this space. So, right now, you’re perhaps using a browser, editor, PDF reader, terminal, email client, and so on. They’re all apps – ultimately, processes and threads; on Linux, they all execute in user space in user mode, which is unprivileged. We shall soon come to what exactly is meant by privileged versus unprivileged.
Kernel space: For the kernel (and all its components) to run in privileged mode – kernel mode. This is the domain of the OS and whatever’s within it (like drivers, networking, I/O, and so on, including kernel modules). They all run with OS privilege; in effect, they can do anything they like! Note carefully that this privilege level is a hardware feature, and it’s not the same as running as root or not (that’s a pure software artifact); in many cases, running with kernel privilege can be thought of as effectively running as root.
The following figure shows this basic architecture:

Diagram Description automatically generated
Figure 4.1: Basic architecture – two address spaces, two privilege modes
A few details on the Linux system architecture follow; do read on.
Library and system call APIs
Section titled “Library and system call APIs”User space applications often rely on Application Programming Interfaces (APIs) to perform their work. A library is essentially a collection or archive of APIs, allowing you to use a standardized, well-written, and well-tested interface (and leverage the usual benefits: not having to reinvent the wheel, portability, standardization, and so on). Linux systems have several libraries: even hundreds on enterprise-class systems are not uncommon. Of these, all user mode Linux applications (executables) are “auto-linked” into one important, always-used library: glibc – the GNU standard C library, as you shall learn. However, libraries are only ever available in user mode; the kernel does not use these user mode libraries (more on this in the following chapter).
Examples of library APIs are the well-known printf(3), scanf(3), strcmp(3), malloc(3), and free(3). (Recall, from Online Chapter, Kernel Workspace Setup, the Using the Linux man pages section.)
Now, a key point: if the user and kernel are separate address spaces and at differing privilege levels, how can a user process – which, as we just learned, is confined to user space – access the kernel? The short answer is: via system calls. A system call is a special API, in the sense that it is the only legal (synchronous) way for user space processes (or threads) to access the kernel. In other words, system calls are the only legal entry point into the kernel space.
They (system calls) have the built-in ability to switch from non-privileged user mode to privileged kernel mode (more on this and the monolithic design in Chapter 6, Kernel Internals Essentials – Processes and Threads, under the Process and interrupt contexts section). Examples of system calls include fork(2), execve(2), open(2), read(2), write(2), socket(2), accept(2), chmod(2), and so on.
Look up all library and system call APIs in the man pages online:
Library APIs, man section 3: https://linux.die.net/man/3/
System call APIs, man section 2: https://linux.die.net/man/2/
The point being stressed here is that it’s only via system calls that user applications (processes and threads) and the kernel communicate – that is the interface. In this book, we do not delve further into these details. If you are interested in knowing more, please refer to my earlier book Hands-On System Programming with Linux, Packt (specifically Chapter 1, Linux System Architecture).
This book is on kernel development, let’s begin to check out the various components of the kernel.
Kernel space components
Section titled “Kernel space components”This book focuses entirely on the kernel space, of course. The Linux kernel today is a rather large and complex beast. Internally, it consists of a few major subsystems and several components. A broad enumeration of kernel subsystems and components yields the following list:
- Core kernel: This code handles the typical hardcore work of any modern operating system, including (user and kernel) process and thread creation/destruction, CPU scheduling, synchronization primitives, signaling, timers, interrupt handling, namespaces, cgroups, module support, crypto, and more.
- Memory Management (MM): This handles all memory-related work, including the setup and maintenance of kernel and process Virtual Address Spaces (VASs).
- VFS (for filesystem support): The Virtual Filesystem Switch (VFS) is an abstraction layer over the actual filesystems implemented within the Linux kernel (for example,
ext[2|4],vfat,ntfs,msdos,iso9660,f2fS,ufS, and many more). - Block I/O: The code paths implementing the actual file I/O, from the filesystems right down to the block device driver and everything in between (really, quite a lot!), are encompassed here.
- Network protocol stack: Linux is well known for its precise, to-the-letter-of-the-RFC, high-quality implementation of the well-known (and not-so-well-known) network protocols at all layers of the model, with TCP/IP being perhaps the most famous.
- Inter-Process Communication (IPC) support: The implementation of IPC mechanisms is done here; Linux supports message queues, shared memory, semaphores (both the older SysV and the newer POSIX ones), and other IPC mechanisms.
- Sound support: All the code that implements audio is here, from the firmware to drivers and codecs.
- Virtualization support: Linux has become extremely popular with large and small cloud providers alike, a big reason being its high-quality, low-footprint virtualization engine, Kernel-based Virtual Machine (KVM).
All this forms the major kernel subsystems; in addition, we have these:
- Arch-specific (meaning CPU-specific) code
- Kernel initialization
- Security frameworks
- Many types of device drivers
Recall that in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, the A brief tour of the kernel source tree section gave the kernel source tree (code) layout corresponding to the major subsystems and other components.
It is a well-known fact that the Linux kernel follows the monolithic kernel architecture (as opposed to microkernel architecture). Essentially, a monolithic design is one in which all kernel components (that we mentioned in this section) live in and share the kernel VAS (or kernel segment). This can be clearly seen in the following diagram:

Diagram Description automatically generated
Figure 4.2: Linux kernel space – major subsystems and blocks
Another fact you should be aware of is that these address spaces are of course virtual address spaces and not physical. The kernel will map, at page granularity level, virtual pages to physical page frames leveraging hardware blocks such as the Memory Management Unit (MMU)and the processor plus Translation Lookaside Buffer (TLB) caches for gaining efficiencies. It does this by using a master kernel paging table to map kernel virtual pages to physical frames (RAM), and, for every single user space process that is alive, it maps the process’s (user) virtual pages to physical page frames via individual paging tables for each process.
More in-depth coverage of the essentials of the kernel and memory management architecture and internals awaits you in Chapter 6, Kernel Internals Essentials – Processes and Threads (and more chapters that follow).
Now that we have a basic understanding of the user and kernel virtual address spaces, let’s move on and begin our journey into the LKM framework.
Exploring LKMs
Section titled “Exploring LKMs”A kernel module is a means to provide kernel-level functionality without resorting to working within the kernel source tree and the static kernel image.
Visualize a scenario where you have to add a support feature to the Linux kernel – perhaps a new device driver in order to use a certain hardware peripheral chip, a new filesystem, or a new I/O scheduler. One way to do this is obvious: update the kernel source tree with the new code, and configure, build, test, and deploy it.
Though this may seem straightforward, it’s a lot of work – every change in the code that we write, no matter how minor, will require us to rebuild the kernel image and then reboot the system in order to test it. There must be a cleaner, easier way; indeed, there is – the LKM framework!
The LKM framework
Section titled “The LKM framework”The LKM framework is a means to compile a piece of kernel code typically outside of the kernel source tree, often referred to as “out-of-tree” code, keeping it independent from the kernel in a limited sense, and then insert or plug in the generated “module object” into kernel memory, kernel VAS, have it run and perform its job, and then remove it (or unplug it) from kernel memory. (Note that the LKM framework can also be leveraged to generate in-tree kernel modules, as we did when we built the kernel. Here, we focus on the out-of-tree module).
The kernel module’s source code, typically consisting of one or more C source files, header files, and a Makefile, is built (via make of course) into a kernel module. The kernel module itself is merely a binary object file and not a binary executable. In Linux 2.4 and earlier, the kernel module’s filename had a .o suffix; on modern 2.6 Linux and later, it instead has a .ko (k ernel o bject) suffix. Once built, you can insert this .ko file – the kernel module – into the live kernel at runtime, effectively making it a part of the kernel.
Note that not all kernel functionality can be provided via the LKM framework. Several core features, such as the core CPU (task) scheduler code, memory management, signaling, timer, interrupt management code paths, platform-specific drivers for driving pin controllers, clocks, and so on, can only be developed within the kernel itself. Similarly, a kernel module is only allowed access to a subset of the full kernel API and data variables; more on this later.
You might ask: how do I insert this module object into the kernel at runtime? Let’s keep it simple – the answer is: via the insmod utility. For now, let’s skip the details (these will be explained in the upcoming Running the kernel module section). The following figure provides an overview of first building and then inserting a kernel module into kernel memory:

Diagram Description automatically generated
Figure 4.3: Building and then inserting a kernel module into kernel memory
Worry not: the actual code for both the kernel module C source as well as its Makefile is dealt with in deep detail in an upcoming section; for now, we want to gain a conceptual understanding only.
The kernel module is loaded into and lives in kernel memory – that is, the kernel VAS (the bottom half of Figure 4.3) in an area of space allocated for it by the kernel. Make no mistake, it is kernel code and runs with kernel privilege.
This way, you, the kernel (or driver) developer, do not have to reconfigure, rebuild, and reboot the system each time. All you have to do is edit the code of the kernel module, rebuild it, remove the old copy from memory (if it exists), and insert the new version. It saves time and increases productivity.
Having said that, in the real world, even kernel modules can (and do) cause system-level crashes, necessitating the need to reboot the system (another reason why running in an isolated VM is advantageous).
Another reason that kernel modules are advantageous is that they lend themselves to dynamic product configuration. For example, kernel modules can be designed to provide different features at differing price points; a script generating the final image for an embedded product could install a given set of kernel modules depending on the price the customer is willing to pay. Here’s another example of how this technology is leveraged in a debug or troubleshooting scenario: a kernel module could be used to dynamically generate diagnostics and debug logs on an existing product. Technologies such as Kprobes and the like allow just this (my Linux Kernel Debugging book covers these in depth).
In effect, the LKM framework gives us a means of dynamically extending kernel functionality by allowing us to insert (and later remove) live code into (from) kernel memory. This ability to plug in and unplug kernel functionality at our whim makes us realize that the Linux kernel is not purely monolithic, it is also modular.
Kernel modules within the kernel source tree
Section titled “Kernel modules within the kernel source tree”In fact, the kernel module object isn’t completely unfamiliar to us. In Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, we built kernel modules as part of the kernel build process and had them installed.
Recall that these kernel modules are part of the kernel source and have been configured as modules by selecting M in the tristate kernel menu config prompt. They get installed in directories under /lib/modules/$(uname -r)/. So, to see a little bit regarding the kernel modules installed under our currently running x86_64 Ubuntu 22.04 LTS guest kernel, we can do this:
$ lsb_release -a 2>/dev/null |grep DescriptionDescription: Ubuntu 22.04.2 LTS$ uname -r5.19.0-45-generic$ find /lib/modules/$(uname -r)/ -name "*.ko" | wc -l6189Okay, the folks at Canonical and elsewhere have been busy! Over six thousand kernel modules… Think about it, it makes sense: distributors cannot know in advance exactly what hardware peripherals a user will end up using (especially on generic computers like x86 PCs). Kernel modules serve as a convenient means to support huge amounts of hardware without insanely bloating the kernel image file (the bzImage or Image files, for example).
The installed kernel modules for our Ubuntu Linux system live within the /lib/modules/$(uname -r)/kernel directory, as seen here:
$ ls /lib/modules/5.19.0-45-generic/kernel/arch/ block/ crypto/ drivers/ fs/ kernel/ lib/ mm/ net/samples/ sound/ ubuntu/ v4l2loopback/ zfs/$ ls /lib/modules/6.1.25-lkp-kernel/kernel/arch/ crypto/ drivers/ fs/ lib/ net/ sound/Here, looking at the top level of the kernel/ directory under /lib/modules/$(uname -r) for the distro kernel (Ubuntu 22.04 LTS running the 5.19.0-45-generic kernel), we see that there are many sub-folders and literally a few thousand kernel modules packed within. By contrast, for the kernel we built (refer 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, for the details), there are much fewer. You will recall from our discussions in Chapter 2, Building the 6.x Linux Kernel from Source – Part 1, that we deliberately used the localmodconfig target to keep the build (relatively) small and fast. Thus, here, for example, our custom 6.1.25 kernel has just some 70-odd kernel modules built against it.
One area that sees heavy usage of kernel modules is that of device drivers. As an example, let’s look at a network device driver that is architected as a kernel module. You can find several (with familiar brand names!) under the distro kernel’s kernel/drivers/net/ethernet folder:

Figure 4.4: Content of our distro kernel’s Ethernet network drivers (kernel modules)
Popular on many Intel-based laptops is the Intel 1GbE Network Interface Card (NIC) Ethernet adapter. The network device driver that drives it is called the e1000 driver (more recent systems perhaps use a later model, and hence the e1000e module driver).
A convenient way to look up all kernel modules currently in kernel memory is via the lsmod utility (read it as “list mod(ules)” – we’ll learn more regarding its output format later). Our x86_64 Ubuntu 22.04 guest (running on an x86_64 host laptop) shows that it indeed uses this driver:
$ lsmod | grep e1000e1000 159744 0Importantly for us right now, we can see that the e1000 driver is a kernel module! How about obtaining some more information on this particular kernel module? That’s quite easily done by leveraging the modinfo utility (for readability, we truncate its verbose output here):
$ ls -l /lib/modules/5.19.0-45-generic/kernel/drivers/net/ethernet/intel/e1000total 364-rw-r--r-- 1 root root 372185 Jun 7 19:53 e1000.ko$ modinfo /lib/modules/5.19.0-45-generic/kernel/drivers/net/ethernet/intel/e1000/e1000.kofilename: /lib/modules/5.19.0-45-generic/kernel/drivers/net/ethernet/intel/e1000/e1000.kolicense: GPL v2description: Intel(R) PRO/1000 Network Driverauthor: Intel Corporation, <[email protected]>srcversion: F35F102C5522A6614A9D65Calias: pci:v00008086d00002E6Esv*sd*bc*sc*i*alias: pci:v00008086d000010B5sv*sd*bc*sc*i*[ … ]intree: Yname: e1000vermagic: 5.19.0-45-generic SMP preempt mod_unload modversionssig_id: PKCS#7signer: Build time autogenerated kernel key[ … ]parm: SmartPowerDownEnable:Enable PHY smart power down (array of int)parm: copybreak:Maximum size of packet that is copied to a new buffer on receive (uint)parm: debug:Debug level (0=none,...,16=all) (int)$The modinfo utility allows us to peek into a kernel module’s binary image and extract some details regarding it; more on using modinfo follows in the next section.
You might find the kernel module file is compressed (for example, e1000.ko.xz); its a feature, not a bug (more on this later). Another way to gain useful information on the system, including information on kernel modules that are currently loaded up, is via the systool utility. For an installed kernel module (details on installing a kernel module follow in the next chapter, in the Auto-loading modules on system boot section), doing systool -m <module-name> -v reveals information about it. Look up the systool(1) man page for usage details.
The bottom line is that kernel modules have come to be the pragmatic way to build and distribute some types of kernel components, with device drivers likely being the most frequent use case for them. Other uses include but aren’t limited to filesystems, network firewalls, packet sniffers, and custom kernel code.
So, if you would like to learn how to write a Linux device driver, a filesystem, or a firewall, it’s highly recommended you first learn how to write a kernel module, thus leveraging the kernel’s powerful LKM framework. That’s precisely what we will be doing next.
Writing our very first kernel module
Section titled “Writing our very first kernel module”When introducing a new programming language or topic, it has become a widely accepted computer programming tradition to mimic the original Hello, world program as the very first piece of code. I’m happy to follow this venerated tradition to introduce the Linux kernel’s powerful LKM framework. In this section, you will learn the steps to code a simple LKM. We explain the code in detail.
Introducing our Hello, world LKM C code
Section titled “Introducing our Hello, world LKM C code”Without further ado, here is some simple Hello, world C code, implemented to abide by the Linux kernel’s LKM framework:
For reasons of readability and space constraints, only the key parts of most source code are displayed here. To view the complete source code (with all comments), build it, and run it, the entire source tree for this book is available in its GitHub repository here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E. We definitely expect you to clone it and use it:
git clone https://github.com/PacktPublishing/Linux-Kernel-Programming_2E.git$ cat <LKP2E_src>/ch4/helloworld_lkm/helloworld_lkm.c#include <linux/init.h>#include <linux/module.h>/* Module stuff */MODULE_AUTHOR("<insert your name here>");MODULE_DESCRIPTION("LKP2E book:ch4/helloworld_lkm: hello, world, our first LKM");MODULE_LICENSE("Dual MIT/GPL");MODULE_VERSION("0.2");static int __init helloworld_lkm_init(void){ printk(KERN_INFO "Hello, world\n"); return 0; /* success */}static void __exit helloworld_lkm_exit(void){ printk(KERN_INFO "Goodbye, world! Climate change has done us in...\n");}module_init(helloworld_lkm_init);module_exit(helloworld_lkm_exit);You can try out this simple Hello, world kernel module right away! Just cd to the correct source directory and use our helper lkm script to build and run it:
$ cd ~/Linux-Kernel-Programming_2E/ch4/helloworld_lkm$ ../../lkm helloworld_lkm.cUsage: lkm name-of-kernel-module-file ONLY (do NOT put any extension).$ ../../lkm helloworld_lkmVersion info:Distro: Ubuntu 22.04.2 LTSKernel: 5.19.0-45-generic[ … ]make || exit 1------------------------------make -C /lib/modules/5.19.0-45-generic/build/ M=/home/c2kp/Linux-Kernel-Programming_2E/ch4/helloworld_lkm modules[ … ]sudo dmesg------------------------------[ 4123.028252] Hello, world$The hows and whys will be explained in a lot of detail shortly. Though tiny, the code of this, our very first kernel module, requires careful perusal and understanding. Do read on!
Breaking it down
Section titled “Breaking it down”The following subsections explain pretty much each line of the preceding Hello, world C LKM code. Remember that although the program appears very small and trivial, there is a lot to be understood regarding it and the surrounding LKM framework. The rest of this chapter focuses on this and goes into detail. I highly recommend that you take the time to read through and understand these fundamentals first. This will help you immensely in later, possibly difficult-to-debug situations.
Kernel headers
Section titled “Kernel headers”First thing in the code, we use #include to (obviously) include a few header files. Unlike in user space C application development, these are kernel headers (as mentioned in the Technical requirements section). Recall from Chapter 3, Building the 6.x Linux Kernel from Source – Part 2, that kernel modules were installed under a specific root-writable branch.
Let’s check it out again (here, we’re running on our guest x86_64 Ubuntu VM with the 5.19.0-45-generic distro kernel):
$ ls -l /lib/modules/$(uname -r)total 6712lrwxrwxrwx 1 root root 40 Jun 7 19:53 build -> /usr/src/linux-headers-5.19.0-45-genericdrwxr-xr-x 2 root root 4096 Jun 23 09:47 initrd[ … ]Notice the symbolic or soft link here named build. It points to the location of the kernel headers on the system. In the preceding code block, you can see that it’s in the directory /usr/src/linux-headers-5.19.0-45-generic/! As you will see, we will supply this information to the Makefile used to build our kernel module. (Also, some systems have a similar soft link called source.)
The kernel-headers or linux-headers package unpacks a limited kernel source tree onto the system, typically under /usr/src/…. This kernel code base, however, isn’t complete, hence our use of the phrase limited source tree. This is because the complete kernel source tree isn’t required for the purpose of building modules – just the required components (the headers, the Makefiles, and so on) are what’s packaged and extracted.
The first line of code in our Hello, world kernel module is #include <linux/init.h>.
The compiler resolves this line by searching for the previously mentioned kernel header file under /lib/modules/$(uname -r)/build/include/. Thus, by following the build soft link, we can see that it ultimately picks up this header file:
$ ls -l /usr/src/linux-headers-5.19.0-45-generic/include/linux/init.h-rw-r--r-- 1 root root 11963 Aug 1 2022 /usr/src/linux-headers-5.19.0-45-generic/include/linux/init.hThe same follows for the other kernel headers included in the kernel module’s source code.
Module macros
Section titled “Module macros”Next, we have a few module macros of the form MODULE_FOO(); (colloquially called “module stuff”). Most are quite intuitive:
MODULE_AUTHOR(): Specifies the author(s) of the kernel moduleMODULE_DESCRIPTION(): Briefly describes the function or purpose of this LKMMODULE_LICENSE(): Specifies the license(s) under which this kernel module is releasedMODULE_VERSION(): Specifies the (local) version string of the kernel module
In the absence of the source code, how will this information be conveyed to the end user (or customer)? Ah, the modinfo utility does precisely that! These macros and their information might seem trivial, but they are important in projects and products.
This information is relied upon, for example, by a vendor establishing the (open source) licenses that code is running under by using grep on the modinfo output on all installed kernel modules. (These are the basic module macros; there are more that we shall cover as we go along.)
Entry and exit points
Section titled “Entry and exit points”Never forget, kernel modules are, after all, kernel code running with kernel privilege. It’s not an application and thus does not have its entry point as the familiar main() function (that we know well and love). This, of course, begs the question: what are the entry and exit points of the kernel module? Notice, at the bottom of our simple kernel module, the following lines:
module_init(helloworld_lkm_init);module_exit(helloworld_lkm_exit);The module_{init|exit}() code are macros specifying the entry and exit points, respectively. The parameter to each is a function pointer. With modern C compilers, we can just specify the name of the function. Thus, in our code, the following applies:
- The
helloworld_lkm_init()function is the entry point. - The
helloworld_lkm_exit()function is the exit point.
You can almost think of these entry and exit points as a constructor/destructor pair for a kernel module. Technically, it’s not the case of course, as this isn’t object-oriented C++ code, it’s plain C. Nevertheless, it’s a useful analogy, perhaps.
Return values
Section titled “Return values”Notice the signature of the init and exit functions is as follows:
static int __init <modulename>_init(void);static void __exit <modulename>_exit(void);As good coding practice, we have used the naming format for the functions as <modulename>_{init|exit}(), where <modulename> is replaced with the name of the kernel module. You will realize that this naming convention is just that – it’s merely a convention that is, technically speaking, unnecessary, but it is intuitive and thus helpful (remember, we humans must write code for humans to read and understand, not machines). Clearly, neither routine receives any parameter.
Marking both functions with the static qualifier implies that they are private to this kernel module. That is what we want.
Now let’s move along to the important convention that is followed for a kernel module’s init function’s return value.
The 0/-E return convention
Section titled “The 0/-E return convention”The kernel module’s init function is to return an integer, a value of type int; this is a key aspect. The Linux kernel has evolved a style or convention, if you will, with regard to returning values from it (meaning from kernel space, where the module resides and runs, to the user space process).
To return a value, the LKM framework follows what is colloquially referred to as the 0/-E convention:
- Upon success, return integer value
0. - Upon failure, return the negative of the value you would like the user space global uninitialized integer
errnoto be set to.
Be aware that errno is a global integer residing in a user process VAS within its uninitialized data segment. With very few exceptions, whenever a Linux system call fails, -1 is returned and errno is set to a positive value, representing the failure code or diagnostic; this work is carried out by glibc “glue” code on the syscall return path.
Furthermore, the errno value is an index into a global table of English error messages (const char * sys_errlist[]); this is how routines such as perror(3), strerror[_r](3), and the like can print out failure diagnostics.
By the way, you can look up the complete list of error (errno) codes available to you from within these (kernel source tree) header files: include/uapi/asm-generic/errno-base.h and include/uapi/asm-generic/errno.h.
A quick example of how to return from a kernel module’s init function will help make this key point clear: say our kernel module’s init function is attempting to dynamically allocate some kernel memory (details on the kmalloc() API and so on will be covered in later chapters of course; please ignore it for now). Then, we could code it like so:
[...]ptr = kmalloc(87, GFP_KERNEL); if (!ptr) { pr_warning("%s():%s():%d: kmalloc failed! Out of memory\n", __FILE__, __func__, __LINE__); return -ENOMEM; } [...]return 0; /* success */If the memory allocation does fail (very unlikely, but hey, it can happen on a bad day!), we do the following:
- First, we emit a warning
printk(don’t worry, we’ll cover these syntax details and much more on theprintk). In this particular case – being “out of memory” – it’s considered pedantic and unnecessary to emit a message. The kernel will certainly emit sufficient diagnostic information if a kernel-space memory allocation ever fails! See this link for more details: https://lkml.org/lkml/2014/6/10/382; we do so here merely as it’s early in the discussion and for reader continuity. - Return the integer value
-ENOMEM:- The layer to which this value will be returned in user space is actually
glibc; it has some “glue” code that multiplies this value by-1and sets the global integererrnoto it.- Now, the
[f]init_module()system call will return-1, indicating failure (this is becauseinsmodactually invokes thefinit_module()(or, earlier, theinit_module()) system call, as you will soon see). errnowill be set toENOMEM, reflecting the fact that the kernel module insertion failed due to a failure to allocate memory.
- Now, the
- The layer to which this value will be returned in user space is actually
Conversely, the framework expects the init function to return the value 0 upon success. In fact, in older kernel versions, failure to return 0 upon success would cause the kernel module to be abruptly and immediately unloaded from kernel memory. Nowadays, this removal of the kernel module does not happen; instead, the kernel emits a warning message regarding the fact that a suspicious non-zero value has been returned. Moreover, modern compilers typically catch the fact that you aren’t returning a value when expected to, triggering an error message similar to this: error: no return statement in function returning non-void [-Werror=return-type].
There’s not much to be said for the cleanup routine. It receives no parameters and returns nothing (void). Its job is to perform any and all required cleanup (freeing memory objects, setting certain registers, perhaps, and so on, depending on what the module’s designed to do) before the kernel module is unloaded from kernel memory.
Not including the module_exit() macro in your kernel module makes it impossible to ever unload it (notwithstanding a system shutdown or reboot, of course). Interesting… I suggest you try this out as a small exercise! Of course, it’s never that simple: this behavior preventing the module from unloading is guaranteed only if the kernel is built with the CONFIG_MODULE_FORCE_UNLOAD flag set to Disabled (the default).
The ERR_PTR and PTR_ERR macros
Section titled “The ERR_PTR and PTR_ERR macros”On the discussion of return values, you now understand that the kernel module’s init routine must return an integer. What if you wish to return a pointer instead? The ERR_PTR() inline function comes to our rescue, allowing us to return an integer disguised as a pointer simply by typecasting it as void *.
It gets better: you can check for an error using the IS_ERR() inline function (which really just figures out whether the value is in the range [-1 to -4095]), encodes a negative error value into a pointer via the ERR_PTR() inline function, and retrieves this value from the pointer using the converse routine PTR_ERR().
As a simple example, see the callee code given here. This time, as an example, we have the (sample) function myfunc() return a pointer (to a structure named mystruct) and not an integer:
struct mystruct * myfunc(void) { struct mystruct *mys = NULL; mys = kzalloc(sizeof(struct mystruct), GFP_KERNEL); if (!mys) return ERR_PTR(-ENOMEM); [...] return mys; }The caller code is as follows:
[...]retp = myfunc();if (IS_ERR(retp)) { pr_warn("myfunc() mystruct alloc failed, aborting...\n"); stat = PTR_ERR(retp); /* sets 'stat' to the value -ENOMEM */ goto out_fail_1; } [...] out_fail_1: return stat; }FYI, the inline ERR_PTR(), PTR_ERR(), and IS_ERR() functions all live within the (kernel header) include/linux/err.h file. One example of usage for these functions is here: https://elixir.bootlin.com/linux/v6.1.25/source/arch/x86/kernel/cpu/sgx/ioctl.c#L269 (and the ERR_PTR() on line 31).
The __init and __exit keywords
Section titled “The __init and __exit keywords”Recall our simple module’s init and cleanup functions:
static int __init helloworld_lkm_init(void){ [ … ]static void __exit helloworld_lkm_exit(void){ [ … ]A niggling leftover: what exactly are the __init and __exit macros we see within the preceding function signatures? These are merely specifying memory optimization linker attributes.
The __init macro defines an init.text section for code. Similarly, any data declared with the __initdata attribute goes into an init.data section. The whole point here is the code and data in the init function are used exactly once during initialization.
Once it’s invoked, it will never be called again; so, once called, all the code and data in these init sections are freed up (via free_initmem()).
The deal is similar with the __exit macro, though, of course, this only makes sense with kernel modules. Once the cleanup function is called, all the memory is freed. If the code were instead part of the static kernel image (or if module support were disabled), this macro would have no effect.
Fine, but so far, we have still not explained some practicalities: how exactly can you build your new kernel module, get it into kernel memory and have it execute, and then unload it, plus several other operations you might wish to perform? Let’s discuss these in the following section.
Common operations on kernel modules
Section titled “Common operations on kernel modules”Now let’s delve into how exactly you can build, load, and unload a kernel module. Besides this, we’ll also walk through the basics regarding the tremendously useful printk() kernel API, details on listing the currently loaded kernel modules with lsmod, and a convenient script for automating some common tasks during kernel module development. So, let’s begin!
Building the kernel module
Section titled “Building the kernel module”At the risk of repetition, we urge you to try out our simple Hello, world kernel module as an exercise (if you haven’t already done so)! To do so, we assume you have cloned this book’s GitHub repository (https://github.com/PacktPublishing/Linux-Kernel-Programming_2E) already. If not, please do so now (refer to the Technical requirements section for details).
Here, we show, step by step, how exactly you can build and then insert our very first kernel module into kernel memory. Again, a quick reminder: we have performed these steps on an x86_64 Linux guest VM (under Oracle VirtualBox 7.x) running the Ubuntu 22.04 LTS distribution (not that it should matter too much which distro you use; the general steps remain the same):
- Change to this book’s source code chapter directory and sub-directory. Our first kernel module lives in its own folder (as it should!) called
helloworld_lkm:cd <book-code-dir>/ch4/helloworld_lkm
<book-code-dir> is, of course, the folder into which you cloned this book’s GitHub repository; on my system (see the screenshot in Figure 4.5), you can see that it’s /home/c2kp/kaiwanTECH/Linux-Kernel-Programming_2E.
- Now verify the code base:
$ pwd<book-code-dir>/ch4/helloworld_lkm$ ls -ltotal 8-rw-rw-r-- 1 c2kp c2kp 1238 Dec 18 12:38 helloworld_lkm.c-rw-rw-r-- 1 c2kp c2kp 290 Oct 27 07:26 Makefile
(It’s all right if the sizes don’t perfectly match the one you have; software evolves.)
- Build the kernel module with
make:
Figure 4.5: Listing and building our very first Hello, world kernel module
If you do come across it when building the module, you can for now quite safely ignore any warning messages related to “Skipping BTF generation for <...>/helloworld_lkm.ko due to the unavailability of vmlinux….”
The preceding screenshot shows that our kernel module has been successfully built; it’s the file, the “kernel object,” named ./helloworld_lkm.ko.
Always use make, and thus the Makefile provided, to build the kernel module; don’t try to manually build it by invoking gcc (or Clang) directly.
Also, note that we booted from, and thus have built the kernel module against, our custom 6.1.25 LTS kernel, built in earlier chapters. Now that we’ve successfully built our module, let’s run it!
Running the kernel module
Section titled “Running the kernel module”In order to have a kernel module run, you need to first load it into kernel memory space, of course. This is known as inserting the module into kernel memory.
Getting the kernel module into the Linux kernel segment or VAS (which is in RAM, of course) can be done in a few ways, which all ultimately boil down to invoking one of the [f]init_module() system calls.
For convenience, several wrapper utilities exist that will do so (or you can always write one). We will use the popular insmod (“ insert module ”) utility below; the parameter to insmod is the pathname to the kernel module to insert (FYI, insmod, under the hood, invokes the finit_module() system call to load the module into kernel memory):
$ insmod ./helloworld_lkm.koinsmod: ERROR: could not insert module ./helloworld_lkm.ko: Operation not permitted$It fails! In fact, it should be obvious why. Think about it: inserting code into the kernel is, in a very real sense, even superior to being root (superuser) on the system – again, I remind you: it’s kernel code and will run with kernel privilege. If any and every user is allowed to insert or remove kernel modules, hackers would have a field day! Deploying malicious code, that too at the level of the OS, would become a trivial affair. So, for security reasons, only with root access can you insert or remove kernel modules.
Technically, being root implies that the process’s (or thread’s) Real and/or Effective UID (RUID/EUID) value is the special value zero. Not only that, but the modern kernel “sees” a thread as having certain capabilities (via the modern and superior POSIX Capabilities model). Besides being root, an even better approach is to leverage this capabilities model; with it, only a process/thread with the CAP_SYS_MODULE capability can (un)load kernel modules. We refer you to the man page on capabilities(7) for more details.
So, let’s again attempt to insert our kernel module into memory, this time with root privileges via sudo:
$ sudo insmod ./helloworld_lkm.ko [sudo] password for c2kp:$ echo $?0Now it works (the $? result variable being 0 implies that the previous shell command was successful)! As alluded to earlier, the insmod utility works by invoking the finit_module() system call. When might the insmod utility fail? There are a few cases:
- The kernel config
CONFIG_MODULESis not set toy– i.e., the kernel’s built without support for loadable kernel modules. - When not run as root, or a lack of the
CAP_SYS_MODULEcapability (errnois then set to the valueEPERM). - When the kernel tunable within the
procfilesystem,/proc/sys/kernel/modules_disabled, is set to1(it defaults to0). - When a kernel module with the same name is already in kernel memory (
errnois then set to the valueEEXISTS).
Okay, here, all looks good. That’s great, but where on earth is our precious Hello, world message? Read on!
A quick first look at the kernel printk()
Section titled “A quick first look at the kernel printk()”To emit a message, the user space C developer will often use the trusty printf() glibc API (or perhaps the cout when writing C++ code). However, it’s important to understand that in kernel space, there are no (user mode or other) libraries. Hence, we simply do not have access to the good old printf() API. Instead, it has essentially been re-implemented within the kernel as the printk() kernel API. Curious as to where its code is? Well, it’s defined here as a macro within the kernel source tree: include/linux/printk.h:printk(fmt, …). The actual function is here: kernel/printk/printk.c:_printk(). The reality is that the internal printk implementation is pretty complex, involving a wrapper layer for printk indexing, and much more; see the Further reading section for more.
Luckily, for the kernel or a kernel module to emit a message via the printk() API is simple and very much similar to doing so with printf(). In our simple kernel module, here’s where the action occurs:
printk(KERN_INFO "Hello, world\n");Though very similar to printf at first glance, the printk API in the kernel is really quite different. In terms of similarities, the API receives a format string as its parameter. The format string is pretty much identical to that of printf.
But the similarities end there. A key difference between printf and printk is this: the user space printf() library API works by formatting a text string as requested and invoking the write() system call, which in turn actually performs a write to the stdout device, which, by default, is the Terminal window (or console device).
The kernel printk API also formats its text string as requested, but its output destination(s) differs. It writes to at least one place – the first one in the following list – and possibly to a few more:
- A (volatile) kernel log buffer in RAM
- A (non-volatile) log file, the kernel log file
- The console device
For now, we shall skip the inner details regarding the workings of printk. Also, right now, please ignore the KERN_INFO token within the printk API; we shall cover all this soon enough.
Next, don’t get overly attached to the printk() API; you’ll soon learn that the modern and recommended way to use it is via macros of the form pr_foo() (we cover them in the upcoming The pr_<foo> convenience macros section).
When you emit a message via printk, it’s guaranteed that the output goes into a log buffer in kernel memory (RAM). This, in effect, constitutes the (volatile) kernel log. It’s important to note that you will never see the printk output directly when working in graphical mode with an X server (Xorg, Xwayland, or whatever) process running (the default environment when working on a typical Linux distro).
So, the obvious question here is: how do you see the kernel log buffer content? There are a few ways. For now, let’s just make use of the quick and easy way.
Use the dmesg utility! By default, dmesg will dump the entire kernel log buffer content to stdout. Let’s try it out!
$ dmesgdmesg: read kernel buffer failed: Operation not permittedWe’ll quite often come across what’s termed a sysctl. Here, sysctl is short for system control, a tuning knob within the kernel, typically located under /proc/sys/<dir>/*; there are several directories, including fs, kernel, net, user, and vm. Typically, root access is required to write to a sysctl, while several can be read without special privileges. The official kernel documentation on the kernel sysctls is here, do have a look: https://www.kernel.org/doc/Documentation/sysctl/kernel.txt. In a similar manner, some of the other branches also have documentation; look here for them: https://www.kernel.org/doc/Documentation/sysctl/. Also look up this useful “sysctl explorer” website: https://sysctl-explorer.net/.
On several recent distros, a sysctl named dmesg_restrict (more on this later) prevents ordinary users from viewing the kernel log content; this is good for security (preventing info leaks). So, now let’s redo this, but this time with root privilege; let’s look up the last two lines of the kernel log buffer:
$ sudo dmesg | tail -n2[39884.691954] Hello, worldThere it is, finally: our Hello, world message!
You may see a message in the kernel log, something like loading out-of-tree module taints kernel and possibly module verification failed: signature and/or required key missing - tainting kernel. You can simply ignore them for now. For security reasons, most modern Linux distros will mark the kernel as tainted (literally, “contaminated” or “polluted”) if a third party/out-of-tree/external (or non-signed) kernel module is inserted. (Well, it’s really more of a pseudo-legal cover-up along the lines of “if something goes wrong from this point in time onward, we are not responsible, and so on…” – you get the idea!)
Within the kernel log, as displayed by the dmesg utility, the numbers within square brackets in the leftmost column are a simple timestamp, in [seconds.microseconds] format – the time elapsed since system boot (it’s not recommended to treat it as being perfectly accurate, though). By the way, this timestamp is a Kconfig variable – a kernel config option – named CONFIG_PRINTK_TIME; it can be overridden by the printk.time kernel parameter (link: https://elixir.bootlin.com/linux/v6.1.25/source/Documentation/admin-guide/kernel-parameters.txt#L4504).
Listing the live kernel modules
Section titled “Listing the live kernel modules”Back to our kernel module. So far, we have built it, loaded it into the kernel, and verified that its entry point, the helloworld_lkm_init() function, got invoked, thus executing the printk API. So after that, what does it do? Well, nothing; the kernel module merely (happily?) sits in kernel memory doing absolutely nothing. We can easily look it up with the lsmod utility:
$ lsmod | headhelloworld_lkm 16384 0isofs 49152 1vboxvideo 45056 0vboxsf 90112 0binfmt_misc 24576 1snd_intel8x0 49152 2snd_ac97_codec 176128 1 snd_intel8x0ac97_bus 16384 1 snd_ac97_codecsnd_pcm 151552 2 snd_intel8x0,snd_ac97_codeclsmod shows all kernel modules currently residing (or live) in kernel memory, sorted in reverse chronological order. Its output is column formatted, with three columns and an optional fourth one. Let’s look at each column separately:
- The first column displays the name of the kernel module.
- The second column is the (static) size in bytes that it’s taking in the kernel.
- The third column is the module usage count.
- The optional fourth column indicates a dependent module(s) and is explained in the next chapter (in the Module stacking section). Also, on recent x86_64 Ubuntu distros, a minimum of 16 KB of kernel memory seems to be taken up by a kernel module, and around 12 KB on Fedora.
So, great! By now you’ve successfully built, loaded, and run your first kernel module in kernel memory and it basically works: what next? Well, nothing much really with this one! We simply learn how to unload it in the following section. There’s a lot more to come of course… keep going!
Unloading the module from kernel memory
Section titled “Unloading the module from kernel memory”To unload the kernel module, we use the convenience utility rmmod (remove module):
$ rmmodrmmod: ERROR: missing module name.$ rmmod helloworld_lkmrmmod: ERROR: ../libkmod/libkmod-module.c:799 kmod_module_remove_module() could not remove 'helloworld_lkm': Operation not permittedrmmod: ERROR: could not remove module helloworld_lkm: Operation not permitted$ sudo rmmod helloworld_lkm [sudo] password for c2kp:$ dmesg | tail -n2[39884.691954] Hello, world[40280.138269] Goodbye, world! Climate change has done us in... $The parameter to rmmod is the name of the kernel module (as shown in the first column of lsmod), not the pathname. Clearly, just as with insmod, we need to run the rmmod utility as the root user for it to succeed (or with the CAP_SYS_MODULE capability).
Here, we can also see that, because of our rmmod, the LKM framework first invokes the exit routine (or “destructor”) helloworld_lkm_exit() function of the kernel module being removed. It in turn invokes printk, which emits the Goodbye, world… message (which we looked up with dmesg).
When could rmmod (note that internally, it invokes the delete_module() system call) fail? Here are some cases:
- Permissions: If it is not run as root or there is a lack of the
CAP_SYS_MODULEcapability (errnois then set to the valueEPERM). - If the kernel module’s code and/or data is being used by another module (if a dependency exists; this is covered in detail in the next chapter’s Module stacking section) or the module is currently in use by a process (or thread), then the module usage count will be positive and
rmmodwill fail (errnois then set to the valueEBUSY); makes sense. - The kernel module did not specify an exit routine (or destructor) with the
module_exit()macro and theCONFIG_MODULE_FORCE_UNLOADkernel config option is disabled.
Several convenience utilities concerned with module management are nothing but symbolic (soft) links to the single kmod utility (analogous to what the popular busybox utility does). The wrappers are lsmod, rmmod, insmod, modinfo, modprobe, and depmod. Take a look at a few of them:
$ ls -l $(which insmod) ; ls -l $(which lsmod) ; ls -l $(which rmmod)lrwxrwxrwx 1 root root 9 Apr 23 2022 /usr/sbin/insmod -> /bin/kmodlrwxrwxrwx 1 root root 9 Apr 23 2022 /usr/sbin/lsmod -> /bin/kmodlrwxrwxrwx 1 root root 9 Apr 23 2022 /usr/sbin/rmmod -> /bin/kmodNote that the precise location of these utilities (/bin, /sbin, or /usr/sbin) can vary with the distribution.
Our lkm convenience script
Section titled “Our lkm convenience script”Let’s round off this first kernel module discussion with a simple yet useful custom Bash script called lkm that helps you out by automating the kernel module build, load, dmesg, and unload workflow.
Here it is (the complete code is in the root of this book’s source tree):
# !/bin/bash# lkm : a silly kernel module dev - build, load, unload - helper wrapper script […]# Turn on unofficial Bash 'strict mode'! V useful# "Convert many kinds of hidden, intermittent, or subtle bugs into immediate, glaringly obvious errors" [...]set -euo pipefailunset ARCHunset CROSS_COMPILEname=$(basename "${0}")# Display and run the provided command. # Parameter(s) : the command to runruncmd(){ local SEP="------------------------------" [[ $# -eq 0 ]] && return echo "${SEP}$*${SEP}" eval "$@" [[ $? -ne 0 ]] && echo " ^--[FAILED]" } ### "main" here [[ $# -ne 1 ]] && { echo "Usage: ${name} name-of-kernel-module-file (without the .c)" exit 1} [[ "${1}" = *"."* ]] && { echo "Usage: ${name} name-of-kernel-module-file ONLY (do NOT put any extension)." exit 1}echo "Version info:" which lsb_release >/dev/null 2>&1 && { echo -n "Distro: " lsb_release -a 2>/dev/null |grep "Description" |awk -F':' '{print $2}' }echo -n "Kernel: " ; uname -rruncmd "sudo rmmod $1 2> /dev/null" || true# runcmd "make clean" || trueruncmd "sudo dmesg -C > /dev/null" || trueruncmd "make || exit 1" || true[[ ! -f "$1".ko ]] && { echo "[!] ${name}: $1.ko has not been built, aborting..." exit 1}runcmd "sudo insmod ./$1.ko && lsmod|grep $1" || true# Ubuntu 20.10 onward has enabled CONFIG_SECURITY_DMESG_RESTRICT !# That's good for security; so we need to 'sudo' dmesgruncmd "sudo dmesg" || trueexit 0Given the name of the kernel module as a parameter – without any extension part (such as .c) – the lkm script performs some validity checks, displays some version information (though, as of now, this works for Ubuntu only), and then uses a wrapper runcmd() Bash function to display the name of and run a given command, in effect getting the build/load/lsmod/dmesg workflow done painlessly. Let’s be empirical and try it out on our first kernel module (note that the /home/c2kp/lkp2e is just a soft link to the full pathname where the books code resides):

Figure 4.6: Screenshot showing our lkm convenience script performing the build, load, and dmesg for our kernel module
All done! Remember to unload the kernel module with rmmod.
Congratulations! You have now learned how to write and try out a simple Hello, world kernel module. Much work remains, though, before you rest on your laurels; the next section delves into more key details regarding kernel logging and the versatile printk API.
Understanding kernel logging and printk
Section titled “Understanding kernel logging and printk”There is still a lot to cover regarding the logging of kernel messages via the printk kernel API. This section delves into some of the details. It’s important for a budding kernel/driver developer like you to clearly understand these topics.
We saw earlier, in the A quick first look at the kernel printk() section, the essentials of using the kernel printk API’s functionality (have another look at it if you wish to). Here, we will explore a lot more with respect to the printk() API’s usage. Let’s get going!
Using the kernel memory ring buffer
Section titled “Using the kernel memory ring buffer”The kernel log buffer is simply a memory buffer within the kernel virtual address space where the printk output is saved (logged). More technically, it’s the global __log_buf[] variable. Its definition in the kernel source is as follows:
kernel/printk/printk.c#define __LOG_BUF_LEN (1 << CONFIG_LOG_BUF_SHIFT)#define LOG_BUF_LEN_MAX (u32)(1 << 31) static char __log_buf[__LOG_BUF_LEN] __aligned(LOG_ALIGN);static char *log_buf = __log_buf;static u32 log_buf_len = __LOG_BUF_LEN;It’s architected as a ring buffer; it has a finite size (__LOG_BUF_LEN bytes), and once it’s full, it gets overwritten from byte zero. Hence, it’s called a “ring” (or circular) buffer. Here, we can see that the size is based on the Kconfig variable CONFIG_LOG_BUF_SHIFT (1 << n in C implies 2^n). This value is shown and can be overridden as part of the kernel (menu)config here: General Setup | Kernel log buffer size.
It’s an integer value with a range of 12-25 (we can always search init/Kconfig and see its spec), with a default value of 18. So, the size of the kernel log buffer by default is (1 << 18), which is 2 18 = 256 KB. However, the actual runtime size is affected by other config directives as well – notably, LOG_CPU_MAX_BUF_SHIFT, which makes the size a function of the number of CPUs on the system. Furthermore, the relevant Kconfig file says, “ Also this option is ignored when the log_buf_len kernel parameter is used as it forces an exact (power of two) size of the ring buffer.” So, that’s interesting; we can often override defaults by passing a kernel parameter (via the bootloader)!
As an aside, kernel parameters are useful, many, and varied, and are well worth checking out. See the official documentation here: https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html.
A snippet from the Linux kernel documentation on the log_buf_len kernel parameter reveals the details:
log_buf_len=n[KMG] Sets the size of the printk ring buffer, in bytes. n must be a power of two and greater than the minimal size. The minimal size is defined by LOG_BUF_SHIFT kernel config parameter. There is also CONFIG_LOG_CPU_MAX_BUF_SHIFT config parameter that allows to increase the default size depending on the number of CPUs. See init/Kconfig for more details.Whatever the size of the kernel log buffer, two issues when dealing with the printk API become obvious:
- Its messages are being logged in volatile memory (RAM); if the system crashes or power cycles in any manner, we will lose the precious kernel log (often severely limiting or even eliminating our ability to debug kernel issues).
- The log buffer isn’t very large by default, typically just 256 KB (and/or perhaps 4 to 8 KB per CPU on the system); thus, it’s clear that voluminous prints will overwhelm the ring buffer, making it wrap around, thus losing information.
How can we fix this? Read on…
Kernel logging and systemd’s journalctl
Section titled “Kernel logging and systemd’s journalctl”Just as user space apps use logs, so does the kernel; the feature is called kernel logging and is required on all but the most resource-constrained systems. An obvious solution to the previously mentioned issues with kernel logging to a small and volatile memory buffer is to write (append, really) every single kernel printk to a file in (non-volatile) secondary storage. This is precisely how most modern Linux distributions are set up. The location of the kernel log file varies with the distro: conventionally, the Red Hat-based ones write into the /var/log/messages file and the Debian-based ones into /var/log/syslog. Traditionally, the kernel printk would hook into the user space system logger daemon (syslogd) to perform file logging, thus automatically getting the benefit of more sophisticated features, such as log rotation, compression, and archival.
Over the past several years, though, system logging has been completely taken over by the useful and powerful new framework for system initialization called systemd (it replaces, or often works in addition to, the old SysV init framework). Indeed, systemd is now routinely used on even embedded Linux devices. Within the systemd framework, logging is performed by a daemon process called systemd-journal, and the journalctl utility is the user interface to it.
The detailed coverage of systemd and its associated utilities is user mode stuff and thus not within the scope of this book. Please refer to the Further reading section of this chapter for links to (a lot) more on it.
One key advantage of using the journal to retrieve and interpret logs is that all logs – those from applications (processes and threads), libraries, system daemons, the kernel, drivers, and so on – are written (merged) here.
This way, we can see a (reverse) chronological timeline of events without having to manually piece together different logs into a timeline. The man page on the journalctl(1) utility covers its various options in detail. Here, we present some (hopefully) convenient aliases based on this utility (we assume it’s within the PATH of course):
#--- a few journalctl(1) aliases# jlog: current (from most recent) boot only, everythingalias jlog='journalctl -b --all --catalog –no-pager'# jlogr: current (from most recent) boot only, everything, # in *reverse* chronological orderalias jlogr='journalctl -b --all --catalog --no-pager --reverse'# jlogall: *everything*, all time; --merge => _all_ logs mergedalias jlogall='journalctl --all --catalog --merge --no-pager'# jlogf: *watch* the live log, akin to 'tail -f' mode; very useful to 'watch live' logs;# use 'journalctl -f -k' to only watch for kernel printk'salias jlogf='journalctl -f'# jlogk: only kernel messages, this (from most recent) bootalias jlogk='journalctl -b -k --no-pager'Note that the -b option implies “show logs for the current boot only” – in other words, the journal is displayed from the most recent system boot date at the present moment. A numbered listing of stored system (re)boots can be seen with journalctl --list-boots.
We deliberately use the --no-pager option as it allows us to further filter the output with standard Linux utilities like grep, awk, sort, and so on, as required. A simple example of using journalctl follows:
$ journalctl -b -k --no-pager | tail -n2Jul 07 12:25:05 osboxes kernel: Goodbye, world! Climate change has done us in...Jul 07 12:37:57 osboxes kernel: Hello, worldNotice the default log format of the journal:
[timestamp] [hostname] [source-of-msg]: [... log message ...]Here, [source-of-msg] is kernel for kernel messages or the name of the particular application or service that writes the message.
It’s useful to see a couple of usage examples from the man page on journalctl(1):
Show all kernel logs from previous boot: journalctl -k -b -1Show a live log display from a system service apache.service: journalctl -f -u apacheFurthermore, journalctl makes it easy to search the logs in a human-friendly time-based fashion – for example, to see all kernel logs that have been written in the last half hour:
journalctl -k --since="30 min ago"The non-volatile logging of kernel messages into files is very useful, of course. Note, though, that there exist circumstances, often dictated by hardware constraints, that might render it impossible. For example, a tiny, highly resource-constrained embedded Linux device might use a small internal flash chip as its storage medium. Now, not only is it small, and all the space is pretty much used up by apps, libraries, the kernel, drivers, and the bootloader, but it is also a fact that flash-based chips have an effective limit on the number of erase-write cycles they can sustain before wearing out. Thus, writing to it a few million times might finish it off! So, sometimes, system designers deliberately and/or additionally use cheaper external flash memory such as (micro)SD/MMC (MultiMediaCard) cards for non-critical data to mitigate this impact, as they’re easily (and cheaply) replaceable.
Let’s move on to understanding printk log levels.
Using printk log levels
Section titled “Using printk log levels”When you emit a message to the kernel log via the printk API (and friends), you typically must also specify the logging level at which the message is logged. To understand and use these printk log levels, let’s begin by reproducing that single line of code – the first printk from our world-famous helloworld_lkm kernel module:
printk(KERN_INFO "Hello, world\n");Let’s now address the elephant in the room: what exactly does KERN_INFO mean? Firstly, be careful now; it’s not what your knee-jerk reaction says it is – a parameter. No! Notice that there is no comma character between it and the “ Hello, world\n ” format string, just white space. KERN_INFO is one of eight log levels that a kernel printk can get logged at. A key thing to understand right away is that this log level is not a priority specifier of any sort; its presence allows us to filter messages based on the log level. The kernel defines eight possible log levels for printk; here they are:
#ifndef __KERN_LEVELS_H__#define __KERN_LEVELS_H__#define KERN_SOH "\001" /* ASCII Start Of Header */#define KERN_SOH_ASCII '\001'#define KERN_EMERG KERN_SOH "0" /* system is unusable */#define KERN_ALERT KERN_SOH "1" /* action must be taken immediately */#define KERN_CRIT KERN_SOH "2" /* critical conditions */#define KERN_ERR KERN_SOH "3" /* error conditions */#define KERN_WARNING KERN_SOH "4" /* warning conditions */#define KERN_NOTICE KERN_SOH "5" /* normal but significant condition */#define KERN_INFO KERN_SOH "6" /* informational */#define KERN_DEBUG KERN_SOH "7" /* debug-level messages */#define KERN_DEFAULT "" /* the default kernel loglevel */So, now we see that the KERN_<FOO> log levels are merely strings ("0", "1", ..., "7") that get prefixed to the kernel message being emitted by printk, nothing more. This gives us the useful ability to filter messages based on log level. The comment on the right of each of them clearly shows the developer when to use which log level.
What’s KERN_SOH? That’s the ASCII Start Of Header (SOH) value \001. See the man page on ascii(7); the ascii utility dumps the ASCII table in various numerical bases. From here, we can clearly see that numeric 1 (or \001) is the SOH character, a convention that is followed here (Er, don’t worry about it).
Now let’s quickly look at a couple of actual printk usage examples from within the Linux kernel source tree. When the kernel’s hangcheck-timer device driver (somewhat akin to a software watchdog) determines that a certain timer expiry (60 seconds by default) was delayed for over a certain threshold (by default, 180 seconds), it restarts the system! Here we show the relevant kernel code – the place where the hangcheck-timer driver emits a printk in this regard https://elixir.bootlin.com/linux/v6.1.25/source/drivers/char/hangcheck-timer.c#L134:
[...]if (hangcheck_reboot) { printk(KERN_CRIT "Hangcheck: hangcheck is restarting the machine.\n"); emergency_restart();} else { [...]Check out how the printk API was called with the log level set to KERN_CRIT.
On the other hand, squeaking out an informational message might be just what the doctor ordered. Here, we see the generic parallel printer driver politely informing all concerned that the printer is on fire (rather understated, yes?). The relevant code is here: https://elixir.bootlin.com/linux/v6.1.25/source/drivers/char/lp.c#L260:
[...]if (last != LP_PERRORP) { last = LP_PERRORP; printk(KERN_INFO "lp%d on fire\n", minor); }You’d think a device being on fire qualifies the printk to be emitted at the emergency logging level, yes? Well, at least arch/x86/kernel/cpu/mce/p5.c:pentium_machine_check() thinks so, https://elixir.bootlin.com/linux/v6.1.25/source/arch/x86/kernel/cpu/mce/p5.c#L24:
[...] pr_emerg("CPU#%d: Machine Check Exception: 0x%8X (type 0x%8X).\n", smp_processor_id(), loaddr, lotype);
if (lotype & (1<<5)) { pr_emerg("CPU#%d: Possible thermal failure (CPU on fire ?).\n", smp_processor_id()); }[...]The pr_<foo>() convenience macros are covered next.
An FAQ: If, within the printk(), the log level is not specified, what log level is the print emitted at? It’s 4 by default – that is, KERN_WARNING (the Writing to the console section reveals why exactly this is). Note, though, that you are expected to always specify a suitable log level when using printk.
There’s an easier way to specify the kernel message log level; it’s what we will delve into next.
The pr_<foo> convenience macros
Section titled “The pr_<foo> convenience macros”The convenience pr_<foo>() (often referred to as pr_*()) macros explained here ease coding pain. The clunky
printk(KERN_FOO "<format-str>", vars...);is replaced with the elegant
pr_foo("<format-str>", vars...);where <foo> is the log level, one of emerg, alert, crit, err, warn, notice, info, or debug. Their use is encouraged:
// include/linux/printk.h:[ ... ]/** * pr_emerg - Print an emergency-level message * @fmt: format string * @...: arguments for the format string * * This macro expands to a printk with KERN_EMERG loglevel. It uses pr_fmt() to * generate the format string. */#define pr_emerg(fmt, ...) \ printk(KERN_EMERG pr_fmt(fmt), ##__VA_ARGS__)/** * pr_alert - Print an alert-level message * @fmt: format string * @...: arguments for the format string * * This macro expands to a printk with KERN_ALERT loglevel. It uses pr_fmt() to * generate the format string. */#define pr_alert(fmt, ...) \ printk(KERN_ALERT pr_fmt(fmt), ##__VA_ARGS__) […]#define pr_err(fmt, ...) \ printk(KERN_ERR pr_fmt(fmt), ##__VA_ARGS__)[ … ]#define pr_warn(fmt, ...) \ printk(KERN_WARNING pr_fmt(fmt), ##__VA_ARGS__)[ … ]#define pr_notice(fmt, ...) \ printk(KERN_NOTICE pr_fmt(fmt), ##__VA_ARGS__)[ … ]#define pr_info(fmt, ...) \ printk(KERN_INFO pr_fmt(fmt), ##__VA_ARGS__)[ … ]/** * pr_devel - Print a debug-level message conditionally [ … ] * This macro expands to a printk with KERN_DEBUG loglevel if DEBUG is * defined. Otherwise it does nothing. [ … ]#ifdef DEBUG#define pr_devel(fmt, ...) \ printk(KERN_DEBUG pr_fmt(fmt), ##__VA_ARGS__)[ … ]While on the subject of using the pr_*() macros, there’s one called pr_cont(). Its job is to act as a continuation string, continuing the previous printk! This can be useful… here’s an example of its usage:
if (last_unloaded_module[0]) pr_cont(" [last unloaded: %s]", last_unloaded_module); pr_cont("\n");We typically ensure that only the final pr_cont() contains the newline character.
To avoid unpleasant surprises, like the printk() seeming to not take effect, make it a habit to end your printk ‘s with a newline character "\n" (this is true for the printf() as well).
From now on, we’ll typically only use these pr_foo() (or pr_*()) style macros when emitting printk messages to the kernel log.
Furthermore, and very importantly: driver authors must use the dev_*() macros. This implies passing along an additional first parameter, a pointer to the device in question (struct device *). You’ll find them all defined here: https://elixir.bootlin.com/linux/v6.1.25/source/include/linux/dev_printk.h#L137. The reason to use them is that the driver core auto-prefixes useful details to the driver printk, thus enabling better logs (and one to quickly spot details). For example, when writing, say, an I2C driver, the dev_*() message will include details like the driver’s name, I2C bus number, and the address the chip is on! Here’s an example, from a (reworked) I2C RTC driver:
ks3231 1-0068: IRQ! #5Here, ks3231 is the driver’s name; for the token 1-0068, 1 is the I2C bus number and 0x68 is the address where the client (RTC) chip resides on that bus. The actual message is IRQ! #5. Useful.
The kernel allows us to pass loglevel=n as a kernel command-line parameter, where n is an integer between 0 and 7, corresponding to the eight log levels mentioned previously. As expected (and as you shall soon learn), all printk instances with a log level less than that which was passed will be directed to the console device as well.
Writing a kernel message directly to the console device is at times very useful; the next section deals with the details of how we can achieve this.
Writing to the console
Section titled “Writing to the console”Recall that the printk output might go to up to three locations:
- The first is the kernel memory log buffer (always)
- The second is non-volatile log files (typical)
- The last one (that we’ll address here) is the console device
Traditionally, the console device is a pure kernel feature, the initial Terminal window that the (super)user logs in to (/dev/console) in a non-graphical environment. Interestingly, on Linux, we can define several consoles – a teletype terminal (tty) window (such as /dev/console), a text-mode VGA console, a framebuffer, or even a serial port served over USB (this being common on embedded systems during development; see more on Linux consoles in the Further reading section of this chapter).
For example, when we connect a Raspberry Pi board to an x86_64 laptop via a USB-to-RS232 TTL UART (USB-to-serial) cable (see the Further reading section of this chapter for a blog article on this very useful accessory and how to set it up on the Raspberry Pi) and then use a Terminal emulator app like minicom (or screen), this is what shows up as the tty device on the Raspberry Pi – it’s the serial port:
rpi # tty/dev/ttyS0The point here is that the console is often the target of important enough log messages, including those originating from deep within the kernel. Linux’s printk uses a sysctl, a proc -based mechanism, for conditionally delivering its logs to the console device. To understand this better, let’s first check out the relevant proc pseudofile (here, on our x86_64 Ubuntu guest):
$ cat /proc/sys/kernel/printk4 4 1 7We interpret the preceding four numbers as printk log levels (with 0 being the highest and 7 the lowest in terms of “urgency”). The preceding four-integer sequence’s meaning is this:
- The current (console) log level. The key implication is that all messages less than this value will be sent to the console device as well!
- The default level for messages that lack an explicit log level.
- The minimum allowed log level.
- The boot-time default log level.
We can see that log level 4 corresponds to KERN_WARNING. Thus, with the first number being 4 (indeed, the typical default on a Linux distro), all printk instances lower than log level 4 will be sent to the console device, in addition to being logged to the kernel log buffer and a file, of course. In effect, with these settings, this applies to all kernel messages at the following log levels: KERN_EMERG, KERN_ALERT, KERN_CRIT, and KERN_ERR will, by default, be automatically sent to the console device as well.
Kernel messages at log level 0 [KERN_EMERG] are always printed to the console, and indeed to all (non-GUI) Terminal windows and the kernel log buffer and log file, regardless of any settings.
It’s worth noting that very often when working on embedded Linux or any kernel development, you will work on the console device, as is the case with the Raspberry Pi example just given. On my Raspberry Pi 4 model B running the stock distro (and kernel), here’s the default printk log level setting:

Figure 4.7: Screenshot of running minicom to connect to the Raspberry Pi board over a USB-to-serial cable, looking up a few things
Notice that the default printk logging levels (i.e., the printk sysctl) are different from those of the x86_64; it happens.
Now, the interesting bit: setting the /proc/sys/kernel/printk pseudofile’s first integer value to 8 will guarantee that all printk instances are sent directly to the console as well, thus making printk behave like a regular printf would! Here, we show how the root user can easily set this up:
$ sudo sh -c "echo '8 4 1 7' > /proc/sys/kernel/printk"$ cat /proc/sys/kernel/printk8 4 1 7Of course, we do this as root; do notice the shell syntax used. Setting the console output like this can be very convenient during development and testing!
However, realize that the changes made to this sysctl (via proc) are temporary; they apply for this session only. Once the system reboots or power cycles, the changes are lost. One way to make changes to a sysctl permanent is via the sysctl (8) utility – for example, running, as root, the following:
sysctl -w kernel.printk='8 4 1 7'This makes the printk sysctl get set to these values on every boot.
On my Raspberry Pi (and other boards), I keep a startup script that contains the following line:
[[ $(id -u) -eq 0 ]] && echo "8 4 1 7" > /proc/sys/kernel/printk
Thus, when running it as root, this takes effect and all printk instances now directly appear on the minicom console, just as printf would; great for debugging! Using sysctl, you can make it permanent.
Talking about the versatile Raspberry Pi, the next section demonstrates running a kernel module on one.
Writing output to the Raspberry Pi console
Section titled “Writing output to the Raspberry Pi console”On to our second kernel module! Here, we shall (from now onward) employ the pr_*() style macros to emit nine printk instances, one at each of the eight log levels, plus one via the pr_devel() macro (which is really nothing but the KERN_DEBUG log level). Let’s check out the relevant code:
[ … ]static int __init printk_loglvl_init(void){ pr_emerg("Hello, world @ log-level KERN_EMERG [0]\n"); pr_alert( "Hello, world @ log-level KERN_ALERT [1]\n"); pr_crit( "Hello, world @ log-level KERN_CRIT [2]\n"); pr_err( "Hello, world @ log-level KERN_ERR [3]\n"); pr_warn( "Hello, world @ log-level KERN_WARNING [4]\n"); pr_notice("Hello, world @ log-level KERN_NOTICE [5]\n"); pr_info( "Hello, world @ log-level KERN_INFO [6]\n"); pr_debug("Hello, world @ log-level KERN_DEBUG [7]\n"); pr_devel( "Hello, world via the pr_devel() macro" " (eff @KERN_DEBUG) [7]\n"); return 0; /* success */}static void __exit printk_loglvl_exit(void){ pr_info("Goodbye, world @ log-level KERN_INFO [6]\n");}module_init(printk_loglvl_init);module_exit(printk_loglvl_exit);Now, we will discuss the output when running the preceding printk_loglvl kernel module on a Raspberry Pi device. If you don’t possess one or it’s not handy, that’s not a problem; please go ahead and try it out on an x86_64 (guest VM or native system).
On the Raspberry Pi device (here, I used the Raspberry Pi 4 model B running the default Raspberry Pi OS), we log in and get ourselves a root shell via a simple sudo -s. We then build the kernel module.
If you have installed the default Raspberry Pi image on the device, all required development tools, kernel headers, and more will be pre-installed! So, log in to the board, build the module, and try it out. Figure 4.8 is a screenshot of running our printk_loglvl kernel module on a Raspberry Pi board. Also, it’s important to realize that we’re running on the console device as we are using the aforementioned USB-to-serial cable over the minicom Terminal emulator app, and not simply over an SSH connection:

Figure 4.8: The minicom Terminal emulator app window – the console – with the printk_loglvl kernel module output
Notice something a bit different from the x86_64 environment: here, by default, the first integer in the output of /proc/sys/kernel/printk – the current console log level – is 3 (not 4). Okay, so this implies that all kernel printk instances at log level less than log level 3 will appear directly on the console device. Look at the screenshot: this is indeed the case! Furthermore, and as expected, the printk instance at the “emergency” log level (0, KERN_EMERG) always appears on the console – indeed, on every open non-GUI Terminal window.
Now for the interesting part; let’s set (as root, of course) the current console log level (remember, it’s the first integer in the output of /proc/sys/kernel/printk) to the value 8. This way, all printk instances should appear directly on the console. We test precisely this here:

Figure 4.9: The minicom Terminal – in effect, the console – with the console log level set to 8
Of course, we first remove the earlier instance of the module from memory via rmmod. Indeed, as expected, we see all the printk instances on the console device itself, thus obviating the need to use dmesg.
Hang on a moment, though: whatever happened to the pr_debug() and pr_devel() macros emitting a kernel message at log level KERN_DEBUG (that is, the integer value 7)? It has not appeared on the console nor in the following dmesg output. We explain this shortly; please read on.
With dmesg, of course, all kernel messages – well, at least those still in the kernel log (ring) buffer in RAM – will be revealed. We see this to be the case here:
rpi # rmmod printk_loglvlrpi # dmesg [...][ 2086.684939] Hello, world @ log-level KERN_EMERG [0][ 2086.690143] Hello, world @ log-level KERN_ALERT [1][ 2086.695526] Hello, world @ log-level KERN_CRIT [2][ 2086.700826] Hello, world @ log-level KERN_ERR [3][ 2086.706233] Hello, world @ log-level KERN_WARNING [4][ 2086.711999] Hello, world @ log-level KERN_NOTICE [5][ 2086.717931] Hello, world @ log-level KERN_INFO [6][ 2372.690250] Goodbye, world @ log-level KERN_INFO [6]rpi #All printk instances – except the KERN_DEBUG ones – are seen as we are looking at the kernel log via the dmesg utility. So, how do we get a debug message displayed? That’s covered in the next section.
Turning on debug-level kernel messages
Section titled “Turning on debug-level kernel messages”We just saw that we can emit printk instances at various log levels; all showed up except for the debug-level messages. Ah yes, pr_debug() (as well as dev_dbg()) turns out to be a bit of a special case; unless the DEBUG symbol is defined for the kernel module, a printk instance at log level KERN_DEBUG does not show up. We can edit the kernel module’s Makefile to enable this. There are (at least) two ways to set this up:
- Insert this line into the Makefile:
CFLAGS_printk_loglvl.o := -DDEBUG
Generically, it’s CFLAGS_<filename>.o := <value>
- We could also – more commonly in fact – just insert this statement into the Makefile:
ccflags_y += -DDEBUG
Traditionally, the Makefile variable to use for passing on more C compiler flags was named EXTRA_CFLAGS; it’s now considered deprecated, hence we use the newer ccflags_y variable.
In our Makefile, we have deliberately kept the -DDEBUG commented out to begin with. Now, to try it out, uncomment one of the following commented-out lines (I’d suggest you uncomment the first one, the ccflags_y variable):
# Enable the pr_debug() as well (rm the comment from one of the lines below)# (Note: EXTRA_CFLAGS deprecated; use ccflags-y)#ccflags-y += -DDEBUG#CFLAGS_printk_loglvl.o := -DDEBUGOnce edited, rebuild it, and insert it using our lkm script. A partial screenshot (Figure 4.10) of the lkm script’s output clearly reveals the dmesg color-coding, with KERN_ALERT / KERN_CRIT / KERN_ERR background highlighted in red/in bold red typeface/in red foreground color, respectively, and KERN_WARNING in bold black typeface, helping us humans quickly spot important kernel messages:

Figure 4.10: Partial screenshot of the lkm script’s output when running the module with DEBUG defined
We’ve highlighted the two printk instances emitted at KERN_DEBUG. Note that the behavior of pr_debug() is not identical when the “dynamic debug” feature (CONFIG_DYNAMIC_DEBUG=y; – covered next) is enabled.
As mentioned before, device driver authors should carefully note that you must use the special dev_*() macros for emitting printk instances, not the usual pr_*() ones used by the kernel and pure modules. This implies passing along an additional first parameter, a pointer to the device in question (struct device *). You’ll find them all defined here: https://elixir.bootlin.com/linux/v6.1.25/source/include/linux/dev_printk.h#L137.
Also, pr_devel() is meant to be used for kernel-internal debug printk instances whose output should never be visible in production systems.
Now, back to the section on console output. So, for perhaps the purpose of kernel/driver debugging (if nothing else), is there any other guaranteed way to ensure that all printk instances are directed to the console? Yes, indeed – just pass the kernel (boot-time) parameter called ignore_level. For more details on this, do look up the description in the official kernel documentation: https://www.kernel.org/doc/html/latest/admin-guide/kernel-parameters.html.
Additionally, you can turn on the ignoring of printk log levels at runtime by echoing Y into the following pseudofile, thus allowing all printk instances to appear on the console device:
sudo bash -c "echo Y > /sys/module/printk/parameters/ignore_loglevel"Conversely, you can turn it off at runtime by echoing N into the same pseudo-file. Useful!
The dmesg utility can also be used to control the enabling/disabling of kernel messages to the console device, as well as the console logging level (that is, the level numerically below which messages will appear on the console) via various option switches (in particular, the --console-level option). I’ll leave it to you to browse through the man page on dmesg (1) for the details.
Important note: Using the printk (and friends) APIs/macros for the express purpose of debugging has been covered in depth in my Linux Kernel Debugging book (specifically in Chapter 3, Debug via Instrumentation – printk and Friends). It covers the usual printk stuff (which we have covered here), printk for debug tips and tricks, rate-limiting, and, importantly, using the powerful dynamic debug kernel framework. Please do check it out.
An introduction to the kernel’s powerful dynamic debug feature
Section titled “An introduction to the kernel’s powerful dynamic debug feature”We, as programmers, need debug techniques. Perhaps the best known is the instrumentation one, where debug prints are sprinkled at strategic locations in the code base. Seeing the log, we then understand the control flow and can perhaps spot the bug.
With the Linux kernel, debug and other prints are emitted into the kernel log via various printk variants – the regular printk() macro, the preferred pr_*() macros, and the dev_*() macros for drivers; those that are emitted with log level KERN_DEBUG are the so-called debug prints. So, in effect, the following are all possible “debug-level” print call sites:
pr_debug("<fmt str>"[, args…]);dev_dbg(dev, "<fmt str>"[, args…]);printk(KERN_DEBUG "<fmt str>"[, args…]);
It’s very important to recall that debug printk instances are always off by default; only when the symbol DEBUG is defined do they actually take effect.
Now, this seems convenient; however, in actual production, what if you need to emit, say, a couple of debug prints from a given module? To do so, you’ll have to define the symbol DEBUG (of course, you can do that within the Makefile), rebuild, unload, and reload the module. This approach, however, just isn’t practical (or even allowed) on most production systems. Thus, we need a more dynamic approach, which is precisely what’s offered by the kernel’s dynamic debug feature.
With the kernel dynamic debug feature, every single printk call site that’s emitted at log level KERN_DEBUG from within the kernel, as well as those from kernel modules, is compiled into the kernel. Within the make menuconfig UI, the dynamic debug option is here: Kernel hacking > printk and dmesg options > Enable dynamic printk() support. The config is a Boolean named CONFIG_DYNAMIC_DEBUG.
We’ll assume you have it on (set to Y; even when so, the overhead when not tracing dynamic prints is considered minimal, which is why the feature was merged!).
As this book isn’t focused on kernel debugging, we cover the basics here; please see the Linux Kernel Debugging book for details. Still, enough is certainly covered here to get you started and to appreciate this powerful feature.
This feature’s “Help” (recall it will be within one of the Kconfig* files) is superb; let’s just dump it, as reading it will make you understand how you’re to use it (on the 6.1.25 kernel, it’s here: https://elixir.bootlin.com/linux/v6.1.25/source/lib/Kconfig.debug#L108:

Figure 4.11: Screenshot showing the “Help” for the kernel’s powerful dynamic debug feature, part 1
As the full details don’t fit, here’s the next screenshot to cover it:

Figure 4.12: Screenshot showing the “Help” for the kernel’s powerful dynamic debug feature, part 2
Do read both Figure 4.11 and Figure 4.12 carefully. They provide enough detail to get you started on using dynamic debug; the official kernel documentation on this feature is superb as well, so please do browse through it: https://www.kernel.org/doc/html/v6.1/admin-guide/dynamic-debug-howto.html#dynamic-debug.
To check whether the kernel’s dynamic debug facility is available (on an x86), if it shows as y (as is the case here), it’s available, else, it’s not:
$ grep "DYNAMIC_DEBUG=y" /boot/config-$(uname -r)CONFIG_DYNAMIC_DEBUG=ySo, our interface to work with dynamic debug is a pseudofile under debugfs: <debugfs_mount_point>/dynamic_debug/control. On many production systems, though, debugfs may not be configured (or is kept as “invisible”); in such cases, the control file is visible via proc: /proc/dynamic_debug/control. Both are identical.
Viewing the control file content shows all debug prints or call sites that are compiled into the kernel. A quick look helps:
$ head -n1 /proc/dynamic_debug/control# filename:lineno [module]function flags formatThe first line reveals the format. All fields are self-explanatory except the (key) one named flags; this is where the magic lies!
Here’s the scoop on flags, in brief: if the value is =_, the debug print is off (typically, this is the case by default); for example, let’s look up a few debug print call sites for the e1000 (module) driver:
# grep "e1000" /proc/dynamic_debug/control | head -n3drivers/net/ethernet/intel/e1000/e1000_hw.c:385 [e1000]e1000_reset_hw =_ "Disabling MWI on 82542 rev 2.0\n"drivers/net/ethernet/intel/e1000/e1000_hw.c:390 [e1000]e1000_reset_hw =_ "Masking off all interrupts\n"drivers/net/ethernet/intel/e1000/e1000_hw.c:423 [e1000]e1000_reset_hw =_ "Issuing a global reset to MAC\n"You can see that the debug prints are off (the =_ confirms this). To turn it on, write the value +p into the flags field. There are several optional values you can write as well: m, f, l, and t; please see the documentation for their meanings.
A few examples follow, running the dynamic debug facility at different levels of scope. Do first ensure the basic prerequisite (CONFIG_DYNAMIC_DEBUG=y) is met. You’ll need to run these as root, of course; also, you can always substitute the control file path of /sys/kernel/debug/dynamic_debug/control used below with the path /proc/dynamic_debug/control:
- File scope: enable all debug messages in all files where the pathname includes the string “
usb”:echo -n 'file *usb* +p' > /sys/kernel/debug/dynamic_debug/control
You can try plugging in/unplugging a USB device while this is on while watching the kernel log with journalctl -k -f in another terminal. Turn it off with the -p:
echo -n 'file *usb* -p' > /sys/kernel/debug/dynamic_debug/control- File scope: enable all debug messages in all files where the pathname includes the string “
ip”:echo -n 'file *ip* +p' > /sys/kernel/debug/dynamic_debug/control
Try pinging a website while watching the kernel log with journalctl -k -f in another terminal. Turn it off with the -p:
echo -n 'file *ip* -p' > /sys/kernel/debug/dynamic_debug/control- Module scope: enable all debug
printkinstances (allpr_debug()|dev_dbg()call sites) for all kernel modules currently in memory:echo -n 'module * +pflmt' > \/sys/kernel/debug/dynamic_debug/control
WARNING: This can often lead to very voluminous output!
Turn it off with:
echo -n 'module * -pflmt' > \ /sys/kernel/debug/dynamic_debug/controlWhile these run, keep a keen eye on the kernel log output in another Terminal window with journalctl -k -f. Of course, the settings are volatile and will reset to defaults on a power cycle or reboot.
The kernel documentation has more examples; do check them out: https://www.kernel.org/doc/html/v6.1/admin-guide/dynamic-debug-howto.html#examples.
The next section deals with another very useful logging feature: rate limiting.
Rate limiting the printk instances
Section titled “Rate limiting the printk instances”When we emit printk instances from a code path that is executed very often, the sheer volume of printk instances might quickly overflow the kernel log buffer (in RAM, remember that it’s a circular buffer!), thus overwriting what might well be key information. Besides that, ever-growing non-volatile log files that repeat pretty much the same kernel log messages (almost) ad infinitum are not a great idea either and waste disk space, or worse, flash space. For example, think of a large-ish printk in an interrupt handler code path. What if the hardware interrupt is invoked at a frequency of, say, 100 Hz – that is, 100 times every single second?
To mitigate these issues, the kernel provides an interesting and useful alternative: the rate-limited printk. The pr_<foo>_ratelimited() macro (where <foo> is one of emerg, alert, crit, err, warn, notice, info, or debug) has identical syntax to the regular printk; the key point is that it effectively suppresses regular prints when certain conditions are fulfilled.
The kernel provides two sysctl files named printk_ratelimit and printk_ratelimit_burst via the proc filesystem for this purpose. Here, we directly reproduce the sysctl documentation (from https://www.kernel.org/doc/Documentation/sysctl/kernel.txt) that explains the precise meaning of these two (pseudo) files:
printk_ratelimit:Some warning messages are rate limited. printk_ratelimit specifiesthe minimum length of time between these messages (in jiffies), bydefault we allow one every 5 seconds.A value of 0 will disable rate limiting.==============================================printk_ratelimit_burst:While long term we enforce one message per printk_ratelimitseconds, we do allow a burst of messages to pass through.printk_ratelimit_burst specifies the number of messages we cansend before ratelimiting kicks in.On our x86_64 Ubuntu 22.04 LTS guest system, we find that their (default) values are as follows:
$ cat /proc/sys/kernel/printk_ratelimit /proc/sys/kernel/printk_ratelimit_burst510This implies that by default, up to 10 instances of the same message occurring within a 5-second time interval can make it through before rate limiting kicks in.
FYI, this a web tool to help you search out what a certain sysctl means; here is an example: https://sysctl-explorer.net/kernel/printk_ratelimit/. Useful.
The printk rate limiter, when it does suppress kernel printk instances, emits a helpful message mentioning exactly how many earlier printk callbacks were suppressed. Some sample output helps make this clear:
ratelimit_test_init: 41 callbacks suppressedratelimit_test:ratelimit_test_init():45: [51] ratelimited printk @ KERN_INFO [6]Rate-limiting macros to use
Section titled “Rate-limiting macros to use”The kernel provides the following macros to help you rate-limit your prints/logging (you should use #include <linux/kernel.h>):
printk_ratelimited(): Warning! Do not use it – the kernel warns against this.pr_*_ratelimited(): Where the wildcard*is replaced by the usual – one of emerg, alert, crit, err, warn, notice, info, or debug.dev_*_ratelimited(): Where the wildcard*is replaced by the usual – one of emerg, alert, crit, err, warn, notice, info, or debug.
Ensure you use the pr_*_ratelimited() macros in preference to printk_ratelimited(); driver authors should use the dev_*_ratelimited() macros.
An example kernel module to demo the rate-limited printk is available in the GitHub repo of my Linux Kernel Debugging book, here: https://github.com/PacktPublishing/Linux-Kernel-Debugging/tree/main/ch3/ratelimit_test. Do try it out.
A code-level example (among several within the kernel tree) of using the rate-limited (driver debug) printk is seen in an AMD GPU driver, https://elixir.bootlin.com/linux/v6.1.25/source/drivers/gpu/drm/amd/amdgpu/sdma_v4_0.c#L2146:
dev_dbg_ratelimited(adev->dev, "[sdma%d] address:0x%016llx src_id:%u ring:%u vmid:%u " "pasid:%u, for process %s pid %d thread %s pid %d\n", instance, addr, entry->src_id, entry->ring_id, entry->vmid, entry->pasid, task_info.process_name, task_info.tgid, task_info.task_name, task_info.pid);With the dev_*_*() macros, notice how the first parameter is always a pointer to the device.
Don’t use the older (and now deprecated) printk_ratelimited() and printk_ratelimit() macros. Also, FYI, the actual rate-limiting code is in lib/ratelimit.c:___ratelimit(). Here is a kernel convention: a function/macro beginning with two or more underscores (__foo()) is considered an internal function/macro. Avoid using it directly; use it’s wrapper foo().
Can we generate kernel-level messages from user space? Sounds interesting; that’s our next sub-topic.
Generating kernel messages from user space
Section titled “Generating kernel messages from user space”A popular debug technique that we programmers use is to sprinkle prints at various points in the code, often allowing us to narrow down the source of an issue. This is indeed a useful debugging technique and is more formally called instrumenting the code. Kernel developers often use the venerable printk API (and friends) for just this purpose.
So, imagine you have written a kernel module and are in the process of debugging it (by adding several printk instances at appropriate points in the code). Your kernel code now emits these several printk instances, which, of course, you can see at runtime via dmesg (or journalctl, or whatever).
That’s fine, but what if, especially because you’re running some automated user space test script, you’d like to see the point at which the script initiated some action within our kernel module, by printing out a certain message? As a concrete example, say we want the log to look something like this:
test_script: @user msg 1 ; kernel_module: msg n, msg n+1, ..., msg n+m ; test_script: @user msg 2 ; ...We can have our user space test script write a message into the kernel log buffer, just like a kernel printk would, by writing said message into the special /dev/kmsg device file:
echo "test_script: @user msg 1" > /dev/kmsgWell, hang on – doing so requires running with root access, of course. However, notice here that a simple sudo before echo just doesn’t work:
$ sudo echo "test_script: @user msg 1" > /dev/kmsgbash: /dev/kmsg: Permission denied$ sudo bash -c "echo \"test_script: @user msg 1\" > /dev/kmsg" [sudo] password for c2kp: $ dmesg |tail -n1 [55527.523756] test_script: @user msg 1The syntax used in the second attempt works, but it’s just simpler to get yourself a root shell (sudo -s) and carry out tasks such as this.
One more thing. The dmesg utility has several options designed to make the output more human-readable; we show some of them via our sample alias to dmesg here, after which we use it:
$ alias dmesg='sudo dmesg --decode --nopager --color --ctime'$ dmesg | tail -n1kern :debug : [Mon Jul 10 08:14:32 2023] wlo1: Limiting TX power to 30 (30 - 0) dBm as advertised by b8:<...>The message written to the kernel log via the special /dev/kmsg device file will be printed at the current default log level, typically, 4 : KERN_WARNING. We can override this by prefixing the message with the required log level (as a number in string format). For example, to write from the user space into the kernel log at log level 6 : KERN_INFO, use this:
$ sudo bash -c "echo \"<6>test_script: test msg at KERN_INFO\" \ > /dev/kmsg" $ dmesg | tail -n1user :info : [Mon Jul 10 08:25:27 2023] test_script: test msg at KERN_INFOWe can see that our latter message is emitted at log level 6, as specified within echo.
There really is no way to distinguish between a user-generated kernel message and a kernel printk() -generated one; they look identical. So, of course, it could be as simple as inserting or prefixing some special signature byte or string within the message, such as @user ..., to help you distinguish these user-generated prints from the kernel ones.
As a bit of an aside, something to note follows.
Interfacing between user and kernel space is a key and important topic, often something that driver authors find themselves needing to do. There are many ways to do so, always, at some level involving issuing a system call from user space as the means to switch into the kernel. Among the available technologies on Linux to interface between user and kernel space are to do so via procfs, sysfs, debugfs, netlink sockets, and the ioctl() system call. These are covered in depth in the Linux Kernel Programming - Part 2 book in Chapter 2, User-Kernel Communication Pathways.
Let’s now move on to seeing how we can easily standardize our kernel printk output format.
Standardizing printk output via the pr_fmt macro
Section titled “Standardizing printk output via the pr_fmt macro”Another important point regarding the kernel printk: pretty often, to give context to your printk() output (where exactly did it occur?), you might write the code like this, taking advantage of various GCC macros like __FILE__, __func__, and __LINE__, which of course emit the filename, function name and line number, respectively, from where the print was emitted:
pr_info("%s:%s:%s():%d: mywork XY failed!\n", OURMODNAME, __FILE__, __func__, __LINE__);This is fine as such; the problem is that if there are a lot of printk instances in your project, it can be painful to guarantee that a standard printk format (for example, first displaying the module name followed by the filename, then the function name and possibly the line number, as seen here) is always consistently and correctly followed by everyone working on the project.
Enter the pr_fmt() macro; defining this macro right at the beginning of your code (it must be even before the first #include), guarantees that every single subsequent printk in your code will be prefixed with the format specified by this macro.
Let’s take an example (we show a snippet of code from the next chapter; worry not, it’s really very simple and serves as a template for your future kernel modules):
[ ... ] */#define pr_fmt(fmt) "%s:%s(): " fmt, KBUILD_MODNAME, __func__#include <linux/init.h>#include <linux/module.h>#include <linux/kernel.h> [ ... ] static int __init lkm_template_init(void) { pr_info("inserted\n"); [ ... ]The pr_fmt() macro is highlighted; it uses the predefined KBUILD_MODNAME macro to substitute the name of your kernel module, and the GCC __func__ specifier to display the name of the function we’re currently running! You can add %s for __FILE__, and %d matched by the corresponding __LINE__ macro to display the line number; it’s really up to you.
So, the bottom line is that the pr_info() we emit in the init function of this LKM will display like this in the kernel log:
[381534.391966] lkm_template:lkm_template_init(): insertedNotice how the module name and the function name are automatically prefixed to the printk message content! This is very useful and indeed very common; in the kernel, literally hundreds of source files begin with the pr_fmt(). A quick search on the 6.1.25 kernel code base revealed over 2,200 instances of this macro in the code base! We too shall follow this convention, though not in all our demo kernel modules.
The pr_fmt() also takes effect on the recommended printk usage for driver authors via the dev_*() macros.
Next, let’s delve into the issue of writing portable code with reference to printk.
Portability and the printk format specifiers
Section titled “Portability and the printk format specifiers”There’s a question to ponder regarding the versatile printk kernel API: how will you ensure that your printk output looks correct (is correctly formatted) and works equally well on any CPU regardless of bit width? The portability issue raises its head here; the good news is that getting familiar with the various format specifiers provided will help you a great deal in this regard, in effect allowing you to write arch-independent printk instances.
It’s important to realize that the size_t – pronounced size type – is a typedef for an unsigned integer; similarly, ssize_t (signed size type) is a typedef for a signed integer.
Here are a few top-of-mind common printk format specifiers to keep in mind when writing portable code:
- For
size_tandssize_t(unsigned and signed) integers, use%zuand%zd, respectively. - For kernel pointers, use
%pKfor security (hashed values), and%pxfor actual pointers (don’t use this in production!). Additionally, use%pafor physical addresses (must pass it by reference). Thekptr_restrictsysctl can be leveraged in this regard; we further delve into this aspect in Chapter 5, Writing Your First Kernel Module – Part 2, in the Proc filesystem tunables affecting the system log section. - For a raw buffer as a string of hex characters, use
%*ph(where*is replaced by the number of characters). Use it for buffers within 64 characters, and use theprint_hex_dump_bytes()routine for more; variations are available (see the kernel documentation – the link follows). - For IPv4 addresses, use
%pI4, and for IPv6 addresses, use%pI6(variations here too).
An exhaustive list of printk format specifiers and an explanation of when to use each (with examples!) is part of the official kernel documentation here: https://www.kernel.org/doc/Documentation/printk-formats.txt.
The kernel also explicitly documents the fact that using the unadorned %p in a printk() statement can lead to security issues (https://www.kernel.org/doc/html/latest/process/deprecated.html#p-format-specifier). I urge you to browse through it!
Let’s round off this section by checking out a recent feature: printk indexing.
Understanding the new printk indexing feature
Section titled “Understanding the new printk indexing feature”So, you’ve written a kernel module (a driver, perhaps) that, as part of the job, emits some printk instances (of course, being a good person, you know to keep the number of prints as low as possible). So, let’s say one of your log messages is mydriver: detected crazy situation X; okay, fine. Your project is deployed in production; lets say a user space monitoring daemon of some sort is (also) monitoring kernel log messages for abnormal conditions so that it can alert the human user. This makes us realize that printk instances aren’t just for human consumption; programs too might be continuously monitoring them, which is often the case in large installations.
Now, a few months later, another developer on the project feels that your kernel log message isn’t great and changes it to mydriver: detected abnormal condition X (come on, admit it, it’s better). The trouble is that the log monitoring daemon process, still looking for your old message (perhaps by grepping for the mydriver: detected crazy situation string), will now completely miss this (new) key message, causing all kinds of problems.
To tackle situations like this (yes, they do arise), Chris Down proposed a kernel printk indexing feature (which has been merged into mainline in 5.15). Essentially what happens with this enabled is this: every printk instance’s metadata – the actual format string (the message in effect), the location in the source from where it’s emitted, the log level, and more – is saved into a structure (struct pi_entry), and all these structures are collated into a special section within the kernel vmlinux image (named .printk_index; the same goes for individual kernel modules!).
These messages are made visible via a debugfs entry (this does indicate a dependency on debugfs being enabled), <debugfs_mount_point>/printk/index/<file>, where <file> can be vmlinux as well as all kernel modules.
The kernel config in question (a Boolean) is named CONFIG_PRINTK_INDEX; it’s off by default (you can see it via the usual make menuconfig UI here: General setup | Printk indexing debugfs interface).
With the kernel built with it turned on, here’s a couple of quick examples (notice we run as root, as debugfs is accessible only as root):
# head -n3 /sys/kernel/debug/printk/index/vmlinux# <level/flags> filename:line function "format"<3> init/main.c:1591 console_on_rootfs "Warning: unable to open an initial console.\n"<3> init/main.c:1569 kernel_init "Default init %s failed (error %d)\n"The format of each line is shown by the very first line (it’s quite intuitive). Here’s another example (let’s look for "fire"):
# grep -Hn -i -w "fire" /sys/kernel/debug/printk/index/*/sys/kernel/debug/printk/index/lp:13:<6> drivers/char/lp.c:262 lp_check_status "lp%d on fire\n"(Ha! We saw this very same example printk in the Using printk log levels section!) So, think about it: the user space monitoring daemon can now look up the kernel vmlinux, as well as any kernel module’s log messages, via the printk index debugfs entries, checking that they’re what’s expected, and if not, can take remedial action (reporting an issue or whatever).
Further, with PRINTK_INDEX disabled, there’s no overhead at all. However, with printk indexing on, at least two possible issues arise: first, the non-inclusion of debugfs in many production systems, and second, the extra memory used up by keeping thousands of format strings within the kernel image (on my 6.1.25 vmlinux image, there are close to 12,000 printk instances detected by this feature!). Still, it does solve, or at least mitigate, a problem; thus, it’s in the mainline kernel.
Exercise: Build the kernel with this feature enabled and try it out.
FYI, here’s the commit that merged in PRINTK_INDEX: https://github.com/torvalds/linux/commit/337015573718b161891a3473d25f59273f2e626b.
A quick thought: is this printk indexing feature pretty much identical to the dynamic kernel debug feature (that we covered in the section An introduction to the kernel’s powerful dynamic debug feature)? No, realize that the dynamic debug covers only all debug printk call sites; printk indexing covers all printk call sites!
Having covered a good amount on the venerable kernel printk (and friends), you might be wondering about internal implementation details. The LWN Kernel Index is a great place to find detailed technical articles on this (and indeed all aspects of the kernel!): https://lwn.net/Kernel/Index/#Kernel_messages. Browsing these (as of this writing, July 2023), you’ll notice a lot of churn in the works, the idea being to finally iron out old latency (and other) issues with the printk, clearing the path to PREEMPT_RT finally being merged (Chapter 11, The CPU Scheduler – Part 2, will provide an introduction to the Linux real-time effort).
Okay! Let’s move toward completing this chapter by learning the basics of how the Makefile for your kernel module looks and works.
Understanding the basics of a kernel module Makefile
Section titled “Understanding the basics of a kernel module Makefile”You may have noticed by now that we tend to follow a one-kernel-module-per-directory rule of sorts. Yes, that definitely helps keep things organized. So, let’s take our second kernel module, the ch4/printk_loglvl one. To build it, we just cd to its folder, type make, and (fingers crossed!) voilà, it’s done. We have the printk_loglevel.ko kernel module object freshly generated (which we can then apply insmod/rmmod to). But how exactly did it get built when we typed make? Explaining this is the purpose of this section.
First off, we do expect you to understand the basics regarding make and the Makefile. If not, don’t fret, we’ve provided links to check this out, within the Further reading section (in the paragraph labeled Makefiles: introductory stuff) of this chapter.. Check it out! (Link: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/main/Further_Reading.md#chapter-4-writing-your-first-kernel-module-lkms-part-1---further-reading).
Next, as this is our very first chapter that deals with the LKM framework and its corresponding Makefile, we will keep things nice and simple, especially regarding the Makefile. However, early on in Chapter 5, Writing Your First Kernel Module – Part 2, in the A better Makefile template for your kernel modules section, we shall introduce a more sophisticated, and (what we hope is) a better Makefile, that is still quite simple to understand. We shall then use this better Makefile in all subsequent code (but not right now); do look out for it and use it!
As you will know, the make command will by default look for a file named Makefile in the current directory; if it exists, it will parse it and execute command sequences as specified within it. Here’s our simple Makefile for the printk_loglevel kernel module project (I use the nl – “number lines” – utility to show it with line numbers prefixed):
$ nl Makefile 1 # ch4/printk_loglvl/Makefile 2 PWD := $(shell pwd) 3 KDIR := /lib/modules/$(shell uname -r)/build/ 4 obj-m += printk_loglvl.o
5 # Enable the pr_debug() and pr_devel() as well by removing the comment from 6 # one of the lines below 7 # (Note: EXTRA_CFLAGS deprecated; use ccflags-y) 8 #ccflags-y += -DDEBUG 9 #CFLAGS_printk_loglvl.o := -DDEBUG
10 all: 11 make -C $(KDIR) M=$(PWD) modules 12 install: 13 make -C $(KDIR) M=$(PWD) modules_install 14 clean: 15 make -C $(KDIR) M=$(PWD) cleanIt should go without saying that the Unix Makefile syntax demands this basic format:
target: [dependent-source-file(s)] rule(s)The rule(s) instances are always prefixed with a [Tab] character, not white space.
Let’s gather the basics regarding how this (module) Makefile works. First off, a key point is this: the kernel’s Kbuild system (which we’ve been mentioning and using since Chapter 2, Building the 6.x Linux Kernel from Source – Part 1), primarily uses two variable strings of software to build, chained up within the two variables obj-y and obj-m.
The obj-y string has the concatenated list of all objects to build and merge into the final kernel image files – the uncompressed vmlinux and the compressed (boot-able) [b][z]Image images. Think about it – it makes sense: the y in obj-y stands for Yes. All kernel built-in and Kconfig options that were set to Y during the kernel configuration process (or are Y by default) are chained together via this item, built, and ultimately woven into the final kernel image files by the Kbuild build system.
On the other hand, it’s now easy to see that the obj-m string is a concatenated list of all kernel objects to build separately, as kernel modules! This is precisely why our Makefile has this all-important line (line 4):
obj-m += printk_loglvl.oIn effect, it tells the Kbuild system to include our code; more correctly, it tells it to implicitly compile the printk_loglvl.c source code into the printk_loglvl.o binary object, and then add this object to the obj-m list. Next, with the default rule for make being the all rule (lines 10 and 11), it is processed:
all: make -C $(KDIR) M=$(PWD) modulesThe processing of this single statement (line 11) is quite involved; here’s what transpires:
- The
-Coption switch tomakehas themakeprocess change directory (via thechdir()system call) to the directory name that follows-C. Thus, it changes the directory to the$(KDIR)directory, which is set (in line 3) to the kernelbuildsymbolic link under/lib/modules/$(uname -r)(which, as we covered earlier, points to the location of the limited kernel source tree that got installed via thekernel-headerspackage). To remind you, here it is (on my Ubuntu guest):$ ls -l /lib/modules/$(uname -r)/buildlrwxrwxrwx 1 root root 31 May 5 10:51 build -> /home/c2kp/kernels/linux-6.1.25/ - So, clearly, the
makeprocess changes directory to the folder~/kernels/linux-6.1.25/, which, in this case, points back to our original 6.1.25 kernel source tree (as we’re running off the custom kernel that we built earlier). Once there, it automatically parses in the content of the kernel’s top-level Makefile – that is, the Makefile that resides there, in the root of this kernel source tree. This is a key point. The kernel top-level Makefile is a rather large and sophisticated one (on 6.1.25, it’s well over 2,000 lines) and contains key build details and variables. This way, being parsed in every time even an out-of-tree module is being built, it’s guaranteed that all kernel modules are tightly coupled to the kernel that they are being built against (more on this a bit later). This also guarantees that kernel modules are built with the exact same set of rules – that is, the compiler/linker configurations (the*CFLAGS*options, the compiler option switches, and so on) – as the kernel image itself is. This is required for binary compatibility. - Next, in the Makefile, still on line 11, you can see the initialization of the variable named
M(to the present working directory), and that the target specified ismodules; hence, themakeprocess now changes the directory to that specified by theMvariable, to$(PWD)– the very folder we started from (line 2:PWD := $(shell pwd)in the Makefile initializes it to the correct value)!
So, interestingly, it’s a recursive build: the build process, having – very importantly – parsed the kernel top-level Makefile, now switches back to the kernel module’s directory and builds the module(s) therein.
Lines 12 and 13 make up the install target (which we cover in the next chapter), and lines 14 and 15 make up the clean target.
Did you notice that when a kernel module is built, a fair number of intermediate working files are generated as well? Among them are modules.order, <file>.mod.c, <file>.o, Module.symvers, <file>.mod.o, .<file>.o.cmd, .<file>.ko.cmd, a folder called .tmp_versions/, and, of course, the kernel module binary object itself, <file>.ko – the whole point of the build exercise. Further, there are several hidden files generated as well. Getting rid of all these temporary build artifacts, including the target (the kernel module object itself) is easy: just perform make clean. The clean rule cleans it all up. We shall delve into the install target in the following chapter.
A screenshot helps convey the output seen on building and then cleaning up:

Figure 4.13: Screenshot showing the build (make) and “make clean” of our printk_loglvl kernel module (on our x86_64 Ubuntu 22.04 guest running our custom-built 6.1.25 LTS kernel)
You can look up what the modules.order and modules.builtin files (and other files) are meant for within the kernel documentation here: https://elixir.bootlin.com/linux/v6.1.25/source/Documentation/kbuild/kbuild.rst. Also, as mentioned previously, we shall, in the following chapter, introduce and use a more sophisticated Makefile variant – a “better” Makefile. It is designed to help you, the kernel module/driver developer, improve code quality by running targets related to kernel coding style checks, static analysis, simple packaging, and (a dummy target) for dynamic analysis.
With that, we conclude this chapter. Well done – you are now well on your way to learning Linux kernel development!
Summary
Section titled “Summary”In this chapter, we covered the basics of Linux kernel architecture and the LKM framework. You learned what a kernel module is and why it’s useful. We then wrote a simple yet complete kernel module, a very basic Hello, world. We then delved further into how it works and the coding conventions to follow, along with the practicalities of how exactly to build, load, see the module listing, and unload it. Kernel logging with printk (and friends) was covered in some detail, along with explanations regarding the printk logging levels, controlling output to the console(s), and more. Details on how to emit pure debug-level kernel messages, and more importantly, an introduction to using the kernel’s dynamic debug feature were then dealt with. We then moved on to the rate-limiting printk, generating kernel messages from user space, standardizing its output format, and understanding the new printk indexing feature. We closed this chapter with an understanding of the basics of the kernel module Makefile and how it operates within the LKM framework.
I urge you to work on the sample code (via the book’s GitHub repository), work on the questions/assignments, and then proceed on to the next chapter, where we continue our coverage on writing a Linux kernel module!
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/ch4_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/master/solutions_to_assgn.
Further reading
Section titled “Further reading”To help you delve 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 document in this book’s GitHub repository. The Further reading document is available here: https://github.com/PacktPublishing/Linux-Kernel-Programming_2E/blob/master/Further_Reading.md.