kernel-hacking.tmpl 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  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(current))
  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_ATOMIC_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. __be32 ipaddress;
  391. printk(KERN_INFO "my ip: %pI4\n", &amp;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/linux/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/linux/irqflags.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. </sect1>
  741. <sect1 id="queue-waking">
  742. <title>Waking Up Queued Tasks</title>
  743. <para>
  744. Call <function>wake_up()</function>
  745. <filename class="headerfile">include/linux/wait.h</filename>;,
  746. which will wake up every process in the queue. The exception is
  747. if one has <constant>TASK_EXCLUSIVE</constant> set, in which case
  748. the remainder of the queue will not be woken. There are other variants
  749. of this basic function available in the same header.
  750. </para>
  751. </sect1>
  752. </chapter>
  753. <chapter id="atomic-ops">
  754. <title>Atomic Operations</title>
  755. <para>
  756. Certain operations are guaranteed atomic on all platforms. The
  757. first class of operations work on <type>atomic_t</type>
  758. <filename class="headerfile">include/asm/atomic.h</filename>; this
  759. contains a signed integer (at least 32 bits long), and you must use
  760. these functions to manipulate or read atomic_t variables.
  761. <function>atomic_read()</function> and
  762. <function>atomic_set()</function> get and set the counter,
  763. <function>atomic_add()</function>,
  764. <function>atomic_sub()</function>,
  765. <function>atomic_inc()</function>,
  766. <function>atomic_dec()</function>, and
  767. <function>atomic_dec_and_test()</function> (returns
  768. <returnvalue>true</returnvalue> if it was decremented to zero).
  769. </para>
  770. <para>
  771. Yes. It returns <returnvalue>true</returnvalue> (i.e. != 0) if the
  772. atomic variable is zero.
  773. </para>
  774. <para>
  775. Note that these functions are slower than normal arithmetic, and
  776. so should not be used unnecessarily.
  777. </para>
  778. <para>
  779. The second class of atomic operations is atomic bit operations on an
  780. <type>unsigned long</type>, defined in
  781. <filename class="headerfile">include/linux/bitops.h</filename>. These
  782. operations generally take a pointer to the bit pattern, and a bit
  783. number: 0 is the least significant bit.
  784. <function>set_bit()</function>, <function>clear_bit()</function>
  785. and <function>change_bit()</function> set, clear, and flip the
  786. given bit. <function>test_and_set_bit()</function>,
  787. <function>test_and_clear_bit()</function> and
  788. <function>test_and_change_bit()</function> do the same thing,
  789. except return true if the bit was previously set; these are
  790. particularly useful for atomically setting flags.
  791. </para>
  792. <para>
  793. It is possible to call these operations with bit indices greater
  794. than BITS_PER_LONG. The resulting behavior is strange on big-endian
  795. platforms though so it is a good idea not to do this.
  796. </para>
  797. </chapter>
  798. <chapter id="symbols">
  799. <title>Symbols</title>
  800. <para>
  801. Within the kernel proper, the normal linking rules apply
  802. (ie. unless a symbol is declared to be file scope with the
  803. <type>static</type> keyword, it can be used anywhere in the
  804. kernel). However, for modules, a special exported symbol table is
  805. kept which limits the entry points to the kernel proper. Modules
  806. can also export symbols.
  807. </para>
  808. <sect1 id="sym-exportsymbols">
  809. <title><function>EXPORT_SYMBOL()</function>
  810. <filename class="headerfile">include/linux/export.h</filename></title>
  811. <para>
  812. This is the classic method of exporting a symbol: dynamically
  813. loaded modules will be able to use the symbol as normal.
  814. </para>
  815. </sect1>
  816. <sect1 id="sym-exportsymbols-gpl">
  817. <title><function>EXPORT_SYMBOL_GPL()</function>
  818. <filename class="headerfile">include/linux/export.h</filename></title>
  819. <para>
  820. Similar to <function>EXPORT_SYMBOL()</function> except that the
  821. symbols exported by <function>EXPORT_SYMBOL_GPL()</function> can
  822. only be seen by modules with a
  823. <function>MODULE_LICENSE()</function> that specifies a GPL
  824. compatible license. It implies that the function is considered
  825. an internal implementation issue, and not really an interface.
  826. Some maintainers and developers may however
  827. require EXPORT_SYMBOL_GPL() when adding any new APIs or functionality.
  828. </para>
  829. </sect1>
  830. </chapter>
  831. <chapter id="conventions">
  832. <title>Routines and Conventions</title>
  833. <sect1 id="conventions-doublelinkedlist">
  834. <title>Double-linked lists
  835. <filename class="headerfile">include/linux/list.h</filename></title>
  836. <para>
  837. There used to be three sets of linked-list routines in the kernel
  838. headers, but this one is the winner. If you don't have some
  839. particular pressing need for a single list, it's a good choice.
  840. </para>
  841. <para>
  842. In particular, <function>list_for_each_entry</function> is useful.
  843. </para>
  844. </sect1>
  845. <sect1 id="convention-returns">
  846. <title>Return Conventions</title>
  847. <para>
  848. For code called in user context, it's very common to defy C
  849. convention, and return <returnvalue>0</returnvalue> for success,
  850. and a negative error number
  851. (eg. <returnvalue>-EFAULT</returnvalue>) for failure. This can be
  852. unintuitive at first, but it's fairly widespread in the kernel.
  853. </para>
  854. <para>
  855. Using <function>ERR_PTR()</function>
  856. <filename class="headerfile">include/linux/err.h</filename>; to
  857. encode a negative error number into a pointer, and
  858. <function>IS_ERR()</function> and <function>PTR_ERR()</function>
  859. to get it back out again: avoids a separate pointer parameter for
  860. the error number. Icky, but in a good way.
  861. </para>
  862. </sect1>
  863. <sect1 id="conventions-borkedcompile">
  864. <title>Breaking Compilation</title>
  865. <para>
  866. Linus and the other developers sometimes change function or
  867. structure names in development kernels; this is not done just to
  868. keep everyone on their toes: it reflects a fundamental change
  869. (eg. can no longer be called with interrupts on, or does extra
  870. checks, or doesn't do checks which were caught before). Usually
  871. this is accompanied by a fairly complete note to the linux-kernel
  872. mailing list; search the archive. Simply doing a global replace
  873. on the file usually makes things <emphasis>worse</emphasis>.
  874. </para>
  875. </sect1>
  876. <sect1 id="conventions-initialising">
  877. <title>Initializing structure members</title>
  878. <para>
  879. The preferred method of initializing structures is to use
  880. designated initialisers, as defined by ISO C99, eg:
  881. </para>
  882. <programlisting>
  883. static struct block_device_operations opt_fops = {
  884. .open = opt_open,
  885. .release = opt_release,
  886. .ioctl = opt_ioctl,
  887. .check_media_change = opt_media_change,
  888. };
  889. </programlisting>
  890. <para>
  891. This makes it easy to grep for, and makes it clear which
  892. structure fields are set. You should do this because it looks
  893. cool.
  894. </para>
  895. </sect1>
  896. <sect1 id="conventions-gnu-extns">
  897. <title>GNU Extensions</title>
  898. <para>
  899. GNU Extensions are explicitly allowed in the Linux kernel.
  900. Note that some of the more complex ones are not very well
  901. supported, due to lack of general use, but the following are
  902. considered standard (see the GCC info page section "C
  903. Extensions" for more details - Yes, really the info page, the
  904. man page is only a short summary of the stuff in info).
  905. </para>
  906. <itemizedlist>
  907. <listitem>
  908. <para>
  909. Inline functions
  910. </para>
  911. </listitem>
  912. <listitem>
  913. <para>
  914. Statement expressions (ie. the ({ and }) constructs).
  915. </para>
  916. </listitem>
  917. <listitem>
  918. <para>
  919. Declaring attributes of a function / variable / type
  920. (__attribute__)
  921. </para>
  922. </listitem>
  923. <listitem>
  924. <para>
  925. typeof
  926. </para>
  927. </listitem>
  928. <listitem>
  929. <para>
  930. Zero length arrays
  931. </para>
  932. </listitem>
  933. <listitem>
  934. <para>
  935. Macro varargs
  936. </para>
  937. </listitem>
  938. <listitem>
  939. <para>
  940. Arithmetic on void pointers
  941. </para>
  942. </listitem>
  943. <listitem>
  944. <para>
  945. Non-Constant initializers
  946. </para>
  947. </listitem>
  948. <listitem>
  949. <para>
  950. Assembler Instructions (not outside arch/ and include/asm/)
  951. </para>
  952. </listitem>
  953. <listitem>
  954. <para>
  955. Function names as strings (__func__).
  956. </para>
  957. </listitem>
  958. <listitem>
  959. <para>
  960. __builtin_constant_p()
  961. </para>
  962. </listitem>
  963. </itemizedlist>
  964. <para>
  965. Be wary when using long long in the kernel, the code gcc generates for
  966. it is horrible and worse: division and multiplication does not work
  967. on i386 because the GCC runtime functions for it are missing from
  968. the kernel environment.
  969. </para>
  970. <!-- FIXME: add a note about ANSI aliasing cleanness -->
  971. </sect1>
  972. <sect1 id="conventions-cplusplus">
  973. <title>C++</title>
  974. <para>
  975. Using C++ in the kernel is usually a bad idea, because the
  976. kernel does not provide the necessary runtime environment
  977. and the include files are not tested for it. It is still
  978. possible, but not recommended. If you really want to do
  979. this, forget about exceptions at least.
  980. </para>
  981. </sect1>
  982. <sect1 id="conventions-ifdef">
  983. <title>&num;if</title>
  984. <para>
  985. It is generally considered cleaner to use macros in header files
  986. (or at the top of .c files) to abstract away functions rather than
  987. using `#if' pre-processor statements throughout the source code.
  988. </para>
  989. </sect1>
  990. </chapter>
  991. <chapter id="submitting">
  992. <title>Putting Your Stuff in the Kernel</title>
  993. <para>
  994. In order to get your stuff into shape for official inclusion, or
  995. even to make a neat patch, there's administrative work to be
  996. done:
  997. </para>
  998. <itemizedlist>
  999. <listitem>
  1000. <para>
  1001. Figure out whose pond you've been pissing in. Look at the top of
  1002. the source files, inside the <filename>MAINTAINERS</filename>
  1003. file, and last of all in the <filename>CREDITS</filename> file.
  1004. You should coordinate with this person to make sure you're not
  1005. duplicating effort, or trying something that's already been
  1006. rejected.
  1007. </para>
  1008. <para>
  1009. Make sure you put your name and EMail address at the top of
  1010. any files you create or mangle significantly. This is the
  1011. first place people will look when they find a bug, or when
  1012. <emphasis>they</emphasis> want to make a change.
  1013. </para>
  1014. </listitem>
  1015. <listitem>
  1016. <para>
  1017. Usually you want a configuration option for your kernel hack.
  1018. Edit <filename>Kconfig</filename> in the appropriate directory.
  1019. The Config language is simple to use by cut and paste, and there's
  1020. complete documentation in
  1021. <filename>Documentation/kbuild/kconfig-language.txt</filename>.
  1022. </para>
  1023. <para>
  1024. In your description of the option, make sure you address both the
  1025. expert user and the user who knows nothing about your feature. Mention
  1026. incompatibilities and issues here. <emphasis> Definitely
  1027. </emphasis> end your description with <quote> if in doubt, say N
  1028. </quote> (or, occasionally, `Y'); this is for people who have no
  1029. idea what you are talking about.
  1030. </para>
  1031. </listitem>
  1032. <listitem>
  1033. <para>
  1034. Edit the <filename>Makefile</filename>: the CONFIG variables are
  1035. exported here so you can usually just add a "obj-$(CONFIG_xxx) +=
  1036. xxx.o" line. The syntax is documented in
  1037. <filename>Documentation/kbuild/makefiles.txt</filename>.
  1038. </para>
  1039. </listitem>
  1040. <listitem>
  1041. <para>
  1042. Put yourself in <filename>CREDITS</filename> if you've done
  1043. something noteworthy, usually beyond a single file (your name
  1044. should be at the top of the source files anyway).
  1045. <filename>MAINTAINERS</filename> means you want to be consulted
  1046. when changes are made to a subsystem, and hear about bugs; it
  1047. implies a more-than-passing commitment to some part of the code.
  1048. </para>
  1049. </listitem>
  1050. <listitem>
  1051. <para>
  1052. Finally, don't forget to read <filename>Documentation/SubmittingPatches</filename>
  1053. and possibly <filename>Documentation/SubmittingDrivers</filename>.
  1054. </para>
  1055. </listitem>
  1056. </itemizedlist>
  1057. </chapter>
  1058. <chapter id="cantrips">
  1059. <title>Kernel Cantrips</title>
  1060. <para>
  1061. Some favorites from browsing the source. Feel free to add to this
  1062. list.
  1063. </para>
  1064. <para>
  1065. <filename>arch/x86/include/asm/delay.h:</filename>
  1066. </para>
  1067. <programlisting>
  1068. #define ndelay(n) (__builtin_constant_p(n) ? \
  1069. ((n) > 20000 ? __bad_ndelay() : __const_udelay((n) * 5ul)) : \
  1070. __ndelay(n))
  1071. </programlisting>
  1072. <para>
  1073. <filename>include/linux/fs.h</filename>:
  1074. </para>
  1075. <programlisting>
  1076. /*
  1077. * Kernel pointers have redundant information, so we can use a
  1078. * scheme where we can return either an error code or a dentry
  1079. * pointer with the same return value.
  1080. *
  1081. * This should be a per-architecture thing, to allow different
  1082. * error and pointer decisions.
  1083. */
  1084. #define ERR_PTR(err) ((void *)((long)(err)))
  1085. #define PTR_ERR(ptr) ((long)(ptr))
  1086. #define IS_ERR(ptr) ((unsigned long)(ptr) > (unsigned long)(-1000))
  1087. </programlisting>
  1088. <para>
  1089. <filename>arch/x86/include/asm/uaccess_32.h:</filename>
  1090. </para>
  1091. <programlisting>
  1092. #define copy_to_user(to,from,n) \
  1093. (__builtin_constant_p(n) ? \
  1094. __constant_copy_to_user((to),(from),(n)) : \
  1095. __generic_copy_to_user((to),(from),(n)))
  1096. </programlisting>
  1097. <para>
  1098. <filename>arch/sparc/kernel/head.S:</filename>
  1099. </para>
  1100. <programlisting>
  1101. /*
  1102. * Sun people can't spell worth damn. "compatability" indeed.
  1103. * At least we *know* we can't spell, and use a spell-checker.
  1104. */
  1105. /* Uh, actually Linus it is I who cannot spell. Too much murky
  1106. * Sparc assembly will do this to ya.
  1107. */
  1108. C_LABEL(cputypvar):
  1109. .asciz "compatibility"
  1110. /* Tested on SS-5, SS-10. Probably someone at Sun applied a spell-checker. */
  1111. .align 4
  1112. C_LABEL(cputypvar_sun4m):
  1113. .asciz "compatible"
  1114. </programlisting>
  1115. <para>
  1116. <filename>arch/sparc/lib/checksum.S:</filename>
  1117. </para>
  1118. <programlisting>
  1119. /* Sun, you just can't beat me, you just can't. Stop trying,
  1120. * give up. I'm serious, I am going to kick the living shit
  1121. * out of you, game over, lights out.
  1122. */
  1123. </programlisting>
  1124. </chapter>
  1125. <chapter id="credits">
  1126. <title>Thanks</title>
  1127. <para>
  1128. Thanks to Andi Kleen for the idea, answering my questions, fixing
  1129. my mistakes, filling content, etc. Philipp Rumpf for more spelling
  1130. and clarity fixes, and some excellent non-obvious points. Werner
  1131. Almesberger for giving me a great summary of
  1132. <function>disable_irq()</function>, and Jes Sorensen and Andrea
  1133. Arcangeli added caveats. Michael Elizabeth Chastain for checking
  1134. and adding to the Configure section. <!-- Rusty insisted on this
  1135. bit; I didn't do it! --> Telsa Gwynne for teaching me DocBook.
  1136. </para>
  1137. </chapter>
  1138. </book>