~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

TOMOYO Linux Cross Reference
Linux/Documentation/kernel-hacking/hacking.rst

Version: ~ [ linux-6.12-rc7 ] ~ [ linux-6.11.7 ] ~ [ linux-6.10.14 ] ~ [ linux-6.9.12 ] ~ [ linux-6.8.12 ] ~ [ linux-6.7.12 ] ~ [ linux-6.6.60 ] ~ [ linux-6.5.13 ] ~ [ linux-6.4.16 ] ~ [ linux-6.3.13 ] ~ [ linux-6.2.16 ] ~ [ linux-6.1.116 ] ~ [ linux-6.0.19 ] ~ [ linux-5.19.17 ] ~ [ linux-5.18.19 ] ~ [ linux-5.17.15 ] ~ [ linux-5.16.20 ] ~ [ linux-5.15.171 ] ~ [ linux-5.14.21 ] ~ [ linux-5.13.19 ] ~ [ linux-5.12.19 ] ~ [ linux-5.11.22 ] ~ [ linux-5.10.229 ] ~ [ linux-5.9.16 ] ~ [ linux-5.8.18 ] ~ [ linux-5.7.19 ] ~ [ linux-5.6.19 ] ~ [ linux-5.5.19 ] ~ [ linux-5.4.285 ] ~ [ linux-5.3.18 ] ~ [ linux-5.2.21 ] ~ [ linux-5.1.21 ] ~ [ linux-5.0.21 ] ~ [ linux-4.20.17 ] ~ [ linux-4.19.323 ] ~ [ linux-4.18.20 ] ~ [ linux-4.17.19 ] ~ [ linux-4.16.18 ] ~ [ linux-4.15.18 ] ~ [ linux-4.14.336 ] ~ [ linux-4.13.16 ] ~ [ linux-4.12.14 ] ~ [ linux-4.11.12 ] ~ [ linux-4.10.17 ] ~ [ linux-4.9.337 ] ~ [ linux-4.4.302 ] ~ [ linux-3.10.108 ] ~ [ linux-2.6.32.71 ] ~ [ linux-2.6.0 ] ~ [ linux-2.4.37.11 ] ~ [ unix-v6-master ] ~ [ ccs-tools-1.8.12 ] ~ [ policy-sample ] ~
Architecture: ~ [ i386 ] ~ [ alpha ] ~ [ m68k ] ~ [ mips ] ~ [ ppc ] ~ [ sparc ] ~ [ sparc64 ] ~

Diff markup

