forked from linux-kernel-labs/linux-kernel-labs.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel_api.html
More file actions
1062 lines (914 loc) · 68.3 KB
/
Copy pathkernel_api.html
File metadata and controls
1062 lines (914 loc) · 68.3 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
<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kernel API — The Linux Kernel 4.11.0+ documentation</title>
<link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
<link rel="stylesheet" href="_static/theme_overrides.css" type="text/css" />
<link rel="top" title="The Linux Kernel 4.11.0+ documentation" href="index.html"/>
<link rel="next" title="Character device drivers" href="device_drivers.html"/>
<link rel="prev" title="Kernel modules" href="kernel_modules.html"/>
<script src="_static/js/modernizr.min.js"></script>
</head>
<body class="wy-body-for-nav" role="document">
<div class="wy-grid-for-nav">
<nav data-toggle="wy-nav-shift" class="wy-nav-side">
<div class="wy-side-scroll">
<div class="wy-side-nav-search">
<a href="index.html" class="icon icon-home"> The Linux Kernel
</a>
<div class="version">
4.12.0-rc4
</div>
<div role="search">
<form id="rtd-search-form" class="wy-form" action="search.html" method="get">
<input type="text" name="q" placeholder="Search docs" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<div class="wy-menu wy-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="vm.html">Virtual Machine Setup</a></li>
<li class="toctree-l1"><a class="reference internal" href="exercises.html">Exercises</a></li>
<li class="toctree-l1"><a class="reference internal" href="kernel_modules.html">Kernel modules</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="">Kernel API</a><ul>
<li class="toctree-l2"><a class="reference internal" href="#lab-objectives">Lab objectives</a></li>
<li class="toctree-l2"><a class="reference internal" href="#overview">Overview</a></li>
<li class="toctree-l2"><a class="reference internal" href="#accessing-memory">Accessing memory</a></li>
<li class="toctree-l2"><a class="reference internal" href="#contexts-of-execution">Contexts of execution</a></li>
<li class="toctree-l2"><a class="reference internal" href="#locking">Locking</a></li>
<li class="toctree-l2"><a class="reference internal" href="#preemptivity">Preemptivity</a></li>
<li class="toctree-l2"><a class="reference internal" href="#linux-kernel-api">Linux Kernel API</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#convention-indicating-errors">Convention indicating errors</a></li>
<li class="toctree-l3"><a class="reference internal" href="#strings-of-characters">Strings of characters</a></li>
<li class="toctree-l3"><a class="reference internal" href="#printk">printk</a></li>
<li class="toctree-l3"><a class="reference internal" href="#memory-allocation">Memory allocation</a></li>
<li class="toctree-l3"><a class="reference internal" href="#lists">lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="#spinlock">Spinlock</a></li>
<li class="toctree-l3"><a class="reference internal" href="#mutex">mutex</a></li>
<li class="toctree-l3"><a class="reference internal" href="#atomic-variables">Atomic variables</a><ul>
<li class="toctree-l4"><a class="reference internal" href="#use-of-atomic-variables">Use of atomic variables</a></li>
</ul>
</li>
<li class="toctree-l3"><a class="reference internal" href="#atomic-bitwise-operations">Atomic bitwise operations</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="#exercises">Exercises</a><ul>
<li class="toctree-l3"><a class="reference internal" href="#intro">0. Intro</a></li>
<li class="toctree-l3"><a class="reference internal" href="#memory-allocation-in-linux-kernel">1. Memory allocation in Linux kernel</a></li>
<li class="toctree-l3"><a class="reference internal" href="#sleeping-in-atomic-context">2. Sleeping in atomic context</a></li>
<li class="toctree-l3"><a class="reference internal" href="#working-with-kernel-memory">3. Working with kernel memory</a></li>
<li class="toctree-l3"><a class="reference internal" href="#working-with-kernel-lists">4. Working with kernel lists</a></li>
<li class="toctree-l3"><a class="reference internal" href="#working-with-kernel-lists-for-process-handling">5. Working with kernel lists for process handling</a></li>
<li class="toctree-l3"><a class="reference internal" href="#synchronizing-list-work">6. Synchronizing list work</a></li>
<li class="toctree-l3"><a class="reference internal" href="#test-module-calling-in-our-list-module">7. Test module calling in our list module</a></li>
</ul>
</li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="device_drivers.html">Character device drivers</a></li>
<li class="toctree-l1"><a class="reference internal" href="interrupts.html">I/O access and Interrupts</a></li>
<li class="toctree-l1"><a class="reference internal" href="deferred_work.html">Deferred work</a></li>
<li class="toctree-l1"><a class="reference internal" href="memory_mapping.html">Memory mapping</a></li>
<li class="toctree-l1"><a class="reference internal" href="device_model.html">Linux Device Model</a></li>
</ul>
</div>
</div>
</nav>
<section data-toggle="wy-nav-shift" class="wy-nav-content-wrap">
<nav class="wy-nav-top" role="navigation" aria-label="top navigation">
<i data-toggle="wy-nav-top" class="fa fa-bars"></i>
<a href="index.html">The Linux Kernel</a>
</nav>
<div class="wy-nav-content">
<div class="rst-content">
<div role="navigation" aria-label="breadcrumbs navigation">
<ul class="wy-breadcrumbs">
<li><a href="index.html">Docs</a> »</li>
<li>Kernel API</li>
<li class="wy-breadcrumbs-aside">
<a href="_sources/kernel_api.txt" rel="nofollow"> View page source</a>
</li>
</ul>
<hr/>
</div>
<div role="main" class="document" itemscope="itemscope" itemtype="http://schema.org/Article">
<div itemprop="articleBody">
<div class="section" id="kernel-api">
<h1>Kernel API<a class="headerlink" href="#kernel-api" title="Permalink to this headline">¶</a></h1>
<div class="section" id="lab-objectives">
<h2>Lab objectives<a class="headerlink" href="#lab-objectives" title="Permalink to this headline">¶</a></h2>
<blockquote>
<div><ul class="simple">
<li>Familiarize yourself with the basic Linux kernel API</li>
<li>Description of memory allocation mechanisms</li>
<li>Description of locking mechanisms</li>
</ul>
</div></blockquote>
</div>
<div class="section" id="overview">
<h2>Overview<a class="headerlink" href="#overview" title="Permalink to this headline">¶</a></h2>
<p>Inside the current lab we present a set of concepts and basic functions required
for starting Linux kernel programming. It is important to note that kernel
programming differs greatly from user space programming. The kernel is a
stand-alone entity that can not use libraries in user-space (not even libc).
As a result, the usual user-space functions (printf, malloc, free, open, read,
write, memcpy, strcpy, etc.) can no longer be used. In conclusion, kernel
programming is based on a totally new and independent API that is unrelated to
the user-space API, whether we refer to POSIX or ANSI C (standard C language
library functions).</p>
</div>
<div class="section" id="accessing-memory">
<h2>Accessing memory<a class="headerlink" href="#accessing-memory" title="Permalink to this headline">¶</a></h2>
<p>An important difference in kernel programming is how to access and allocate
memory. Due to the fact that kernel programming is very close to the physical
machine, there are important rules for memory management. First, it works with
several types of memory:</p>
<blockquote>
<div><ul class="simple">
<li>Physical memory</li>
<li>Virtual memory from the kernel address space</li>
<li>Virtual memory from a process’s address space</li>
<li>Resident memory - we know for sure that the accessed pages are present in
physical memory</li>
</ul>
</div></blockquote>
<p>Virtual memory in a process’s address space can not be considered resident due
to the virtual memory mechanisms implemented by the operating system: pages may
be swapped or simply may not be present in physical memory as a result of the
demand paging mechanism. The memory in the kernel address space can be resident
or not. Both the data and code segments of a module and the kernel stack of a
process are resident. Dynamic memory may or may not be a resident, depending
on how it is allocated.</p>
<p>When working with resident memory, things are simple: memory can be accessed at
any time. But if working with non-resident memory, then it can only be accessed
from certain contexts. Non-resident memory can only be accessed from the
process context. Accessing non-resident memory from the context of the
interruption has unpredictable results and, therefore, when the operating
system detects such access, it will take drastic measures: blocking or
resetting the system to prevent serious corruption.</p>
<p>The virtual memory of a process can not be accessed directly from the kernel.
In general, it is totally discouraged to access the address space of a process,
but there are situations where a device driver needs to do it. The typical case
is where the device driver needs to access a buffer from the user-space. In
this case, the device driver must use special features and not directly access
the buffer. This is necessary to prevent access to invalid memory areas.</p>
<p>Another difference from the userpace scheduling, relative to memory, is due to
the stack, a stack whose size is fixed and limited. In the Linux 2.6.x kernel,
a stack of 4K , and a stack of 12K is used in Windows. For this reason, the
allocation of large-scale stack structures or the use of recursive calls should
be avoided.</p>
</div>
<div class="section" id="contexts-of-execution">
<h2>Contexts of execution<a class="headerlink" href="#contexts-of-execution" title="Permalink to this headline">¶</a></h2>
<p>In relation to kernel execution, we distinguish two contexts: process context
and interrupt context. We are in the process context when we run code as a
result of a system call or when we run in the context of a thread kernel. When
we run in a routine to handle an interrupt or a deferrable action, we run in
an interrupt context.</p>
<p>Some of the kernel API calls can block the current process. Common examples are
using a semaphore or waiting for a condition. In this case, the process is
put into the WAITING state and another process is running. An interesting
situation occurs when a function that can lead to suspension of the current
process is called from an interrupt context. In this case, there is no current
process, and therefore the results are unpredictable. Whenever the operating
system detects this condition will generate an error condition that will cause
the operating system to shut down.</p>
</div>
<div class="section" id="locking">
<h2>Locking<a class="headerlink" href="#locking" title="Permalink to this headline">¶</a></h2>
<p>One of the most important features of kernel programming is parallelism. Linux
support SMP systems with multiple processors and kernel preemptivity. This makes
kernel programming more difficult because access to global variables must be
synchronized with either spinlock primitives or blocking primitives. Although
it is recommended to use blocking primitives, they can not be used in an interrupt
context, so the only locking solution in the context of the interrupt is spinlocks.</p>
<p>Spinlocks are used to achieve mutual exclusion. When it can not get access to
the critical region, it does not suspend the current process, but it use the
busy-waiting mechanism (waiting in a loop while releasing the lock). The code
that runs in the critical region protected by a spinlock is not allowed to
suspend the current process (it must adhere to the execution conditions in the
context of an interrupt). Moreover, the CPU will not be released except for
interrupts. Due to the mechanism used, it is important that a spinlock be
detained as little time as possible.</p>
</div>
<div class="section" id="preemptivity">
<h2>Preemptivity<a class="headerlink" href="#preemptivity" title="Permalink to this headline">¶</a></h2>
<p>Linux uses a preemptive kernels. The notion of preemptive multitasking should not
be confused with the notion of preemptive kernel. The notion of preemptive multitasking
refers to the fact that the operating system interrupts a process by force when
it expires its quantum of time and runs in user-space to run another process.
A kernel is preemptive if a process running in kernel mode (as a result of a system call)
can be interrupted to run another process.</p>
<p>Because of preemptivity, when we share resources between two portions of code
that can run from different process contexts, we need to protect ourselves with
synchronization primitives, even with the single processor.</p>
</div>
<div class="section" id="linux-kernel-api">
<h2>Linux Kernel API<a class="headerlink" href="#linux-kernel-api" title="Permalink to this headline">¶</a></h2>
<div class="section" id="convention-indicating-errors">
<h3>Convention indicating errors<a class="headerlink" href="#convention-indicating-errors" title="Permalink to this headline">¶</a></h3>
<p>For Linux kernel programming, the convention used to call functions to indicate
success is the same as UNIX programming: 0 for success, or a value other than 0
for failure. For failures negative values are returned as shown in the example below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="k">if</span> <span class="p">(</span><span class="n">alloc_memory</span><span class="p">()</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
<span class="k">return</span> <span class="o">-</span><span class="n">ENOMEM</span><span class="p">;</span>
<span class="k">if</span> <span class="p">(</span><span class="n">user_parameter_valid</span><span class="p">()</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">)</span>
<span class="k">return</span> <span class="o">-</span><span class="n">EINVAL</span><span class="p">;</span>
</pre></div>
</div>
<p>The exhaustive list of errors and a summary explanation can be found in
<code class="docutils literal"><span class="pre">include/asm-generic/errno-base.h</span></code> and <code class="docutils literal"><span class="pre">includes/asm-generic/ernno.h</span></code>.</p>
</div>
<div class="section" id="strings-of-characters">
<h3>Strings of characters<a class="headerlink" href="#strings-of-characters" title="Permalink to this headline">¶</a></h3>
<p>In Linux, the kernel programmer is provided with the usual routine functions:
<code class="docutils literal"><span class="pre">strcpy</span></code>, <code class="docutils literal"><span class="pre">strncpy</span></code>, <code class="docutils literal"><span class="pre">strlcpy</span></code>, <code class="docutils literal"><span class="pre">strcat</span></code>, <code class="docutils literal"><span class="pre">strncat</span></code>, <code class="docutils literal"><span class="pre">strlcat</span></code>,
<code class="docutils literal"><span class="pre">strcmp</span></code>, <code class="docutils literal"><span class="pre">strncmp</span></code>, <code class="docutils literal"><span class="pre">strnicmp</span></code>, <code class="docutils literal"><span class="pre">strnchr</span></code>, <code class="docutils literal"><span class="pre">strrchr</span></code>, <code class="docutils literal"><span class="pre">strrchr</span></code>,
<code class="docutils literal"><span class="pre">strstr</span></code>, <code class="docutils literal"><span class="pre">strlen</span></code>, <code class="docutils literal"><span class="pre">memset</span></code>, <code class="docutils literal"><span class="pre">memmove</span></code>, <code class="docutils literal"><span class="pre">memcmp</span></code>, etc. These functions
are declared in the <code class="docutils literal"><span class="pre">include/linux/string.h</span></code> header and are implemented in the
kernel in the <code class="docutils literal"><span class="pre">lib/string.c</span></code> file.</p>
</div>
<div class="section" id="printk">
<h3>printk<a class="headerlink" href="#printk" title="Permalink to this headline">¶</a></h3>
<p>The printf equivalent in the kernel is printk , defined in
<code class="docutils literal"><span class="pre">include/linux/printk.h</span></code>. The printk syntax is very similar to printf. The first
parameter of printk decides the message category in which the current message falls:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#define KERN_EMERG "<0>" </span><span class="cm">/* system is unusable */</span><span class="cp"></span>
<span class="cp">#define KERN_ALERT "<1>" </span><span class="cm">/* action must be taken immediately */</span><span class="cp"></span>
<span class="cp">#define KERN_CRIT "<2>" </span><span class="cm">/* critical conditions */</span><span class="cp"></span>
<span class="cp">#define KERN_ERR "<3>" </span><span class="cm">/* error conditions */</span><span class="cp"></span>
<span class="cp">#define KERN_WARNING "<4>" </span><span class="cm">/* warning conditions */</span><span class="cp"></span>
<span class="cp">#define KERN_NOTICE "<5>" </span><span class="cm">/* normal but significant condition */</span><span class="cp"></span>
<span class="cp">#define KERN_INFO "<6>" </span><span class="cm">/* informational */</span><span class="cp"></span>
<span class="cp">#define KERN_DEBUG "<7>" </span><span class="cm">/* debug-level messages */</span><span class="cp"></span>
</pre></div>
</div>
<p>Thus, a warning message in the kernel would be sent with:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="n">printk</span><span class="p">(</span><span class="n">KERN_WARNING</span> <span class="s">"my_module input string %s</span><span class="se">\n</span><span class="s">"</span><span class="p">,</span> <span class="n">buff</span><span class="p">);</span>
</pre></div>
</div>
<p>If the logging level is missing from the printk call, logging is done with the
default level at the time of the call. One thing to keep in mind is that
messages sent with printk are only visible on the console and only if their
level exceeds the default level set on the console.</p>
<p>To reduce the size of lines when using printk, it is recommended to use the
following help functions instead of directly using the printk call:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="n">pr_emerg</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_EMERG pr_fmt(fmt), ...); */</span>
<span class="n">pr_alert</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_ALERT pr_fmt(fmt), ...); */</span>
<span class="n">pr_crit</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_CRIT pr_fmt(fmt), ...); */</span>
<span class="n">pr_err</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_ERR pr_fmt(fmt), ...); */</span>
<span class="n">pr_warning</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_WARNING pr_fmt(fmt), ...); */</span>
<span class="n">pr_warn</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with cu printk(KERN_WARNING pr_fmt(fmt), ...); */</span>
<span class="n">pr_notice</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_NOTICE pr_fmt(fmt), ...); */</span>
<span class="n">pr_info</span><span class="p">(</span><span class="n">fmt</span><span class="p">,</span> <span class="p">...);</span> <span class="cm">/* similar with printk(KERN_INFO pr_fmt(fmt), ...); */</span>
</pre></div>
</div>
<p>A special case is pr_debug that calls the printk function only when the DEBUG
macro is defined or if dynamic debugging is used.</p>
</div>
<div class="section" id="memory-allocation">
<h3>Memory allocation<a class="headerlink" href="#memory-allocation" title="Permalink to this headline">¶</a></h3>
<p>In Linux only resident memory can be allocated, using kmalloc call. A typical kmalloc
call is presented below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><linux/slab.h></span><span class="cp"></span>
<span class="n">string</span> <span class="o">=</span> <span class="n">kmalloc</span> <span class="p">(</span><span class="n">string_len</span> <span class="o">+</span> <span class="mi">1</span><span class="p">,</span> <span class="n">GFP_KERNEL</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">string</span><span class="p">)</span> <span class="p">{</span>
<span class="c1">//report error: -ENOMEM;</span>
<span class="p">}</span>
</pre></div>
</div>
<p>As you can see, the first parameter indicates the size in bytes of the allocated
area. The function returns a pointer to a memory area that can be directly used
in the kernel, or NULL if memory could not be allocated. The second parameter
specifies how allocation should be done and the most commonly used values are:</p>
<blockquote>
<div><ul class="simple">
<li><code class="docutils literal"><span class="pre">GFP_KERNEL</span></code> - using this value may cause the current process to be
suspended. Thus, can not be used in the interrupt context.</li>
<li><code class="docutils literal"><span class="pre">GFP_ATOMIC</span></code> - when using this value it ensures that the kmalloc function
does not suspend the current process. Can be used anytime.</li>
</ul>
</div></blockquote>
<p>Complement to the kmalloc function is <code class="docutils literal"><span class="pre">kfree</span></code>, a function that receives as
argument an area allocated by kmalloc. This feature does not suspend the current
process and can therefore be called from any context.</p>
</div>
<div class="section" id="lists">
<h3>lists<a class="headerlink" href="#lists" title="Permalink to this headline">¶</a></h3>
<p>Because linked lists are often used, the Linux kernel API provides a unified
way of defining and using lists. This involves using a list_head structure
element in the structure we want to consider as a list node. The list_head
list_head is defined in <code class="docutils literal"><span class="pre">include/linux/list.h</span></code> along with all the other
functions that work on the lists. The following code shows the definition of
the list_head list_head and the use of an element of this type in another
well-known structure in the Linux kernel:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="k">struct</span> <span class="n">list_head</span> <span class="p">{</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">next</span><span class="p">,</span> <span class="o">*</span><span class="n">prev</span><span class="p">;</span>
<span class="p">};</span>
<span class="k">struct</span> <span class="n">task_struct</span> <span class="p">{</span>
<span class="p">...</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="n">children</span><span class="p">;</span>
<span class="p">...</span>
<span class="p">};</span>
</pre></div>
</div>
<p>The usual routines for working with lists are as follows:</p>
<blockquote>
<div><ul class="simple">
<li><code class="docutils literal"><span class="pre">LIST_HEAD(name)</span></code> is used to declare the sentinel of a list</li>
<li><code class="docutils literal"><span class="pre">INIT_LIST_HEAD(struct</span> <span class="pre">list_head</span> <span class="pre">*list)</span></code> is used to initialize the sentinel
of a list when dynamic allocation is made by setting the value of the next and
prev to list fields.</li>
<li><code class="docutils literal"><span class="pre">list_add(struct</span> <span class="pre">list_head</span> <span class="pre">*new,</span> <span class="pre">struct</span> <span class="pre">list_head</span> <span class="pre">*head)</span></code> adds the new
element after the head element.</li>
<li><code class="docutils literal"><span class="pre">list_del(struct</span> <span class="pre">list_head</span> <span class="pre">*entry)</span></code> deletes the item at the entry address of
the list it belongs to.</li>
<li><code class="docutils literal"><span class="pre">list_entry(ptr,</span> <span class="pre">type,</span> <span class="pre">member)</span></code> returns the type structure that contains the
element ptr the member with the member name within the structure.</li>
<li><code class="docutils literal"><span class="pre">list_for_each(pos,</span> <span class="pre">head)</span></code> iterates a list using pos as a cursor.</li>
<li><code class="docutils literal"><span class="pre">list_for_each_safe(pos,</span> <span class="pre">n,</span> <span class="pre">head)</span></code> iterates a list, using pos as a cursor and
and <code class="docutils literal"><span class="pre">n</span></code> as a temporary cursor. This macro is used to delete an item from the list.</li>
</ul>
</div></blockquote>
<p>The following code shows how to use these routines:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><linux/slab.h></span><span class="cp"></span>
<span class="cp">#include</span> <span class="cpf"><linux/list.h></span><span class="cp"></span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="p">{</span>
<span class="kt">pid_t</span> <span class="n">pid</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="n">list</span><span class="p">;</span>
<span class="p">};</span>
<span class="n">LIST_HEAD</span><span class="p">(</span><span class="n">my_list</span><span class="p">);</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">add_pid</span><span class="p">(</span><span class="kt">pid_t</span> <span class="n">pid</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="o">*</span><span class="n">ple</span> <span class="o">=</span> <span class="n">kmalloc</span><span class="p">(</span><span class="k">sizeof</span> <span class="o">*</span><span class="n">ple</span><span class="p">,</span> <span class="n">GFP_KERNEL</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="n">ple</span><span class="p">)</span>
<span class="k">return</span> <span class="o">-</span><span class="n">ENOMEM</span><span class="p">;</span>
<span class="n">ple</span><span class="o">-></span><span class="n">pid</span> <span class="o">=</span> <span class="n">pid</span><span class="p">;</span>
<span class="n">list_add</span><span class="p">(</span><span class="o">&</span><span class="n">ple</span><span class="o">-></span><span class="n">list</span><span class="p">,</span> <span class="o">&</span><span class="n">my_list</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">del_pid</span><span class="p">(</span><span class="kt">pid_t</span> <span class="n">pid</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">i</span><span class="p">,</span> <span class="o">*</span><span class="n">tmp</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="o">*</span><span class="n">ple</span><span class="p">;</span>
<span class="n">list_for_each_safe</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">tmp</span><span class="p">,</span> <span class="o">&</span><span class="n">my_list</span><span class="p">)</span> <span class="p">{</span>
<span class="n">ple</span> <span class="o">=</span> <span class="n">list_entry</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="k">struct</span> <span class="n">pid_list</span><span class="p">,</span> <span class="n">list</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">ple</span><span class="o">-></span><span class="n">pid</span> <span class="o">==</span> <span class="n">pid</span><span class="p">)</span> <span class="p">{</span>
<span class="n">list_del</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
<span class="n">kfree</span><span class="p">(</span><span class="n">ple</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="k">return</span> <span class="o">-</span><span class="n">EINVAL</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">destroy_list</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">i</span><span class="p">,</span> <span class="o">*</span><span class="n">n</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="o">*</span><span class="n">ple</span><span class="p">;</span>
<span class="n">list_for_each_safe</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">n</span><span class="p">,</span> <span class="o">&</span><span class="n">my_list</span><span class="p">)</span> <span class="p">{</span>
<span class="n">ple</span> <span class="o">=</span> <span class="n">list_entry</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="k">struct</span> <span class="n">pid_list</span><span class="p">,</span> <span class="n">list</span><span class="p">);</span>
<span class="n">list_del</span><span class="p">(</span><span class="n">i</span><span class="p">);</span>
<span class="n">kfree</span><span class="p">(</span><span class="n">ple</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The evolution of the list can be seen in the following figure:</p>
<p>You see the stack type behavior introduced by the list_add macro, and the use
of a sentinel.</p>
<p>From the above example, it is noted that the way to define and use a list
(double-linked) is generic and, at the same time, does not introduce an
additional overhead. The list_head list_head is used to maintain the links
between the list elements. It is also noted that list iteration is also done
with this structure, and the list item is list_entry using list_entry . This
idea of implementing and using a list is not new, as The Art of Computer
Programming in The Art of Computer Programming by Donald Knuth in the 1980s.</p>
<p>Several kernel list functions and macrodefinitions are presented and explained
in the include/linux/list.h header.</p>
</div>
<div class="section" id="spinlock">
<h3>Spinlock<a class="headerlink" href="#spinlock" title="Permalink to this headline">¶</a></h3>
<p>spinlock_t (defined in <code class="docutils literal"><span class="pre">linux/spinlock.h</span></code>) is the basic type that implements
the spinlock concept in Linux. It describes a spinlock, and the operations
associated with a spinlock are spin_lock_init, spin_lock, spin_unlock . An
example of use is given below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><linux/spinlock.h></span><span class="cp"></span>
<span class="n">DEFINE_SPINLOCK</span><span class="p">(</span><span class="n">lock1</span><span class="p">);</span>
<span class="n">spinlock_t</span> <span class="n">lock2</span><span class="p">;</span>
<span class="n">spin_lock_init</span><span class="p">(</span><span class="o">&</span><span class="n">lock2</span><span class="p">);</span>
<span class="n">spin_lock</span><span class="p">(</span><span class="o">&</span><span class="n">lock1</span><span class="p">);</span>
<span class="cm">/* critical region */</span>
<span class="n">spin_unlock</span><span class="p">(</span><span class="o">&</span><span class="n">lock1</span><span class="p">);</span>
<span class="n">spin_lock</span><span class="p">(</span><span class="o">&</span><span class="n">lock2</span><span class="p">);</span>
<span class="cm">/* critical region */</span>
<span class="n">spin_unlock</span><span class="p">(</span><span class="o">&</span><span class="n">lock2</span><span class="p">);</span>
</pre></div>
</div>
<p>In Linux, you can use read / write spinlocks useful for writer-reader issues.
These types of locks are identified by <code class="docutils literal"><span class="pre">rwlock_t</span></code>, and the functions that can
work on a read / write spinlock are <code class="docutils literal"><span class="pre">rwlock_init</span></code>, <code class="docutils literal"><span class="pre">read_lock</span></code>, <code class="docutils literal"><span class="pre">write_lock</span></code>.
An example of use:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><linux/spinlock.h></span><span class="cp"></span>
<span class="n">DEFINE_RWLOCK</span><span class="p">(</span><span class="n">lock</span><span class="p">);</span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="p">{</span>
<span class="kt">pid_t</span> <span class="n">pid</span><span class="p">;</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="n">list</span><span class="p">;</span>
<span class="p">};</span>
<span class="kt">int</span> <span class="nf">have_pid</span><span class="p">(</span><span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">lh</span><span class="p">,</span> <span class="kt">int</span> <span class="n">pid</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">i</span><span class="p">;</span>
<span class="kt">void</span> <span class="o">*</span><span class="n">elem</span><span class="p">;</span>
<span class="n">read_lock</span><span class="p">(</span><span class="o">&</span><span class="n">lock</span><span class="p">);</span>
<span class="n">list_for_each</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="n">lh</span><span class="p">)</span> <span class="p">{</span>
<span class="k">struct</span> <span class="n">pid_list</span> <span class="o">*</span><span class="n">pl</span> <span class="o">=</span> <span class="n">list_entry</span><span class="p">(</span><span class="n">i</span><span class="p">,</span> <span class="k">struct</span> <span class="n">pid_list</span><span class="p">,</span> <span class="n">list</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">pl</span><span class="o">-></span><span class="n">pid</span> <span class="o">==</span> <span class="n">pid</span><span class="p">)</span> <span class="p">{</span>
<span class="n">read_unlock</span><span class="p">(</span><span class="o">&</span><span class="n">lock</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">1</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="n">read_unlock</span><span class="p">(</span><span class="o">&</span><span class="n">lock</span><span class="p">);</span>
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">add_pid</span><span class="p">(</span><span class="k">struct</span> <span class="n">list_head</span> <span class="o">*</span><span class="n">lh</span><span class="p">,</span> <span class="k">struct</span> <span class="n">pid_list</span> <span class="o">*</span><span class="n">pl</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">write_lock</span><span class="p">(</span><span class="o">&</span><span class="n">lock</span><span class="p">);</span>
<span class="n">list_add</span><span class="p">(</span><span class="o">&</span><span class="n">pl</span><span class="o">-></span><span class="n">list</span><span class="p">,</span> <span class="n">lh</span><span class="p">);</span>
<span class="n">write_unlock</span><span class="p">(</span><span class="o">&</span><span class="n">lock</span><span class="p">);</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
<div class="section" id="mutex">
<h3>mutex<a class="headerlink" href="#mutex" title="Permalink to this headline">¶</a></h3>
<p>A mutex is a variable of the <code class="docutils literal"><span class="pre">struct</span> <span class="pre">mutex</span></code> type (defined in linux/mutex.h ).
Functions and macros for working with mutex are listed below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><linux/mutex.h></span><span class="cp"></span>
<span class="cm">/* functions for mutex initialization */</span>
<span class="kt">void</span> <span class="nf">mutex_init</span><span class="p">(</span><span class="k">struct</span> <span class="n">mutex</span> <span class="o">*</span><span class="n">mutex</span><span class="p">);</span>
<span class="n">DEFINE_MUTEX</span><span class="p">(</span><span class="n">name</span><span class="p">);</span>
<span class="cm">/* functions for mutex acquire */</span>
<span class="kt">void</span> <span class="nf">mutex_lock</span><span class="p">(</span><span class="k">struct</span> <span class="n">mutex</span> <span class="o">*</span><span class="n">mutex</span><span class="p">);</span>
<span class="cm">/* functions for mutex release */</span>
<span class="kt">void</span> <span class="nf">mutex_unlock</span><span class="p">(</span><span class="k">struct</span> <span class="n">mutex</span> <span class="o">*</span><span class="n">mutex</span><span class="p">);</span>
</pre></div>
</div>
<p>Operations are similar to classic mutex operations in userspace or spinlock
operations: the mutex is acquired before entering the critical area and
releases to the critical area. Unlike spin-locks, these operations can only be
used in process context.</p>
</div>
<div class="section" id="atomic-variables">
<span id="id1"></span><h3>Atomic variables<a class="headerlink" href="#atomic-variables" title="Permalink to this headline">¶</a></h3>
<p>Often, you only need to synchronize access to a simple variable, such as a
counter. For this, an <code class="docutils literal"><span class="pre">atomic_t</span></code> can be used (defined in include/linux/atomic.h
) that holds an integer value. Below are some operations that can be performed on
an atomic_t variable.</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><asm/atomic.h></span><span class="cp"></span>
<span class="kt">void</span> <span class="nf">atomic_set</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">,</span> <span class="kt">int</span> <span class="n">i</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">atomic_read</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">atomic_add</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">atomic_sub</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span><span class="p">,</span> <span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">atomic_inc</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">atomic_dec</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">atomic_inc_and_test</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">atomic_dec_and_test</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">atomic_cmpxchg</span><span class="p">(</span><span class="n">atomic_t</span> <span class="o">*</span><span class="n">v</span><span class="p">,</span> <span class="kt">int</span> <span class="n">old</span><span class="p">,</span> <span class="kt">int</span> <span class="n">new</span><span class="p">);</span>
</pre></div>
</div>
<div class="section" id="use-of-atomic-variables">
<h4>Use of atomic variables<a class="headerlink" href="#use-of-atomic-variables" title="Permalink to this headline">¶</a></h4>
<p>A common way of using atomic variables is to maintain the status of an action
(eg a flag). So we can use an atomic variable to mark exclusive actions. For
example, we consider that an atomic variable can have the LOCKED and UNLOCKED
values, and if LOCKED then a specific function -EBUSY with an -EBUSY message.
The mode of use is shown schematically in the code below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#define LOCKED 0</span>
<span class="cp">#define UNLOCKED 1</span>
<span class="k">static</span> <span class="n">atomic_t</span> <span class="n">flag</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">int</span> <span class="nf">my_acquire</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">int</span> <span class="n">initial_flag</span><span class="p">;</span>
<span class="cm">/*</span>
<span class="cm"> * Check if flag is UNLOCKED; if not, lock it and do it atomically.</span>
<span class="cm"> *</span>
<span class="cm"> * This is the atomic equivalent of</span>
<span class="cm"> * if (flag == UNLOCKED)</span>
<span class="cm"> * flag = LOCKED;</span>
<span class="cm"> * else</span>
<span class="cm"> * return -EBUSY;</span>
<span class="cm"> */</span>
<span class="n">initial_flag</span> <span class="o">=</span> <span class="n">atomic_cmpxchg</span><span class="p">(</span><span class="o">&</span><span class="n">flag</span><span class="p">,</span> <span class="n">UNLOCKED</span><span class="p">,</span> <span class="n">LOCKED</span><span class="p">);</span>
<span class="k">if</span> <span class="p">(</span><span class="n">initial_flag</span> <span class="o">==</span> <span class="n">LOCKED</span><span class="p">)</span> <span class="p">{</span>
<span class="n">printk</span><span class="p">(</span><span class="n">KERN_ALERT</span> <span class="s">"Already locked.</span><span class="se">\n</span><span class="s">"</span><span class="p">);</span>
<span class="k">return</span> <span class="o">-</span><span class="n">EBUSY</span><span class="p">;</span>
<span class="p">}</span>
<span class="cm">/* Do your thing after getting the lock. */</span>
<span class="p">[...]</span>
<span class="p">}</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">my_release</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="cm">/* Release flag; mark it as unlocked. */</span>
<span class="n">atomic_set</span><span class="p">(</span><span class="o">&</span><span class="n">flag</span><span class="p">,</span> <span class="n">UNLOCKED</span><span class="p">);</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">my_init</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="p">[...]</span>
<span class="cm">/* Atomic variable is initially unlocked. */</span>
<span class="n">atomic_set</span><span class="p">(</span><span class="o">&</span><span class="n">flag</span><span class="p">,</span> <span class="n">UNLOCKED</span><span class="p">);</span>
<span class="p">[...]</span>
<span class="p">}</span>
</pre></div>
</div>
<p>The above code is the equivalent of using a trylock (such as pthread_mutex_trylock).</p>
<p>We can also use a variable to remember the size of a buffer and for atomic
updates. For example, the code below:</p>
<div class="highlight-c"><div class="highlight"><pre><span class="k">static</span> <span class="kt">unsigned</span> <span class="kt">char</span> <span class="n">buffer</span><span class="p">[</span><span class="n">MAX_SIZE</span><span class="p">];</span>
<span class="k">static</span> <span class="n">atomic_t</span> <span class="n">size</span><span class="p">;</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">add_to_buffer</span><span class="p">(</span><span class="kt">unsigned</span> <span class="kt">char</span> <span class="n">value</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">buffer</span><span class="p">[</span><span class="n">atomic_read</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">)]</span> <span class="o">=</span> <span class="n">value</span><span class="p">;</span>
<span class="n">atomic_inc</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">static</span> <span class="kt">unsigned</span> <span class="kt">char</span> <span class="nf">remove_from_buffer</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="kt">unsigned</span> <span class="kt">char</span> <span class="n">value</span><span class="p">;</span>
<span class="n">value</span> <span class="o">=</span> <span class="n">buffer</span><span class="p">[</span><span class="n">atomic_read</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">)];</span>
<span class="n">atomic_dec</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">);</span>
<span class="k">return</span> <span class="n">value</span>
<span class="p">}</span>
<span class="k">static</span> <span class="kt">void</span> <span class="nf">reset_buffer</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">atomic_set</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="p">}</span>
<span class="kt">void</span> <span class="nf">my_init</span><span class="p">(</span><span class="kt">void</span><span class="p">)</span>
<span class="p">{</span>
<span class="p">[...]</span>
<span class="cm">/* Initilized buffer and size. */</span>
<span class="n">atomic_set</span><span class="p">(</span><span class="o">&</span><span class="n">size</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span>
<span class="n">memset</span><span class="p">(</span><span class="n">buffer</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="k">sizeof</span><span class="p">(</span><span class="n">buffer</span><span class="p">));</span>
<span class="p">[...]</span>
<span class="p">}</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="atomic-bitwise-operations">
<h3>Atomic bitwise operations<a class="headerlink" href="#atomic-bitwise-operations" title="Permalink to this headline">¶</a></h3>
<p>The kernel provides a set of functions (in <code class="docutils literal"><span class="pre">asm/bitops.h</span></code>) that modify or test
bits in an atomic way.</p>
<div class="highlight-c"><div class="highlight"><pre><span class="cp">#include</span> <span class="cpf"><asm/bitops.h></span><span class="cp"></span>
<span class="kt">void</span> <span class="nf">set_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">clear_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
<span class="kt">void</span> <span class="nf">change_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">test_and_set_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">test_and_clear_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
<span class="kt">int</span> <span class="nf">test_and_change_bit</span><span class="p">(</span><span class="kt">int</span> <span class="n">nr</span><span class="p">,</span> <span class="kt">void</span> <span class="o">*</span><span class="n">addr</span><span class="p">);</span>
</pre></div>
</div>
<p>Addr represents the address of the memory area whose bits are being modified or
tested and the nr is the bit on which the operation is performed.</p>
</div>
</div>
<div class="section" id="exercises">
<h2>Exercises<a class="headerlink" href="#exercises" title="Permalink to this headline">¶</a></h2>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p>To solve exercises need to perform these steps:</p>
<blockquote>
<div><ul class="simple">
<li>prepare skeletons from templates</li>
<li>build modules</li>
<li>copy modules to VM</li>
<li>start the VM and test the module in the VM.</li>
</ul>
</div></blockquote>
<p>The current lab name is kernel_api. See the exercises for the task name.</p>
<div class="toggle last docutils container">
<div class="header docutils container">
<strong>See details</strong></div>
<p>The skeleton code is generated from full source examples located in
<code class="docutils literal"><span class="pre">tools/labs/templates</span></code>. To solve the tasks start by generating
the skeleton code:</p>
<div class="highlight-none"><div class="highlight"><pre>shell
tools/labs $ make clean
tools/labs $ LABS=<lab name>/<task name> make skels
</pre></div>
</div>
<p>Where task name is defined for each task. Once the skelton drivers are
generated build the source:</p>
<div class="highlight-shell"><div class="highlight"><pre>tools/labs $ make build
</pre></div>
</div>
<p>Then copy the modules and start the VM:</p>
<div class="highlight-shell"><div class="highlight"><pre>tools/labs $ make copy
tools/labs $ make boot
</pre></div>
</div>
<p>The modules are placed in /home/root/skels/kernel_api/<task_name>.</p>
<p>Review the <a class="reference internal" href="#exercises">Exercises</a> section for more detailed information.</p>
</div>
</div>
<div class="section" id="intro">
<h3>0. Intro<a class="headerlink" href="#intro" title="Permalink to this headline">¶</a></h3>
<p>Using <a class="reference external" href="http://elixir.free-electrons.com/linux/latest/source">LXR</a> find the definitions of the following symbols in the Linux kernel:</p>
<blockquote>
<div><ul class="simple">
<li><code class="xref c c-type docutils literal"><span class="pre">struct</span> <span class="pre">list_head</span></code></li>
<li><code class="xref c c-type docutils literal"><span class="pre">INIT_LIST_HEAD</span></code></li>
<li><code class="xref c c-func docutils literal"><span class="pre">list_add()</span></code></li>
<li><code class="xref c c-func docutils literal"><span class="pre">list_for_each()</span></code></li>
<li><code class="xref c c-func docutils literal"><span class="pre">list_entry()</span></code></li>
<li><code class="xref c c-func docutils literal"><span class="pre">container_of()</span></code></li>
<li><code class="xref c c-func docutils literal"><span class="pre">offsetof()</span></code></li>
</ul>
</div></blockquote>
</div>
<div class="section" id="memory-allocation-in-linux-kernel">
<h3>1. Memory allocation in Linux kernel<a class="headerlink" href="#memory-allocation-in-linux-kernel" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>1-mem</strong> and browse the
contents of the <code class="docutils literal"><span class="pre">mem.c</span></code> file. Observe the use of kmalloc call for
memory allocation.</p>
<blockquote>
<div><ol class="arabic simple">
<li>Compile the source code and load the <code class="docutils literal"><span class="pre">mem.ko</span></code> module using <code class="docutils literal"><span class="pre">insmod</span></code>.</li>
<li>View the kernel messages using the <code class="docutils literal"><span class="pre">dmesg</span></code> command.</li>
<li>Unload the kernel module using the <code class="docutils literal"><span class="pre">rmmod</span> <span class="pre">mem</span></code> command.</li>
</ol>
</div></blockquote>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Review the <a class="reference internal" href="#memory-allocation">Memory Allocation</a> section in the lab.</p>
</div>
</div>
<div class="section" id="sleeping-in-atomic-context">
<h3>2. Sleeping in atomic context<a class="headerlink" href="#sleeping-in-atomic-context" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>2-sched-spin</strong> and browse
the contents of <code class="docutils literal"><span class="pre">sched-spin.c</span></code> file.</p>
<blockquote>
<div><ol class="arabic simple">
<li>Compile the source code and load the module.</li>
<li>Notice that it is waiting for 5 seconds until the insertion
order is complete.</li>
<li>Unload the kernel mode.</li>
<li>Look for the lines marked with TODO0 to create an atomic
section. Re-compile the source code and reload the module into
the kernel.</li>
</ol>
</div></blockquote>
<p>You should now get an error. Look at the stack trace. What is the
cause of the error?</p>
<div class="admonition hint">
<p class="first admonition-title">Hint</p>
<p class="last">In the error message, follow the line containing the BUG for
a description of the error. You are not allowed to sleep in
atomic context. The atomic context is given by a section
between a lock operation and an unlock on a spinlock.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">The schedule_timeout function, corroborated with the
set_current_state macro, forces the current process to wait
S seconds.</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Review the <a class="reference internal" href="#contexts-of-execution">Contexts of execution</a>, <cite>Locking</cite> and <a class="reference internal" href="#spinlock">Spinlock</a> sections.</p>
</div>
</div>
<div class="section" id="working-with-kernel-memory">
<h3>3. Working with kernel memory<a class="headerlink" href="#working-with-kernel-memory" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>3-memory</strong> directory and
browse the contents of the <code class="docutils literal"><span class="pre">memory.c</span></code> file. Notice the comments
marked with TODO. You must allocate 4 structures of type <code class="docutils literal"><span class="pre">struct</span>
<span class="pre">task_info</span></code> and initialize them (in <code class="docutils literal"><span class="pre">memory_init</span></code>), then print and
free them (in <code class="docutils literal"><span class="pre">memory_exit</span></code>).</p>
<blockquote>
<div><ol class="arabic simple">
<li>(TODO 1) Allocate memory for task_info structure and initialize
its fields:<ul>
<li>The pid field to the PID transmitted as a parameter;</li>
<li>The timestamp field to the value of the jiffies variable,
which hold the number of ticks that have occurred since the
system booted.</li>
</ul>
</li>
<li>(TODO 2) Allocate task_info for current process, parent process,
next process, the next process of the next process.</li>
<li>(TODO 3) Display the four structures.<ul>
<li>Use pr_info to display their two fields: pid and timestamp.</li>
</ul>
</li>
<li>(TODO 4) Release the space occupied by structures (use kfree).</li>
</ol>
</div></blockquote>
<div class="admonition hint">
<p class="first admonition-title">Hint</p>
<ul class="last simple">
<li>You can access the current process using <code class="docutils literal"><span class="pre">current</span></code>
macro.</li>
<li>Look for the relevant fields in the task_struct structure
(pid, parent).</li>
<li>Use the next_task macro. The macro returns the pointer to
the next process of <code class="docutils literal"><span class="pre">struct</span> <span class="pre">task_struct</span> <span class="pre">*</span></code> type.</li>
</ul>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p>The task_struct struct contains two fields to designate the
parent of a task:</p>
<ul class="simple">
<li><dl class="first docutils">
<dt><code class="docutils literal"><span class="pre">real_parent</span></code> points to the process that created the</dt>
<dd>task or to process with pid 1 (init) if the parent
completed its execution.</dd>
</dl>
</li>
<li><dl class="first docutils">
<dt><code class="docutils literal"><span class="pre">parent</span></code> indicates to the current task parent (the</dt>
<dd>process that will be reported if the task completes
execution).</dd>
</dl>
</li>
</ul>
<p class="last">In general, the values of the two fields are the same, but
there are situations where they differ, for example when
using the ptrace system call.</p>
</div>
<div class="admonition hint">
<p class="first admonition-title">Hint</p>
<p class="last">Review the <a class="reference internal" href="#memory-allocation">Memory allocation</a> section in the lab.</p>
</div>
</div>
<div class="section" id="working-with-kernel-lists">
<h3>4. Working with kernel lists<a class="headerlink" href="#working-with-kernel-lists" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>4-list</strong>. Browse the
contents of the <code class="docutils literal"><span class="pre">list.c</span></code> file and notice the comments marked with
TODO. The current process will add the four structures from the
previous exercise into a list. The list will be built in the
<code class="docutils literal"><span class="pre">task_info_add_for_current</span></code> function which is called when module is
loaded. The list will printed and deleted in the <code class="docutils literal"><span class="pre">list_exit</span></code>
function and the <code class="docutils literal"><span class="pre">task_info_purge_list</span></code> function.</p>
<blockquote>
<div><ol class="arabic simple">
<li>(TODO 1) Complete the task_info_add_to_list function to allocate
a <code class="docutils literal"><span class="pre">task_info</span></code> struct and add it to the list.</li>
<li>(TODO 2) Complete the task_info_purge_list function to delete
all the elements in the list.</li>
<li>Compile the kernel module. Load and unload the module by
following the messages displayed by the kernel.</li>
</ol>
</div></blockquote>
<div class="admonition hint">
<p class="first admonition-title">Hint</p>
<p class="last">Review the labs <a class="reference internal" href="#lists">Lists</a> section. When deleting items from
the list, you will need to use the
<code class="xref c c-func docutils literal"><span class="pre">list_for_each_safe()</span></code> or
<code class="xref c c-func docutils literal"><span class="pre">list_for_each_entry_safe()</span></code> calls.</p>
</div>
</div>
<div class="section" id="working-with-kernel-lists-for-process-handling">
<h3>5. Working with kernel lists for process handling<a class="headerlink" href="#working-with-kernel-lists-for-process-handling" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>5-list-full</strong>. Browse the
contents of the <code class="docutils literal"><span class="pre">list-full.c</span></code> and notice comments marked with
TODO. In addition to the <code class="docutils literal"><span class="pre">4-list</span></code> functionality we add the
following:</p>
<blockquote>
<div><ul>
<li><p class="first">A count field showing how many times a process has been “added”
to the list.</p>
</li>
<li><p class="first">If a process is “added” several times, no new entry is created in
the list, but:</p>
<blockquote>
<div><ul class="simple">
<li>Update the timestamp field.</li>
<li>Increment count.</li>
</ul>
</div></blockquote>
</li>
<li><p class="first">To implement the counter facility, add a <code class="docutils literal"><span class="pre">task_info_find_pid</span></code>
function that searches for a pid in the existing list.</p>
<blockquote>
<div><ul class="simple">
<li>If found, return the reference to the task_info struct. If
not, return NULL</li>
</ul>
</div></blockquote>
</li>
<li><p class="first">An expiration facility. If a process was added more than 3
seconds ago and if it does not have a count greater than 5 then
it is considered expired and is removed from the list.</p>
</li>
<li><p class="first">The expiration facility is already implemented in the
<code class="docutils literal"><span class="pre">task_info_remove_expired</span></code> function.</p>
</li>
</ul>
<p>1. (TODO 1) Implement the task_info_find_pid function.
3. (TODO 2) Change a field of an item in the list so it does not</p>
<blockquote>
<div>expire.</div></blockquote>
</div></blockquote>
<div class="admonition hint">
<p class="first admonition-title">Hint</p>
<p class="last">For TODO 2, extract the first element from the list (the one
referred by head.next) and set the count field to a large
enough value. Use <code class="docutils literal"><span class="pre">atomic_set</span></code>.</p>
</div>
</div>
<div class="section" id="synchronizing-list-work">
<h3>6. Synchronizing list work<a class="headerlink" href="#synchronizing-list-work" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>6-list-sync</strong>.</p>
<blockquote>
<div><ol class="arabic simple">
<li>Browse the code and look for <code class="docutils literal"><span class="pre">TODO</span></code> string.</li>
<li>Use a spinlock or a read-write lock to synchronize access to the
list.</li>
<li>Compile, load and unload the kernel module.</li>
</ol>
</div></blockquote>
<div class="admonition important">
<p class="first admonition-title">Important</p>
<p class="last">Always lock data, not code!</p>
</div>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Read <a class="reference internal" href="#spinlock">Spinlock</a> section of the lab.</p>
</div>
</div>
<div class="section" id="test-module-calling-in-our-list-module">
<h3>7. Test module calling in our list module<a class="headerlink" href="#test-module-calling-in-our-list-module" title="Permalink to this headline">¶</a></h3>
<p>Generate the skeleton for the task named <strong>7-list-test</strong> and browse
the contents of the <code class="docutils literal"><span class="pre">list-test.c</span></code> file. We’ll use it as a test
module. It will call functions exported by the <strong>6-list-sync</strong>
task. The exported functions are the ones marked with <strong>extern</strong> in
<code class="docutils literal"><span class="pre">list-test.c</span></code> file.</p>
<p>To export the above functions from the 6-list-sync/ module, the
following steps are required:</p>
<blockquote>
<div><ol class="arabic simple">
<li>Functions must not be static.</li>
<li>Use the EXPORT_SYMBOL macro to export the kernel symbols. For
example: <code class="docutils literal"><span class="pre">EXPORT_SYMBOL(task_info_remove_expired)</span></code>; . The
macro must be used for each function after the function is
defined.</li>
<li>Remove from the 6-list-sync/ that avoid the expiration of a
list item.</li>
<li>Compile and load the module from 6-list-sync/ . Once loaded, it
exposes exported functions and can be used by the test
module. You can check this by searching for the function names
in /proc/kallsyms before and after loading the module.</li>
<li>Compile the test module and then load it.</li>
<li>Use lsmod to check that the two modules have loaded. What do
you notice?</li>
<li>Unload the kernel test module.</li>
</ol>
</div></blockquote>
<p>What should be the unload order of the two modules (6-list-sync and
test)? What if you use another order?</p>
</div>
</div>
</div>
</div>
</div>
<footer>
<div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">