kernel-hacking.tmpl 43 KB

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