Differences between /Documentation/kernel-hacking/hacking.rst (Version linux-6.12-rc7) and /Documentation/kernel-hacking/hacking.rst (Version linux-5.9.16)


  1 .. _kernel_hacking_hack:                            1 .. _kernel_hacking_hack:
  2                                                     2 
  3 ============================================        3 ============================================
  4 Unreliable Guide To Hacking The Linux Kernel        4 Unreliable Guide To Hacking The Linux Kernel
  5 ============================================        5 ============================================
  6                                                     6 
  7 :Author: Rusty Russell                              7 :Author: Rusty Russell
  8                                                     8 
  9 Introduction                                        9 Introduction
 10 ============                                       10 ============
 11                                                    11 
 12 Welcome, gentle reader, to Rusty's Remarkably      12 Welcome, gentle reader, to Rusty's Remarkably Unreliable Guide to Linux
 13 Kernel Hacking. This document describes the co     13 Kernel Hacking. This document describes the common routines and general
 14 requirements for kernel code: its goal is to s     14 requirements for kernel code: its goal is to serve as a primer for Linux
 15 kernel development for experienced C programme     15 kernel development for experienced C programmers. I avoid implementation
 16 details: that's what the code is for, and I ig     16 details: that's what the code is for, and I ignore whole tracts of
 17 useful routines.                                   17 useful routines.
 18                                                    18 
 19 Before you read this, please understand that I     19 Before you read this, please understand that I never wanted to write
 20 this document, being grossly under-qualified,      20 this document, being grossly under-qualified, but I always wanted to
 21 read it, and this was the only way. I hope it      21 read it, and this was the only way. I hope it will grow into a
 22 compendium of best practice, common starting p     22 compendium of best practice, common starting points and random
 23 information.                                       23 information.
 24                                                    24 
 25 The Players                                        25 The Players
 26 ===========                                        26 ===========
 27                                                    27 
 28 At any time each of the CPUs in a system can b     28 At any time each of the CPUs in a system can be:
 29                                                    29 
 30 -  not associated with any process, serving a      30 -  not associated with any process, serving a hardware interrupt;
 31                                                    31 
 32 -  not associated with any process, serving a      32 -  not associated with any process, serving a softirq or tasklet;
 33                                                    33 
 34 -  running in kernel space, associated with a      34 -  running in kernel space, associated with a process (user context);
 35                                                    35 
 36 -  running a process in user space.                36 -  running a process in user space.
 37                                                    37 
 38 There is an ordering between these. The bottom     38 There is an ordering between these. The bottom two can preempt each
 39 other, but above that is a strict hierarchy: e     39 other, but above that is a strict hierarchy: each can only be preempted
 40 by the ones above it. For example, while a sof     40 by the ones above it. For example, while a softirq is running on a CPU,
 41 no other softirq will preempt it, but a hardwa     41 no other softirq will preempt it, but a hardware interrupt can. However,
 42 any other CPUs in the system execute independe     42 any other CPUs in the system execute independently.
 43                                                    43 
 44 We'll see a number of ways that the user conte     44 We'll see a number of ways that the user context can block interrupts,
 45 to become truly non-preemptable.                   45 to become truly non-preemptable.
 46                                                    46 
 47 User Context                                       47 User Context
 48 ------------                                       48 ------------
 49                                                    49 
 50 User context is when you are coming in from a      50 User context is when you are coming in from a system call or other trap:
 51 like userspace, you can be preempted by more i     51 like userspace, you can be preempted by more important tasks and by
 52 interrupts. You can sleep, by calling :c:func:     52 interrupts. You can sleep, by calling :c:func:`schedule()`.
 53                                                    53 
 54 .. note::                                          54 .. note::
 55                                                    55 
 56     You are always in user context on module l     56     You are always in user context on module load and unload, and on
 57     operations on the block device layer.          57     operations on the block device layer.
 58                                                    58 
 59 In user context, the ``current`` pointer (indi     59 In user context, the ``current`` pointer (indicating the task we are
 60 currently executing) is valid, and :c:func:`in     60 currently executing) is valid, and :c:func:`in_interrupt()`
 61 (``include/linux/preempt.h``) is false.            61 (``include/linux/preempt.h``) is false.
 62                                                    62 
 63 .. warning::                                       63 .. warning::
 64                                                    64 
 65     Beware that if you have preemption or soft     65     Beware that if you have preemption or softirqs disabled (see below),
 66     :c:func:`in_interrupt()` will return a fal     66     :c:func:`in_interrupt()` will return a false positive.
 67                                                    67 
 68 Hardware Interrupts (Hard IRQs)                    68 Hardware Interrupts (Hard IRQs)
 69 -------------------------------                    69 -------------------------------
 70                                                    70 
 71 Timer ticks, network cards and keyboard are ex     71 Timer ticks, network cards and keyboard are examples of real hardware
 72 which produce interrupts at any time. The kern     72 which produce interrupts at any time. The kernel runs interrupt
 73 handlers, which services the hardware. The ker     73 handlers, which services the hardware. The kernel guarantees that this
 74 handler is never re-entered: if the same inter     74 handler is never re-entered: if the same interrupt arrives, it is queued
 75 (or dropped). Because it disables interrupts,      75 (or dropped). Because it disables interrupts, this handler has to be
 76 fast: frequently it simply acknowledges the in     76 fast: frequently it simply acknowledges the interrupt, marks a 'software
 77 interrupt' for execution and exits.                77 interrupt' for execution and exits.
 78                                                    78 
 79 You can tell you are in a hardware interrupt,  !!  79 You can tell you are in a hardware interrupt, because
 80 true.                                          !!  80 :c:func:`in_irq()` returns true.
 81                                                    81 
 82 .. warning::                                       82 .. warning::
 83                                                    83 
 84     Beware that this will return a false posit     84     Beware that this will return a false positive if interrupts are
 85     disabled (see below).                          85     disabled (see below).
 86                                                    86 
 87 Software Interrupt Context: Softirqs and Taskl     87 Software Interrupt Context: Softirqs and Tasklets
 88 ----------------------------------------------     88 -------------------------------------------------
 89                                                    89 
 90 Whenever a system call is about to return to u     90 Whenever a system call is about to return to userspace, or a hardware
 91 interrupt handler exits, any 'software interru     91 interrupt handler exits, any 'software interrupts' which are marked
 92 pending (usually by hardware interrupts) are r     92 pending (usually by hardware interrupts) are run (``kernel/softirq.c``).
 93                                                    93 
 94 Much of the real interrupt handling work is do     94 Much of the real interrupt handling work is done here. Early in the
 95 transition to SMP, there were only 'bottom hal     95 transition to SMP, there were only 'bottom halves' (BHs), which didn't
 96 take advantage of multiple CPUs. Shortly after     96 take advantage of multiple CPUs. Shortly after we switched from wind-up
 97 computers made of match-sticks and snot, we ab     97 computers made of match-sticks and snot, we abandoned this limitation
 98 and switched to 'softirqs'.                        98 and switched to 'softirqs'.
 99                                                    99 
100 ``include/linux/interrupt.h`` lists the differ    100 ``include/linux/interrupt.h`` lists the different softirqs. A very
101 important softirq is the timer softirq (``incl    101 important softirq is the timer softirq (``include/linux/timer.h``): you
102 can register to have it call functions for you    102 can register to have it call functions for you in a given length of
103 time.                                             103 time.
104                                                   104 
105 Softirqs are often a pain to deal with, since     105 Softirqs are often a pain to deal with, since the same softirq will run
106 simultaneously on more than one CPU. For this     106 simultaneously on more than one CPU. For this reason, tasklets
107 (``include/linux/interrupt.h``) are more often    107 (``include/linux/interrupt.h``) are more often used: they are
108 dynamically-registrable (meaning you can have     108 dynamically-registrable (meaning you can have as many as you want), and
109 they also guarantee that any tasklet will only    109 they also guarantee that any tasklet will only run on one CPU at any
110 time, although different tasklets can run simu    110 time, although different tasklets can run simultaneously.
111                                                   111 
112 .. warning::                                      112 .. warning::
113                                                   113 
114     The name 'tasklet' is misleading: they hav    114     The name 'tasklet' is misleading: they have nothing to do with
115     'tasks'.                                   !! 115     'tasks', and probably more to do with some bad vodka Alexey
                                                   >> 116     Kuznetsov had at the time.
116                                                   117 
117 You can tell you are in a softirq (or tasklet)    118 You can tell you are in a softirq (or tasklet) using the
118 :c:func:`in_softirq()` macro (``include/linux/    119 :c:func:`in_softirq()` macro (``include/linux/preempt.h``).
119                                                   120 
120 .. warning::                                      121 .. warning::
121                                                   122 
122     Beware that this will return a false posit    123     Beware that this will return a false positive if a
123     :ref:`bottom half lock <local_bh_disable>` !! 124     :ref:`botton half lock <local_bh_disable>` is held.
124                                                   125 
125 Some Basic Rules                                  126 Some Basic Rules
126 ================                                  127 ================
127                                                   128 
128 No memory protection                              129 No memory protection
129     If you corrupt memory, whether in user con    130     If you corrupt memory, whether in user context or interrupt context,
130     the whole machine will crash. Are you sure    131     the whole machine will crash. Are you sure you can't do what you
131     want in userspace?                            132     want in userspace?
132                                                   133 
133 No floating point or MMX                          134 No floating point or MMX
134     The FPU context is not saved; even in user    135     The FPU context is not saved; even in user context the FPU state
135     probably won't correspond with the current    136     probably won't correspond with the current process: you would mess
136     with some user process' FPU state. If you     137     with some user process' FPU state. If you really want to do this,
137     you would have to explicitly save/restore     138     you would have to explicitly save/restore the full FPU state (and
138     avoid context switches). It is generally a    139     avoid context switches). It is generally a bad idea; use fixed point
139     arithmetic first.                             140     arithmetic first.
140                                                   141 
141 A rigid stack limit                               142 A rigid stack limit
142     Depending on configuration options the ker    143     Depending on configuration options the kernel stack is about 3K to
143     6K for most 32-bit architectures: it's abo    144     6K for most 32-bit architectures: it's about 14K on most 64-bit
144     archs, and often shared with interrupts so    145     archs, and often shared with interrupts so you can't use it all.
145     Avoid deep recursion and huge local arrays    146     Avoid deep recursion and huge local arrays on the stack (allocate
146     them dynamically instead).                    147     them dynamically instead).
147                                                   148 
148 The Linux kernel is portable                      149 The Linux kernel is portable
149     Let's keep it that way. Your code should b    150     Let's keep it that way. Your code should be 64-bit clean, and
150     endian-independent. You should also minimi    151     endian-independent. You should also minimize CPU specific stuff,
151     e.g. inline assembly should be cleanly enc    152     e.g. inline assembly should be cleanly encapsulated and minimized to
152     ease porting. Generally it should be restr    153     ease porting. Generally it should be restricted to the
153     architecture-dependent part of the kernel     154     architecture-dependent part of the kernel tree.
154                                                   155 
155 ioctls: Not writing a new system call             156 ioctls: Not writing a new system call
156 =====================================             157 =====================================
157                                                   158 
158 A system call generally looks like this::         159 A system call generally looks like this::
159                                                   160 
160     asmlinkage long sys_mycall(int arg)           161     asmlinkage long sys_mycall(int arg)
161     {                                             162     {
162             return 0;                             163             return 0;
163     }                                             164     }
164                                                   165 
165                                                   166 
166 First, in most cases you don't want to create     167 First, in most cases you don't want to create a new system call. You
167 create a character device and implement an app    168 create a character device and implement an appropriate ioctl for it.
168 This is much more flexible than system calls,     169 This is much more flexible than system calls, doesn't have to be entered
169 in every architecture's ``include/asm/unistd.h    170 in every architecture's ``include/asm/unistd.h`` and
170 ``arch/kernel/entry.S`` file, and is much more    171 ``arch/kernel/entry.S`` file, and is much more likely to be accepted by
171 Linus.                                            172 Linus.
172                                                   173 
173 If all your routine does is read or write some    174 If all your routine does is read or write some parameter, consider
174 implementing a :c:func:`sysfs()` interface ins    175 implementing a :c:func:`sysfs()` interface instead.
175                                                   176 
176 Inside the ioctl you're in user context to a p    177 Inside the ioctl you're in user context to a process. When a error
177 occurs you return a negated errno (see            178 occurs you return a negated errno (see
178 ``include/uapi/asm-generic/errno-base.h``,        179 ``include/uapi/asm-generic/errno-base.h``,
179 ``include/uapi/asm-generic/errno.h`` and ``inc    180 ``include/uapi/asm-generic/errno.h`` and ``include/linux/errno.h``),
180 otherwise you return 0.                           181 otherwise you return 0.
181                                                   182 
182 After you slept you should check if a signal o    183 After you slept you should check if a signal occurred: the Unix/Linux
183 way of handling signals is to temporarily exit    184 way of handling signals is to temporarily exit the system call with the
184 ``-ERESTARTSYS`` error. The system call entry     185 ``-ERESTARTSYS`` error. The system call entry code will switch back to
185 user context, process the signal handler and t    186 user context, process the signal handler and then your system call will
186 be restarted (unless the user disabled that).     187 be restarted (unless the user disabled that). So you should be prepared
187 to process the restart, e.g. if you're in the     188 to process the restart, e.g. if you're in the middle of manipulating
188 some data structure.                              189 some data structure.
189                                                   190 
190 ::                                                191 ::
191                                                   192 
192     if (signal_pending(current))                  193     if (signal_pending(current))
193             return -ERESTARTSYS;                  194             return -ERESTARTSYS;
194                                                   195 
195                                                   196 
196 If you're doing longer computations: first thi    197 If you're doing longer computations: first think userspace. If you
197 **really** want to do it in kernel you should     198 **really** want to do it in kernel you should regularly check if you need
198 to give up the CPU (remember there is cooperat    199 to give up the CPU (remember there is cooperative multitasking per CPU).
199 Idiom::                                           200 Idiom::
200                                                   201 
201     cond_resched(); /* Will sleep */              202     cond_resched(); /* Will sleep */
202                                                   203 
203                                                   204 
204 A short note on interface design: the UNIX sys    205 A short note on interface design: the UNIX system call motto is "Provide
205 mechanism not policy".                            206 mechanism not policy".
206                                                   207 
207 Recipes for Deadlock                              208 Recipes for Deadlock
208 ====================                              209 ====================
209                                                   210 
210 You cannot call any routines which may sleep,     211 You cannot call any routines which may sleep, unless:
211                                                   212 
212 -  You are in user context.                       213 -  You are in user context.
213                                                   214 
214 -  You do not own any spinlocks.                  215 -  You do not own any spinlocks.
215                                                   216 
216 -  You have interrupts enabled (actually, Andi    217 -  You have interrupts enabled (actually, Andi Kleen says that the
217    scheduling code will enable them for you, b    218    scheduling code will enable them for you, but that's probably not
218    what you wanted).                              219    what you wanted).
219                                                   220 
220 Note that some functions may sleep implicitly:    221 Note that some functions may sleep implicitly: common ones are the user
221 space access functions (\*_user) and memory al    222 space access functions (\*_user) and memory allocation functions
222 without ``GFP_ATOMIC``.                           223 without ``GFP_ATOMIC``.
223                                                   224 
224 You should always compile your kernel ``CONFIG    225 You should always compile your kernel ``CONFIG_DEBUG_ATOMIC_SLEEP`` on,
225 and it will warn you if you break these rules.    226 and it will warn you if you break these rules. If you **do** break the
226 rules, you will eventually lock up your box.      227 rules, you will eventually lock up your box.
227                                                   228 
228 Really.                                           229 Really.
229                                                   230 
230 Common Routines                                   231 Common Routines
231 ===============                                   232 ===============
232                                                   233 
233 :c:func:`printk()`                                234 :c:func:`printk()`
234 ------------------                                235 ------------------
235                                                   236 
236 Defined in ``include/linux/printk.h``             237 Defined in ``include/linux/printk.h``
237                                                   238 
238 :c:func:`printk()` feeds kernel messages to th    239 :c:func:`printk()` feeds kernel messages to the console, dmesg, and
239 the syslog daemon. It is useful for debugging     240 the syslog daemon. It is useful for debugging and reporting errors, and
240 can be used inside interrupt context, but use     241 can be used inside interrupt context, but use with caution: a machine
241 which has its console flooded with printk mess    242 which has its console flooded with printk messages is unusable. It uses
242 a format string mostly compatible with ANSI C     243 a format string mostly compatible with ANSI C printf, and C string
243 concatenation to give it a first "priority" ar    244 concatenation to give it a first "priority" argument::
244                                                   245 
245     printk(KERN_INFO "i = %u\n", i);              246     printk(KERN_INFO "i = %u\n", i);
246                                                   247 
247                                                   248 
248 See ``include/linux/kern_levels.h``; for other    249 See ``include/linux/kern_levels.h``; for other ``KERN_`` values; these are
249 interpreted by syslog as the level. Special ca    250 interpreted by syslog as the level. Special case: for printing an IP
250 address use::                                     251 address use::
251                                                   252 
252     __be32 ipaddress;                             253     __be32 ipaddress;
253     printk(KERN_INFO "my ip: %pI4\n", &ipaddre    254     printk(KERN_INFO "my ip: %pI4\n", &ipaddress);
254                                                   255 
255                                                   256 
256 :c:func:`printk()` internally uses a 1K buffer    257 :c:func:`printk()` internally uses a 1K buffer and does not catch
257 overruns. Make sure that will be enough.          258 overruns. Make sure that will be enough.
258                                                   259 
259 .. note::                                         260 .. note::
260                                                   261 
261     You will know when you are a real kernel h    262     You will know when you are a real kernel hacker when you start
262     typoing printf as printk in your user prog    263     typoing printf as printk in your user programs :)
263                                                   264 
264 .. note::                                         265 .. note::
265                                                   266 
266     Another sidenote: the original Unix Versio    267     Another sidenote: the original Unix Version 6 sources had a comment
267     on top of its printf function: "Printf sho    268     on top of its printf function: "Printf should not be used for
268     chit-chat". You should follow that advice.    269     chit-chat". You should follow that advice.
269                                                   270 
270 :c:func:`copy_to_user()` / :c:func:`copy_from_    271 :c:func:`copy_to_user()` / :c:func:`copy_from_user()` / :c:func:`get_user()` / :c:func:`put_user()`
271 ----------------------------------------------    272 ---------------------------------------------------------------------------------------------------
272                                                   273 
273 Defined in ``include/linux/uaccess.h`` / ``asm    274 Defined in ``include/linux/uaccess.h`` / ``asm/uaccess.h``
274                                                   275 
275 **[SLEEPS]**                                      276 **[SLEEPS]**
276                                                   277 
277 :c:func:`put_user()` and :c:func:`get_user()`     278 :c:func:`put_user()` and :c:func:`get_user()` are used to get
278 and put single values (such as an int, char, o    279 and put single values (such as an int, char, or long) from and to
279 userspace. A pointer into userspace should nev    280 userspace. A pointer into userspace should never be simply dereferenced:
280 data should be copied using these routines. Bo    281 data should be copied using these routines. Both return ``-EFAULT`` or
281 0.                                                282 0.
282                                                   283 
283 :c:func:`copy_to_user()` and :c:func:`copy_fro    284 :c:func:`copy_to_user()` and :c:func:`copy_from_user()` are
284 more general: they copy an arbitrary amount of    285 more general: they copy an arbitrary amount of data to and from
285 userspace.                                        286 userspace.
286                                                   287 
287 .. warning::                                      288 .. warning::
288                                                   289 
289     Unlike :c:func:`put_user()` and :c:func:`g    290     Unlike :c:func:`put_user()` and :c:func:`get_user()`, they
290     return the amount of uncopied data (ie. 0     291     return the amount of uncopied data (ie. 0 still means success).
291                                                   292 
292 [Yes, this objectionable interface makes me cr !! 293 [Yes, this moronic interface makes me cringe. The flamewar comes up
293 up every year or so. --RR.]                    !! 294 every year or so. --RR.]
294                                                   295 
295 The functions may sleep implicitly. This shoul    296 The functions may sleep implicitly. This should never be called outside
296 user context (it makes no sense), with interru    297 user context (it makes no sense), with interrupts disabled, or a
297 spinlock held.                                    298 spinlock held.
298                                                   299 
299 :c:func:`kmalloc()`/:c:func:`kfree()`             300 :c:func:`kmalloc()`/:c:func:`kfree()`
300 -------------------------------------             301 -------------------------------------
301                                                   302 
302 Defined in ``include/linux/slab.h``               303 Defined in ``include/linux/slab.h``
303                                                   304 
304 **[MAY SLEEP: SEE BELOW]**                        305 **[MAY SLEEP: SEE BELOW]**
305                                                   306 
306 These routines are used to dynamically request    307 These routines are used to dynamically request pointer-aligned chunks of
307 memory, like malloc and free do in userspace,     308 memory, like malloc and free do in userspace, but
308 :c:func:`kmalloc()` takes an extra flag word.     309 :c:func:`kmalloc()` takes an extra flag word. Important values:
309                                                   310 
310 ``GFP_KERNEL``                                    311 ``GFP_KERNEL``
311     May sleep and swap to free memory. Only al    312     May sleep and swap to free memory. Only allowed in user context, but
312     is the most reliable way to allocate memor    313     is the most reliable way to allocate memory.
313                                                   314 
314 ``GFP_ATOMIC``                                    315 ``GFP_ATOMIC``
315     Don't sleep. Less reliable than ``GFP_KERN    316     Don't sleep. Less reliable than ``GFP_KERNEL``, but may be called
316     from interrupt context. You should **reall    317     from interrupt context. You should **really** have a good
317     out-of-memory error-handling strategy.        318     out-of-memory error-handling strategy.
318                                                   319 
319 ``GFP_DMA``                                       320 ``GFP_DMA``
320     Allocate ISA DMA lower than 16MB. If you d    321     Allocate ISA DMA lower than 16MB. If you don't know what that is you
321     don't need it. Very unreliable.               322     don't need it. Very unreliable.
322                                                   323 
323 If you see a sleeping function called from inv    324 If you see a sleeping function called from invalid context warning
324 message, then maybe you called a sleeping allo    325 message, then maybe you called a sleeping allocation function from
325 interrupt context without ``GFP_ATOMIC``. You     326 interrupt context without ``GFP_ATOMIC``. You should really fix that.
326 Run, don't walk.                                  327 Run, don't walk.
327                                                   328 
328 If you are allocating at least ``PAGE_SIZE`` (    329 If you are allocating at least ``PAGE_SIZE`` (``asm/page.h`` or
329 ``asm/page_types.h``) bytes, consider using :c    330 ``asm/page_types.h``) bytes, consider using :c:func:`__get_free_pages()`
330 (``include/linux/gfp.h``). It takes an order a    331 (``include/linux/gfp.h``). It takes an order argument (0 for page sized,
331 1 for double page, 2 for four pages etc.) and     332 1 for double page, 2 for four pages etc.) and the same memory priority
332 flag word as above.                               333 flag word as above.
333                                                   334 
334 If you are allocating more than a page worth o    335 If you are allocating more than a page worth of bytes you can use
335 :c:func:`vmalloc()`. It'll allocate virtual me    336 :c:func:`vmalloc()`. It'll allocate virtual memory in the kernel
336 map. This block is not contiguous in physical     337 map. This block is not contiguous in physical memory, but the MMU makes
337 it look like it is for you (so it'll only look    338 it look like it is for you (so it'll only look contiguous to the CPUs,
338 not to external device drivers). If you really    339 not to external device drivers). If you really need large physically
339 contiguous memory for some weird device, you h    340 contiguous memory for some weird device, you have a problem: it is
340 poorly supported in Linux because after some t    341 poorly supported in Linux because after some time memory fragmentation
341 in a running kernel makes it hard. The best wa    342 in a running kernel makes it hard. The best way is to allocate the block
342 early in the boot process via the :c:func:`all    343 early in the boot process via the :c:func:`alloc_bootmem()`
343 routine.                                          344 routine.
344                                                   345 
345 Before inventing your own cache of often-used     346 Before inventing your own cache of often-used objects consider using a
346 slab cache in ``include/linux/slab.h``            347 slab cache in ``include/linux/slab.h``
347                                                   348 
348 :c:macro:`current`                             !! 349 :c:func:`current()`
349 ------------------                             !! 350 -------------------
350                                                   351 
351 Defined in ``include/asm/current.h``              352 Defined in ``include/asm/current.h``
352                                                   353 
353 This global variable (really a macro) contains    354 This global variable (really a macro) contains a pointer to the current
354 task structure, so is only valid in user conte    355 task structure, so is only valid in user context. For example, when a
355 process makes a system call, this will point t    356 process makes a system call, this will point to the task structure of
356 the calling process. It is **not NULL** in int    357 the calling process. It is **not NULL** in interrupt context.
357                                                   358 
358 :c:func:`mdelay()`/:c:func:`udelay()`             359 :c:func:`mdelay()`/:c:func:`udelay()`
359 -------------------------------------             360 -------------------------------------
360                                                   361 
361 Defined in ``include/asm/delay.h`` / ``include    362 Defined in ``include/asm/delay.h`` / ``include/linux/delay.h``
362                                                   363 
363 The :c:func:`udelay()` and :c:func:`ndelay()`     364 The :c:func:`udelay()` and :c:func:`ndelay()` functions can be
364 used for small pauses. Do not use large values    365 used for small pauses. Do not use large values with them as you risk
365 overflow - the helper function :c:func:`mdelay    366 overflow - the helper function :c:func:`mdelay()` is useful here, or
366 consider :c:func:`msleep()`.                      367 consider :c:func:`msleep()`.
367                                                   368 
368 :c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()    369 :c:func:`cpu_to_be32()`/:c:func:`be32_to_cpu()`/:c:func:`cpu_to_le32()`/:c:func:`le32_to_cpu()`
369 ----------------------------------------------    370 -----------------------------------------------------------------------------------------------
370                                                   371 
371 Defined in ``include/asm/byteorder.h``            372 Defined in ``include/asm/byteorder.h``
372                                                   373 
373 The :c:func:`cpu_to_be32()` family (where the     374 The :c:func:`cpu_to_be32()` family (where the "32" can be replaced
374 by 64 or 16, and the "be" can be replaced by "    375 by 64 or 16, and the "be" can be replaced by "le") are the general way
375 to do endian conversions in the kernel: they r    376 to do endian conversions in the kernel: they return the converted value.
376 All variations supply the reverse as well:        377 All variations supply the reverse as well:
377 :c:func:`be32_to_cpu()`, etc.                     378 :c:func:`be32_to_cpu()`, etc.
378                                                   379 
379 There are two major variations of these functi    380 There are two major variations of these functions: the pointer
380 variation, such as :c:func:`cpu_to_be32p()`, w    381 variation, such as :c:func:`cpu_to_be32p()`, which take a pointer
381 to the given type, and return the converted va    382 to the given type, and return the converted value. The other variation
382 is the "in-situ" family, such as :c:func:`cpu_    383 is the "in-situ" family, such as :c:func:`cpu_to_be32s()`, which
383 convert value referred to by the pointer, and     384 convert value referred to by the pointer, and return void.
384                                                   385 
385 :c:func:`local_irq_save()`/:c:func:`local_irq_    386 :c:func:`local_irq_save()`/:c:func:`local_irq_restore()`
386 ----------------------------------------------    387 --------------------------------------------------------
387                                                   388 
388 Defined in ``include/linux/irqflags.h``           389 Defined in ``include/linux/irqflags.h``
389                                                   390 
390 These routines disable hard interrupts on the     391 These routines disable hard interrupts on the local CPU, and restore
391 them. They are reentrant; saving the previous     392 them. They are reentrant; saving the previous state in their one
392 ``unsigned long flags`` argument. If you know     393 ``unsigned long flags`` argument. If you know that interrupts are
393 enabled, you can simply use :c:func:`local_irq    394 enabled, you can simply use :c:func:`local_irq_disable()` and
394 :c:func:`local_irq_enable()`.                     395 :c:func:`local_irq_enable()`.
395                                                   396 
396 .. _local_bh_disable:                             397 .. _local_bh_disable:
397                                                   398 
398 :c:func:`local_bh_disable()`/:c:func:`local_bh    399 :c:func:`local_bh_disable()`/:c:func:`local_bh_enable()`
399 ----------------------------------------------    400 --------------------------------------------------------
400                                                   401 
401 Defined in ``include/linux/bottom_half.h``        402 Defined in ``include/linux/bottom_half.h``
402                                                   403 
403                                                   404 
404 These routines disable soft interrupts on the     405 These routines disable soft interrupts on the local CPU, and restore
405 them. They are reentrant; if soft interrupts w    406 them. They are reentrant; if soft interrupts were disabled before, they
406 will still be disabled after this pair of func    407 will still be disabled after this pair of functions has been called.
407 They prevent softirqs and tasklets from runnin    408 They prevent softirqs and tasklets from running on the current CPU.
408                                                   409 
409 :c:func:`smp_processor_id()`                      410 :c:func:`smp_processor_id()`
410 ----------------------------                      411 ----------------------------
411                                                   412 
412 Defined in ``include/linux/smp.h``                413 Defined in ``include/linux/smp.h``
413                                                   414 
414 :c:func:`get_cpu()` disables preemption (so yo    415 :c:func:`get_cpu()` disables preemption (so you won't suddenly get
415 moved to another CPU) and returns the current     416 moved to another CPU) and returns the current processor number, between
416 0 and ``NR_CPUS``. Note that the CPU numbers a    417 0 and ``NR_CPUS``. Note that the CPU numbers are not necessarily
417 continuous. You return it again with :c:func:`    418 continuous. You return it again with :c:func:`put_cpu()` when you
418 are done.                                         419 are done.
419                                                   420 
420 If you know you cannot be preempted by another    421 If you know you cannot be preempted by another task (ie. you are in
421 interrupt context, or have preemption disabled    422 interrupt context, or have preemption disabled) you can use
422 smp_processor_id().                               423 smp_processor_id().
423                                                   424 
424 ``__init``/``__exit``/``__initdata``              425 ``__init``/``__exit``/``__initdata``
425 ------------------------------------              426 ------------------------------------
426                                                   427 
427 Defined in  ``include/linux/init.h``              428 Defined in  ``include/linux/init.h``
428                                                   429 
429 After boot, the kernel frees up a special sect    430 After boot, the kernel frees up a special section; functions marked with
430 ``__init`` and data structures marked with ``_    431 ``__init`` and data structures marked with ``__initdata`` are dropped
431 after boot is complete: similarly modules disc    432 after boot is complete: similarly modules discard this memory after
432 initialization. ``__exit`` is used to declare     433 initialization. ``__exit`` is used to declare a function which is only
433 required on exit: the function will be dropped    434 required on exit: the function will be dropped if this file is not
434 compiled as a module. See the header file for     435 compiled as a module. See the header file for use. Note that it makes no
435 sense for a function marked with ``__init`` to    436 sense for a function marked with ``__init`` to be exported to modules
436 with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXP    437 with :c:func:`EXPORT_SYMBOL()` or :c:func:`EXPORT_SYMBOL_GPL()`- this
437 will break.                                       438 will break.
438                                                   439 
439 :c:func:`__initcall()`/:c:func:`module_init()`    440 :c:func:`__initcall()`/:c:func:`module_init()`
440 ----------------------------------------------    441 ----------------------------------------------
441                                                   442 
442 Defined in  ``include/linux/init.h`` / ``inclu    443 Defined in  ``include/linux/init.h`` / ``include/linux/module.h``
443                                                   444 
444 Many parts of the kernel are well served as a     445 Many parts of the kernel are well served as a module
445 (dynamically-loadable parts of the kernel). Us    446 (dynamically-loadable parts of the kernel). Using the
446 :c:func:`module_init()` and :c:func:`module_ex    447 :c:func:`module_init()` and :c:func:`module_exit()` macros it
447 is easy to write code without #ifdefs which ca    448 is easy to write code without #ifdefs which can operate both as a module
448 or built into the kernel.                         449 or built into the kernel.
449                                                   450 
450 The :c:func:`module_init()` macro defines whic    451 The :c:func:`module_init()` macro defines which function is to be
451 called at module insertion time (if the file i    452 called at module insertion time (if the file is compiled as a module),
452 or at boot time: if the file is not compiled a    453 or at boot time: if the file is not compiled as a module the
453 :c:func:`module_init()` macro becomes equivale    454 :c:func:`module_init()` macro becomes equivalent to
454 :c:func:`__initcall()`, which through linker m    455 :c:func:`__initcall()`, which through linker magic ensures that
455 the function is called on boot.                   456 the function is called on boot.
456                                                   457 
457 The function can return a negative error numbe    458 The function can return a negative error number to cause module loading
458 to fail (unfortunately, this has no effect if     459 to fail (unfortunately, this has no effect if the module is compiled
459 into the kernel). This function is called in u    460 into the kernel). This function is called in user context with
460 interrupts enabled, so it can sleep.              461 interrupts enabled, so it can sleep.
461                                                   462 
462 :c:func:`module_exit()`                           463 :c:func:`module_exit()`
463 -----------------------                           464 -----------------------
464                                                   465 
465                                                   466 
466 Defined in  ``include/linux/module.h``            467 Defined in  ``include/linux/module.h``
467                                                   468 
468 This macro defines the function to be called a    469 This macro defines the function to be called at module removal time (or
469 never, in the case of the file compiled into t    470 never, in the case of the file compiled into the kernel). It will only
470 be called if the module usage count has reache    471 be called if the module usage count has reached zero. This function can
471 also sleep, but cannot fail: everything must b    472 also sleep, but cannot fail: everything must be cleaned up by the time
472 it returns.                                       473 it returns.
473                                                   474 
474 Note that this macro is optional: if it is not    475 Note that this macro is optional: if it is not present, your module will
475 not be removable (except for 'rmmod -f').         476 not be removable (except for 'rmmod -f').
476                                                   477 
477 :c:func:`try_module_get()`/:c:func:`module_put    478 :c:func:`try_module_get()`/:c:func:`module_put()`
478 ----------------------------------------------    479 -------------------------------------------------
479                                                   480 
480 Defined in ``include/linux/module.h``             481 Defined in ``include/linux/module.h``
481                                                   482 
482 These manipulate the module usage count, to pr    483 These manipulate the module usage count, to protect against removal (a
483 module also can't be removed if another module    484 module also can't be removed if another module uses one of its exported
484 symbols: see below). Before calling into modul    485 symbols: see below). Before calling into module code, you should call
485 :c:func:`try_module_get()` on that module: if     486 :c:func:`try_module_get()` on that module: if it fails, then the
486 module is being removed and you should act as     487 module is being removed and you should act as if it wasn't there.
487 Otherwise, you can safely enter the module, an    488 Otherwise, you can safely enter the module, and call
488 :c:func:`module_put()` when you're finished.      489 :c:func:`module_put()` when you're finished.
489                                                   490 
490 Most registerable structures have an owner fie    491 Most registerable structures have an owner field, such as in the
491 :c:type:`struct file_operations <file_operatio    492 :c:type:`struct file_operations <file_operations>` structure.
492 Set this field to the macro ``THIS_MODULE``.      493 Set this field to the macro ``THIS_MODULE``.
493                                                   494 
494 Wait Queues ``include/linux/wait.h``              495 Wait Queues ``include/linux/wait.h``
495 ====================================              496 ====================================
496                                                   497 
497 **[SLEEPS]**                                      498 **[SLEEPS]**
498                                                   499 
499 A wait queue is used to wait for someone to wa    500 A wait queue is used to wait for someone to wake you up when a certain
500 condition is true. They must be used carefully    501 condition is true. They must be used carefully to ensure there is no
501 race condition. You declare a :c:type:`wait_qu    502 race condition. You declare a :c:type:`wait_queue_head_t`, and then processes
502 which want to wait for that condition declare     503 which want to wait for that condition declare a :c:type:`wait_queue_entry_t`
503 referring to themselves, and place that in the    504 referring to themselves, and place that in the queue.
504                                                   505 
505 Declaring                                         506 Declaring
506 ---------                                         507 ---------
507                                                   508 
508 You declare a ``wait_queue_head_t`` using the     509 You declare a ``wait_queue_head_t`` using the
509 :c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or     510 :c:func:`DECLARE_WAIT_QUEUE_HEAD()` macro, or using the
510 :c:func:`init_waitqueue_head()` routine in you    511 :c:func:`init_waitqueue_head()` routine in your initialization
511 code.                                             512 code.
512                                                   513 
513 Queuing                                           514 Queuing
514 -------                                           515 -------
515                                                   516 
516 Placing yourself in the waitqueue is fairly co    517 Placing yourself in the waitqueue is fairly complex, because you must
517 put yourself in the queue before checking the     518 put yourself in the queue before checking the condition. There is a
518 macro to do this: :c:func:`wait_event_interrup    519 macro to do this: :c:func:`wait_event_interruptible()`
519 (``include/linux/wait.h``) The first argument     520 (``include/linux/wait.h``) The first argument is the wait queue head, and
520 the second is an expression which is evaluated    521 the second is an expression which is evaluated; the macro returns 0 when
521 this expression is true, or ``-ERESTARTSYS`` i    522 this expression is true, or ``-ERESTARTSYS`` if a signal is received. The
522 :c:func:`wait_event()` version ignores signals    523 :c:func:`wait_event()` version ignores signals.
523                                                   524 
524 Waking Up Queued Tasks                            525 Waking Up Queued Tasks
525 ----------------------                            526 ----------------------
526                                                   527 
527 Call :c:func:`wake_up()` (``include/linux/wait    528 Call :c:func:`wake_up()` (``include/linux/wait.h``), which will wake
528 up every process in the queue. The exception i    529 up every process in the queue. The exception is if one has
529 ``TASK_EXCLUSIVE`` set, in which case the rema    530 ``TASK_EXCLUSIVE`` set, in which case the remainder of the queue will
530 not be woken. There are other variants of this    531 not be woken. There are other variants of this basic function available
531 in the same header.                               532 in the same header.
532                                                   533 
533 Atomic Operations                                 534 Atomic Operations
534 =================                                 535 =================
535                                                   536 
536 Certain operations are guaranteed atomic on al    537 Certain operations are guaranteed atomic on all platforms. The first
537 class of operations work on :c:type:`atomic_t`    538 class of operations work on :c:type:`atomic_t` (``include/asm/atomic.h``);
538 this contains a signed integer (at least 32 bi    539 this contains a signed integer (at least 32 bits long), and you must use
539 these functions to manipulate or read :c:type:    540 these functions to manipulate or read :c:type:`atomic_t` variables.
540 :c:func:`atomic_read()` and :c:func:`atomic_se    541 :c:func:`atomic_read()` and :c:func:`atomic_set()` get and set
541 the counter, :c:func:`atomic_add()`, :c:func:`    542 the counter, :c:func:`atomic_add()`, :c:func:`atomic_sub()`,
542 :c:func:`atomic_inc()`, :c:func:`atomic_dec()`    543 :c:func:`atomic_inc()`, :c:func:`atomic_dec()`, and
543 :c:func:`atomic_dec_and_test()` (returns true     544 :c:func:`atomic_dec_and_test()` (returns true if it was
544 decremented to zero).                             545 decremented to zero).
545                                                   546 
546 Yes. It returns true (i.e. != 0) if the atomic    547 Yes. It returns true (i.e. != 0) if the atomic variable is zero.
547                                                   548 
548 Note that these functions are slower than norm    549 Note that these functions are slower than normal arithmetic, and so
549 should not be used unnecessarily.                 550 should not be used unnecessarily.
550                                                   551 
551 The second class of atomic operations is atomi    552 The second class of atomic operations is atomic bit operations on an
552 ``unsigned long``, defined in ``include/linux/    553 ``unsigned long``, defined in ``include/linux/bitops.h``. These
553 operations generally take a pointer to the bit    554 operations generally take a pointer to the bit pattern, and a bit
554 number: 0 is the least significant bit. :c:fun    555 number: 0 is the least significant bit. :c:func:`set_bit()`,
555 :c:func:`clear_bit()` and :c:func:`change_bit(    556 :c:func:`clear_bit()` and :c:func:`change_bit()` set, clear,
556 and flip the given bit. :c:func:`test_and_set_    557 and flip the given bit. :c:func:`test_and_set_bit()`,
557 :c:func:`test_and_clear_bit()` and                558 :c:func:`test_and_clear_bit()` and
558 :c:func:`test_and_change_bit()` do the same th    559 :c:func:`test_and_change_bit()` do the same thing, except return
559 true if the bit was previously set; these are     560 true if the bit was previously set; these are particularly useful for
560 atomically setting flags.                         561 atomically setting flags.
561                                                   562 
562 It is possible to call these operations with b    563 It is possible to call these operations with bit indices greater than
563 ``BITS_PER_LONG``. The resulting behavior is s    564 ``BITS_PER_LONG``. The resulting behavior is strange on big-endian
564 platforms though so it is a good idea not to d    565 platforms though so it is a good idea not to do this.
565                                                   566 
566 Symbols                                           567 Symbols
567 =======                                           568 =======
568                                                   569 
569 Within the kernel proper, the normal linking r    570 Within the kernel proper, the normal linking rules apply (ie. unless a
570 symbol is declared to be file scope with the `    571 symbol is declared to be file scope with the ``static`` keyword, it can
571 be used anywhere in the kernel). However, for     572 be used anywhere in the kernel). However, for modules, a special
572 exported symbol table is kept which limits the    573 exported symbol table is kept which limits the entry points to the
573 kernel proper. Modules can also export symbols    574 kernel proper. Modules can also export symbols.
574                                                   575 
575 :c:func:`EXPORT_SYMBOL()`                         576 :c:func:`EXPORT_SYMBOL()`
576 -------------------------                         577 -------------------------
577                                                   578 
578 Defined in ``include/linux/export.h``             579 Defined in ``include/linux/export.h``
579                                                   580 
580 This is the classic method of exporting a symb    581 This is the classic method of exporting a symbol: dynamically loaded
581 modules will be able to use the symbol as norm    582 modules will be able to use the symbol as normal.
582                                                   583 
583 :c:func:`EXPORT_SYMBOL_GPL()`                     584 :c:func:`EXPORT_SYMBOL_GPL()`
584 -----------------------------                     585 -----------------------------
585                                                   586 
586 Defined in ``include/linux/export.h``             587 Defined in ``include/linux/export.h``
587                                                   588 
588 Similar to :c:func:`EXPORT_SYMBOL()` except th    589 Similar to :c:func:`EXPORT_SYMBOL()` except that the symbols
589 exported by :c:func:`EXPORT_SYMBOL_GPL()` can     590 exported by :c:func:`EXPORT_SYMBOL_GPL()` can only be seen by
590 modules with a :c:func:`MODULE_LICENSE()` that    591 modules with a :c:func:`MODULE_LICENSE()` that specifies a GPL
591 compatible license. It implies that the functi    592 compatible license. It implies that the function is considered an
592 internal implementation issue, and not really     593 internal implementation issue, and not really an interface. Some
593 maintainers and developers may however require    594 maintainers and developers may however require EXPORT_SYMBOL_GPL()
594 when adding any new APIs or functionality.        595 when adding any new APIs or functionality.
595                                                   596 
596 :c:func:`EXPORT_SYMBOL_NS()`                      597 :c:func:`EXPORT_SYMBOL_NS()`
597 ----------------------------                      598 ----------------------------
598                                                   599 
599 Defined in ``include/linux/export.h``             600 Defined in ``include/linux/export.h``
600                                                   601 
601 This is the variant of `EXPORT_SYMBOL()` that     602 This is the variant of `EXPORT_SYMBOL()` that allows specifying a symbol
602 namespace. Symbol Namespaces are documented in    603 namespace. Symbol Namespaces are documented in
603 Documentation/core-api/symbol-namespaces.rst   !! 604 :doc:`../core-api/symbol-namespaces`
604                                                   605 
605 :c:func:`EXPORT_SYMBOL_NS_GPL()`                  606 :c:func:`EXPORT_SYMBOL_NS_GPL()`
606 --------------------------------                  607 --------------------------------
607                                                   608 
608 Defined in ``include/linux/export.h``             609 Defined in ``include/linux/export.h``
609                                                   610 
610 This is the variant of `EXPORT_SYMBOL_GPL()` t    611 This is the variant of `EXPORT_SYMBOL_GPL()` that allows specifying a symbol
611 namespace. Symbol Namespaces are documented in    612 namespace. Symbol Namespaces are documented in
612 Documentation/core-api/symbol-namespaces.rst   !! 613 :doc:`../core-api/symbol-namespaces`
613                                                   614 
614 Routines and Conventions                          615 Routines and Conventions
615 ========================                          616 ========================
616                                                   617 
617 Double-linked lists ``include/linux/list.h``      618 Double-linked lists ``include/linux/list.h``
618 --------------------------------------------      619 --------------------------------------------
619                                                   620 
620 There used to be three sets of linked-list rou    621 There used to be three sets of linked-list routines in the kernel
621 headers, but this one is the winner. If you do    622 headers, but this one is the winner. If you don't have some particular
622 pressing need for a single list, it's a good c    623 pressing need for a single list, it's a good choice.
623                                                   624 
624 In particular, :c:func:`list_for_each_entry()`    625 In particular, :c:func:`list_for_each_entry()` is useful.
625                                                   626 
626 Return Conventions                                627 Return Conventions
627 ------------------                                628 ------------------
628                                                   629 
629 For code called in user context, it's very com    630 For code called in user context, it's very common to defy C convention,
630 and return 0 for success, and a negative error    631 and return 0 for success, and a negative error number (eg. ``-EFAULT``) for
631 failure. This can be unintuitive at first, but    632 failure. This can be unintuitive at first, but it's fairly widespread in
632 the kernel.                                       633 the kernel.
633                                                   634 
634 Using :c:func:`ERR_PTR()` (``include/linux/err    635 Using :c:func:`ERR_PTR()` (``include/linux/err.h``) to encode a
635 negative error number into a pointer, and :c:f    636 negative error number into a pointer, and :c:func:`IS_ERR()` and
636 :c:func:`PTR_ERR()` to get it back out again:     637 :c:func:`PTR_ERR()` to get it back out again: avoids a separate
637 pointer parameter for the error number. Icky,     638 pointer parameter for the error number. Icky, but in a good way.
638                                                   639 
639 Breaking Compilation                              640 Breaking Compilation
640 --------------------                              641 --------------------
641                                                   642 
642 Linus and the other developers sometimes chang    643 Linus and the other developers sometimes change function or structure
643 names in development kernels; this is not done    644 names in development kernels; this is not done just to keep everyone on
644 their toes: it reflects a fundamental change (    645 their toes: it reflects a fundamental change (eg. can no longer be
645 called with interrupts on, or does extra check    646 called with interrupts on, or does extra checks, or doesn't do checks
646 which were caught before). Usually this is acc    647 which were caught before). Usually this is accompanied by a fairly
647 complete note to the appropriate kernel develo !! 648 complete note to the linux-kernel mailing list; search the archive.
648 the archives. Simply doing a global replace on !! 649 Simply doing a global replace on the file usually makes things **worse**.
649 things **worse**.                              << 
650                                                   650 
651 Initializing structure members                    651 Initializing structure members
652 ------------------------------                    652 ------------------------------
653                                                   653 
654 The preferred method of initializing structure    654 The preferred method of initializing structures is to use designated
655 initialisers, as defined by ISO C99, eg::         655 initialisers, as defined by ISO C99, eg::
656                                                   656 
657     static struct block_device_operations opt_    657     static struct block_device_operations opt_fops = {
658             .open               = opt_open,       658             .open               = opt_open,
659             .release            = opt_release,    659             .release            = opt_release,
660             .ioctl              = opt_ioctl,      660             .ioctl              = opt_ioctl,
661             .check_media_change = opt_media_ch    661             .check_media_change = opt_media_change,
662     };                                            662     };
663                                                   663 
664                                                   664 
665 This makes it easy to grep for, and makes it c    665 This makes it easy to grep for, and makes it clear which structure
666 fields are set. You should do this because it     666 fields are set. You should do this because it looks cool.
667                                                   667 
668 GNU Extensions                                    668 GNU Extensions
669 --------------                                    669 --------------
670                                                   670 
671 GNU Extensions are explicitly allowed in the L    671 GNU Extensions are explicitly allowed in the Linux kernel. Note that
672 some of the more complex ones are not very wel    672 some of the more complex ones are not very well supported, due to lack
673 of general use, but the following are consider    673 of general use, but the following are considered standard (see the GCC
674 info page section "C Extensions" for more deta    674 info page section "C Extensions" for more details - Yes, really the info
675 page, the man page is only a short summary of     675 page, the man page is only a short summary of the stuff in info).
676                                                   676 
677 -  Inline functions                               677 -  Inline functions
678                                                   678 
679 -  Statement expressions (ie. the ({ and }) co    679 -  Statement expressions (ie. the ({ and }) constructs).
680                                                   680 
681 -  Declaring attributes of a function / variab    681 -  Declaring attributes of a function / variable / type
682    (__attribute__)                                682    (__attribute__)
683                                                   683 
684 -  typeof                                         684 -  typeof
685                                                   685 
686 -  Zero length arrays                             686 -  Zero length arrays
687                                                   687 
688 -  Macro varargs                                  688 -  Macro varargs
689                                                   689 
690 -  Arithmetic on void pointers                    690 -  Arithmetic on void pointers
691                                                   691 
692 -  Non-Constant initializers                      692 -  Non-Constant initializers
693                                                   693 
694 -  Assembler Instructions (not outside arch/ a    694 -  Assembler Instructions (not outside arch/ and include/asm/)
695                                                   695 
696 -  Function names as strings (__func__).          696 -  Function names as strings (__func__).
697                                                   697 
698 -  __builtin_constant_p()                         698 -  __builtin_constant_p()
699                                                   699 
700 Be wary when using long long in the kernel, th    700 Be wary when using long long in the kernel, the code gcc generates for
701 it is horrible and worse: division and multipl    701 it is horrible and worse: division and multiplication does not work on
702 i386 because the GCC runtime functions for it     702 i386 because the GCC runtime functions for it are missing from the
703 kernel environment.                               703 kernel environment.
704                                                   704 
705 C++                                               705 C++
706 ---                                               706 ---
707                                                   707 
708 Using C++ in the kernel is usually a bad idea,    708 Using C++ in the kernel is usually a bad idea, because the kernel does
709 not provide the necessary runtime environment     709 not provide the necessary runtime environment and the include files are
710 not tested for it. It is still possible, but n    710 not tested for it. It is still possible, but not recommended. If you
711 really want to do this, forget about exception    711 really want to do this, forget about exceptions at least.
712                                                   712 
713 #if                                               713 #if
714 ---                                               714 ---
715                                                   715 
716 It is generally considered cleaner to use macr    716 It is generally considered cleaner to use macros in header files (or at
717 the top of .c files) to abstract away function    717 the top of .c files) to abstract away functions rather than using \`#if'
718 pre-processor statements throughout the source    718 pre-processor statements throughout the source code.
719                                                   719 
720 Putting Your Stuff in the Kernel                  720 Putting Your Stuff in the Kernel
721 ================================                  721 ================================
722                                                   722 
723 In order to get your stuff into shape for offi    723 In order to get your stuff into shape for official inclusion, or even to
724 make a neat patch, there's administrative work    724 make a neat patch, there's administrative work to be done:
725                                                   725 
726 -  Figure out who are the owners of the code y !! 726 -  Figure out whose pond you've been pissing in. Look at the top of the
727    at the top of the source files, inside the  !! 727    source files, inside the ``MAINTAINERS`` file, and last of all in the
728    last of all in the ``CREDITS`` file. You sh !! 728    ``CREDITS`` file. You should coordinate with this person to make sure
729    people to make sure you're not duplicating  !! 729    you're not duplicating effort, or trying something that's already
730    that's already been rejected.               !! 730    been rejected.
731                                                   731 
732    Make sure you put your name and email addre !! 732    Make sure you put your name and EMail address at the top of any files
733    you create or modify significantly. This is !! 733    you create or mangle significantly. This is the first place people
734    will look when they find a bug, or when **t    734    will look when they find a bug, or when **they** want to make a change.
735                                                   735 
736 -  Usually you want a configuration option for    736 -  Usually you want a configuration option for your kernel hack. Edit
737    ``Kconfig`` in the appropriate directory. T    737    ``Kconfig`` in the appropriate directory. The Config language is
738    simple to use by cut and paste, and there's    738    simple to use by cut and paste, and there's complete documentation in
739    ``Documentation/kbuild/kconfig-language.rst    739    ``Documentation/kbuild/kconfig-language.rst``.
740                                                   740 
741    In your description of the option, make sur    741    In your description of the option, make sure you address both the
742    expert user and the user who knows nothing     742    expert user and the user who knows nothing about your feature.
743    Mention incompatibilities and issues here.     743    Mention incompatibilities and issues here. **Definitely** end your
744    description with “if in doubt, say N” (    744    description with “if in doubt, say N” (or, occasionally, \`Y'); this
745    is for people who have no idea what you are    745    is for people who have no idea what you are talking about.
746                                                   746 
747 -  Edit the ``Makefile``: the CONFIG variables    747 -  Edit the ``Makefile``: the CONFIG variables are exported here so you
748    can usually just add a "obj-$(CONFIG_xxx) +    748    can usually just add a "obj-$(CONFIG_xxx) += xxx.o" line. The syntax
749    is documented in ``Documentation/kbuild/mak    749    is documented in ``Documentation/kbuild/makefiles.rst``.
750                                                   750 
751 -  Put yourself in ``CREDITS`` if you consider !! 751 -  Put yourself in ``CREDITS`` if you've done something noteworthy,
752    noteworthy, usually beyond a single file (y !! 752    usually beyond a single file (your name should be at the top of the
753    top of the source files anyway). ``MAINTAIN !! 753    source files anyway). ``MAINTAINERS`` means you want to be consulted
754    consulted when changes are made to a subsys !! 754    when changes are made to a subsystem, and hear about bugs; it implies
755    it implies a more-than-passing commitment t !! 755    a more-than-passing commitment to some part of the code.
756                                                   756 
757 -  Finally, don't forget to read                  757 -  Finally, don't forget to read
758    ``Documentation/process/submitting-patches. !! 758    ``Documentation/process/submitting-patches.rst`` and possibly
                                                   >> 759    ``Documentation/process/submitting-drivers.rst``.
759                                                   760 
760 Kernel Cantrips                                   761 Kernel Cantrips
761 ===============                                   762 ===============
762                                                   763 
763 Some favorites from browsing the source. Feel     764 Some favorites from browsing the source. Feel free to add to this list.
764                                                   765 
765 ``arch/x86/include/asm/delay.h``::                766 ``arch/x86/include/asm/delay.h``::
766                                                   767 
767     #define ndelay(n) (__builtin_constant_p(n)    768     #define ndelay(n) (__builtin_constant_p(n) ? \
768             ((n) > 20000 ? __bad_ndelay() : __    769             ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
769             __ndelay(n))                          770             __ndelay(n))
770                                                   771 
771                                                   772 
772 ``include/linux/fs.h``::                          773 ``include/linux/fs.h``::
773                                                   774 
774     /*                                            775     /*
775      * Kernel pointers have redundant informat    776      * Kernel pointers have redundant information, so we can use a
776      * scheme where we can return either an er    777      * scheme where we can return either an error code or a dentry
777      * pointer with the same return value.        778      * pointer with the same return value.
778      *                                            779      *
779      * This should be a per-architecture thing    780      * This should be a per-architecture thing, to allow different
780      * error and pointer decisions.               781      * error and pointer decisions.
781      */                                           782      */
782      #define ERR_PTR(err)    ((void *)((long)(    783      #define ERR_PTR(err)    ((void *)((long)(err)))
783      #define PTR_ERR(ptr)    ((long)(ptr))        784      #define PTR_ERR(ptr)    ((long)(ptr))
784      #define IS_ERR(ptr)     ((unsigned long)(    785      #define IS_ERR(ptr)     ((unsigned long)(ptr) > (unsigned long)(-1000))
785                                                   786 
786 ``arch/x86/include/asm/uaccess_32.h:``::          787 ``arch/x86/include/asm/uaccess_32.h:``::
787                                                   788 
788     #define copy_to_user(to,from,n)               789     #define copy_to_user(to,from,n)                         \
789             (__builtin_constant_p(n) ?            790             (__builtin_constant_p(n) ?                      \
790              __constant_copy_to_user((to),(fro    791              __constant_copy_to_user((to),(from),(n)) :     \
791              __generic_copy_to_user((to),(from    792              __generic_copy_to_user((to),(from),(n)))
792                                                   793 
793                                                   794 
794 ``arch/sparc/kernel/head.S:``::                   795 ``arch/sparc/kernel/head.S:``::
795                                                   796 
796     /*                                            797     /*
797      * Sun people can't spell worth damn. "com    798      * Sun people can't spell worth damn. "compatability" indeed.
798      * At least we *know* we can't spell, and     799      * At least we *know* we can't spell, and use a spell-checker.
799      */                                           800      */
800                                                   801 
801     /* Uh, actually Linus it is I who cannot s    802     /* Uh, actually Linus it is I who cannot spell. Too much murky
802      * Sparc assembly will do this to ya.         803      * Sparc assembly will do this to ya.
803      */                                           804      */
804     C_LABEL(cputypvar):                           805     C_LABEL(cputypvar):
805             .asciz "compatibility"                806             .asciz "compatibility"
806                                                   807 
807     /* Tested on SS-5, SS-10. Probably someone    808     /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
808             .align 4                              809             .align 4
809     C_LABEL(cputypvar_sun4m):                     810     C_LABEL(cputypvar_sun4m):
810             .asciz "compatible"                   811             .asciz "compatible"
811                                                   812 
812                                                   813 
813 ``arch/sparc/lib/checksum.S:``::                  814 ``arch/sparc/lib/checksum.S:``::
814                                                   815 
815             /* Sun, you just can't beat me, yo    816             /* Sun, you just can't beat me, you just can't.  Stop trying,
816              * give up.  I'm serious, I am goi    817              * give up.  I'm serious, I am going to kick the living shit
817              * out of you, game over, lights o    818              * out of you, game over, lights out.
818              */                                   819              */
819                                                   820 
820                                                   821 
821 Thanks                                            822 Thanks
822 ======                                            823 ======
823                                                   824 
824 Thanks to Andi Kleen for the idea, answering m    825 Thanks to Andi Kleen for the idea, answering my questions, fixing my
825 mistakes, filling content, etc. Philipp Rumpf     826 mistakes, filling content, etc. Philipp Rumpf for more spelling and
826 clarity fixes, and some excellent non-obvious     827 clarity fixes, and some excellent non-obvious points. Werner Almesberger
827 for giving me a great summary of :c:func:`disa    828 for giving me a great summary of :c:func:`disable_irq()`, and Jes
828 Sorensen and Andrea Arcangeli added caveats. M    829 Sorensen and Andrea Arcangeli added caveats. Michael Elizabeth Chastain
829 for checking and adding to the Configure secti    830 for checking and adding to the Configure section. Telsa Gwynne for
830 teaching me DocBook.                              831 teaching me DocBook.
                                                      

~ [ source navigation ] ~ [ diff markup ] ~ [ identifier search ] ~

kernel.org | git.kernel.org | LWN.net | Project Home | SVN repository | Mail admin

Linux® is a registered trademark of Linus Torvalds in the United States and other countries.
TOMOYO® is a registered trademark of NTT DATA CORPORATION.

sflogo.php