-
Notifications
You must be signed in to change notification settings - Fork 621
Expand file tree
/
Copy pathlkmpg.tex
More file actions
3817 lines (3138 loc) · 209 KB
/
Copy pathlkmpg.tex
File metadata and controls
3817 lines (3138 loc) · 209 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
\documentclass[10pt, oneside]{book}
\ifdefined\HCode\else
\usepackage[Bjornstrup]{fncychap}
\fi
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{fancyhdr}
\usepackage{xparse}
\usepackage{ifthen}
\usepackage{pdfpages}
% tikz settings
\usepackage{tikz}
\usetikzlibrary{shapes.geometric, arrows, shadows, decorations.text}
\tikzstyle{startstop} = [rectangle, rounded corners, minimum width=3cm, minimum height=1cm,text centered, draw=black, fill=red!30, drop shadow]
\tikzstyle{io} = [trapezium, trapezium left angle=70, trapezium right angle=110, minimum width=3cm, minimum height=1cm, text centered, draw=black, fill=blue!30]
\tikzstyle{process} = [rectangle, minimum width=3cm, minimum height=1cm, text centered, text width=3cm, draw=black, fill=orange!30]
\tikzstyle{decision} = [diamond, minimum width=1cm, minimum height=1cm, text centered, draw=black, fill=green!30]
\tikzstyle{arrow} = [thick,->,>=stealth]
\tikzstyle{line} = [draw, -latex']
% packages for code
\usepackage{verbatim}
\usepackage{minted}
% citation
\usepackage{cite}
\usepackage[colorlinks,citecolor=green]{hyperref}
\usepackage{cleveref}
\usepackage{xcolor}
\hypersetup{
colorlinks,
linkcolor = {red!50!black},
citecolor = {blue!50!black},
urlcolor = {blue!80!black}
}
\makeatletter
\@removefromreset{section}{chapter}
\makeatother
\renewcommand{\thesection}{\arabic{section}}
\input{lib/codeblock}
\input{lib/kernelsrc}
\author{Peter Jay Salzman, Michael Burian, Ori Pomerantz, Bob Mottram, Jim Huang}
\date{\today}
\title{The Linux Kernel Module Programming Guide}
\begin{document}
\maketitle
\ifdefined\HCode
\includegraphics{assets/cover-with-names.png}
\tableofcontents
\else
\pagestyle{empty}
\begin{tikzpicture}[remember picture, overlay]
\node at (current page.center) {\includegraphics[width=\paperwidth, height=\paperheight]{assets/cover.png}}; \\
\node at (11, -9.5) {\Large \textbf{Peter Jay Salzman, Michael Burian,}}; \\
\node at (11, -10.5) {\Large \textbf{Ori Pomerantz, Bob Mottram,}}; \\
\node at (11, -11.5) {\Large \textbf{Jim Huang}};
\end{tikzpicture}
\tableofcontents
\fi
\chapter{Getting Started}
This chapter introduces the guide, outlines the basic development environment,
and builds up from the first loadable module. The emphasis is on getting a
working workflow in place before moving on to the broader kernel interfaces
used by more capable modules.
\section{Introduction}
\label{sec:introduction}
The Linux Kernel Module Programming Guide is a free book; you may reproduce or modify it under the terms of the \href{https://opensource.org/licenses/OSL-3.0}{Open Software License}, version 3.0.
This book is distributed in the hope that it would be useful, but without any warranty,
without even the implied warranty of merchantability or fitness for a particular purpose.
The author encourages wide distribution of this book for personal or commercial use,
provided the above copyright notice remains intact and the method adheres to the provisions of the \href{https://opensource.org/licenses/OSL-3.0}{Open Software License}.
In summary, you may copy and distribute this book free of charge or for a profit.
No explicit permission is required from the author for reproduction of this book in any medium, physical or electronic.
Derivative works and translations of this document must be placed under the Open Software License, and the original copyright notice must remain intact.
If you have contributed new material to this book, you must make the material and source code available for your revisions.
Please make revisions and updates available directly to the document maintainer, Ching-Chun (Jim) Huang <jserv@ccns.ncku.edu.tw>.
This will allow for the merging of updates and provide consistent revisions to the Linux community.
If you publish or distribute this book commercially, donations, royalties,
or printed copies are greatly appreciated by the author and the \href{https://tldp.org/}{Linux Documentation Project} (LDP).
Contributing in this way shows your support for free software and the LDP.
If you have questions or comments, please contact the address above.
\subsection{Authorship}
\label{sec:authorship}
The Linux Kernel Module Programming Guide was initially authored by Ori Pomerantz for Linux v2.2.
As the Linux kernel evolved, Ori's availability to maintain the document diminished.
Consequently, Peter Jay Salzman assumed the role of maintainer and updated the guide for Linux v2.4.
Similar constraints arose for Peter when tracking developments in Linux v2.6,
leading to Michael Burian joining as a co-maintainer to bring the guide up to speed with Linux v2.6.
Bob Mottram contributed to the guide by updating examples for Linux v3.8 and later.
Jim Huang then undertook the task of updating the guide for recent Linux versions (v5.0 and beyond),
along with revising the LaTeX document.
The guide now uses Linux v5.10 as its minimum supported baseline and aims to keep examples and guidance compatible across current long-term support kernels.
\subsection{Acknowledgements}
\label{sec:acknowledgements}
The following people have contributed corrections or good suggestions:
\begin{flushleft}
\input{contrib}
\end{flushleft}
\subsection{What Is A Kernel Module?}
\label{sec:kernelmod}
Involvement in the development of Linux kernel modules requires a foundation in the C programming language and a track record of creating conventional programs intended for process execution.
This pursuit delves into a domain where an unregulated pointer, if disregarded,
may potentially trigger the total elimination of an entire filesystem,
resulting in a scenario that necessitates a complete system reboot.
A Linux kernel module is precisely defined as a code segment capable of dynamic loading and unloading within the kernel as needed.
These modules enhance kernel capabilities without necessitating a system reboot.
A notable example is seen in the device driver module, which facilitates kernel interaction with hardware components linked to the system.
In the absence of modules, the prevailing approach leans toward monolithic kernels,
requiring direct integration of new functionalities into the kernel image.
This approach leads to larger kernels and necessitates kernel rebuilding and subsequent system rebooting when new functionalities are desired.
\subsection{Kernel module package}
\label{sec:packages}
Linux distributions provide the commands \sh|modprobe|, \sh|insmod| and \sh|depmod| within a package.
On Ubuntu/Debian GNU/Linux:
\begin{codebash}
sudo apt-get install build-essential kmod
\end{codebash}
On Arch Linux:
\begin{codebash}
sudo pacman -S gcc kmod
\end{codebash}
\subsection{What Modules are in my Kernel?}
\label{sec:modutils}
To discover what modules are already loaded within your current kernel, use the command \sh|lsmod|.
\begin{codebash}
lsmod
\end{codebash}
Modules are stored within the file \verb|/proc/modules|, so you can also see them with:
\begin{codebash}
cat /proc/modules
\end{codebash}
This can be a long list, and you might prefer to search for something particular.
To search for the \verb|fat| module:
\begin{codebash}
lsmod | grep fat
\end{codebash}
\subsection{Is there a need to download and compile the kernel?}
\label{sec:buildkernel}
To effectively follow this guide, there is no obligatory requirement for performing such actions.
Nonetheless, a prudent approach involves executing the examples within an isolated environment,
thus mitigating any potential risk of disrupting the system.
This guide includes a \verb|devtools/| directory that automates kernel module testing
inside a QEMU virtual machine.
It downloads a kernel source tree and a minimal BusyBox root filesystem, builds both,
and boots the result in QEMU with the host \verb|examples/| directory shared into the
guest via the 9p virtfs protocol.
You edit source files on your host and \sh|insmod| the compiled modules in the guest---no
disk images to manage, no root filesystem to rebuild.
See \Cref{sec:devtools_setup} for the complete setup procedure.
\subsection{Before We Begin}
\label{sec:preparation}
Before delving into code, certain matters require attention.
Variances exist among individuals' systems, and distinct personal approaches are evident.
The achievement of successful compilation and loading of the inaugural ``hello world'' program may,
at times, present challenges.
It is reassuring to note that overcoming the initial obstacle on the first attempt paves the way for subsequent endeavors to proceed seamlessly.
\begin{enumerate}
\item Modversioning.
A module compiled for one kernel will not load if a different kernel is booted,
unless \cpp|CONFIG_MODVERSIONS| is enabled in the kernel.
Module versioning will be discussed later in this guide.
Until module versioning is covered, the examples in this guide may not work correctly if running a kernel with modversioning turned on.
However, most stock Linux distribution kernels come with modversioning enabled.
If difficulties arise when loading the modules due to versioning errors, consider compiling a kernel with modversioning turned off.
\item Using the X Window System.
It is highly recommended to extract, compile, and load all the examples discussed in this guide from a console.
Working on these tasks within the X Window System is discouraged.
Modules cannot directly print to the screen like \cpp|printf()| can,
but they can log information and warnings to the kernel's log ring buffer.
This output is \emph{not} automatically displayed on any console or terminal.
To view kernel module messages, you must use \sh|dmesg| to read the kernel log ring buffer,
or check the systemd journal with \sh|journalctl -k| for kernel messages.
Refer to \Cref{sec:helloworld} for more information.
The terminal or environment from which you load the module does not affect where the output goes—it always goes to the kernel log.
\item SecureBoot.
Numerous modern computers arrive pre-configured with UEFI SecureBoot enabled—an essential security standard ensuring booting exclusively through trusted software endorsed by the original equipment manufacturer.
Certain Linux distributions even ship with the default Linux kernel configured to support SecureBoot.
In these cases, the kernel module necessitates a signed security key.
Failing that, an attempt to insert your first ``hello world'' module would result in the message: ``\emph{ERROR: could not insert module}''.
If this message ``\emph{Lockdown: insmod: unsigned module loading is restricted;
see man kernel lockdown.7}'' appears in the \sh|dmesg| output,
the simplest approach involves disabling UEFI SecureBoot from the boot menu of your PC or laptop,
allowing the successful insertion of the ``hello world'' module.
Naturally, an alternative involves undergoing intricate procedures such as generating keys, system key installation,
and module signing to achieve functionality.
However, this intricate process is less appropriate for beginners. If interested,
more detailed steps for \href{https://wiki.debian.org/SecureBoot}{SecureBoot} can be explored and followed.
In the real world—especailly in enterprise environment, production servers, or laptops where your IT staffs mandate strict security—it is not eligible to disable SecureBoot.
If you ever encounter such situations, visit \Cref{sec:secure_boot_signing_guide} for a SecureBoot signing thorough guide.
\end{enumerate}
If you are building your own kernel for module development, these \verb|.config| options are useful for debugging and development:
\begin{itemize}
\item \cpp|CONFIG_DEBUG_INFO|: include debug symbols so \sh|gdb|, \sh|addr2line|, and \sh|objdump| can map crash addresses to source lines.
\item \cpp|CONFIG_DYNAMIC_DEBUG|: enable runtime-switchable \cpp|pr_debug()| statements (see \Cref{sec:printk}).
\item \cpp|CONFIG_KASAN| (Kernel Address Sanitizer): instruments memory accesses to detect out-of-bounds, use-after-free, and other memory errors at the cost of roughly 2$\times$ memory usage and some CPU overhead.
\item \cpp|CONFIG_LOCKDEP| (lock dependency checker): detects potential deadlocks (lock order inversions, sleeping under spinlocks, wrong lock type for context) at runtime, before they actually hang the system.
\item \cpp|CONFIG_DEBUG_ATOMIC_SLEEP|: flags attempts to sleep in atomic context, catching the most common spinlock misuse.
\item \cpp|CONFIG_MODULE_FORCE_UNLOAD|: allows \sh|rmmod -f| as a last resort during development, but use it with care because force-unloading can hide lifetime bugs and leave the kernel in an inconsistent state.
\end{itemize}
The QEMU-based environment described below already enables
\cpp|CONFIG_DEBUG_INFO| and \cpp|CONFIG_MODULE_FORCE_UNLOAD|; enable the
others explicitly if you want those extra diagnostics.
\subsection{QEMU-Based Development Environment}
\label{sec:devtools_setup}
An alternative to installing kernel headers on your host and loading modules
into your running kernel is to use the QEMU-based development environment
provided under \verb|devtools/|.
This approach is especially useful on machines where you cannot (or prefer not to)
load arbitrary kernel modules (for example, hosts with SecureBoot enabled, corporate
laptops, or macOS workstations).
The setup compiles a minimal Linux kernel with module, debugfs, procfs, and 9p
filesystem support, along with a statically linked BusyBox initramfs.
QEMU boots this kernel and shares the project directory into the guest via the 9p
virtfs protocol, so every file you edit on the host is immediately visible inside the
virtual machine.
\textbf{Prerequisites.}
The kernel and BusyBox builds require a Linux host (or a Linux environment such as
Docker or \href{https://lima-vm.io/}{Lima} on macOS).
QEMU itself runs natively on Linux and macOS.
\begin{codebash}
# Debian/Ubuntu: install the build toolchain and QEMU
sudo apt-get install build-essential flex bison bc libelf-dev libssl-dev cpio qemu-system-x86
# macOS: install QEMU (kernel build runs inside Lima or Docker)
brew install qemu
\end{codebash}
\textbf{One-time setup} (downloads a kernel tarball and BusyBox, builds both, and
packs an initramfs):
\begin{codebash}
devtools/setup.sh
\end{codebash}
\textbf{Building modules} against the QEMU kernel (must be run on Linux):
\begin{codebash}
devtools/build-modules.sh
\end{codebash}
\textbf{Interactive testing.}
Boot QEMU and get a shell inside the guest.
The project tree is mounted at \verb|/mnt/lkmpg/|, with compiled modules at
\verb|/mnt/lkmpg/examples/*.ko|:
\begin{codebash}
devtools/boot.sh
# Inside the guest:
insmod /mnt/lkmpg/examples/hello-1.ko
dmesg | tail
rmmod hello_1
\end{codebash}
\textbf{Automated testing.}
Build all modules and run \sh|insmod|/\sh|rmmod| for every module in a single
command.
Modules listed in \verb|.ci/non-working| are automatically skipped:
\begin{codebash}
devtools/test-modules.sh
\end{codebash}
\textbf{Kernel debugging with GDB.}
GDB requires the \verb|vmlinux| image with debug symbols.
Prebuilt setups omit it for size; rebuild from source first:
\begin{codebash}
LKMPG_NO_PREBUILT=1 devtools/setup.sh
\end{codebash}
Then start QEMU paused and attach GDB from a second terminal:
\begin{codebash}
# Terminal 1: QEMU waits for a debugger connection
devtools/boot.sh --gdb
# Terminal 2: connect GDB
gdb devtools/.cache/kernel-build/vmlinux \
-ex "target remote :1234" \
-ex "break do_init_module" \
-ex continue
\end{codebash}
When you \sh|insmod| a module in the guest, GDB will break at the module
initialization entry point.
\textbf{Overriding defaults.}
Create \verb|devtools/config.local| (gitignored) to change the kernel version,
QEMU memory size, or other settings:
\begin{code}
KERNEL_VERSION="6.6.70"
QEMU_MEM="1G"
\end{code}
Rerun \verb|devtools/setup.sh| after changing \verb|KERNEL_VERSION|.
\section{Kernel Headers}
\label{sec:headers}
Before building anything, it is necessary to install the header files for the kernel.
If you are using the QEMU-based environment described in \Cref{sec:devtools_setup},
the kernel headers are built automatically by \verb|devtools/setup.sh| and you can
skip this step.
On Ubuntu/Debian GNU/Linux:
\begin{codebash}
sudo apt-get update
apt-cache search linux-headers-`uname -r`
\end{codebash}
The following command provides information about the available kernel header files.
Then, for example:
\begin{codebash}
sudo apt-get install linux-headers-`uname -r`
\end{codebash}
On Arch Linux:
\begin{codebash}
sudo pacman -S linux-headers
\end{codebash}
On Fedora:
\begin{codebash}
sudo dnf install kernel-devel kernel-headers
\end{codebash}
\section{Examples}
\label{sec:examples}
All the examples from this document are available within the \verb|examples| subdirectory.
To build all examples at once, run \sh|make| from within the \verb|examples/| directory
(requires kernel headers installed, see \Cref{sec:headers}), or use the QEMU-based
environment:
\begin{codebash}
devtools/build-modules.sh
\end{codebash}
To run automated \sh|insmod|/\sh|rmmod| tests for every module inside QEMU:
\begin{codebash}
devtools/test-modules.sh
\end{codebash}
Should compile errors occur, it may be due to a more recent kernel version being in use,
or there might be a need to install the corresponding kernel header files.
\section{Hello World}
\label{sec:helloworld}
\subsection{The Simplest Module}
\label{sec:org2d3e245}
Most individuals beginning their programming journey typically start with some variant of a \emph{hello world} example.
It is unclear what the outcomes are for those who deviate from this tradition, but it seems prudent to adhere to it.
The learning process will begin with a series of hello world programs that illustrate various fundamental aspects of writing a kernel module.
Presented next is the simplest possible module.
Make a test directory:
\begin{codebash}
mkdir -p ~/develop/kernel/hello-1
cd ~/develop/kernel/hello-1
\end{codebash}
Paste this into your favorite editor and save it as \verb|hello-1.c|:
\samplec{examples/hello-1.c}
Now you will need a \verb|Makefile|. If you copy and paste this, change the indentation to use \textit{tabs}, not spaces.
\begin{code}
obj-m += hello-1.o
PWD := $(CURDIR)
all:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
\end{code}
In \verb|Makefile|, \verb|$(CURDIR)| can be set to the absolute pathname of the current working directory (after all \verb|-C| options are processed, if any).
See more about \verb|CURDIR| in \href{https://www.gnu.org/software/make/manual/make.html}{GNU make manual}.
And finally, just run \verb|make| directly.
\begin{codebash}
make
\end{codebash}
If there is no \verb|PWD := $(CURDIR)| statement in the Makefile, then it may not compile correctly with \verb|sudo make|.
This is because some environment variables are specified by the security policy and cannot be inherited.
The default security policy is \verb|sudoers|.
In the \verb|sudoers| security policy, \verb|env_reset| is enabled by default, which restricts environment variables.
Specifically, path variables are not retained from the user environment;
they are set to default values (for more information, see: \href{https://www.sudo.ws/docs/man/sudoers.man/}{sudoers manual}).
You can see the environment variable settings by:
\begin{verbatim}
$ sudo -s
# sudo -V
\end{verbatim}
Here is a simple Makefile as an example to demonstrate the problem mentioned above.
\begin{code}
all:
echo $(PWD)
\end{code}
Then, we can use the \verb|-p| flag to print out the environment variable values from the Makefile.
\begin{verbatim}
$ make -p | grep PWD
PWD = /home/ubuntu/temp
OLDPWD = /home/ubuntu
echo $(PWD)
\end{verbatim}
The \verb|PWD| variable will not be inherited with \verb|sudo|.
\begin{verbatim}
$ sudo make -p | grep PWD
echo $(PWD)
\end{verbatim}
However, there are three ways to solve this problem.
\begin{enumerate}
\item {
You can use the \verb|-E| flag to temporarily preserve them.
\begin{codebash}
$ sudo -E make -p | grep PWD
PWD = /home/ubuntu/temp
OLDPWD = /home/ubuntu
echo $(PWD)
\end{codebash}
}
\item {
You can disable \verb|env_reset| by editing \verb|/etc/sudoers| as root using \verb|visudo|.
\begin{code}
## sudoers file.
##
...
Defaults env_reset
## Change env_reset to !env_reset in previous line to keep all environment variables
\end{code}
Then execute \verb|env| and \verb|sudo env| individually.
\begin{codebash}
# disable the env_reset
echo "user:" > non-env_reset.log; env >> non-env_reset.log
echo "root:" >> non-env_reset.log; sudo env >> non-env_reset.log
# enable the env_reset
echo "user:" > env_reset.log; env >> env_reset.log
echo "root:" >> env_reset.log; sudo env >> env_reset.log
\end{codebash}
You can view and compare these logs to find differences between \verb|env_reset| and \verb|!env_reset|.
}
\item {You can preserve environment variables by appending them to \verb|env_keep| in \verb|/etc/sudoers|.
\begin{code}
Defaults env_keep += "PWD"
\end{code}
After applying the above change, you can check the environment variable settings by:
\begin{verbatim}
$ sudo -s
# sudo -V
\end{verbatim}
}
\end{enumerate}
If all goes smoothly you should then find that you have a compiled \verb|hello-1.ko| module.
You can find info on it with the command:
\begin{codebash}
modinfo hello-1.ko
\end{codebash}
At this point the command:
\begin{codebash}
lsmod | grep hello
\end{codebash}
should return nothing.
You can try loading your new module with:
\begin{codebash}
sudo insmod hello-1.ko
\end{codebash}
The dash character will get converted to an underscore, so when you again try:
\begin{codebash}
lsmod | grep hello
\end{codebash}
You should now see your loaded module. It can be removed again with:
\begin{codebash}
sudo rmmod hello_1
\end{codebash}
Notice that the dash was replaced by an underscore.
To see the module's output messages, use \sh|dmesg| to view the kernel log ring buffer:
\begin{codebash}
sudo dmesg | tail -10
\end{codebash}
You should see messages like ``Hello world 1.'' and ``Goodbye world 1.'' from your module.
Alternatively, you can check the systemd journal for kernel messages:
\begin{codebash}
journalctl --since "1 hour ago" | grep kernel
\end{codebash}
If you are using the QEMU environment from \Cref{sec:devtools_setup} instead, the
same exercise looks like this:
\begin{codebash}
devtools/build-modules.sh # compile all examples
devtools/boot.sh # boot into the QEMU guest
# inside the guest:
insmod /mnt/lkmpg/examples/hello-1.ko
dmesg | tail
rmmod hello_1
\end{codebash}
No \sh|sudo| is needed because the guest runs as root.
You now know the basics of creating, compiling, installing and removing modules.
Now for more of a description of how this module works.
Kernel modules must have at least two functions: a "start" (initialization) function called \cpp|init_module()| which is called when the module is \sh|insmod|ed into the kernel,
and an "end" (cleanup) function called \cpp|cleanup_module()| which is called just before it is removed from the kernel.
Actually, things have changed starting with kernel 2.3.13.
% TODO: adjust the section anchor
You can now use whatever name you like for the start and end functions of a module,
and you will learn how to do this in \Cref{sec:hello_n_goodbye}.
In fact, the new method is the preferred method.
The old \cpp|init_module()| and \cpp|cleanup_module()| have been deprecated for x86 systems with indirect branch tracking (IBT) enabled starting from \href{https://github.com/torvalds/linux/commit/4fab2d76}{commit 4fab2d76} in kernel 6.15, causing build failures.
However, many existing examples still use these names for their start and end functions.
Typically, \cpp|init_module()| either registers a handler for something with the kernel,
or it replaces one of the kernel functions with its own code (usually code to do something and then call the original function).
The \cpp|cleanup_module()| function is supposed to undo whatever \cpp|init_module()| did, so the module can be unloaded safely.
Lastly, every kernel module needs to include \src{include/linux/module.h}.
% TODO: adjust the section anchor
We needed to include \src{include/linux/printk.h} only for the macro expansion for the \cpp|pr_alert()| log level, which you'll learn about in \Cref{sec:printk}.
\begin{enumerate}
\item A point about coding style.
Another thing that may not be immediately obvious to anyone getting started with kernel programming is that indentation within your code should use \textbf{tabs} and \textbf{not spaces}.
It is one of the coding conventions of the kernel.
You may not like it, but you will need to get used to it if you ever submit a patch upstream.
\item Introducing print macros.
\label{sec:printk}
In the beginning there was \cpp|printk|, usually followed by a priority such as \cpp|KERN_INFO| or \cpp|KERN_DEBUG|.
More recently, this can also be expressed in abbreviated form using a set of print macros, such as \cpp|pr_info| and \cpp|pr_debug|.
This just saves some mindless keyboard bashing and looks a bit neater.
They can be found within \src{include/linux/printk.h}.
Take time to read through the available priority macros.
\textbf{Important:} These functions write to the kernel log ring buffer, \emph{not} directly to any terminal or console.
To view the output from your kernel modules, you must use \sh|dmesg| or \sh|journalctl -k|.
The kernel log buffer is a fixed-size circular buffer (sized via \cpp|CONFIG_LOG_BUF_SHIFT| in the kernel configuration).
Excessive logging can overflow the buffer and push out earlier messages before they are read.
In hot paths (interrupt handlers, per-packet processing, or tight loops), use the rate-limited variants \cpp|pr_info_ratelimited()|, \cpp|pr_warn_ratelimited()|, etc., or the explicit \cpp|printk_ratelimit()| guard, to avoid flooding the log and slowing down the system due to console output overhead.
See \src{include/linux/ratelimit.h} for details.
For development, \cpp|pr_debug()| is particularly useful.
When the kernel is compiled with \cpp|CONFIG_DYNAMIC_DEBUG|, \cpp|pr_debug()| calls are compiled in but disabled by default.
You can selectively enable them at runtime without recompiling or reloading the module by writing to \verb|/sys/kernel/debug/dynamic_debug/control|:
\begin{codebash}
echo "module mymodule +p" > /sys/kernel/debug/dynamic_debug/control
\end{codebash}
The \verb|+p| flag activates printing; \verb|-p| disables it.
You can filter by file, function, or line number.
See \src{Documentation/admin-guide/dynamic-debug-howto.rst} for the full syntax.
\item About Compiling.
Kernel modules need to be compiled a bit differently from regular userspace apps.
Former kernel versions required us to care much about these settings, which are usually stored in Makefiles.
Although hierarchically organized, many redundant settings accumulated in sublevel Makefiles and made them large and rather difficult to maintain.
Fortunately, there is a new way of doing these things, called kbuild, and the build process for external loadable modules is now fully integrated into the standard kernel build mechanism.
To learn more about how to compile modules which are not part of the official kernel (such as all the examples you will find in this guide), see file \src{Documentation/kbuild/modules.rst}.
Additional details about Makefiles for kernel modules are available in \src{Documentation/kbuild/makefiles.rst}.
Be sure to read this and the related files before starting to hack Makefiles. It will probably save you lots of work.
\begin{quote}
Here is another exercise for the reader.
See that comment above the return statement in \cpp|init_module()|?
Change the return value to something negative, recompile and load the module again.
What happens?
\end{quote}
\end{enumerate}
\subsection{Hello and Goodbye}
\label{sec:hello_n_goodbye}
In early kernel versions you had to use the \cpp|init_module| and \cpp|cleanup_module| functions, as in the first hello world example,
but these days you can name those anything you want by using the \cpp|module_init| and \cpp|module_exit| macros.
These macros are defined in \src{include/linux/module.h}.
The only requirement is that your init and cleanup functions must be defined before calling those macros, otherwise you will get compilation errors.
Here is an example of this technique:
\samplec{examples/hello-2.c}
So now we have two real kernel modules under our belt. Adding another module is as simple as this:
\begin{code}
obj-m += hello-1.o
obj-m += hello-2.o
PWD := $(CURDIR)
all:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
\end{code}
Now have a look at \src{drivers/char/Makefile} for a real world example.
As you can see, some things got hardwired into the kernel (\verb|obj-y|) but where have all those \verb|obj-m| gone?
Those familiar with shell scripts will easily be able to spot them.
For those who are not, the \verb|obj-$(CONFIG_FOO)| entries you see everywhere expand into \verb|obj-y| or \verb|obj-m|,
depending on whether the \verb|CONFIG_FOO| variable has been set to \verb|y| or \verb|m|.
While we are at it, those were exactly the kind of variables that you have set in the \verb|.config| file in the top-level directory of the Linux kernel source tree,
the last time you ran \sh|make menuconfig| or something similar.
\subsection{The \_\_init and \_\_exit Macros}
\label{sec:init_n_exit}
The \cpp|__init| macro causes the init function to be discarded and its memory freed once the init function finishes for built-in drivers.
For loadable modules, \cpp|__init| still places the function into an init-only section, \cpp|do_free_init| may still be observable during module loading even without \cpp|__init|.
If you think about when the init function is invoked, this makes perfect sense.
There is also an \cpp|__initdata| which works similarly to \cpp|__init| but for init variables rather than functions.
The \cpp|__exit| macro causes the omission of the function when the module is built into the kernel, and like \cpp|__init|, has no effect for loadable modules.
Again, if you consider when the cleanup function runs, this makes complete sense; built-in drivers do not need a cleanup function, while loadable modules do.
These macros are defined in \src{include/linux/init.h} and serve to free up kernel memory.
When you boot your kernel and see something like Freeing unused kernel memory: 236k freed, this is precisely what the kernel is freeing.
\samplec{examples/hello-3.c}
\subsection{Licensing and Module Documentation}
\label{sec:modlicense}
Honestly, who loads or even cares about proprietary modules?
If you do then you might have seen something like this:
\begin{verbatim}
$ sudo insmod xxxxxx.ko
loading out-of-tree module taints kernel.
module license 'unspecified' taints kernel.
\end{verbatim}
You can use a few macros to indicate the license for your module.
Some examples are "GPL", "GPL v2", "GPL and additional rights", "Dual BSD/GPL", "Dual MIT/GPL", "Dual MPL/GPL" and "Proprietary".
They are defined within \src{include/linux/module.h}.
To reference what license you are using, a macro is available called \cpp|MODULE_LICENSE|.
This and a few other macros describing the module are illustrated in the example below.
\samplec{examples/hello-4.c}
\subsection{Passing Command Line Arguments to a Module}
\label{sec:modparam}
Modules can take command line arguments, but not with the argc/argv you might be used to.
To allow arguments to be passed to your module, declare the variables that will take the values of the command line arguments as global and then use the \cpp|module_param()| macro (defined in \src{include/linux/moduleparam.h}) to set the mechanism up.
At runtime, \sh|insmod| will fill the variables with any command line arguments that are given, like \sh|insmod mymodule.ko myvariable=5|.
The variable declarations and macros should be placed at the beginning of the module for clarity.
The example code should clear up my admittedly lousy explanation.
The \cpp|module_param()| macro takes 3 arguments: the name of the variable, its type and permissions for the corresponding file in sysfs.
Integer types can be signed as usual or unsigned. If you would like to use arrays of integers or strings,
see \cpp|module_param_array()| and \cpp|module_param_string()|.
\begin{code}
int myint = 3;
module_param(myint, int, 0);
\end{code}
Arrays are supported too, but things are a bit different now than they were in the olden days.
To keep track of the number of parameters, you need to pass a pointer to a count variable as the third parameter.
At your option, you could also ignore the count and pass \cpp|NULL| instead.
We show both possibilities here:
\begin{code}
int myintarray[2];
module_param_array(myintarray, int, NULL, 0); /* not interested in count */
short myshortarray[4];
int count;
module_param_array(myshortarray, short, &count, 0); /* put count into "count" variable */
\end{code}
A good use for this is to have the module variable's default values set, like a port or IO address.
If the variables contain the default values, then perform autodetection (explained elsewhere).
Otherwise, keep the current value.
This will be made clear later on.
Lastly, there is a macro function, \cpp|MODULE_PARM_DESC()|, that is used to document arguments that the module can take.
It takes two parameters: a variable name and a free form string describing that variable.
\samplec{examples/hello-5.c}
If you need to validate a parameter or react whenever it changes, use \cpp|module_param_cb()|.
This variant takes four arguments: the parameter name, a pointer to a \cpp|struct kernel_param_ops|,
an argument pointer (typically the address of the backing variable), and the sysfs permissions.
The callbacks stored in \cpp|struct kernel_param_ops| let you override the \cpp|set| and \cpp|get|
operations instead of relying on the default helpers such as \cpp|param_set_int()| and \cpp|param_get_int()|.
With non-zero permissions, the parameter is also exposed through sysfs so the same callbacks can run after the module has already been loaded.
\begin{code}
static int watched = 42;
static int watched_set(const char *val, const struct kernel_param *kp)
{
int ret = param_set_int(val, kp);
if (ret)
return ret;
pr_info("watched updated to %d\n", watched);
return 0;
}
static const struct kernel_param_ops watched_ops = {
.set = watched_set,
.get = param_get_int,
};
module_param_cb(watched, &watched_ops, &watched, 0644);
\end{code}
The full example below also overrides \cpp|.get| so that every sysfs read is logged:
\samplec{examples/hello-6.c}
It is recommended to experiment with the following code:
\begin{verbatim}
$ sudo insmod hello-5.ko mystring="bebop" myintarray=-1
$ sudo dmesg -t | tail -7
myshort is a short integer: 1
myint is an integer: 420
mylong is a long integer: 9999
mystring is a string: bebop
myintarray[0] = -1
myintarray[1] = 420
got 1 arguments for myintarray.
$ sudo rmmod hello-5
$ sudo dmesg -t | tail -1
Goodbye, world 5
$ sudo insmod hello-5.ko mystring="supercalifragilisticexpialidocious" myintarray=-1,-1
$ sudo dmesg -t | tail -7
myshort is a short integer: 1
myint is an integer: 420
mylong is a long integer: 9999
mystring is a string: supercalifragilisticexpialidocious
myintarray[0] = -1
myintarray[1] = -1
got 2 arguments for myintarray.
$ sudo rmmod hello-5
$ sudo dmesg -t | tail -1
Goodbye, world 5
$ sudo insmod hello-5.ko mylong=hello
insmod: ERROR: could not insert module hello-5.ko: Invalid parameters
\end{verbatim}
% break for proper layout
\begin{verbatim}
$ sudo insmod hello-6.ko watched=7
$ sudo dmesg -t | tail -3
watched updated to 7
Hello, world 6
watched starts at 7
$ cat /sys/module/hello_6/parameters/watched
7
$ sudo dmesg -t | tail -1
watched was read
$ echo 21 | sudo tee /sys/module/hello_6/parameters/watched
21
$ sudo dmesg -t | tail -1
watched updated to 21
$ sudo rmmod hello-6
\end{verbatim}
\subsection{Modules Spanning Multiple Files}
\label{sec:modfiles}
Sometimes it makes sense to divide a kernel module between several source files.
Here is an example of such a kernel module.
\samplec{examples/start.c}
The next file:
\samplec{examples/stop.c}
And finally, the makefile:
\begin{code}
obj-m += hello-1.o
obj-m += hello-2.o
obj-m += hello-3.o
obj-m += hello-4.o
obj-m += hello-5.o
obj-m += hello-6.o
obj-m += startstop.o
startstop-objs := start.o stop.o
PWD := $(CURDIR)
all:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
$(MAKE) -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
\end{code}
This is the complete makefile for all the examples we have seen so far.
The first five lines are nothing special, but for the last example we will need two lines.
First we invent an object name for our combined module, second we tell \sh|make| what object files are part of that module.
\subsection{Building modules for a precompiled kernel}
\label{sec:precompiled}
% TODO: Recent Linux kernel images shipped with distributions should already have sufficient debugging features enabled for LKMPG.
Obviously, we strongly suggest you to recompile your kernel, so that you can enable a number of useful debugging features,
such as forced module unloading (\cpp|MODULE_FORCE_UNLOAD|): when this option is enabled,
you can force the kernel to unload a module even when it believes it is unsafe, via a \sh|sudo rmmod -f module| command.
This option can save you a lot of time and a number of reboots during the development of a module.
If you do not want to recompile your kernel then you should consider using the QEMU-based
environment described in \Cref{sec:devtools_setup}, which already enables
\cpp|MODULE_FORCE_UNLOAD| and other debugging options in its kernel configuration.
If you mess anything up inside the guest you can simply close and reboot the virtual machine.
There are a number of cases in which you may want to load your module into a precompiled running kernel,
such as the ones shipped with common Linux distributions, or a kernel you have compiled in the past.
In certain circumstances you could require to compile and insert a module into a running kernel which you are not allowed to recompile,
or on a machine that you prefer not to reboot.
If you can't think of a case that will force you to use modules for a precompiled kernel you might want to skip this and treat the rest of this chapter as a big footnote.
Now, if you just install a kernel source tree, use it to compile your kernel module and you try to insert your module into the kernel,
in most cases you would obtain an error as follows:
\begin{verbatim}
insmod: ERROR: could not insert module poet.ko: Invalid module format
\end{verbatim}
Less cryptic information is logged to the systemd journal:
\begin{verbatim}
kernel: poet: disagrees about version of symbol module_layout
\end{verbatim}
In other words, your kernel refuses to accept your module because version strings (more precisely, \textit{version magic}, see \src{include/linux/vermagic.h}) do not match.
The version magic string encodes the kernel version, the SMP configuration, preemption model, and other build flags that affect the kernel ABI.
When you \sh|insmod| a module, the kernel compares the module's version magic against its own; any mismatch means the module was compiled for a different kernel configuration and loading it could corrupt kernel data structures.
Additionally, if \cpp|CONFIG_MODVERSIONS| is enabled, each exported symbol carries a CRC checksum of its prototype. A module will be rejected if any symbol signature changed between the kernel it was compiled against and the one it is being loaded into.
Version magic strings are stored in the module object in the form of a static string, starting with \cpp|vermagic:|.
Version data are inserted in your module when it is linked against the \verb|kernel/module.o| file.
To inspect version magics and other strings stored in a given module, issue the command \sh|modinfo module.ko|:
\begin{verbatim}
$ modinfo hello-4.ko
description: A sample driver
author: LKMPG
license: GPL
srcversion: B2AA7FBFCC2C39AED665382
depends:
retpoline: Y
name: hello_4
vermagic: 5.4.0-70-generic SMP mod_unload modversions
\end{verbatim}
To overcome this problem we could resort to the \verb|--force-vermagic| option, but this solution is potentially unsafe, and unquestionably unacceptable in production modules.
Consequently, we want to compile our module in an environment which was identical to the one in which our precompiled kernel was built.
How to do this, is the subject of the remainder of this chapter.
First of all, make sure that a kernel source tree is available, having exactly the same version as your current kernel.
Then, find the configuration file which was used to compile your precompiled kernel.
Usually, this is available in your current \verb|boot| directory, under a name like \verb|config-5.14.x|.
You may just want to copy it to your kernel source tree: \sh|cp /boot/config-`uname -r` .config|.
Let's focus again on the previous error message: a closer look at the version magic strings suggests that, even with two configuration files which are exactly the same, a slight difference in the version magic could be possible, and it is sufficient to prevent insertion of the module into the kernel.
That slight difference, namely the custom string which appears in the module's version magic and not in the kernel's one, is due to a modification with respect to the original, in the makefile that some distributions include.
Then, examine your \verb|Makefile|, and make sure that the specified version information matches exactly the one used for your current kernel.
For example, your makefile could start as follows:
\begin{verbatim}
VERSION = 5
PATCHLEVEL = 14
SUBLEVEL = 0
EXTRAVERSION = -rc2
\end{verbatim}
In this case, you need to restore the value of symbol \textbf{EXTRAVERSION} to \textbf{-rc2}.
We suggest keeping a backup copy of the makefile used to compile your kernel available in \verb|/lib/modules/5.14.0-rc2/build|.
A simple command as follows should suffice.
\begin{codebash}
cp /lib/modules/`uname -r`/build/Makefile linux-`uname -r`
\end{codebash}
Here \sh|linux-`uname -r`| is the Linux kernel source you are attempting to build.
Now, please run \sh|make| to update configuration and version headers and objects:
\begin{verbatim}
$ make
SYNC include/config/auto.conf.cmd
HOSTCC scripts/basic/fixdep
HOSTCC scripts/kconfig/conf.o
HOSTCC scripts/kconfig/confdata.o
HOSTCC scripts/kconfig/expr.o
LEX scripts/kconfig/lexer.lex.c
YACC scripts/kconfig/parser.tab.[ch]
HOSTCC scripts/kconfig/preprocess.o
HOSTCC scripts/kconfig/symbol.o
HOSTCC scripts/kconfig/util.o
HOSTCC scripts/kconfig/lexer.lex.o
HOSTCC scripts/kconfig/parser.tab.o
HOSTLD scripts/kconfig/conf
\end{verbatim}
If you do not desire to actually compile the kernel, you can interrupt the build process (CTRL-C) just after the SPLIT line, because at that time, the files you need are ready.
Now you can turn back to the directory of your module and compile it: It will be built exactly according to your current kernel settings, and it will load into it without any errors.
\chapter{Core Kernel Interfaces}
With the toolchain and first examples out of the way, the focus shifts to the
interfaces that let modules cooperate with the rest of the kernel. The
following sections introduce execution basics and then move through the common
entry points used to expose functionality to user space.
\section{Preliminaries}
\subsection{How modules begin and end}
\label{sec:module_init_exit}
A typical program starts with a \cpp|main()| function, executes a series of instructions,
and terminates after completing these instructions.
Kernel modules, however, follow a different pattern.
A module always begins with either the \cpp|init_module| function or a function designated by the \cpp|module_init| call.
This function acts as the module's entry point,
informing the kernel of the module's functionalities and preparing the kernel to utilize the module's functions when necessary.
After performing these tasks, the entry function returns, and the module remains inactive until the kernel requires its code.
All modules conclude by invoking either \cpp|cleanup_module| or a function specified through the \cpp|module_exit| call.
This serves as the module's exit function, reversing the actions of the entry function by unregistering the previously registered functionalities.
It is mandatory for every module to have both an entry and an exit function.
While there are multiple methods to define these functions, the terms ``entry function'' and ``exit function'' are generally used.
However, they may occasionally be referred to as \cpp|init_module| and \cpp|cleanup_module|,
which are understood to mean the same.
\subsubsection{Error handling during initialization}
\label{sec:init_error_handling}
Registration and allocation calls in the init function can fail.
Every resource acquired must be released on error, otherwise the system leaks memory or, worse, becomes unstable.
The canonical kernel pattern uses \cpp|goto|-based cleanup in reverse allocation order:
\begin{code}
static int __init my_init(void)