-
Notifications
You must be signed in to change notification settings - Fork 519
/
lkmpg.tex
2176 lines (1734 loc) · 125 KB
/
lkmpg.tex
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}
\usepackage[Bjornstrup]{fncychap}
\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{xcolor}
\hypersetup{
colorlinks,
linkcolor = {red!50!black},
citecolor = {blue!50!black},
urlcolor = {blue!80!black}
}
\input{lib/codeblock}
\input{lib/kernelsrc}
% FIXME: classify with chapters instead of sections
\renewcommand{\thesection}{\arabic{section}}
\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}
% turn off TOC
\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
\section{Introduction}
\label{sec:introduction}
The Linux Kernel Module Programming Guide is a free book; you may reproduce and/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, 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, and/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.
\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 file system,
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 a test distribution on a virtual machine,
thus mitigating any potential risk of disrupting the system.
\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 in 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 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 that are eventually displayed on the screen,
specifically within a console.
If a module is loaded from an \sh|xterm|, the information and warnings will be logged,
but solely within the systemd journal. These logs will not be visible unless consulting the \sh|journalctl|.
Refer to \ref{sec:helloworld} for more information.
For instant access to this information, it is advisable to perform all tasks from the console.
\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 this, 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 ``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.
\end{enumerate}
\section{Headers}
\label{sec:headers}
Before building anything, it is necessary to install the header files for the kernel.
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 on the available kernel header files.
Then for example:
\begin{codebash}
sudo apt-get install kmod linux-headers-5.4.0-80-generic
\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.
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 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 Makefile, then it may not compile correctly with \verb|sudo make|.
Because some environment variables are specified by the security policy, they can't 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 \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 won't 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 set the \verb|env_reset| disabled by editing the \verb|/etc/sudoers| with root and \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 shiny 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 what just happened in the logs:
\begin{codebash}
journalctl --since "1 hour ago" | grep kernel
\end{codebash}
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 Section \ref{hello_n_goodbye}.
In fact, the new method is the preferred method.
However, many people still use \cpp|init_module()| and \cpp|cleanup_module()| 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 \verb|<linux/module.h>|.
% TODO: adjust the section anchor
We needed to include \verb|<linux/printk.h>| only for the macro expansion for the \cpp|pr_alert()| log level, which you'll learn about in Section \ref{sec:printk}.
\begin{enumerate}
\item A point about coding style.
Another thing which may not be immediately obvious to anyone getting started with kernel programming is that indentation within your code should be using \textbf{tabs} and \textbf{not spaces}.
It is one of the coding conventions of the kernel.
You may not like it, but you'll need to get used to it if you ever submit a patch upstream.
\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.
\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 on 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{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 the those macros, otherwise you'll 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 Linux kernel source tree, the last time when you said \sh|make menuconfig| or something like that.
\subsection{The \_\_init and \_\_exit Macros}
\label{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, but not loadable modules.
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{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're using a macro is available called \cpp|MODULE_LICENSE|.
This and a few other macros describing the module are illustrated in the below example.
\samplec{examples/hello-4.c}
\subsection{Passing Command Line Arguments to a Module}
\label{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'd 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 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}
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}
\subsection{Modules Spanning Multiple Files}
\label{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 += 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{precompiled}
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 running the examples within a test distribution on a virtual machine.
If you mess anything up then you can easily reboot or restore the virtual machine (VM).
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.
Incidentally, 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 following 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.
\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.
\subsection{Functions available to modules}
\label{sec:avail_func}
Programmers use functions they do not define all the time.
A prime example of this is \cpp|printf()|.
You use these library functions which are provided by the standard C library, libc.
The definitions for these functions do not actually enter your program until the linking stage, which ensures that the code (for \cpp|printf()| for example) is available, and fixes the call instruction to point to that code.
Kernel modules are different here, too. In the hello world example, you might have noticed that we used a function, \cpp|pr_info()| but did not include a standard I/O library.
That is because modules are object files whose symbols get resolved upon running \sh|insmod| or \sh|modprobe|.
The definition for the symbols comes from the kernel itself; the only external functions you can use are the ones provided by the kernel.
If you're curious about what symbols have been exported by your kernel, take a look at \verb|/proc/kallsyms|.
One point to keep in mind is the difference between library functions and system calls. Library functions are higher level, run completely in user space and provide a more convenient interface for the programmer to the functions that do the real work --- system calls.
System calls run in kernel mode on the user's behalf and are provided by the kernel itself.
The library function \cpp|printf()| may look like a very general printing function, but all it really does is format the data into strings and write the string data using the low-level system call \cpp|write()|, which then sends the data to standard output.
Would you like to see what system calls are made by \cpp|printf()|?
It is easy!
Compile the following program:
\begin{code}
#include <stdio.h>
int main(void)
{
printf("hello");
return 0;
}
\end{code}
with \sh|gcc -Wall -o hello hello.c|.
Run the executable with \sh|strace ./hello|.
Are you impressed?
Every line you see corresponds to a system call.
\href{https://strace.io/}{strace} is a handy program that gives you details about what system calls a program is making, including which call is made, what its arguments are and what it returns.
It is an invaluable tool for figuring out things like what files a program is trying to access.
Towards the end, you will see a line which looks like \cpp|write(1, "hello", 5hello)|.
There it is.
The face behind the \cpp|printf()| mask.
You may not be familiar with write, since most people use library functions for file I/O (like \cpp|fopen|, \cpp|fputs|, \cpp|fclose|).
If that is the case, try looking at man 2 write.
The 2nd man section is devoted to system calls (like \cpp|kill()| and \cpp|read()|).
The 3rd man section is devoted to library calls, which you would probably be more familiar with (like \cpp|cosh()| and \cpp|random()|).
You can even write modules to replace the kernel's system calls, which we will do shortly.
Crackers often make use of this sort of thing for backdoors or trojans, but you can write your own modules to do more benign things, like have the kernel write Tee hee, that tickles! every time someone tries to delete a file on your system.
\subsection{User Space vs Kernel Space}
\label{sec:user_kernl_space}
The kernel primarily manages access to resources, be it a video card, hard drive, or memory.
Programs frequently vie for the same resources.
For instance, as a document is saved, updatedb might commence updating the locate database.
Sessions in editors like vim and processes like updatedb can simultaneously utilize the hard drive.
The kernel's role is to maintain order, ensuring that users do not access resources indiscriminately.
To manage this, CPUs operate in different modes, each offering varying levels of system control.
The Intel 80386 architecture, for example, featured four such modes, known as rings.
Unix, however, utilizes only two of these rings: the highest ring (ring 0, also known as ``supervisor mode'',
where all actions are permissible) and the lowest ring, referred to as ``user mode''.
Recall the discussion about library functions vs system calls.
Typically, you use a library function in user mode.
The library function calls one or more system calls, and these system calls execute on the library function's behalf, but do so in supervisor mode since they are part of the kernel itself.
Once the system call completes its task, it returns and execution gets transferred back to user mode.
\subsection{Name Space}
\label{sec:namespace}
When you write a small C program, you use variables which are convenient and make sense to the reader.
If, on the other hand, you are writing routines which will be part of a bigger problem, any global variables you have are part of a community of other peoples' global variables; some of the variable names can clash.
When a program has lots of global variables which aren't meaningful enough to be distinguished, you get namespace pollution.
In large projects, effort must be made to remember reserved names, and to find ways to develop a scheme for naming unique variable names and symbols.
When writing kernel code, even the smallest module will be linked against the entire kernel, so this is definitely an issue.
The best way to deal with this is to declare all your variables as static and to use a well-defined prefix for your symbols.
By convention, all kernel prefixes are lowercase. If you do not want to declare everything as static, another option is to declare a symbol table and register it with the kernel.
We will get to this later.
The file \verb|/proc/kallsyms| holds all the symbols that the kernel knows about and which are therefore accessible to your modules since they share the kernel's codespace.
\subsection{Code space}
\label{sec:codespace}
Memory management is a very complicated subject and the majority of O'Reilly's \href{https://www.oreilly.com/library/view/understanding-the-linux/0596005652/}{Understanding The Linux Kernel} exclusively covers memory management!
We are not setting out to be experts on memory managements, but we do need to know a couple of facts to even begin worrying about writing real modules.
If you have not thought about what a segfault really means, you may be surprised to hear that pointers do not actually point to memory locations.
Not real ones, anyway.
When a process is created, the kernel sets aside a portion of real physical memory and hands it to the process to use for its executing code, variables, stack, heap and other things which a computer scientist would know about.
This memory begins with 0x00000000 and extends up to whatever it needs to be.
Since the memory space for any two processes do not overlap, every process that can access a memory address, say 0xbffff978, would be accessing a different location in real physical memory! The processes would be accessing an index named 0xbffff978 which points to some kind of offset into the region of memory set aside for that particular process.
For the most part, a process like our Hello, World program can't access the space of another process, although there are ways which we will talk about later.
The kernel has its own space of memory as well. Since a module is code which can be dynamically inserted and removed in the kernel (as opposed to a semi-autonomous object), it shares the kernel's codespace rather than having its own.
Therefore, if your module segfaults, the kernel segfaults.
And if you start writing over data because of an off-by-one error, then you're trampling on kernel data (or code).
This is even worse than it sounds, so try your best to be careful.
It should be noted that the aforementioned discussion applies to any operating system utilizing a monolithic kernel.
This concept differs slightly from \emph{``building all your modules into the kernel''},
although the underlying principle is similar.
In contrast, there are microkernels, where modules are allocated their own code space.
Two notable examples of microkernels include the \href{https://www.gnu.org/software/hurd/}{GNU Hurd} and the \href{https://fuchsia.dev/fuchsia-src/concepts/kernel}{Zircon kernel} of Google's Fuchsia.
\subsection{Device Drivers}
\label{sec:device_drivers}
One class of module is the device driver, which provides functionality for hardware like a serial port.
On Unix, each piece of hardware is represented by a file located in \verb|/dev| named a device file which provides the means to communicate with the hardware.
The device driver provides the communication on behalf of a user program.
% FIXME: use popular device for example
So the es1370.ko sound card device driver might connect the \verb|/dev/sound| device file to the Ensoniq IS1370 sound card.
A userspace program like mp3blaster can use \verb|/dev/sound| without ever knowing what kind of sound card is installed.
Let's look at some device files.
% FIXME: use popular devices
Here are device files which represent the first three partitions on the primary master IDE hard drive:
\begin{verbatim}
$ ls -l /dev/hda[1-3]
brw-rw---- 1 root disk 3, 1 Jul 5 2000 /dev/hda1
brw-rw---- 1 root disk 3, 2 Jul 5 2000 /dev/hda2
brw-rw---- 1 root disk 3, 3 Jul 5 2000 /dev/hda3
\end{verbatim}
Notice the column of numbers separated by a comma.
The first number is called the device's major number.
The second number is the minor number.
The major number tells you which driver is used to access the hardware.
Each driver is assigned a unique major number; all device files with the same major number are controlled by the same driver.
All the above major numbers are 3, because they're all controlled by the same driver.
The minor number is used by the driver to distinguish between the various hardware it controls.
Returning to the example above, although all three devices are handled by the same driver they have unique minor numbers because the driver sees them as being different pieces of hardware.
Devices are divided into two types: character devices and block devices.
The difference is that block devices have a buffer for requests, so they can choose the best order in which to respond to the requests.
This is important in the case of storage devices, where it is faster to read or write sectors which are close to each other, rather than those which are further apart.
Another difference is that block devices can only accept input and return output in blocks (whose size can vary according to the device), whereas character devices are allowed to use as many or as few bytes as they like.
Most devices in the world are character, because they don't need this type of buffering, and they don't operate with a fixed block size.
You can tell whether a device file is for a block device or a character device by looking at the first character in the output of \sh|ls -l|.
If it is `b' then it is a block device, and if it is `c' then it is a character device.
The devices you see above are block devices. Here are some character devices (the serial ports):
\begin{verbatim}
crw-rw---- 1 root dial 4, 64 Feb 18 23:34 /dev/ttyS0
crw-r----- 1 root dial 4, 65 Nov 17 10:26 /dev/ttyS1
crw-rw---- 1 root dial 4, 66 Jul 5 2000 /dev/ttyS2
crw-rw---- 1 root dial 4, 67 Jul 5 2000 /dev/ttyS3
\end{verbatim}
If you want to see which major numbers have been assigned, you can look at \src{Documentation/admin-guide/devices.txt}.
When the system was installed, all of those device files were created by the \sh|mknod| command.
To create a new char device named \verb|coffee| with major/minor number 12 and 2, simply do \sh|mknod /dev/coffee c 12 2|.
You do not have to put your device files into \verb|/dev|, but it is done by convention.
Linus put his device files in \verb|/dev|, and so should you.
However, when creating a device file for testing purposes, it is probably OK to place it in your working directory where you compile the kernel module.
Just be sure to put it in the right place when you're done writing the device driver.
A few final points, although implicit in the previous discussion, are worth stating explicitly for clarity.
When a device file is accessed, the kernel utilizes the file's major number to identify the appropriate driver for handling the access.
This indicates that the kernel does not necessarily rely on or need to be aware of the minor number.
It is the driver that concerns itself with the minor number, using it to differentiate between various pieces of hardware.
It is important to note that when referring to \emph{``hardware''},
the term is used in a slightly more abstract sense than just a physical PCI card that can be held in hand.
Consider the following two device files:
\begin{verbatim}
$ ls -l /dev/sda /dev/sdb
brw-rw---- 1 root disk 8, 0 Jan 3 09:02 /dev/sda
brw-rw---- 1 root disk 8, 16 Jan 3 09:02 /dev/sdb
\end{verbatim}
By now you can look at these two device files and know instantly that they are block devices and are handled by same driver (block major 8).
Sometimes two device files with the same major but different minor number can actually represent the same piece of physical hardware.
So just be aware that the word ``hardware'' in our discussion can mean something very abstract.
\section{Character Device drivers}
\label{sec:chardev}
\subsection{The file\_operations Structure}
\label{sec:file_operations}
The \cpp|file_operations| structure is defined in \src{include/linux/fs.h}, and holds pointers to functions defined by the driver that perform various operations on the device.
Each field of the structure corresponds to the address of some function defined by the driver to handle a requested operation.
For example, every character driver needs to define a function that reads from the device.
The \cpp|file_operations| structure holds the address of the module's function that performs that operation.
Here is what the definition looks like for kernel 5.4:
\begin{code}
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*read_iter) (struct kiocb *, struct iov_iter *);
ssize_t (*write_iter) (struct kiocb *, struct iov_iter *);
int (*iopoll)(struct kiocb *kiocb, bool spin);
int (*iterate) (struct file *, struct dir_context *);
int (*iterate_shared) (struct file *, struct dir_context *);
__poll_t (*poll) (struct file *, struct poll_table_struct *);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
unsigned long mmap_supported_flags;
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
int (*setlease)(struct file *, long, struct file_lock **, void **);
long (*fallocate)(struct file *file, int mode, loff_t offset,
loff_t len);
void (*show_fdinfo)(struct seq_file *m, struct file *f);
ssize_t (*copy_file_range)(struct file *, loff_t, struct file *,
loff_t, size_t, unsigned int);
loff_t (*remap_file_range)(struct file *file_in, loff_t pos_in,
struct file *file_out, loff_t pos_out,
loff_t len, unsigned int remap_flags);
int (*fadvise)(struct file *, loff_t, loff_t, int);
} __randomize_layout;
\end{code}
Some operations are not implemented by a driver.
For example, a driver that handles a video card will not need to read from a directory structure.
The corresponding entries in the \cpp|file_operations| structure should be set to \cpp|NULL|.
There is a gcc extension that makes assigning to this structure more convenient.
You will see it in modern drivers, and may catch you by surprise.
This is what the new way of assigning to the structure looks like:
\begin{code}
struct file_operations fops = {
read: device_read,
write: device_write,
open: device_open,
release: device_release
};
\end{code}
However, there is also a C99 way of assigning to elements of a structure, \href{https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html}{designated initializers}, and this is definitely preferred over using the GNU extension.
You should use this syntax in case someone wants to port your driver.
It will help with compatibility:
\begin{code}
struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
\end{code}
The meaning is clear, and you should be aware that any member of the structure which you do not explicitly assign will be initialized to \cpp|NULL| by gcc.
An instance of \cpp|struct file_operations| containing pointers to functions that are used to implement \cpp|read|, \cpp|write|, \cpp|open|, \ldots{} system calls is commonly named \cpp|fops|.
Since Linux v3.14, the read, write and seek operations are guaranteed for thread-safe by using the \cpp|f_pos| specific lock, which makes the file position update to become the mutual exclusion.
So, we can safely implement those operations without unnecessary locking.
Additionally, since Linux v5.6, the \cpp|proc_ops| structure was introduced to replace the use of the \cpp|file_operations| structure when registering proc handlers.
See more information in the \ref{sec:proc_ops} section.
\subsection{The file structure}
\label{sec:file_struct}
Each device is represented in the kernel by a file structure, which is defined in \src{include/linux/fs.h}.
Be aware that a file is a kernel level structure and never appears in a user space program.
It is not the same thing as a \cpp|FILE|, which is defined by glibc and would never appear in a kernel space function.