ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / Documentation / DocBook / kernel-hacking.tmpl
1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
2
3 <book id="lk-hacking-guide">
4  <bookinfo>
5   <title>Unreliable Guide To Hacking The Linux Kernel</title>
6   
7   <authorgroup>
8    <author>
9     <firstname>Paul</firstname>
10     <othername>Rusty</othername>
11     <surname>Russell</surname>
12     <affiliation>
13      <address>
14       <email>rusty@rustcorp.com.au</email>
15      </address>
16     </affiliation>
17    </author>
18   </authorgroup>
19
20   <copyright>
21    <year>2001</year>
22    <holder>Rusty Russell</holder>
23   </copyright>
24
25   <legalnotice>
26    <para>
27     This documentation is free software; you can redistribute
28     it and/or modify it under the terms of the GNU General Public
29     License as published by the Free Software Foundation; either
30     version 2 of the License, or (at your option) any later
31     version.
32    </para>
33    
34    <para>
35     This program is distributed in the hope that it will be
36     useful, but WITHOUT ANY WARRANTY; without even the implied
37     warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
38     See the GNU General Public License for more details.
39    </para>
40    
41    <para>
42     You should have received a copy of the GNU General Public
43     License along with this program; if not, write to the Free
44     Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
45     MA 02111-1307 USA
46    </para>
47    
48    <para>
49     For more details see the file COPYING in the source
50     distribution of Linux.
51    </para>
52   </legalnotice>
53
54   <releaseinfo>
55    This is the first release of this document as part of the kernel tarball.
56   </releaseinfo>
57
58  </bookinfo>
59
60  <toc></toc>
61
62  <chapter id="introduction">
63   <title>Introduction</title>
64   <para>
65    Welcome, gentle reader, to Rusty's Unreliable Guide to Linux
66    Kernel Hacking.  This document describes the common routines and
67    general requirements for kernel code: its goal is to serve as a
68    primer for Linux kernel development for experienced C
69    programmers.  I avoid implementation details: that's what the
70    code is for, and I ignore whole tracts of useful routines.
71   </para>
72   <para>
73    Before you read this, please understand that I never wanted to
74    write this document, being grossly under-qualified, but I always
75    wanted to read it, and this was the only way.  I hope it will
76    grow into a compendium of best practice, common starting points
77    and random information.
78   </para>
79  </chapter>
80
81  <chapter id="basic-players">
82   <title>The Players</title>
83
84   <para>
85    At any time each of the CPUs in a system can be:
86   </para>
87
88   <itemizedlist>
89    <listitem>
90     <para>
91      not associated with any process, serving a hardware interrupt;
92     </para>
93    </listitem>
94
95    <listitem>
96     <para>
97      not associated with any process, serving a softirq, tasklet or bh;
98     </para>
99    </listitem>
100
101    <listitem>
102     <para>
103      running in kernel space, associated with a process;
104     </para>
105    </listitem>
106
107    <listitem>
108     <para>
109      running a process in user space.
110     </para>
111    </listitem>
112   </itemizedlist>
113
114   <para>
115    There is a strict ordering between these: other than the last
116    category (userspace) each can only be pre-empted by those above.
117    For example, while a softirq is running on a CPU, no other
118    softirq will pre-empt it, but a hardware interrupt can.  However,
119    any other CPUs in the system execute independently.
120   </para>
121
122   <para>
123    We'll see a number of ways that the user context can block
124    interrupts, to become truly non-preemptable.
125   </para>
126   
127   <sect1 id="basics-usercontext">
128    <title>User Context</title>
129
130    <para>
131     User context is when you are coming in from a system call or
132     other trap: you can sleep, and you own the CPU (except for
133     interrupts) until you call <function>schedule()</function>.  
134     In other words, user context (unlike userspace) is not pre-emptable.
135    </para>
136
137    <note>
138     <para>
139      You are always in user context on module load and unload,
140      and on operations on the block device layer.
141     </para>
142    </note>
143
144    <para>
145     In user context, the <varname>current</varname> pointer (indicating 
146     the task we are currently executing) is valid, and
147     <function>in_interrupt()</function>
148     (<filename>include/asm/hardirq.h</filename>) is <returnvalue>false
149     </returnvalue>.  
150    </para>
151
152    <caution>
153     <para>
154      Beware that if you have interrupts or bottom halves disabled 
155      (see below), <function>in_interrupt()</function> will return a 
156      false positive.
157     </para>
158    </caution>
159   </sect1>
160
161   <sect1 id="basics-hardirqs">
162    <title>Hardware Interrupts (Hard IRQs)</title>
163
164    <para>
165     Timer ticks, <hardware>network cards</hardware> and 
166     <hardware>keyboard</hardware> are examples of real
167     hardware which produce interrupts at any time.  The kernel runs
168     interrupt handlers, which services the hardware.  The kernel
169     guarantees that this handler is never re-entered: if another
170     interrupt arrives, it is queued (or dropped).  Because it
171     disables interrupts, this handler has to be fast: frequently it
172     simply acknowledges the interrupt, marks a `software interrupt'
173     for execution and exits.
174    </para>
175
176    <para>
177     You can tell you are in a hardware interrupt, because 
178     <function>in_irq()</function> returns <returnvalue>true</returnvalue>.  
179    </para>
180    <caution>
181     <para>
182      Beware that this will return a false positive if interrupts are disabled 
183      (see below).
184     </para>
185    </caution>
186   </sect1>
187
188   <sect1 id="basics-softirqs">
189    <title>Software Interrupt Context: Bottom Halves, Tasklets, softirqs</title>
190
191    <para>
192     Whenever a system call is about to return to userspace, or a
193     hardware interrupt handler exits, any `software interrupts'
194     which are marked pending (usually by hardware interrupts) are
195     run (<filename>kernel/softirq.c</filename>).
196    </para>
197
198    <para>
199     Much of the real interrupt handling work is done here.  Early in
200     the transition to <acronym>SMP</acronym>, there were only `bottom 
201     halves' (BHs), which didn't take advantage of multiple CPUs.  Shortly 
202     after we switched from wind-up computers made of match-sticks and snot,
203     we abandoned this limitation.
204    </para>
205
206    <para>
207     <filename class="headerfile">include/linux/interrupt.h</filename> lists the
208     different BH's.  No matter how many CPUs you have, no two BHs will run at 
209     the same time. This made the transition to SMP simpler, but sucks hard for
210     scalable performance.  A very important bottom half is the timer
211     BH (<filename class="headerfile">include/linux/timer.h</filename>): you
212     can register to have it call functions for you in a given length of time.
213    </para>
214
215    <para>
216     2.3.43 introduced softirqs, and re-implemented the (now
217     deprecated) BHs underneath them.  Softirqs are fully-SMP
218     versions of BHs: they can run on as many CPUs at once as
219     required.  This means they need to deal with any races in shared
220     data using their own locks.  A bitmask is used to keep track of
221     which are enabled, so the 32 available softirqs should not be
222     used up lightly.  (<emphasis>Yes</emphasis>, people will
223     notice).
224    </para>
225
226    <para>
227     tasklets (<filename class="headerfile">include/linux/interrupt.h</filename>)
228     are like softirqs, except they are dynamically-registrable (meaning you 
229     can have as many as you want), and they also guarantee that any tasklet 
230     will only run on one CPU at any time, although different tasklets can 
231     run simultaneously (unlike different BHs).  
232    </para>
233    <caution>
234     <para>
235      The name `tasklet' is misleading: they have nothing to do with `tasks', 
236      and probably more to do with some bad vodka Alexey Kuznetsov had at the 
237      time.
238     </para>
239    </caution>
240
241    <para>
242     You can tell you are in a softirq (or bottom half, or tasklet)
243     using the <function>in_softirq()</function> macro 
244     (<filename class="headerfile">include/asm/hardirq.h</filename>).
245    </para>
246    <caution>
247     <para>
248      Beware that this will return a false positive if a bh lock (see below)
249      is held.
250     </para>
251    </caution>
252   </sect1>
253  </chapter>
254
255  <chapter id="basic-rules">
256   <title>Some Basic Rules</title>
257
258   <variablelist>
259    <varlistentry>
260     <term>No memory protection</term>
261     <listitem>
262      <para>
263       If you corrupt memory, whether in user context or
264       interrupt context, the whole machine will crash.  Are you
265       sure you can't do what you want in userspace?
266      </para>
267     </listitem>
268    </varlistentry>
269
270    <varlistentry>
271     <term>No floating point or <acronym>MMX</acronym></term>
272     <listitem>
273      <para>
274       The <acronym>FPU</acronym> context is not saved; even in user
275       context the <acronym>FPU</acronym> state probably won't
276       correspond with the current process: you would mess with some
277       user process' <acronym>FPU</acronym> state.  If you really want
278       to do this, you would have to explicitly save/restore the full
279       <acronym>FPU</acronym> state (and avoid context switches).  It
280       is generally a bad idea; use fixed point arithmetic first.
281      </para>
282     </listitem>
283    </varlistentry>
284
285    <varlistentry>
286     <term>A rigid stack limit</term>
287     <listitem>
288      <para>
289       The kernel stack is about 6K in 2.2 (for most
290       architectures: it's about 14K on the Alpha), and shared
291       with interrupts so you can't use it all.  Avoid deep
292       recursion and huge local arrays on the stack (allocate
293       them dynamically instead).
294      </para>
295     </listitem>
296    </varlistentry>
297
298    <varlistentry>
299     <term>The Linux kernel is portable</term>
300     <listitem>
301      <para>
302       Let's keep it that way.  Your code should be 64-bit clean,
303       and endian-independent.  You should also minimize CPU
304       specific stuff, e.g. inline assembly should be cleanly
305       encapsulated and minimized to ease porting.  Generally it
306       should be restricted to the architecture-dependent part of
307       the kernel tree.
308      </para>
309     </listitem>
310    </varlistentry>
311   </variablelist>
312  </chapter>
313
314  <chapter id="ioctls">
315   <title>ioctls: Not writing a new system call</title>
316
317   <para>
318    A system call generally looks like this
319   </para>
320
321   <programlisting>
322 asmlinkage long sys_mycall(int arg)
323 {
324         return 0; 
325 }
326   </programlisting>
327
328   <para>
329    First, in most cases you don't want to create a new system call.
330    You create a character device and implement an appropriate ioctl
331    for it.  This is much more flexible than system calls, doesn't have
332    to be entered in every architecture's
333    <filename class="headerfile">include/asm/unistd.h</filename> and
334    <filename>arch/kernel/entry.S</filename> file, and is much more
335    likely to be accepted by Linus.
336   </para>
337
338   <para>
339    If all your routine does is read or write some parameter, consider
340    implementing a <function>sysctl</function> interface instead.
341   </para>
342
343   <para>
344    Inside the ioctl you're in user context to a process.  When a
345    error occurs you return a negated errno (see
346    <filename class="headerfile">include/linux/errno.h</filename>),
347    otherwise you return <returnvalue>0</returnvalue>.
348   </para>
349
350   <para>
351    After you slept you should check if a signal occurred: the
352    Unix/Linux way of handling signals is to temporarily exit the
353    system call with the <constant>-ERESTARTSYS</constant> error.  The
354    system call entry code will switch back to user context, process
355    the signal handler and then your system call will be restarted
356    (unless the user disabled that).  So you should be prepared to
357    process the restart, e.g. if you're in the middle of manipulating
358    some data structure.
359   </para>
360
361   <programlisting>
362 if (signal_pending()) 
363         return -ERESTARTSYS;
364   </programlisting>
365
366   <para>
367    If you're doing longer computations: first think userspace. If you
368    <emphasis>really</emphasis> want to do it in kernel you should
369    regularly check if you need to give up the CPU (remember there is
370    cooperative multitasking per CPU).  Idiom:
371   </para>
372
373   <programlisting>
374 cond_resched(); /* Will sleep */ 
375   </programlisting>
376
377   <para>
378    A short note on interface design: the UNIX system call motto is
379    "Provide mechanism not policy".
380   </para>
381  </chapter>
382
383  <chapter id="deadlock-recipes">
384   <title>Recipes for Deadlock</title>
385
386   <para>
387    You cannot call any routines which may sleep, unless:
388   </para>
389   <itemizedlist>
390    <listitem>
391     <para>
392      You are in user context.
393     </para>
394    </listitem>
395
396    <listitem>
397     <para>
398      You do not own any spinlocks.
399     </para>
400    </listitem>
401
402    <listitem>
403     <para>
404      You have interrupts enabled (actually, Andi Kleen says
405      that the scheduling code will enable them for you, but
406      that's probably not what you wanted).
407     </para>
408    </listitem>
409   </itemizedlist>
410
411   <para>
412    Note that some functions may sleep implicitly: common ones are
413    the user space access functions (*_user) and memory allocation
414    functions without <symbol>GFP_ATOMIC</symbol>.
415   </para>
416
417   <para>
418    You will eventually lock up your box if you break these rules.  
419   </para>
420
421   <para>
422    Really.
423   </para>
424  </chapter>
425
426  <chapter id="common-routines">
427   <title>Common Routines</title>
428
429   <sect1 id="routines-printk">
430    <title>
431     <function>printk()</function>
432     <filename class="headerfile">include/linux/kernel.h</filename>
433    </title>
434
435    <para>
436     <function>printk()</function> feeds kernel messages to the
437     console, dmesg, and the syslog daemon.  It is useful for debugging
438     and reporting errors, and can be used inside interrupt context,
439     but use with caution: a machine which has its console flooded with
440     printk messages is unusable.  It uses a format string mostly
441     compatible with ANSI C printf, and C string concatenation to give
442     it a first "priority" argument:
443    </para>
444
445    <programlisting>
446 printk(KERN_INFO "i = %u\n", i);
447    </programlisting>
448
449    <para>
450     See <filename class="headerfile">include/linux/kernel.h</filename>;
451     for other KERN_ values; these are interpreted by syslog as the
452     level.  Special case: for printing an IP address use
453    </para>
454
455    <programlisting>
456 __u32 ipaddress;
457 printk(KERN_INFO "my ip: %d.%d.%d.%d\n", NIPQUAD(ipaddress));
458    </programlisting>
459
460    <para>
461     <function>printk()</function> internally uses a 1K buffer and does
462     not catch overruns.  Make sure that will be enough.
463    </para>
464
465    <note>
466     <para>
467      You will know when you are a real kernel hacker
468      when you start typoing printf as printk in your user programs :)
469     </para>
470    </note>
471
472    <!--- From the Lions book reader department --> 
473
474    <note>
475     <para>
476      Another sidenote: the original Unix Version 6 sources had a
477      comment on top of its printf function: "Printf should not be
478      used for chit-chat".  You should follow that advice.
479     </para>
480    </note>
481   </sect1>
482
483   <sect1 id="routines-copy">
484    <title>
485     <function>copy_[to/from]_user()</function>
486     /
487     <function>get_user()</function>
488     /
489     <function>put_user()</function>
490     <filename class="headerfile">include/asm/uaccess.h</filename>
491    </title>  
492
493    <para>
494     <emphasis>[SLEEPS]</emphasis>
495    </para>
496
497    <para>
498     <function>put_user()</function> and <function>get_user()</function>
499     are used to get and put single values (such as an int, char, or
500     long) from and to userspace.  A pointer into userspace should
501     never be simply dereferenced: data should be copied using these
502     routines.  Both return <constant>-EFAULT</constant> or 0.
503    </para>
504    <para>
505     <function>copy_to_user()</function> and
506     <function>copy_from_user()</function> are more general: they copy
507     an arbitrary amount of data to and from userspace.
508     <caution>
509      <para>
510       Unlike <function>put_user()</function> and
511       <function>get_user()</function>, they return the amount of
512       uncopied data (ie. <returnvalue>0</returnvalue> still means
513       success).
514      </para>
515     </caution>
516     [Yes, this moronic interface makes me cringe.  Please submit a
517     patch and become my hero --RR.]
518    </para>
519    <para>
520     The functions may sleep implicitly. This should never be called
521     outside user context (it makes no sense), with interrupts
522     disabled, or a spinlock held.
523    </para>
524   </sect1>
525
526   <sect1 id="routines-kmalloc">
527    <title><function>kmalloc()</function>/<function>kfree()</function>
528     <filename class="headerfile">include/linux/slab.h</filename></title>
529
530    <para>
531     <emphasis>[MAY SLEEP: SEE BELOW]</emphasis>
532    </para>
533
534    <para>
535     These routines are used to dynamically request pointer-aligned
536     chunks of memory, like malloc and free do in userspace, but
537     <function>kmalloc()</function> takes an extra flag word.
538     Important values:
539    </para>
540
541    <variablelist>
542     <varlistentry>
543      <term>
544       <constant>
545        GFP_KERNEL
546       </constant>
547      </term>
548      <listitem>
549       <para>
550        May sleep and swap to free memory. Only allowed in user
551        context, but is the most reliable way to allocate memory.
552       </para>
553      </listitem>
554     </varlistentry>
555     
556     <varlistentry>
557      <term>
558       <constant>
559        GFP_ATOMIC
560       </constant>
561      </term>
562      <listitem>
563       <para>
564        Don't sleep. Less reliable than <constant>GFP_KERNEL</constant>,
565        but may be called from interrupt context. You should
566        <emphasis>really</emphasis> have a good out-of-memory
567        error-handling strategy.
568       </para>
569      </listitem>
570     </varlistentry>
571     
572     <varlistentry>
573      <term>
574       <constant>
575        GFP_DMA
576       </constant>
577      </term>
578      <listitem>
579       <para>
580        Allocate ISA DMA lower than 16MB. If you don't know what that
581        is you don't need it.  Very unreliable.
582       </para>
583      </listitem>
584     </varlistentry>
585    </variablelist>
586
587    <para>
588     If you see a <errorname>kmem_grow: Called nonatomically from int
589     </errorname> warning message you called a memory allocation function
590     from interrupt context without <constant>GFP_ATOMIC</constant>.
591     You should really fix that.  Run, don't walk.
592    </para>
593
594    <para>
595     If you are allocating at least <constant>PAGE_SIZE</constant>
596     (<filename class="headerfile">include/asm/page.h</filename>) bytes,
597     consider using <function>__get_free_pages()</function>
598
599     (<filename class="headerfile">include/linux/mm.h</filename>).  It
600     takes an order argument (0 for page sized, 1 for double page, 2
601     for four pages etc.) and the same memory priority flag word as
602     above.
603    </para>
604
605    <para>
606     If you are allocating more than a page worth of bytes you can use
607     <function>vmalloc()</function>.  It'll allocate virtual memory in
608     the kernel map.  This block is not contiguous in physical memory,
609     but the <acronym>MMU</acronym> makes it look like it is for you
610     (so it'll only look contiguous to the CPUs, not to external device
611     drivers).  If you really need large physically contiguous memory
612     for some weird device, you have a problem: it is poorly supported
613     in Linux because after some time memory fragmentation in a running
614     kernel makes it hard.  The best way is to allocate the block early
615     in the boot process via the <function>alloc_bootmem()</function>
616     routine.
617    </para>
618
619    <para>
620     Before inventing your own cache of often-used objects consider
621     using a slab cache in
622     <filename class="headerfile">include/linux/slab.h</filename>
623    </para>
624   </sect1>
625
626   <sect1 id="routines-current">
627    <title><function>current</function>
628     <filename class="headerfile">include/asm/current.h</filename></title>
629
630    <para>
631     This global variable (really a macro) contains a pointer to
632     the current task structure, so is only valid in user context.
633     For example, when a process makes a system call, this will
634     point to the task structure of the calling process.  It is
635     <emphasis>not NULL</emphasis> in interrupt context.
636    </para>
637   </sect1>
638
639   <sect1 id="routines-udelay">
640    <title><function>udelay()</function>/<function>mdelay()</function>
641      <filename class="headerfile">include/asm/delay.h</filename>
642      <filename class="headerfile">include/linux/delay.h</filename>
643    </title>
644
645    <para>
646     The <function>udelay()</function> function can be used for small pauses.
647     Do not use large values with <function>udelay()</function> as you risk
648     overflow - the helper function <function>mdelay()</function> is useful
649     here, or even consider <function>schedule_timeout()</function>.
650    </para> 
651   </sect1>
652  
653   <sect1 id="routines-endian">
654    <title><function>cpu_to_be32()</function>/<function>be32_to_cpu()</function>/<function>cpu_to_le32()</function>/<function>le32_to_cpu()</function>
655      <filename class="headerfile">include/asm/byteorder.h</filename>
656    </title>
657
658    <para>
659     The <function>cpu_to_be32()</function> family (where the "32" can
660     be replaced by 64 or 16, and the "be" can be replaced by "le") are
661     the general way to do endian conversions in the kernel: they
662     return the converted value.  All variations supply the reverse as
663     well: <function>be32_to_cpu()</function>, etc.
664    </para>
665
666    <para>
667     There are two major variations of these functions: the pointer
668     variation, such as <function>cpu_to_be32p()</function>, which take
669     a pointer to the given type, and return the converted value.  The
670     other variation is the "in-situ" family, such as
671     <function>cpu_to_be32s()</function>, which convert value referred
672     to by the pointer, and return void.
673    </para> 
674   </sect1>
675
676   <sect1 id="routines-local-irqs">
677    <title><function>local_irq_save()</function>/<function>local_irq_restore()</function>
678     <filename class="headerfile">include/asm/system.h</filename>
679    </title>
680
681    <para>
682     These routines disable hard interrupts on the local CPU, and
683     restore them.  They are reentrant; saving the previous state in
684     their one <varname>unsigned long flags</varname> argument.  If you
685     know that interrupts are enabled, you can simply use
686     <function>local_irq_disable()</function> and
687     <function>local_irq_enable()</function>.
688    </para>
689   </sect1>
690
691   <sect1 id="routines-softirqs">
692    <title><function>local_bh_disable()</function>/<function>local_bh_enable()</function>
693     <filename class="headerfile">include/linux/interrupt.h</filename></title>
694
695    <para>
696     These routines disable soft interrupts on the local CPU, and
697     restore them.  They are reentrant; if soft interrupts were
698     disabled before, they will still be disabled after this pair
699     of functions has been called.  They prevent softirqs, tasklets
700     and bottom halves from running on the current CPU.
701    </para>
702   </sect1>
703
704   <sect1 id="routines-processorids">
705    <title><function>smp_processor_id</function>()
706     <filename class="headerfile">include/asm/smp.h</filename></title>
707    
708    <para>
709     <function>smp_processor_id()</function> returns the current
710     processor number, between 0 and <symbol>NR_CPUS</symbol> (the
711     maximum number of CPUs supported by Linux, currently 32).  These
712     values are not necessarily continuous.
713    </para>
714   </sect1>
715
716   <sect1 id="routines-init">
717    <title><type>__init</type>/<type>__exit</type>/<type>__initdata</type>
718     <filename class="headerfile">include/linux/init.h</filename></title>
719
720    <para>
721     After boot, the kernel frees up a special section; functions
722     marked with <type>__init</type> and data structures marked with
723     <type>__initdata</type> are dropped after boot is complete (within
724     modules this directive is currently ignored).  <type>__exit</type>
725     is used to declare a function which is only required on exit: the
726     function will be dropped if this file is not compiled as a module.
727     See the header file for use. Note that it makes no sense for a function
728     marked with <type>__init</type> to be exported to modules with 
729     <function>EXPORT_SYMBOL()</function> - this will break.
730    </para>
731    <para>
732    Static data structures marked as <type>__initdata</type> must be initialised
733    (as opposed to ordinary static data which is zeroed BSS) and cannot be 
734    <type>const</type>.
735    </para> 
736
737   </sect1>
738
739   <sect1 id="routines-init-again">
740    <title><function>__initcall()</function>/<function>module_init()</function>
741     <filename class="headerfile">include/linux/init.h</filename></title>
742    <para>
743     Many parts of the kernel are well served as a module
744     (dynamically-loadable parts of the kernel).  Using the
745     <function>module_init()</function> and
746     <function>module_exit()</function> macros it is easy to write code
747     without #ifdefs which can operate both as a module or built into
748     the kernel.
749    </para>
750
751    <para>
752     The <function>module_init()</function> macro defines which
753     function is to be called at module insertion time (if the file is
754     compiled as a module), or at boot time: if the file is not
755     compiled as a module the <function>module_init()</function> macro
756     becomes equivalent to <function>__initcall()</function>, which
757     through linker magic ensures that the function is called on boot.
758    </para>
759
760    <para>
761     The function can return a negative error number to cause
762     module loading to fail (unfortunately, this has no effect if
763     the module is compiled into the kernel).  For modules, this is
764     called in user context, with interrupts enabled, and the
765     kernel lock held, so it can sleep.
766    </para>
767   </sect1>
768   
769   <sect1 id="routines-moduleexit">
770    <title> <function>module_exit()</function>
771     <filename class="headerfile">include/linux/init.h</filename> </title>
772
773    <para>
774     This macro defines the function to be called at module removal
775     time (or never, in the case of the file compiled into the
776     kernel).  It will only be called if the module usage count has
777     reached zero.  This function can also sleep, but cannot fail:
778     everything must be cleaned up by the time it returns.
779    </para>
780   </sect1>
781
782   <sect1 id="routines-module-use-counters">
783    <title> <function>MOD_INC_USE_COUNT</function>/<function>MOD_DEC_USE_COUNT</function>
784     <filename class="headerfile">include/linux/module.h</filename></title>
785
786    <para>
787     These manipulate the module usage count, to protect against
788     removal (a module also can't be removed if another module uses
789     one of its exported symbols: see below).  Every reference to
790     the module from user context should be reflected by this
791     counter (e.g. for every data structure or socket) before the
792     function sleeps.  To quote Tim Waugh:
793    </para>
794
795    <programlisting>
796 /* THIS IS BAD */
797 foo_open (...)
798 {
799         stuff..
800         if (fail)
801                 return -EBUSY;
802         sleep.. (might get unloaded here)
803         stuff..
804         MOD_INC_USE_COUNT;
805         return 0;
806 }
807
808 /* THIS IS GOOD /
809 foo_open (...)
810 {
811         MOD_INC_USE_COUNT;
812         stuff..
813         if (fail) {
814                 MOD_DEC_USE_COUNT;
815                 return -EBUSY;
816         }
817         sleep.. (safe now)
818         stuff..
819         return 0;
820 }
821    </programlisting>
822
823    <para>
824    You can often avoid having to deal with these problems by using the 
825    <structfield>owner</structfield> field of the 
826    <structname>file_operations</structname> structure. Set this field
827    as the macro <symbol>THIS_MODULE</symbol>.
828    </para>
829
830    <para>
831    For more complicated module unload locking requirements, you can set the
832    <structfield>can_unload</structfield> function pointer to your own routine,
833    which should return <returnvalue>0</returnvalue> if the module is
834    unloadable, or <returnvalue>-EBUSY</returnvalue> otherwise.
835    </para> 
836   
837   </sect1>
838  </chapter>
839
840  <chapter id="queues">
841   <title>Wait Queues
842    <filename class="headerfile">include/linux/wait.h</filename>
843   </title>
844   <para>
845    <emphasis>[SLEEPS]</emphasis>
846   </para>
847
848   <para>
849    A wait queue is used to wait for someone to wake you up when a
850    certain condition is true.  They must be used carefully to ensure
851    there is no race condition.  You declare a
852    <type>wait_queue_head_t</type>, and then processes which want to
853    wait for that condition declare a <type>wait_queue_t</type>
854    referring to themselves, and place that in the queue.
855   </para>
856
857   <sect1 id="queue-declaring">
858    <title>Declaring</title>
859    
860    <para>
861     You declare a <type>wait_queue_head_t</type> using the
862     <function>DECLARE_WAIT_QUEUE_HEAD()</function> macro, or using the
863     <function>init_waitqueue_head()</function> routine in your
864     initialization code.
865    </para>
866   </sect1>
867   
868   <sect1 id="queue-waitqueue">
869    <title>Queuing</title>
870    
871    <para>
872     Placing yourself in the waitqueue is fairly complex, because you
873     must put yourself in the queue before checking the condition.
874     There is a macro to do this:
875     <function>wait_event_interruptible()</function>
876
877     <filename class="headerfile">include/linux/sched.h</filename> The
878     first argument is the wait queue head, and the second is an
879     expression which is evaluated; the macro returns
880     <returnvalue>0</returnvalue> when this expression is true, or
881     <returnvalue>-ERESTARTSYS</returnvalue> if a signal is received.
882     The <function>wait_event()</function> version ignores signals.
883    </para>
884    <para>
885    Do not use the <function>sleep_on()</function> function family -
886    it is very easy to accidentally introduce races; almost certainly
887    one of the <function>wait_event()</function> family will do, or a
888    loop around <function>schedule_timeout()</function>. If you choose
889    to loop around <function>schedule_timeout()</function> remember
890    you must set the task state (with 
891    <function>set_current_state()</function>) on each iteration to avoid
892    busy-looping.
893    </para>
894  
895   </sect1>
896
897   <sect1 id="queue-waking">
898    <title>Waking Up Queued Tasks</title>
899    
900    <para>
901     Call <function>wake_up()</function>
902
903     <filename class="headerfile">include/linux/sched.h</filename>;,
904     which will wake up every process in the queue.  The exception is
905     if one has <constant>TASK_EXCLUSIVE</constant> set, in which case
906     the remainder of the queue will not be woken.
907    </para>
908   </sect1>
909  </chapter>
910
911  <chapter id="atomic-ops">
912   <title>Atomic Operations</title>
913
914   <para>
915    Certain operations are guaranteed atomic on all platforms.  The
916    first class of operations work on <type>atomic_t</type>
917
918    <filename class="headerfile">include/asm/atomic.h</filename>; this
919    contains a signed integer (at least 24 bits long), and you must use
920    these functions to manipulate or read atomic_t variables.
921    <function>atomic_read()</function> and
922    <function>atomic_set()</function> get and set the counter,
923    <function>atomic_add()</function>,
924    <function>atomic_sub()</function>,
925    <function>atomic_inc()</function>,
926    <function>atomic_dec()</function>, and
927    <function>atomic_dec_and_test()</function> (returns
928    <returnvalue>true</returnvalue> if it was decremented to zero).
929   </para>
930
931   <para>
932    Yes.  It returns <returnvalue>true</returnvalue> (i.e. != 0) if the
933    atomic variable is zero.
934   </para>
935
936   <para>
937    Note that these functions are slower than normal arithmetic, and
938    so should not be used unnecessarily.  On some platforms they
939    are much slower, like 32-bit Sparc where they use a spinlock.
940   </para>
941
942   <para>
943    The second class of atomic operations is atomic bit operations on a
944    <type>long</type>, defined in
945
946    <filename class="headerfile">include/asm/bitops.h</filename>.  These
947    operations generally take a pointer to the bit pattern, and a bit
948    number: 0 is the least significant bit.
949    <function>set_bit()</function>, <function>clear_bit()</function>
950    and <function>change_bit()</function> set, clear, and flip the
951    given bit.  <function>test_and_set_bit()</function>,
952    <function>test_and_clear_bit()</function> and
953    <function>test_and_change_bit()</function> do the same thing,
954    except return true if the bit was previously set; these are
955    particularly useful for very simple locking.
956   </para>
957   
958   <para>
959    It is possible to call these operations with bit indices greater
960    than BITS_PER_LONG.  The resulting behavior is strange on big-endian
961    platforms though so it is a good idea not to do this.
962   </para>
963
964   <para>
965    Note that the order of bits depends on the architecture, and in
966    particular, the bitfield passed to these operations must be at
967    least as large as a <type>long</type>.
968   </para>
969  </chapter>
970
971  <chapter id="symbols">
972   <title>Symbols</title>
973
974   <para>
975    Within the kernel proper, the normal linking rules apply
976    (ie. unless a symbol is declared to be file scope with the
977    <type>static</type> keyword, it can be used anywhere in the
978    kernel).  However, for modules, a special exported symbol table is
979    kept which limits the entry points to the kernel proper.  Modules
980    can also export symbols.
981   </para>
982
983   <sect1 id="sym-exportsymbols">
984    <title><function>EXPORT_SYMBOL()</function>
985     <filename class="headerfile">include/linux/module.h</filename></title>
986
987    <para>
988     This is the classic method of exporting a symbol, and it works
989     for both modules and non-modules.  In the kernel all these
990     declarations are often bundled into a single file to help
991     genksyms (which searches source files for these declarations).
992     See the comment on genksyms and Makefiles below.
993    </para>
994   </sect1>
995
996   <sect1 id="sym-exportsymbols-gpl">
997    <title><function>EXPORT_SYMBOL_GPL()</function>
998     <filename class="headerfile">include/linux/module.h</filename></title>
999
1000    <para>
1001     Similar to <function>EXPORT_SYMBOL()</function> except that the
1002     symbols exported by <function>EXPORT_SYMBOL_GPL()</function> can
1003     only be seen by modules with a
1004     <function>MODULE_LICENSE()</function> that specifies a GPL
1005     compatible license.
1006    </para>
1007   </sect1>
1008  </chapter>
1009
1010  <chapter id="conventions">
1011   <title>Routines and Conventions</title>
1012
1013   <sect1 id="conventions-doublelinkedlist">
1014    <title>Double-linked lists
1015     <filename class="headerfile">include/linux/list.h</filename></title>
1016
1017    <para>
1018     There are three sets of linked-list routines in the kernel
1019     headers, but this one seems to be winning out (and Linus has
1020     used it).  If you don't have some particular pressing need for
1021     a single list, it's a good choice.  In fact, I don't care
1022     whether it's a good choice or not, just use it so we can get
1023     rid of the others.
1024    </para>
1025   </sect1>
1026
1027   <sect1 id="convention-returns">
1028    <title>Return Conventions</title>
1029
1030    <para>
1031     For code called in user context, it's very common to defy C
1032     convention, and return <returnvalue>0</returnvalue> for success,
1033     and a negative error number
1034     (eg. <returnvalue>-EFAULT</returnvalue>) for failure.  This can be
1035     unintuitive at first, but it's fairly widespread in the networking
1036     code, for example.
1037    </para>
1038
1039    <para>
1040     The filesystem code uses <function>ERR_PTR()</function>
1041
1042     <filename class="headerfile">include/linux/fs.h</filename>; to
1043     encode a negative error number into a pointer, and
1044     <function>IS_ERR()</function> and <function>PTR_ERR()</function>
1045     to get it back out again: avoids a separate pointer parameter for
1046     the error number.  Icky, but in a good way.
1047    </para>
1048   </sect1>
1049
1050   <sect1 id="conventions-borkedcompile">
1051    <title>Breaking Compilation</title>
1052
1053    <para>
1054     Linus and the other developers sometimes change function or
1055     structure names in development kernels; this is not done just to
1056     keep everyone on their toes: it reflects a fundamental change
1057     (eg. can no longer be called with interrupts on, or does extra
1058     checks, or doesn't do checks which were caught before).  Usually
1059     this is accompanied by a fairly complete note to the linux-kernel
1060     mailing list; search the archive.  Simply doing a global replace
1061     on the file usually makes things <emphasis>worse</emphasis>.
1062    </para>
1063   </sect1>
1064
1065   <sect1 id="conventions-initialising">
1066    <title>Initializing structure members</title>
1067
1068    <para>
1069     The preferred method of initializing structures is to use
1070     designated initialisers, as defined by ISO C99, eg:
1071    </para>
1072    <programlisting>
1073 static struct block_device_operations opt_fops = {
1074         .open               = opt_open,
1075         .release            = opt_release,
1076         .ioctl              = opt_ioctl,
1077         .check_media_change = opt_media_change,
1078 };
1079    </programlisting>
1080    <para>
1081     This makes it easy to grep for, and makes it clear which
1082     structure fields are set.  You should do this because it looks
1083     cool.
1084    </para>
1085   </sect1>
1086
1087   <sect1 id="conventions-gnu-extns">
1088    <title>GNU Extensions</title>
1089
1090    <para>
1091     GNU Extensions are explicitly allowed in the Linux kernel.
1092     Note that some of the more complex ones are not very well
1093     supported, due to lack of general use, but the following are
1094     considered standard (see the GCC info page section "C
1095     Extensions" for more details - Yes, really the info page, the
1096     man page is only a short summary of the stuff in info):
1097    </para>
1098    <itemizedlist>
1099     <listitem>
1100      <para>
1101       Inline functions
1102      </para>
1103     </listitem>
1104     <listitem>
1105      <para>
1106       Statement expressions (ie. the ({ and }) constructs).
1107      </para>
1108     </listitem>
1109     <listitem>
1110      <para>
1111       Declaring attributes of a function / variable / type
1112       (__attribute__)
1113      </para>
1114     </listitem>
1115     <listitem>
1116      <para>
1117       typeof
1118      </para>
1119     </listitem>
1120     <listitem>
1121      <para>
1122       Zero length arrays
1123      </para>
1124     </listitem>
1125     <listitem>
1126      <para>
1127       Macro varargs
1128      </para>
1129     </listitem>
1130     <listitem>
1131      <para>
1132       Arithmetic on void pointers
1133      </para>
1134     </listitem>
1135     <listitem>
1136      <para>
1137       Non-Constant initializers
1138      </para>
1139     </listitem>
1140     <listitem>
1141      <para>
1142       Assembler Instructions (not outside arch/ and include/asm/)
1143      </para>
1144     </listitem>
1145     <listitem>
1146      <para>
1147       Function names as strings (__FUNCTION__)
1148      </para>
1149     </listitem>
1150     <listitem>
1151      <para>
1152       __builtin_constant_p()
1153      </para>
1154     </listitem>
1155    </itemizedlist>
1156
1157    <para>
1158     Be wary when using long long in the kernel, the code gcc generates for
1159     it is horrible and worse: division and multiplication does not work
1160     on i386 because the GCC runtime functions for it are missing from
1161     the kernel environment.
1162    </para>
1163
1164     <!-- FIXME: add a note about ANSI aliasing cleanness -->
1165   </sect1>
1166
1167   <sect1 id="conventions-cplusplus">
1168    <title>C++</title>
1169    
1170    <para>
1171     Using C++ in the kernel is usually a bad idea, because the
1172     kernel does not provide the necessary runtime environment
1173     and the include files are not tested for it.  It is still
1174     possible, but not recommended.  If you really want to do
1175     this, forget about exceptions at least.
1176    </para>
1177   </sect1>
1178
1179   <sect1 id="conventions-ifdef">
1180    <title>&num;if</title>
1181    
1182    <para>
1183     It is generally considered cleaner to use macros in header files
1184     (or at the top of .c files) to abstract away functions rather than
1185     using `#if' pre-processor statements throughout the source code.
1186    </para>
1187   </sect1>
1188  </chapter>
1189
1190  <chapter id="submitting">
1191   <title>Putting Your Stuff in the Kernel</title>
1192
1193   <para>
1194    In order to get your stuff into shape for official inclusion, or
1195    even to make a neat patch, there's administrative work to be
1196    done:
1197   </para>
1198   <itemizedlist>
1199    <listitem>
1200     <para>
1201      Figure out whose pond you've been pissing in.  Look at the top of
1202      the source files, inside the <filename>MAINTAINERS</filename>
1203      file, and last of all in the <filename>CREDITS</filename> file.
1204      You should coordinate with this person to make sure you're not
1205      duplicating effort, or trying something that's already been
1206      rejected.
1207     </para>
1208
1209     <para>
1210      Make sure you put your name and EMail address at the top of
1211      any files you create or mangle significantly.  This is the
1212      first place people will look when they find a bug, or when
1213      <emphasis>they</emphasis> want to make a change.
1214     </para>
1215    </listitem>
1216
1217    <listitem>
1218     <para>
1219      Usually you want a configuration option for your kernel hack.
1220      Edit <filename>Config.in</filename> in the appropriate directory
1221      (but under <filename>arch/</filename> it's called
1222      <filename>config.in</filename>).  The Config Language used is not
1223      bash, even though it looks like bash; the safe way is to use only
1224      the constructs that you already see in
1225      <filename>Config.in</filename> files (see
1226      <filename>Documentation/kbuild/kconfig-language.txt</filename>).
1227      It's good to run "make xconfig" at least once to test (because
1228      it's the only one with a static parser).
1229     </para>
1230
1231     <para>
1232      Variables which can be Y or N use <type>bool</type> followed by a
1233      tagline and the config define name (which must start with
1234      CONFIG_).  The <type>tristate</type> function is the same, but
1235      allows the answer M (which defines
1236      <symbol>CONFIG_foo_MODULE</symbol> in your source, instead of
1237      <symbol>CONFIG_FOO</symbol>) if <symbol>CONFIG_MODULES</symbol>
1238      is enabled.
1239     </para>
1240
1241     <para>
1242      You may well want to make your CONFIG option only visible if
1243      <symbol>CONFIG_EXPERIMENTAL</symbol> is enabled: this serves as a
1244      warning to users.  There many other fancy things you can do: see
1245      the various <filename>Config.in</filename> files for ideas.
1246     </para>
1247    </listitem>
1248
1249    <listitem>
1250     <para>
1251      Edit the <filename>Makefile</filename>: the CONFIG variables are
1252      exported here so you can conditionalize compilation with `ifeq'.
1253      If your file exports symbols then add the names to
1254      <varname>export-objs</varname> so that genksyms will find them.
1255      <caution>
1256       <para>
1257        There is a restriction on the kernel build system that objects
1258        which export symbols must have globally unique names.
1259        If your object does not have a globally unique name then the
1260        standard fix is to move the
1261        <function>EXPORT_SYMBOL()</function> statements to their own
1262        object with a unique name.
1263        This is why several systems have separate exporting objects,
1264        usually suffixed with ksyms.
1265       </para>
1266      </caution>
1267     </para>
1268    </listitem>
1269
1270    <listitem>
1271     <para>
1272      Document your option in Documentation/Configure.help.  Mention
1273      incompatibilities and issues here.  <emphasis> Definitely
1274      </emphasis> end your description with <quote> if in doubt, say N
1275      </quote> (or, occasionally, `Y'); this is for people who have no
1276      idea what you are talking about.
1277     </para>
1278    </listitem>
1279
1280    <listitem>
1281     <para>
1282      Put yourself in <filename>CREDITS</filename> if you've done
1283      something noteworthy, usually beyond a single file (your name
1284      should be at the top of the source files anyway).
1285      <filename>MAINTAINERS</filename> means you want to be consulted
1286      when changes are made to a subsystem, and hear about bugs; it
1287      implies a more-than-passing commitment to some part of the code.
1288     </para>
1289    </listitem>
1290    
1291    <listitem>
1292     <para>
1293      Finally, don't forget to read <filename>Documentation/SubmittingPatches</filename>
1294      and possibly <filename>Documentation/SubmittingDrivers</filename>.
1295     </para>
1296    </listitem>
1297   </itemizedlist>
1298  </chapter>
1299
1300  <chapter id="cantrips">
1301   <title>Kernel Cantrips</title>
1302
1303   <para>
1304    Some favorites from browsing the source.  Feel free to add to this
1305    list.
1306   </para>
1307
1308   <para>
1309    <filename>include/linux/brlock.h:</filename>
1310   </para>
1311   <programlisting>
1312 extern inline void br_read_lock (enum brlock_indices idx)
1313 {
1314         /*
1315          * This causes a link-time bug message if an
1316          * invalid index is used:
1317          */
1318         if (idx >= __BR_END)
1319                 __br_lock_usage_bug();
1320
1321         read_lock(&amp;__brlock_array[smp_processor_id()][idx]);
1322 }
1323   </programlisting>
1324
1325   <para>
1326    <filename>include/linux/fs.h</filename>:
1327   </para>
1328   <programlisting>
1329 /*
1330  * Kernel pointers have redundant information, so we can use a
1331  * scheme where we can return either an error code or a dentry
1332  * pointer with the same return value.
1333  *
1334  * This should be a per-architecture thing, to allow different
1335  * error and pointer decisions.
1336  */
1337  #define ERR_PTR(err)    ((void *)((long)(err)))
1338  #define PTR_ERR(ptr)    ((long)(ptr))
1339  #define IS_ERR(ptr)     ((unsigned long)(ptr) > (unsigned long)(-1000))
1340 </programlisting>
1341
1342   <para>
1343    <filename>include/asm-i386/uaccess.h:</filename>
1344   </para>
1345
1346   <programlisting>
1347 #define copy_to_user(to,from,n)                         \
1348         (__builtin_constant_p(n) ?                      \
1349          __constant_copy_to_user((to),(from),(n)) :     \
1350          __generic_copy_to_user((to),(from),(n)))
1351   </programlisting>
1352
1353   <para>
1354    <filename>arch/sparc/kernel/head.S:</filename>
1355   </para>
1356
1357   <programlisting>
1358 /*
1359  * Sun people can't spell worth damn. "compatability" indeed.
1360  * At least we *know* we can't spell, and use a spell-checker.
1361  */
1362
1363 /* Uh, actually Linus it is I who cannot spell. Too much murky
1364  * Sparc assembly will do this to ya.
1365  */
1366 C_LABEL(cputypvar):
1367         .asciz "compatability"
1368
1369 /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
1370         .align 4
1371 C_LABEL(cputypvar_sun4m):
1372         .asciz "compatible"
1373   </programlisting>
1374
1375   <para>
1376    <filename>arch/sparc/lib/checksum.S:</filename>
1377   </para>
1378
1379   <programlisting>
1380         /* Sun, you just can't beat me, you just can't.  Stop trying,
1381          * give up.  I'm serious, I am going to kick the living shit
1382          * out of you, game over, lights out.
1383          */
1384   </programlisting>
1385  </chapter>
1386
1387  <chapter id="credits">
1388   <title>Thanks</title>
1389
1390   <para>
1391    Thanks to Andi Kleen for the idea, answering my questions, fixing
1392    my mistakes, filling content, etc.  Philipp Rumpf for more spelling
1393    and clarity fixes, and some excellent non-obvious points.  Werner
1394    Almesberger for giving me a great summary of
1395    <function>disable_irq()</function>, and Jes Sorensen and Andrea
1396    Arcangeli added caveats. Michael Elizabeth Chastain for checking
1397    and adding to the Configure section. <!-- Rusty insisted on this
1398    bit; I didn't do it! --> Telsa Gwynne for teaching me DocBook. 
1399   </para>
1400  </chapter>
1401 </book>
1402