kernel-hacking.tmpl 44 KB

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