kernel-locking.tmpl 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151
  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="LKLockingGuide">
  5. <bookinfo>
  6. <title>Unreliable Guide To Locking</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>2003</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. </bookinfo>
  48. <toc></toc>
  49. <chapter id="intro">
  50. <title>Introduction</title>
  51. <para>
  52. Welcome, to Rusty's Remarkably Unreliable Guide to Kernel
  53. Locking issues. This document describes the locking systems in
  54. the Linux Kernel in 2.6.
  55. </para>
  56. <para>
  57. With the wide availability of HyperThreading, and <firstterm
  58. linkend="gloss-preemption">preemption </firstterm> in the Linux
  59. Kernel, everyone hacking on the kernel needs to know the
  60. fundamentals of concurrency and locking for
  61. <firstterm linkend="gloss-smp"><acronym>SMP</acronym></firstterm>.
  62. </para>
  63. </chapter>
  64. <chapter id="races">
  65. <title>The Problem With Concurrency</title>
  66. <para>
  67. (Skip this if you know what a Race Condition is).
  68. </para>
  69. <para>
  70. In a normal program, you can increment a counter like so:
  71. </para>
  72. <programlisting>
  73. very_important_count++;
  74. </programlisting>
  75. <para>
  76. This is what they would expect to happen:
  77. </para>
  78. <table>
  79. <title>Expected Results</title>
  80. <tgroup cols="2" align="left">
  81. <thead>
  82. <row>
  83. <entry>Instance 1</entry>
  84. <entry>Instance 2</entry>
  85. </row>
  86. </thead>
  87. <tbody>
  88. <row>
  89. <entry>read very_important_count (5)</entry>
  90. <entry></entry>
  91. </row>
  92. <row>
  93. <entry>add 1 (6)</entry>
  94. <entry></entry>
  95. </row>
  96. <row>
  97. <entry>write very_important_count (6)</entry>
  98. <entry></entry>
  99. </row>
  100. <row>
  101. <entry></entry>
  102. <entry>read very_important_count (6)</entry>
  103. </row>
  104. <row>
  105. <entry></entry>
  106. <entry>add 1 (7)</entry>
  107. </row>
  108. <row>
  109. <entry></entry>
  110. <entry>write very_important_count (7)</entry>
  111. </row>
  112. </tbody>
  113. </tgroup>
  114. </table>
  115. <para>
  116. This is what might happen:
  117. </para>
  118. <table>
  119. <title>Possible Results</title>
  120. <tgroup cols="2" align="left">
  121. <thead>
  122. <row>
  123. <entry>Instance 1</entry>
  124. <entry>Instance 2</entry>
  125. </row>
  126. </thead>
  127. <tbody>
  128. <row>
  129. <entry>read very_important_count (5)</entry>
  130. <entry></entry>
  131. </row>
  132. <row>
  133. <entry></entry>
  134. <entry>read very_important_count (5)</entry>
  135. </row>
  136. <row>
  137. <entry>add 1 (6)</entry>
  138. <entry></entry>
  139. </row>
  140. <row>
  141. <entry></entry>
  142. <entry>add 1 (6)</entry>
  143. </row>
  144. <row>
  145. <entry>write very_important_count (6)</entry>
  146. <entry></entry>
  147. </row>
  148. <row>
  149. <entry></entry>
  150. <entry>write very_important_count (6)</entry>
  151. </row>
  152. </tbody>
  153. </tgroup>
  154. </table>
  155. <sect1 id="race-condition">
  156. <title>Race Conditions and Critical Regions</title>
  157. <para>
  158. This overlap, where the result depends on the
  159. relative timing of multiple tasks, is called a <firstterm>race condition</firstterm>.
  160. The piece of code containing the concurrency issue is called a
  161. <firstterm>critical region</firstterm>. And especially since Linux starting running
  162. on SMP machines, they became one of the major issues in kernel
  163. design and implementation.
  164. </para>
  165. <para>
  166. Preemption can have the same effect, even if there is only one
  167. CPU: by preempting one task during the critical region, we have
  168. exactly the same race condition. In this case the thread which
  169. preempts might run the critical region itself.
  170. </para>
  171. <para>
  172. The solution is to recognize when these simultaneous accesses
  173. occur, and use locks to make sure that only one instance can
  174. enter the critical region at any time. There are many
  175. friendly primitives in the Linux kernel to help you do this.
  176. And then there are the unfriendly primitives, but I'll pretend
  177. they don't exist.
  178. </para>
  179. </sect1>
  180. </chapter>
  181. <chapter id="locks">
  182. <title>Locking in the Linux Kernel</title>
  183. <para>
  184. If I could give you one piece of advice: never sleep with anyone
  185. crazier than yourself. But if I had to give you advice on
  186. locking: <emphasis>keep it simple</emphasis>.
  187. </para>
  188. <para>
  189. Be reluctant to introduce new locks.
  190. </para>
  191. <para>
  192. Strangely enough, this last one is the exact reverse of my advice when
  193. you <emphasis>have</emphasis> slept with someone crazier than yourself.
  194. And you should think about getting a big dog.
  195. </para>
  196. <sect1 id="lock-intro">
  197. <title>Two Main Types of Kernel Locks: Spinlocks and Mutexes</title>
  198. <para>
  199. There are two main types of kernel locks. The fundamental type
  200. is the spinlock
  201. (<filename class="headerfile">include/asm/spinlock.h</filename>),
  202. which is a very simple single-holder lock: if you can't get the
  203. spinlock, you keep trying (spinning) until you can. Spinlocks are
  204. very small and fast, and can be used anywhere.
  205. </para>
  206. <para>
  207. The second type is a mutex
  208. (<filename class="headerfile">include/linux/mutex.h</filename>): it
  209. is like a spinlock, but you may block holding a mutex.
  210. If you can't lock a mutex, your task will suspend itself, and be woken
  211. up when the mutex is released. This means the CPU can do something
  212. else while you are waiting. There are many cases when you simply
  213. can't sleep (see <xref linkend="sleeping-things"/>), and so have to
  214. use a spinlock instead.
  215. </para>
  216. <para>
  217. Neither type of lock is recursive: see
  218. <xref linkend="deadlock"/>.
  219. </para>
  220. </sect1>
  221. <sect1 id="uniprocessor">
  222. <title>Locks and Uniprocessor Kernels</title>
  223. <para>
  224. For kernels compiled without <symbol>CONFIG_SMP</symbol>, and
  225. without <symbol>CONFIG_PREEMPT</symbol> spinlocks do not exist at
  226. all. This is an excellent design decision: when no-one else can
  227. run at the same time, there is no reason to have a lock.
  228. </para>
  229. <para>
  230. If the kernel is compiled without <symbol>CONFIG_SMP</symbol>,
  231. but <symbol>CONFIG_PREEMPT</symbol> is set, then spinlocks
  232. simply disable preemption, which is sufficient to prevent any
  233. races. For most purposes, we can think of preemption as
  234. equivalent to SMP, and not worry about it separately.
  235. </para>
  236. <para>
  237. You should always test your locking code with <symbol>CONFIG_SMP</symbol>
  238. and <symbol>CONFIG_PREEMPT</symbol> enabled, even if you don't have an SMP test box, because it
  239. will still catch some kinds of locking bugs.
  240. </para>
  241. <para>
  242. Mutexes still exist, because they are required for
  243. synchronization between <firstterm linkend="gloss-usercontext">user
  244. contexts</firstterm>, as we will see below.
  245. </para>
  246. </sect1>
  247. <sect1 id="usercontextlocking">
  248. <title>Locking Only In User Context</title>
  249. <para>
  250. If you have a data structure which is only ever accessed from
  251. user context, then you can use a simple mutex
  252. (<filename>include/linux/mutex.h</filename>) to protect it. This
  253. is the most trivial case: you initialize the mutex. Then you can
  254. call <function>mutex_lock_interruptible()</function> to grab the mutex,
  255. and <function>mutex_unlock()</function> to release it. There is also a
  256. <function>mutex_lock()</function>, which should be avoided, because it
  257. will not return if a signal is received.
  258. </para>
  259. <para>
  260. Example: <filename>net/netfilter/nf_sockopt.c</filename> allows
  261. registration of new <function>setsockopt()</function> and
  262. <function>getsockopt()</function> calls, with
  263. <function>nf_register_sockopt()</function>. Registration and
  264. de-registration are only done on module load and unload (and boot
  265. time, where there is no concurrency), and the list of registrations
  266. is only consulted for an unknown <function>setsockopt()</function>
  267. or <function>getsockopt()</function> system call. The
  268. <varname>nf_sockopt_mutex</varname> is perfect to protect this,
  269. especially since the setsockopt and getsockopt calls may well
  270. sleep.
  271. </para>
  272. </sect1>
  273. <sect1 id="lock-user-bh">
  274. <title>Locking Between User Context and Softirqs</title>
  275. <para>
  276. If a <firstterm linkend="gloss-softirq">softirq</firstterm> shares
  277. data with user context, you have two problems. Firstly, the current
  278. user context can be interrupted by a softirq, and secondly, the
  279. critical region could be entered from another CPU. This is where
  280. <function>spin_lock_bh()</function>
  281. (<filename class="headerfile">include/linux/spinlock.h</filename>) is
  282. used. It disables softirqs on that CPU, then grabs the lock.
  283. <function>spin_unlock_bh()</function> does the reverse. (The
  284. '_bh' suffix is a historical reference to "Bottom Halves", the
  285. old name for software interrupts. It should really be
  286. called spin_lock_softirq()' in a perfect world).
  287. </para>
  288. <para>
  289. Note that you can also use <function>spin_lock_irq()</function>
  290. or <function>spin_lock_irqsave()</function> here, which stop
  291. hardware interrupts as well: see <xref linkend="hardirq-context"/>.
  292. </para>
  293. <para>
  294. This works perfectly for <firstterm linkend="gloss-up"><acronym>UP
  295. </acronym></firstterm> as well: the spin lock vanishes, and this macro
  296. simply becomes <function>local_bh_disable()</function>
  297. (<filename class="headerfile">include/linux/interrupt.h</filename>), which
  298. protects you from the softirq being run.
  299. </para>
  300. </sect1>
  301. <sect1 id="lock-user-tasklet">
  302. <title>Locking Between User Context and Tasklets</title>
  303. <para>
  304. This is exactly the same as above, because <firstterm
  305. linkend="gloss-tasklet">tasklets</firstterm> are actually run
  306. from a softirq.
  307. </para>
  308. </sect1>
  309. <sect1 id="lock-user-timers">
  310. <title>Locking Between User Context and Timers</title>
  311. <para>
  312. This, too, is exactly the same as above, because <firstterm
  313. linkend="gloss-timers">timers</firstterm> are actually run from
  314. a softirq. From a locking point of view, tasklets and timers
  315. are identical.
  316. </para>
  317. </sect1>
  318. <sect1 id="lock-tasklets">
  319. <title>Locking Between Tasklets/Timers</title>
  320. <para>
  321. Sometimes a tasklet or timer might want to share data with
  322. another tasklet or timer.
  323. </para>
  324. <sect2 id="lock-tasklets-same">
  325. <title>The Same Tasklet/Timer</title>
  326. <para>
  327. Since a tasklet is never run on two CPUs at once, you don't
  328. need to worry about your tasklet being reentrant (running
  329. twice at once), even on SMP.
  330. </para>
  331. </sect2>
  332. <sect2 id="lock-tasklets-different">
  333. <title>Different Tasklets/Timers</title>
  334. <para>
  335. If another tasklet/timer wants
  336. to share data with your tasklet or timer , you will both need to use
  337. <function>spin_lock()</function> and
  338. <function>spin_unlock()</function> calls.
  339. <function>spin_lock_bh()</function> is
  340. unnecessary here, as you are already in a tasklet, and
  341. none will be run on the same CPU.
  342. </para>
  343. </sect2>
  344. </sect1>
  345. <sect1 id="lock-softirqs">
  346. <title>Locking Between Softirqs</title>
  347. <para>
  348. Often a softirq might
  349. want to share data with itself or a tasklet/timer.
  350. </para>
  351. <sect2 id="lock-softirqs-same">
  352. <title>The Same Softirq</title>
  353. <para>
  354. The same softirq can run on the other CPUs: you can use a
  355. per-CPU array (see <xref linkend="per-cpu"/>) for better
  356. performance. If you're going so far as to use a softirq,
  357. you probably care about scalable performance enough
  358. to justify the extra complexity.
  359. </para>
  360. <para>
  361. You'll need to use <function>spin_lock()</function> and
  362. <function>spin_unlock()</function> for shared data.
  363. </para>
  364. </sect2>
  365. <sect2 id="lock-softirqs-different">
  366. <title>Different Softirqs</title>
  367. <para>
  368. You'll need to use <function>spin_lock()</function> and
  369. <function>spin_unlock()</function> for shared data, whether it
  370. be a timer, tasklet, different softirq or the same or another
  371. softirq: any of them could be running on a different CPU.
  372. </para>
  373. </sect2>
  374. </sect1>
  375. </chapter>
  376. <chapter id="hardirq-context">
  377. <title>Hard IRQ Context</title>
  378. <para>
  379. Hardware interrupts usually communicate with a
  380. tasklet or softirq. Frequently this involves putting work in a
  381. queue, which the softirq will take out.
  382. </para>
  383. <sect1 id="hardirq-softirq">
  384. <title>Locking Between Hard IRQ and Softirqs/Tasklets</title>
  385. <para>
  386. If a hardware irq handler shares data with a softirq, you have
  387. two concerns. Firstly, the softirq processing can be
  388. interrupted by a hardware interrupt, and secondly, the
  389. critical region could be entered by a hardware interrupt on
  390. another CPU. This is where <function>spin_lock_irq()</function> is
  391. used. It is defined to disable interrupts on that cpu, then grab
  392. the lock. <function>spin_unlock_irq()</function> does the reverse.
  393. </para>
  394. <para>
  395. The irq handler does not to use
  396. <function>spin_lock_irq()</function>, because the softirq cannot
  397. run while the irq handler is running: it can use
  398. <function>spin_lock()</function>, which is slightly faster. The
  399. only exception would be if a different hardware irq handler uses
  400. the same lock: <function>spin_lock_irq()</function> will stop
  401. that from interrupting us.
  402. </para>
  403. <para>
  404. This works perfectly for UP as well: the spin lock vanishes,
  405. and this macro simply becomes <function>local_irq_disable()</function>
  406. (<filename class="headerfile">include/asm/smp.h</filename>), which
  407. protects you from the softirq/tasklet/BH being run.
  408. </para>
  409. <para>
  410. <function>spin_lock_irqsave()</function>
  411. (<filename>include/linux/spinlock.h</filename>) is a variant
  412. which saves whether interrupts were on or off in a flags word,
  413. which is passed to <function>spin_unlock_irqrestore()</function>. This
  414. means that the same code can be used inside an hard irq handler (where
  415. interrupts are already off) and in softirqs (where the irq
  416. disabling is required).
  417. </para>
  418. <para>
  419. Note that softirqs (and hence tasklets and timers) are run on
  420. return from hardware interrupts, so
  421. <function>spin_lock_irq()</function> also stops these. In that
  422. sense, <function>spin_lock_irqsave()</function> is the most
  423. general and powerful locking function.
  424. </para>
  425. </sect1>
  426. <sect1 id="hardirq-hardirq">
  427. <title>Locking Between Two Hard IRQ Handlers</title>
  428. <para>
  429. It is rare to have to share data between two IRQ handlers, but
  430. if you do, <function>spin_lock_irqsave()</function> should be
  431. used: it is architecture-specific whether all interrupts are
  432. disabled inside irq handlers themselves.
  433. </para>
  434. </sect1>
  435. </chapter>
  436. <chapter id="cheatsheet">
  437. <title>Cheat Sheet For Locking</title>
  438. <para>
  439. Pete Zaitcev gives the following summary:
  440. </para>
  441. <itemizedlist>
  442. <listitem>
  443. <para>
  444. If you are in a process context (any syscall) and want to
  445. lock other process out, use a mutex. You can take a mutex
  446. and sleep (<function>copy_from_user*(</function> or
  447. <function>kmalloc(x,GFP_KERNEL)</function>).
  448. </para>
  449. </listitem>
  450. <listitem>
  451. <para>
  452. Otherwise (== data can be touched in an interrupt), use
  453. <function>spin_lock_irqsave()</function> and
  454. <function>spin_unlock_irqrestore()</function>.
  455. </para>
  456. </listitem>
  457. <listitem>
  458. <para>
  459. Avoid holding spinlock for more than 5 lines of code and
  460. across any function call (except accessors like
  461. <function>readb</function>).
  462. </para>
  463. </listitem>
  464. </itemizedlist>
  465. <sect1 id="minimum-lock-reqirements">
  466. <title>Table of Minimum Requirements</title>
  467. <para> The following table lists the <emphasis>minimum</emphasis>
  468. locking requirements between various contexts. In some cases,
  469. the same context can only be running on one CPU at a time, so
  470. no locking is required for that context (eg. a particular
  471. thread can only run on one CPU at a time, but if it needs
  472. shares data with another thread, locking is required).
  473. </para>
  474. <para>
  475. Remember the advice above: you can always use
  476. <function>spin_lock_irqsave()</function>, which is a superset
  477. of all other spinlock primitives.
  478. </para>
  479. <table>
  480. <title>Table of Locking Requirements</title>
  481. <tgroup cols="11">
  482. <tbody>
  483. <row>
  484. <entry></entry>
  485. <entry>IRQ Handler A</entry>
  486. <entry>IRQ Handler B</entry>
  487. <entry>Softirq A</entry>
  488. <entry>Softirq B</entry>
  489. <entry>Tasklet A</entry>
  490. <entry>Tasklet B</entry>
  491. <entry>Timer A</entry>
  492. <entry>Timer B</entry>
  493. <entry>User Context A</entry>
  494. <entry>User Context B</entry>
  495. </row>
  496. <row>
  497. <entry>IRQ Handler A</entry>
  498. <entry>None</entry>
  499. </row>
  500. <row>
  501. <entry>IRQ Handler B</entry>
  502. <entry>SLIS</entry>
  503. <entry>None</entry>
  504. </row>
  505. <row>
  506. <entry>Softirq A</entry>
  507. <entry>SLI</entry>
  508. <entry>SLI</entry>
  509. <entry>SL</entry>
  510. </row>
  511. <row>
  512. <entry>Softirq B</entry>
  513. <entry>SLI</entry>
  514. <entry>SLI</entry>
  515. <entry>SL</entry>
  516. <entry>SL</entry>
  517. </row>
  518. <row>
  519. <entry>Tasklet A</entry>
  520. <entry>SLI</entry>
  521. <entry>SLI</entry>
  522. <entry>SL</entry>
  523. <entry>SL</entry>
  524. <entry>None</entry>
  525. </row>
  526. <row>
  527. <entry>Tasklet B</entry>
  528. <entry>SLI</entry>
  529. <entry>SLI</entry>
  530. <entry>SL</entry>
  531. <entry>SL</entry>
  532. <entry>SL</entry>
  533. <entry>None</entry>
  534. </row>
  535. <row>
  536. <entry>Timer A</entry>
  537. <entry>SLI</entry>
  538. <entry>SLI</entry>
  539. <entry>SL</entry>
  540. <entry>SL</entry>
  541. <entry>SL</entry>
  542. <entry>SL</entry>
  543. <entry>None</entry>
  544. </row>
  545. <row>
  546. <entry>Timer B</entry>
  547. <entry>SLI</entry>
  548. <entry>SLI</entry>
  549. <entry>SL</entry>
  550. <entry>SL</entry>
  551. <entry>SL</entry>
  552. <entry>SL</entry>
  553. <entry>SL</entry>
  554. <entry>None</entry>
  555. </row>
  556. <row>
  557. <entry>User Context A</entry>
  558. <entry>SLI</entry>
  559. <entry>SLI</entry>
  560. <entry>SLBH</entry>
  561. <entry>SLBH</entry>
  562. <entry>SLBH</entry>
  563. <entry>SLBH</entry>
  564. <entry>SLBH</entry>
  565. <entry>SLBH</entry>
  566. <entry>None</entry>
  567. </row>
  568. <row>
  569. <entry>User Context B</entry>
  570. <entry>SLI</entry>
  571. <entry>SLI</entry>
  572. <entry>SLBH</entry>
  573. <entry>SLBH</entry>
  574. <entry>SLBH</entry>
  575. <entry>SLBH</entry>
  576. <entry>SLBH</entry>
  577. <entry>SLBH</entry>
  578. <entry>MLI</entry>
  579. <entry>None</entry>
  580. </row>
  581. </tbody>
  582. </tgroup>
  583. </table>
  584. <table>
  585. <title>Legend for Locking Requirements Table</title>
  586. <tgroup cols="2">
  587. <tbody>
  588. <row>
  589. <entry>SLIS</entry>
  590. <entry>spin_lock_irqsave</entry>
  591. </row>
  592. <row>
  593. <entry>SLI</entry>
  594. <entry>spin_lock_irq</entry>
  595. </row>
  596. <row>
  597. <entry>SL</entry>
  598. <entry>spin_lock</entry>
  599. </row>
  600. <row>
  601. <entry>SLBH</entry>
  602. <entry>spin_lock_bh</entry>
  603. </row>
  604. <row>
  605. <entry>MLI</entry>
  606. <entry>mutex_lock_interruptible</entry>
  607. </row>
  608. </tbody>
  609. </tgroup>
  610. </table>
  611. </sect1>
  612. </chapter>
  613. <chapter id="trylock-functions">
  614. <title>The trylock Functions</title>
  615. <para>
  616. There are functions that try to acquire a lock only once and immediately
  617. return a value telling about success or failure to acquire the lock.
  618. They can be used if you need no access to the data protected with the lock
  619. when some other thread is holding the lock. You should acquire the lock
  620. later if you then need access to the data protected with the lock.
  621. </para>
  622. <para>
  623. <function>spin_trylock()</function> does not spin but returns non-zero if
  624. it acquires the spinlock on the first try or 0 if not. This function can
  625. be used in all contexts like <function>spin_lock</function>: you must have
  626. disabled the contexts that might interrupt you and acquire the spin lock.
  627. </para>
  628. <para>
  629. <function>mutex_trylock()</function> does not suspend your task
  630. but returns non-zero if it could lock the mutex on the first try
  631. or 0 if not. This function cannot be safely used in hardware or software
  632. interrupt contexts despite not sleeping.
  633. </para>
  634. </chapter>
  635. <chapter id="Examples">
  636. <title>Common Examples</title>
  637. <para>
  638. Let's step through a simple example: a cache of number to name
  639. mappings. The cache keeps a count of how often each of the objects is
  640. used, and when it gets full, throws out the least used one.
  641. </para>
  642. <sect1 id="examples-usercontext">
  643. <title>All In User Context</title>
  644. <para>
  645. For our first example, we assume that all operations are in user
  646. context (ie. from system calls), so we can sleep. This means we can
  647. use a mutex to protect the cache and all the objects within
  648. it. Here's the code:
  649. </para>
  650. <programlisting>
  651. #include &lt;linux/list.h&gt;
  652. #include &lt;linux/slab.h&gt;
  653. #include &lt;linux/string.h&gt;
  654. #include &lt;linux/mutex.h&gt;
  655. #include &lt;asm/errno.h&gt;
  656. struct object
  657. {
  658. struct list_head list;
  659. int id;
  660. char name[32];
  661. int popularity;
  662. };
  663. /* Protects the cache, cache_num, and the objects within it */
  664. static DEFINE_MUTEX(cache_lock);
  665. static LIST_HEAD(cache);
  666. static unsigned int cache_num = 0;
  667. #define MAX_CACHE_SIZE 10
  668. /* Must be holding cache_lock */
  669. static struct object *__cache_find(int id)
  670. {
  671. struct object *i;
  672. list_for_each_entry(i, &amp;cache, list)
  673. if (i-&gt;id == id) {
  674. i-&gt;popularity++;
  675. return i;
  676. }
  677. return NULL;
  678. }
  679. /* Must be holding cache_lock */
  680. static void __cache_delete(struct object *obj)
  681. {
  682. BUG_ON(!obj);
  683. list_del(&amp;obj-&gt;list);
  684. kfree(obj);
  685. cache_num--;
  686. }
  687. /* Must be holding cache_lock */
  688. static void __cache_add(struct object *obj)
  689. {
  690. list_add(&amp;obj-&gt;list, &amp;cache);
  691. if (++cache_num > MAX_CACHE_SIZE) {
  692. struct object *i, *outcast = NULL;
  693. list_for_each_entry(i, &amp;cache, list) {
  694. if (!outcast || i-&gt;popularity &lt; outcast-&gt;popularity)
  695. outcast = i;
  696. }
  697. __cache_delete(outcast);
  698. }
  699. }
  700. int cache_add(int id, const char *name)
  701. {
  702. struct object *obj;
  703. if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
  704. return -ENOMEM;
  705. strlcpy(obj-&gt;name, name, sizeof(obj-&gt;name));
  706. obj-&gt;id = id;
  707. obj-&gt;popularity = 0;
  708. mutex_lock(&amp;cache_lock);
  709. __cache_add(obj);
  710. mutex_unlock(&amp;cache_lock);
  711. return 0;
  712. }
  713. void cache_delete(int id)
  714. {
  715. mutex_lock(&amp;cache_lock);
  716. __cache_delete(__cache_find(id));
  717. mutex_unlock(&amp;cache_lock);
  718. }
  719. int cache_find(int id, char *name)
  720. {
  721. struct object *obj;
  722. int ret = -ENOENT;
  723. mutex_lock(&amp;cache_lock);
  724. obj = __cache_find(id);
  725. if (obj) {
  726. ret = 0;
  727. strcpy(name, obj-&gt;name);
  728. }
  729. mutex_unlock(&amp;cache_lock);
  730. return ret;
  731. }
  732. </programlisting>
  733. <para>
  734. Note that we always make sure we have the cache_lock when we add,
  735. delete, or look up the cache: both the cache infrastructure itself and
  736. the contents of the objects are protected by the lock. In this case
  737. it's easy, since we copy the data for the user, and never let them
  738. access the objects directly.
  739. </para>
  740. <para>
  741. There is a slight (and common) optimization here: in
  742. <function>cache_add</function> we set up the fields of the object
  743. before grabbing the lock. This is safe, as no-one else can access it
  744. until we put it in cache.
  745. </para>
  746. </sect1>
  747. <sect1 id="examples-interrupt">
  748. <title>Accessing From Interrupt Context</title>
  749. <para>
  750. Now consider the case where <function>cache_find</function> can be
  751. called from interrupt context: either a hardware interrupt or a
  752. softirq. An example would be a timer which deletes object from the
  753. cache.
  754. </para>
  755. <para>
  756. The change is shown below, in standard patch format: the
  757. <symbol>-</symbol> are lines which are taken away, and the
  758. <symbol>+</symbol> are lines which are added.
  759. </para>
  760. <programlisting>
  761. --- cache.c.usercontext 2003-12-09 13:58:54.000000000 +1100
  762. +++ cache.c.interrupt 2003-12-09 14:07:49.000000000 +1100
  763. @@ -12,7 +12,7 @@
  764. int popularity;
  765. };
  766. -static DEFINE_MUTEX(cache_lock);
  767. +static DEFINE_SPINLOCK(cache_lock);
  768. static LIST_HEAD(cache);
  769. static unsigned int cache_num = 0;
  770. #define MAX_CACHE_SIZE 10
  771. @@ -55,6 +55,7 @@
  772. int cache_add(int id, const char *name)
  773. {
  774. struct object *obj;
  775. + unsigned long flags;
  776. if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
  777. return -ENOMEM;
  778. @@ -63,30 +64,33 @@
  779. obj-&gt;id = id;
  780. obj-&gt;popularity = 0;
  781. - mutex_lock(&amp;cache_lock);
  782. + spin_lock_irqsave(&amp;cache_lock, flags);
  783. __cache_add(obj);
  784. - mutex_unlock(&amp;cache_lock);
  785. + spin_unlock_irqrestore(&amp;cache_lock, flags);
  786. return 0;
  787. }
  788. void cache_delete(int id)
  789. {
  790. - mutex_lock(&amp;cache_lock);
  791. + unsigned long flags;
  792. +
  793. + spin_lock_irqsave(&amp;cache_lock, flags);
  794. __cache_delete(__cache_find(id));
  795. - mutex_unlock(&amp;cache_lock);
  796. + spin_unlock_irqrestore(&amp;cache_lock, flags);
  797. }
  798. int cache_find(int id, char *name)
  799. {
  800. struct object *obj;
  801. int ret = -ENOENT;
  802. + unsigned long flags;
  803. - mutex_lock(&amp;cache_lock);
  804. + spin_lock_irqsave(&amp;cache_lock, flags);
  805. obj = __cache_find(id);
  806. if (obj) {
  807. ret = 0;
  808. strcpy(name, obj-&gt;name);
  809. }
  810. - mutex_unlock(&amp;cache_lock);
  811. + spin_unlock_irqrestore(&amp;cache_lock, flags);
  812. return ret;
  813. }
  814. </programlisting>
  815. <para>
  816. Note that the <function>spin_lock_irqsave</function> will turn off
  817. interrupts if they are on, otherwise does nothing (if we are already
  818. in an interrupt handler), hence these functions are safe to call from
  819. any context.
  820. </para>
  821. <para>
  822. Unfortunately, <function>cache_add</function> calls
  823. <function>kmalloc</function> with the <symbol>GFP_KERNEL</symbol>
  824. flag, which is only legal in user context. I have assumed that
  825. <function>cache_add</function> is still only called in user context,
  826. otherwise this should become a parameter to
  827. <function>cache_add</function>.
  828. </para>
  829. </sect1>
  830. <sect1 id="examples-refcnt">
  831. <title>Exposing Objects Outside This File</title>
  832. <para>
  833. If our objects contained more information, it might not be sufficient
  834. to copy the information in and out: other parts of the code might want
  835. to keep pointers to these objects, for example, rather than looking up
  836. the id every time. This produces two problems.
  837. </para>
  838. <para>
  839. The first problem is that we use the <symbol>cache_lock</symbol> to
  840. protect objects: we'd need to make this non-static so the rest of the
  841. code can use it. This makes locking trickier, as it is no longer all
  842. in one place.
  843. </para>
  844. <para>
  845. The second problem is the lifetime problem: if another structure keeps
  846. a pointer to an object, it presumably expects that pointer to remain
  847. valid. Unfortunately, this is only guaranteed while you hold the
  848. lock, otherwise someone might call <function>cache_delete</function>
  849. and even worse, add another object, re-using the same address.
  850. </para>
  851. <para>
  852. As there is only one lock, you can't hold it forever: no-one else would
  853. get any work done.
  854. </para>
  855. <para>
  856. The solution to this problem is to use a reference count: everyone who
  857. has a pointer to the object increases it when they first get the
  858. object, and drops the reference count when they're finished with it.
  859. Whoever drops it to zero knows it is unused, and can actually delete it.
  860. </para>
  861. <para>
  862. Here is the code:
  863. </para>
  864. <programlisting>
  865. --- cache.c.interrupt 2003-12-09 14:25:43.000000000 +1100
  866. +++ cache.c.refcnt 2003-12-09 14:33:05.000000000 +1100
  867. @@ -7,6 +7,7 @@
  868. struct object
  869. {
  870. struct list_head list;
  871. + unsigned int refcnt;
  872. int id;
  873. char name[32];
  874. int popularity;
  875. @@ -17,6 +18,35 @@
  876. static unsigned int cache_num = 0;
  877. #define MAX_CACHE_SIZE 10
  878. +static void __object_put(struct object *obj)
  879. +{
  880. + if (--obj-&gt;refcnt == 0)
  881. + kfree(obj);
  882. +}
  883. +
  884. +static void __object_get(struct object *obj)
  885. +{
  886. + obj-&gt;refcnt++;
  887. +}
  888. +
  889. +void object_put(struct object *obj)
  890. +{
  891. + unsigned long flags;
  892. +
  893. + spin_lock_irqsave(&amp;cache_lock, flags);
  894. + __object_put(obj);
  895. + spin_unlock_irqrestore(&amp;cache_lock, flags);
  896. +}
  897. +
  898. +void object_get(struct object *obj)
  899. +{
  900. + unsigned long flags;
  901. +
  902. + spin_lock_irqsave(&amp;cache_lock, flags);
  903. + __object_get(obj);
  904. + spin_unlock_irqrestore(&amp;cache_lock, flags);
  905. +}
  906. +
  907. /* Must be holding cache_lock */
  908. static struct object *__cache_find(int id)
  909. {
  910. @@ -35,6 +65,7 @@
  911. {
  912. BUG_ON(!obj);
  913. list_del(&amp;obj-&gt;list);
  914. + __object_put(obj);
  915. cache_num--;
  916. }
  917. @@ -63,6 +94,7 @@
  918. strlcpy(obj-&gt;name, name, sizeof(obj-&gt;name));
  919. obj-&gt;id = id;
  920. obj-&gt;popularity = 0;
  921. + obj-&gt;refcnt = 1; /* The cache holds a reference */
  922. spin_lock_irqsave(&amp;cache_lock, flags);
  923. __cache_add(obj);
  924. @@ -79,18 +111,15 @@
  925. spin_unlock_irqrestore(&amp;cache_lock, flags);
  926. }
  927. -int cache_find(int id, char *name)
  928. +struct object *cache_find(int id)
  929. {
  930. struct object *obj;
  931. - int ret = -ENOENT;
  932. unsigned long flags;
  933. spin_lock_irqsave(&amp;cache_lock, flags);
  934. obj = __cache_find(id);
  935. - if (obj) {
  936. - ret = 0;
  937. - strcpy(name, obj-&gt;name);
  938. - }
  939. + if (obj)
  940. + __object_get(obj);
  941. spin_unlock_irqrestore(&amp;cache_lock, flags);
  942. - return ret;
  943. + return obj;
  944. }
  945. </programlisting>
  946. <para>
  947. We encapsulate the reference counting in the standard 'get' and 'put'
  948. functions. Now we can return the object itself from
  949. <function>cache_find</function> which has the advantage that the user
  950. can now sleep holding the object (eg. to
  951. <function>copy_to_user</function> to name to userspace).
  952. </para>
  953. <para>
  954. The other point to note is that I said a reference should be held for
  955. every pointer to the object: thus the reference count is 1 when first
  956. inserted into the cache. In some versions the framework does not hold
  957. a reference count, but they are more complicated.
  958. </para>
  959. <sect2 id="examples-refcnt-atomic">
  960. <title>Using Atomic Operations For The Reference Count</title>
  961. <para>
  962. In practice, <type>atomic_t</type> would usually be used for
  963. <structfield>refcnt</structfield>. There are a number of atomic
  964. operations defined in
  965. <filename class="headerfile">include/asm/atomic.h</filename>: these are
  966. guaranteed to be seen atomically from all CPUs in the system, so no
  967. lock is required. In this case, it is simpler than using spinlocks,
  968. although for anything non-trivial using spinlocks is clearer. The
  969. <function>atomic_inc</function> and
  970. <function>atomic_dec_and_test</function> are used instead of the
  971. standard increment and decrement operators, and the lock is no longer
  972. used to protect the reference count itself.
  973. </para>
  974. <programlisting>
  975. --- cache.c.refcnt 2003-12-09 15:00:35.000000000 +1100
  976. +++ cache.c.refcnt-atomic 2003-12-11 15:49:42.000000000 +1100
  977. @@ -7,7 +7,7 @@
  978. struct object
  979. {
  980. struct list_head list;
  981. - unsigned int refcnt;
  982. + atomic_t refcnt;
  983. int id;
  984. char name[32];
  985. int popularity;
  986. @@ -18,33 +18,15 @@
  987. static unsigned int cache_num = 0;
  988. #define MAX_CACHE_SIZE 10
  989. -static void __object_put(struct object *obj)
  990. -{
  991. - if (--obj-&gt;refcnt == 0)
  992. - kfree(obj);
  993. -}
  994. -
  995. -static void __object_get(struct object *obj)
  996. -{
  997. - obj-&gt;refcnt++;
  998. -}
  999. -
  1000. void object_put(struct object *obj)
  1001. {
  1002. - unsigned long flags;
  1003. -
  1004. - spin_lock_irqsave(&amp;cache_lock, flags);
  1005. - __object_put(obj);
  1006. - spin_unlock_irqrestore(&amp;cache_lock, flags);
  1007. + if (atomic_dec_and_test(&amp;obj-&gt;refcnt))
  1008. + kfree(obj);
  1009. }
  1010. void object_get(struct object *obj)
  1011. {
  1012. - unsigned long flags;
  1013. -
  1014. - spin_lock_irqsave(&amp;cache_lock, flags);
  1015. - __object_get(obj);
  1016. - spin_unlock_irqrestore(&amp;cache_lock, flags);
  1017. + atomic_inc(&amp;obj-&gt;refcnt);
  1018. }
  1019. /* Must be holding cache_lock */
  1020. @@ -65,7 +47,7 @@
  1021. {
  1022. BUG_ON(!obj);
  1023. list_del(&amp;obj-&gt;list);
  1024. - __object_put(obj);
  1025. + object_put(obj);
  1026. cache_num--;
  1027. }
  1028. @@ -94,7 +76,7 @@
  1029. strlcpy(obj-&gt;name, name, sizeof(obj-&gt;name));
  1030. obj-&gt;id = id;
  1031. obj-&gt;popularity = 0;
  1032. - obj-&gt;refcnt = 1; /* The cache holds a reference */
  1033. + atomic_set(&amp;obj-&gt;refcnt, 1); /* The cache holds a reference */
  1034. spin_lock_irqsave(&amp;cache_lock, flags);
  1035. __cache_add(obj);
  1036. @@ -119,7 +101,7 @@
  1037. spin_lock_irqsave(&amp;cache_lock, flags);
  1038. obj = __cache_find(id);
  1039. if (obj)
  1040. - __object_get(obj);
  1041. + object_get(obj);
  1042. spin_unlock_irqrestore(&amp;cache_lock, flags);
  1043. return obj;
  1044. }
  1045. </programlisting>
  1046. </sect2>
  1047. </sect1>
  1048. <sect1 id="examples-lock-per-obj">
  1049. <title>Protecting The Objects Themselves</title>
  1050. <para>
  1051. In these examples, we assumed that the objects (except the reference
  1052. counts) never changed once they are created. If we wanted to allow
  1053. the name to change, there are three possibilities:
  1054. </para>
  1055. <itemizedlist>
  1056. <listitem>
  1057. <para>
  1058. You can make <symbol>cache_lock</symbol> non-static, and tell people
  1059. to grab that lock before changing the name in any object.
  1060. </para>
  1061. </listitem>
  1062. <listitem>
  1063. <para>
  1064. You can provide a <function>cache_obj_rename</function> which grabs
  1065. this lock and changes the name for the caller, and tell everyone to
  1066. use that function.
  1067. </para>
  1068. </listitem>
  1069. <listitem>
  1070. <para>
  1071. You can make the <symbol>cache_lock</symbol> protect only the cache
  1072. itself, and use another lock to protect the name.
  1073. </para>
  1074. </listitem>
  1075. </itemizedlist>
  1076. <para>
  1077. Theoretically, you can make the locks as fine-grained as one lock for
  1078. every field, for every object. In practice, the most common variants
  1079. are:
  1080. </para>
  1081. <itemizedlist>
  1082. <listitem>
  1083. <para>
  1084. One lock which protects the infrastructure (the <symbol>cache</symbol>
  1085. list in this example) and all the objects. This is what we have done
  1086. so far.
  1087. </para>
  1088. </listitem>
  1089. <listitem>
  1090. <para>
  1091. One lock which protects the infrastructure (including the list
  1092. pointers inside the objects), and one lock inside the object which
  1093. protects the rest of that object.
  1094. </para>
  1095. </listitem>
  1096. <listitem>
  1097. <para>
  1098. Multiple locks to protect the infrastructure (eg. one lock per hash
  1099. chain), possibly with a separate per-object lock.
  1100. </para>
  1101. </listitem>
  1102. </itemizedlist>
  1103. <para>
  1104. Here is the "lock-per-object" implementation:
  1105. </para>
  1106. <programlisting>
  1107. --- cache.c.refcnt-atomic 2003-12-11 15:50:54.000000000 +1100
  1108. +++ cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
  1109. @@ -6,11 +6,17 @@
  1110. struct object
  1111. {
  1112. + /* These two protected by cache_lock. */
  1113. struct list_head list;
  1114. + int popularity;
  1115. +
  1116. atomic_t refcnt;
  1117. +
  1118. + /* Doesn't change once created. */
  1119. int id;
  1120. +
  1121. + spinlock_t lock; /* Protects the name */
  1122. char name[32];
  1123. - int popularity;
  1124. };
  1125. static DEFINE_SPINLOCK(cache_lock);
  1126. @@ -77,6 +84,7 @@
  1127. obj-&gt;id = id;
  1128. obj-&gt;popularity = 0;
  1129. atomic_set(&amp;obj-&gt;refcnt, 1); /* The cache holds a reference */
  1130. + spin_lock_init(&amp;obj-&gt;lock);
  1131. spin_lock_irqsave(&amp;cache_lock, flags);
  1132. __cache_add(obj);
  1133. </programlisting>
  1134. <para>
  1135. Note that I decide that the <structfield>popularity</structfield>
  1136. count should be protected by the <symbol>cache_lock</symbol> rather
  1137. than the per-object lock: this is because it (like the
  1138. <structname>struct list_head</structname> inside the object) is
  1139. logically part of the infrastructure. This way, I don't need to grab
  1140. the lock of every object in <function>__cache_add</function> when
  1141. seeking the least popular.
  1142. </para>
  1143. <para>
  1144. I also decided that the <structfield>id</structfield> member is
  1145. unchangeable, so I don't need to grab each object lock in
  1146. <function>__cache_find()</function> to examine the
  1147. <structfield>id</structfield>: the object lock is only used by a
  1148. caller who wants to read or write the <structfield>name</structfield>
  1149. field.
  1150. </para>
  1151. <para>
  1152. Note also that I added a comment describing what data was protected by
  1153. which locks. This is extremely important, as it describes the runtime
  1154. behavior of the code, and can be hard to gain from just reading. And
  1155. as Alan Cox says, <quote>Lock data, not code</quote>.
  1156. </para>
  1157. </sect1>
  1158. </chapter>
  1159. <chapter id="common-problems">
  1160. <title>Common Problems</title>
  1161. <sect1 id="deadlock">
  1162. <title>Deadlock: Simple and Advanced</title>
  1163. <para>
  1164. There is a coding bug where a piece of code tries to grab a
  1165. spinlock twice: it will spin forever, waiting for the lock to
  1166. be released (spinlocks, rwlocks and mutexes are not
  1167. recursive in Linux). This is trivial to diagnose: not a
  1168. stay-up-five-nights-talk-to-fluffy-code-bunnies kind of
  1169. problem.
  1170. </para>
  1171. <para>
  1172. For a slightly more complex case, imagine you have a region
  1173. shared by a softirq and user context. If you use a
  1174. <function>spin_lock()</function> call to protect it, it is
  1175. possible that the user context will be interrupted by the softirq
  1176. while it holds the lock, and the softirq will then spin
  1177. forever trying to get the same lock.
  1178. </para>
  1179. <para>
  1180. Both of these are called deadlock, and as shown above, it can
  1181. occur even with a single CPU (although not on UP compiles,
  1182. since spinlocks vanish on kernel compiles with
  1183. <symbol>CONFIG_SMP</symbol>=n. You'll still get data corruption
  1184. in the second example).
  1185. </para>
  1186. <para>
  1187. This complete lockup is easy to diagnose: on SMP boxes the
  1188. watchdog timer or compiling with <symbol>DEBUG_SPINLOCK</symbol> set
  1189. (<filename>include/linux/spinlock.h</filename>) will show this up
  1190. immediately when it happens.
  1191. </para>
  1192. <para>
  1193. A more complex problem is the so-called 'deadly embrace',
  1194. involving two or more locks. Say you have a hash table: each
  1195. entry in the table is a spinlock, and a chain of hashed
  1196. objects. Inside a softirq handler, you sometimes want to
  1197. alter an object from one place in the hash to another: you
  1198. grab the spinlock of the old hash chain and the spinlock of
  1199. the new hash chain, and delete the object from the old one,
  1200. and insert it in the new one.
  1201. </para>
  1202. <para>
  1203. There are two problems here. First, if your code ever
  1204. tries to move the object to the same chain, it will deadlock
  1205. with itself as it tries to lock it twice. Secondly, if the
  1206. same softirq on another CPU is trying to move another object
  1207. in the reverse direction, the following could happen:
  1208. </para>
  1209. <table>
  1210. <title>Consequences</title>
  1211. <tgroup cols="2" align="left">
  1212. <thead>
  1213. <row>
  1214. <entry>CPU 1</entry>
  1215. <entry>CPU 2</entry>
  1216. </row>
  1217. </thead>
  1218. <tbody>
  1219. <row>
  1220. <entry>Grab lock A -&gt; OK</entry>
  1221. <entry>Grab lock B -&gt; OK</entry>
  1222. </row>
  1223. <row>
  1224. <entry>Grab lock B -&gt; spin</entry>
  1225. <entry>Grab lock A -&gt; spin</entry>
  1226. </row>
  1227. </tbody>
  1228. </tgroup>
  1229. </table>
  1230. <para>
  1231. The two CPUs will spin forever, waiting for the other to give up
  1232. their lock. It will look, smell, and feel like a crash.
  1233. </para>
  1234. </sect1>
  1235. <sect1 id="techs-deadlock-prevent">
  1236. <title>Preventing Deadlock</title>
  1237. <para>
  1238. Textbooks will tell you that if you always lock in the same
  1239. order, you will never get this kind of deadlock. Practice
  1240. will tell you that this approach doesn't scale: when I
  1241. create a new lock, I don't understand enough of the kernel
  1242. to figure out where in the 5000 lock hierarchy it will fit.
  1243. </para>
  1244. <para>
  1245. The best locks are encapsulated: they never get exposed in
  1246. headers, and are never held around calls to non-trivial
  1247. functions outside the same file. You can read through this
  1248. code and see that it will never deadlock, because it never
  1249. tries to grab another lock while it has that one. People
  1250. using your code don't even need to know you are using a
  1251. lock.
  1252. </para>
  1253. <para>
  1254. A classic problem here is when you provide callbacks or
  1255. hooks: if you call these with the lock held, you risk simple
  1256. deadlock, or a deadly embrace (who knows what the callback
  1257. will do?). Remember, the other programmers are out to get
  1258. you, so don't do this.
  1259. </para>
  1260. <sect2 id="techs-deadlock-overprevent">
  1261. <title>Overzealous Prevention Of Deadlocks</title>
  1262. <para>
  1263. Deadlocks are problematic, but not as bad as data
  1264. corruption. Code which grabs a read lock, searches a list,
  1265. fails to find what it wants, drops the read lock, grabs a
  1266. write lock and inserts the object has a race condition.
  1267. </para>
  1268. <para>
  1269. If you don't see why, please stay the fuck away from my code.
  1270. </para>
  1271. </sect2>
  1272. </sect1>
  1273. <sect1 id="racing-timers">
  1274. <title>Racing Timers: A Kernel Pastime</title>
  1275. <para>
  1276. Timers can produce their own special problems with races.
  1277. Consider a collection of objects (list, hash, etc) where each
  1278. object has a timer which is due to destroy it.
  1279. </para>
  1280. <para>
  1281. If you want to destroy the entire collection (say on module
  1282. removal), you might do the following:
  1283. </para>
  1284. <programlisting>
  1285. /* THIS CODE BAD BAD BAD BAD: IF IT WAS ANY WORSE IT WOULD USE
  1286. HUNGARIAN NOTATION */
  1287. spin_lock_bh(&amp;list_lock);
  1288. while (list) {
  1289. struct foo *next = list-&gt;next;
  1290. del_timer(&amp;list-&gt;timer);
  1291. kfree(list);
  1292. list = next;
  1293. }
  1294. spin_unlock_bh(&amp;list_lock);
  1295. </programlisting>
  1296. <para>
  1297. Sooner or later, this will crash on SMP, because a timer can
  1298. have just gone off before the <function>spin_lock_bh()</function>,
  1299. and it will only get the lock after we
  1300. <function>spin_unlock_bh()</function>, and then try to free
  1301. the element (which has already been freed!).
  1302. </para>
  1303. <para>
  1304. This can be avoided by checking the result of
  1305. <function>del_timer()</function>: if it returns
  1306. <returnvalue>1</returnvalue>, the timer has been deleted.
  1307. If <returnvalue>0</returnvalue>, it means (in this
  1308. case) that it is currently running, so we can do:
  1309. </para>
  1310. <programlisting>
  1311. retry:
  1312. spin_lock_bh(&amp;list_lock);
  1313. while (list) {
  1314. struct foo *next = list-&gt;next;
  1315. if (!del_timer(&amp;list-&gt;timer)) {
  1316. /* Give timer a chance to delete this */
  1317. spin_unlock_bh(&amp;list_lock);
  1318. goto retry;
  1319. }
  1320. kfree(list);
  1321. list = next;
  1322. }
  1323. spin_unlock_bh(&amp;list_lock);
  1324. </programlisting>
  1325. <para>
  1326. Another common problem is deleting timers which restart
  1327. themselves (by calling <function>add_timer()</function> at the end
  1328. of their timer function). Because this is a fairly common case
  1329. which is prone to races, you should use <function>del_timer_sync()</function>
  1330. (<filename class="headerfile">include/linux/timer.h</filename>)
  1331. to handle this case. It returns the number of times the timer
  1332. had to be deleted before we finally stopped it from adding itself back
  1333. in.
  1334. </para>
  1335. </sect1>
  1336. </chapter>
  1337. <chapter id="Efficiency">
  1338. <title>Locking Speed</title>
  1339. <para>
  1340. There are three main things to worry about when considering speed of
  1341. some code which does locking. First is concurrency: how many things
  1342. are going to be waiting while someone else is holding a lock. Second
  1343. is the time taken to actually acquire and release an uncontended lock.
  1344. Third is using fewer, or smarter locks. I'm assuming that the lock is
  1345. used fairly often: otherwise, you wouldn't be concerned about
  1346. efficiency.
  1347. </para>
  1348. <para>
  1349. Concurrency depends on how long the lock is usually held: you should
  1350. hold the lock for as long as needed, but no longer. In the cache
  1351. example, we always create the object without the lock held, and then
  1352. grab the lock only when we are ready to insert it in the list.
  1353. </para>
  1354. <para>
  1355. Acquisition times depend on how much damage the lock operations do to
  1356. the pipeline (pipeline stalls) and how likely it is that this CPU was
  1357. the last one to grab the lock (ie. is the lock cache-hot for this
  1358. CPU): on a machine with more CPUs, this likelihood drops fast.
  1359. Consider a 700MHz Intel Pentium III: an instruction takes about 0.7ns,
  1360. an atomic increment takes about 58ns, a lock which is cache-hot on
  1361. this CPU takes 160ns, and a cacheline transfer from another CPU takes
  1362. an additional 170 to 360ns. (These figures from Paul McKenney's
  1363. <ulink url="http://www.linuxjournal.com/article.php?sid=6993"> Linux
  1364. Journal RCU article</ulink>).
  1365. </para>
  1366. <para>
  1367. These two aims conflict: holding a lock for a short time might be done
  1368. by splitting locks into parts (such as in our final per-object-lock
  1369. example), but this increases the number of lock acquisitions, and the
  1370. results are often slower than having a single lock. This is another
  1371. reason to advocate locking simplicity.
  1372. </para>
  1373. <para>
  1374. The third concern is addressed below: there are some methods to reduce
  1375. the amount of locking which needs to be done.
  1376. </para>
  1377. <sect1 id="efficiency-rwlocks">
  1378. <title>Read/Write Lock Variants</title>
  1379. <para>
  1380. Both spinlocks and mutexes have read/write variants:
  1381. <type>rwlock_t</type> and <structname>struct rw_semaphore</structname>.
  1382. These divide users into two classes: the readers and the writers. If
  1383. you are only reading the data, you can get a read lock, but to write to
  1384. the data you need the write lock. Many people can hold a read lock,
  1385. but a writer must be sole holder.
  1386. </para>
  1387. <para>
  1388. If your code divides neatly along reader/writer lines (as our
  1389. cache code does), and the lock is held by readers for
  1390. significant lengths of time, using these locks can help. They
  1391. are slightly slower than the normal locks though, so in practice
  1392. <type>rwlock_t</type> is not usually worthwhile.
  1393. </para>
  1394. </sect1>
  1395. <sect1 id="efficiency-read-copy-update">
  1396. <title>Avoiding Locks: Read Copy Update</title>
  1397. <para>
  1398. There is a special method of read/write locking called Read Copy
  1399. Update. Using RCU, the readers can avoid taking a lock
  1400. altogether: as we expect our cache to be read more often than
  1401. updated (otherwise the cache is a waste of time), it is a
  1402. candidate for this optimization.
  1403. </para>
  1404. <para>
  1405. How do we get rid of read locks? Getting rid of read locks
  1406. means that writers may be changing the list underneath the
  1407. readers. That is actually quite simple: we can read a linked
  1408. list while an element is being added if the writer adds the
  1409. element very carefully. For example, adding
  1410. <symbol>new</symbol> to a single linked list called
  1411. <symbol>list</symbol>:
  1412. </para>
  1413. <programlisting>
  1414. new-&gt;next = list-&gt;next;
  1415. wmb();
  1416. list-&gt;next = new;
  1417. </programlisting>
  1418. <para>
  1419. The <function>wmb()</function> is a write memory barrier. It
  1420. ensures that the first operation (setting the new element's
  1421. <symbol>next</symbol> pointer) is complete and will be seen by
  1422. all CPUs, before the second operation is (putting the new
  1423. element into the list). This is important, since modern
  1424. compilers and modern CPUs can both reorder instructions unless
  1425. told otherwise: we want a reader to either not see the new
  1426. element at all, or see the new element with the
  1427. <symbol>next</symbol> pointer correctly pointing at the rest of
  1428. the list.
  1429. </para>
  1430. <para>
  1431. Fortunately, there is a function to do this for standard
  1432. <structname>struct list_head</structname> lists:
  1433. <function>list_add_rcu()</function>
  1434. (<filename>include/linux/list.h</filename>).
  1435. </para>
  1436. <para>
  1437. Removing an element from the list is even simpler: we replace
  1438. the pointer to the old element with a pointer to its successor,
  1439. and readers will either see it, or skip over it.
  1440. </para>
  1441. <programlisting>
  1442. list-&gt;next = old-&gt;next;
  1443. </programlisting>
  1444. <para>
  1445. There is <function>list_del_rcu()</function>
  1446. (<filename>include/linux/list.h</filename>) which does this (the
  1447. normal version poisons the old object, which we don't want).
  1448. </para>
  1449. <para>
  1450. The reader must also be careful: some CPUs can look through the
  1451. <symbol>next</symbol> pointer to start reading the contents of
  1452. the next element early, but don't realize that the pre-fetched
  1453. contents is wrong when the <symbol>next</symbol> pointer changes
  1454. underneath them. Once again, there is a
  1455. <function>list_for_each_entry_rcu()</function>
  1456. (<filename>include/linux/list.h</filename>) to help you. Of
  1457. course, writers can just use
  1458. <function>list_for_each_entry()</function>, since there cannot
  1459. be two simultaneous writers.
  1460. </para>
  1461. <para>
  1462. Our final dilemma is this: when can we actually destroy the
  1463. removed element? Remember, a reader might be stepping through
  1464. this element in the list right now: if we free this element and
  1465. the <symbol>next</symbol> pointer changes, the reader will jump
  1466. off into garbage and crash. We need to wait until we know that
  1467. all the readers who were traversing the list when we deleted the
  1468. element are finished. We use <function>call_rcu()</function> to
  1469. register a callback which will actually destroy the object once
  1470. all pre-existing readers are finished. Alternatively,
  1471. <function>synchronize_rcu()</function> may be used to block until
  1472. all pre-existing are finished.
  1473. </para>
  1474. <para>
  1475. But how does Read Copy Update know when the readers are
  1476. finished? The method is this: firstly, the readers always
  1477. traverse the list inside
  1478. <function>rcu_read_lock()</function>/<function>rcu_read_unlock()</function>
  1479. pairs: these simply disable preemption so the reader won't go to
  1480. sleep while reading the list.
  1481. </para>
  1482. <para>
  1483. RCU then waits until every other CPU has slept at least once:
  1484. since readers cannot sleep, we know that any readers which were
  1485. traversing the list during the deletion are finished, and the
  1486. callback is triggered. The real Read Copy Update code is a
  1487. little more optimized than this, but this is the fundamental
  1488. idea.
  1489. </para>
  1490. <programlisting>
  1491. --- cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
  1492. +++ cache.c.rcupdate 2003-12-11 17:55:14.000000000 +1100
  1493. @@ -1,15 +1,18 @@
  1494. #include &lt;linux/list.h&gt;
  1495. #include &lt;linux/slab.h&gt;
  1496. #include &lt;linux/string.h&gt;
  1497. +#include &lt;linux/rcupdate.h&gt;
  1498. #include &lt;linux/mutex.h&gt;
  1499. #include &lt;asm/errno.h&gt;
  1500. struct object
  1501. {
  1502. - /* These two protected by cache_lock. */
  1503. + /* This is protected by RCU */
  1504. struct list_head list;
  1505. int popularity;
  1506. + struct rcu_head rcu;
  1507. +
  1508. atomic_t refcnt;
  1509. /* Doesn't change once created. */
  1510. @@ -40,7 +43,7 @@
  1511. {
  1512. struct object *i;
  1513. - list_for_each_entry(i, &amp;cache, list) {
  1514. + list_for_each_entry_rcu(i, &amp;cache, list) {
  1515. if (i-&gt;id == id) {
  1516. i-&gt;popularity++;
  1517. return i;
  1518. @@ -49,19 +52,25 @@
  1519. return NULL;
  1520. }
  1521. +/* Final discard done once we know no readers are looking. */
  1522. +static void cache_delete_rcu(void *arg)
  1523. +{
  1524. + object_put(arg);
  1525. +}
  1526. +
  1527. /* Must be holding cache_lock */
  1528. static void __cache_delete(struct object *obj)
  1529. {
  1530. BUG_ON(!obj);
  1531. - list_del(&amp;obj-&gt;list);
  1532. - object_put(obj);
  1533. + list_del_rcu(&amp;obj-&gt;list);
  1534. cache_num--;
  1535. + call_rcu(&amp;obj-&gt;rcu, cache_delete_rcu);
  1536. }
  1537. /* Must be holding cache_lock */
  1538. static void __cache_add(struct object *obj)
  1539. {
  1540. - list_add(&amp;obj-&gt;list, &amp;cache);
  1541. + list_add_rcu(&amp;obj-&gt;list, &amp;cache);
  1542. if (++cache_num > MAX_CACHE_SIZE) {
  1543. struct object *i, *outcast = NULL;
  1544. list_for_each_entry(i, &amp;cache, list) {
  1545. @@ -104,12 +114,11 @@
  1546. struct object *cache_find(int id)
  1547. {
  1548. struct object *obj;
  1549. - unsigned long flags;
  1550. - spin_lock_irqsave(&amp;cache_lock, flags);
  1551. + rcu_read_lock();
  1552. obj = __cache_find(id);
  1553. if (obj)
  1554. object_get(obj);
  1555. - spin_unlock_irqrestore(&amp;cache_lock, flags);
  1556. + rcu_read_unlock();
  1557. return obj;
  1558. }
  1559. </programlisting>
  1560. <para>
  1561. Note that the reader will alter the
  1562. <structfield>popularity</structfield> member in
  1563. <function>__cache_find()</function>, and now it doesn't hold a lock.
  1564. One solution would be to make it an <type>atomic_t</type>, but for
  1565. this usage, we don't really care about races: an approximate result is
  1566. good enough, so I didn't change it.
  1567. </para>
  1568. <para>
  1569. The result is that <function>cache_find()</function> requires no
  1570. synchronization with any other functions, so is almost as fast on SMP
  1571. as it would be on UP.
  1572. </para>
  1573. <para>
  1574. There is a further optimization possible here: remember our original
  1575. cache code, where there were no reference counts and the caller simply
  1576. held the lock whenever using the object? This is still possible: if
  1577. you hold the lock, no one can delete the object, so you don't need to
  1578. get and put the reference count.
  1579. </para>
  1580. <para>
  1581. Now, because the 'read lock' in RCU is simply disabling preemption, a
  1582. caller which always has preemption disabled between calling
  1583. <function>cache_find()</function> and
  1584. <function>object_put()</function> does not need to actually get and
  1585. put the reference count: we could expose
  1586. <function>__cache_find()</function> by making it non-static, and
  1587. such callers could simply call that.
  1588. </para>
  1589. <para>
  1590. The benefit here is that the reference count is not written to: the
  1591. object is not altered in any way, which is much faster on SMP
  1592. machines due to caching.
  1593. </para>
  1594. </sect1>
  1595. <sect1 id="per-cpu">
  1596. <title>Per-CPU Data</title>
  1597. <para>
  1598. Another technique for avoiding locking which is used fairly
  1599. widely is to duplicate information for each CPU. For example,
  1600. if you wanted to keep a count of a common condition, you could
  1601. use a spin lock and a single counter. Nice and simple.
  1602. </para>
  1603. <para>
  1604. If that was too slow (it's usually not, but if you've got a
  1605. really big machine to test on and can show that it is), you
  1606. could instead use a counter for each CPU, then none of them need
  1607. an exclusive lock. See <function>DEFINE_PER_CPU()</function>,
  1608. <function>get_cpu_var()</function> and
  1609. <function>put_cpu_var()</function>
  1610. (<filename class="headerfile">include/linux/percpu.h</filename>).
  1611. </para>
  1612. <para>
  1613. Of particular use for simple per-cpu counters is the
  1614. <type>local_t</type> type, and the
  1615. <function>cpu_local_inc()</function> and related functions,
  1616. which are more efficient than simple code on some architectures
  1617. (<filename class="headerfile">include/asm/local.h</filename>).
  1618. </para>
  1619. <para>
  1620. Note that there is no simple, reliable way of getting an exact
  1621. value of such a counter, without introducing more locks. This
  1622. is not a problem for some uses.
  1623. </para>
  1624. </sect1>
  1625. <sect1 id="mostly-hardirq">
  1626. <title>Data Which Mostly Used By An IRQ Handler</title>
  1627. <para>
  1628. If data is always accessed from within the same IRQ handler, you
  1629. don't need a lock at all: the kernel already guarantees that the
  1630. irq handler will not run simultaneously on multiple CPUs.
  1631. </para>
  1632. <para>
  1633. Manfred Spraul points out that you can still do this, even if
  1634. the data is very occasionally accessed in user context or
  1635. softirqs/tasklets. The irq handler doesn't use a lock, and
  1636. all other accesses are done as so:
  1637. </para>
  1638. <programlisting>
  1639. spin_lock(&amp;lock);
  1640. disable_irq(irq);
  1641. ...
  1642. enable_irq(irq);
  1643. spin_unlock(&amp;lock);
  1644. </programlisting>
  1645. <para>
  1646. The <function>disable_irq()</function> prevents the irq handler
  1647. from running (and waits for it to finish if it's currently
  1648. running on other CPUs). The spinlock prevents any other
  1649. accesses happening at the same time. Naturally, this is slower
  1650. than just a <function>spin_lock_irq()</function> call, so it
  1651. only makes sense if this type of access happens extremely
  1652. rarely.
  1653. </para>
  1654. </sect1>
  1655. </chapter>
  1656. <chapter id="sleeping-things">
  1657. <title>What Functions Are Safe To Call From Interrupts?</title>
  1658. <para>
  1659. Many functions in the kernel sleep (ie. call schedule())
  1660. directly or indirectly: you can never call them while holding a
  1661. spinlock, or with preemption disabled. This also means you need
  1662. to be in user context: calling them from an interrupt is illegal.
  1663. </para>
  1664. <sect1 id="sleeping">
  1665. <title>Some Functions Which Sleep</title>
  1666. <para>
  1667. The most common ones are listed below, but you usually have to
  1668. read the code to find out if other calls are safe. If everyone
  1669. else who calls it can sleep, you probably need to be able to
  1670. sleep, too. In particular, registration and deregistration
  1671. functions usually expect to be called from user context, and can
  1672. sleep.
  1673. </para>
  1674. <itemizedlist>
  1675. <listitem>
  1676. <para>
  1677. Accesses to
  1678. <firstterm linkend="gloss-userspace">userspace</firstterm>:
  1679. </para>
  1680. <itemizedlist>
  1681. <listitem>
  1682. <para>
  1683. <function>copy_from_user()</function>
  1684. </para>
  1685. </listitem>
  1686. <listitem>
  1687. <para>
  1688. <function>copy_to_user()</function>
  1689. </para>
  1690. </listitem>
  1691. <listitem>
  1692. <para>
  1693. <function>get_user()</function>
  1694. </para>
  1695. </listitem>
  1696. <listitem>
  1697. <para>
  1698. <function>put_user()</function>
  1699. </para>
  1700. </listitem>
  1701. </itemizedlist>
  1702. </listitem>
  1703. <listitem>
  1704. <para>
  1705. <function>kmalloc(GFP_KERNEL)</function>
  1706. </para>
  1707. </listitem>
  1708. <listitem>
  1709. <para>
  1710. <function>mutex_lock_interruptible()</function> and
  1711. <function>mutex_lock()</function>
  1712. </para>
  1713. <para>
  1714. There is a <function>mutex_trylock()</function> which does not
  1715. sleep. Still, it must not be used inside interrupt context since
  1716. its implementation is not safe for that.
  1717. <function>mutex_unlock()</function> will also never sleep.
  1718. It cannot be used in interrupt context either since a mutex
  1719. must be released by the same task that acquired it.
  1720. </para>
  1721. </listitem>
  1722. </itemizedlist>
  1723. </sect1>
  1724. <sect1 id="dont-sleep">
  1725. <title>Some Functions Which Don't Sleep</title>
  1726. <para>
  1727. Some functions are safe to call from any context, or holding
  1728. almost any lock.
  1729. </para>
  1730. <itemizedlist>
  1731. <listitem>
  1732. <para>
  1733. <function>printk()</function>
  1734. </para>
  1735. </listitem>
  1736. <listitem>
  1737. <para>
  1738. <function>kfree()</function>
  1739. </para>
  1740. </listitem>
  1741. <listitem>
  1742. <para>
  1743. <function>add_timer()</function> and <function>del_timer()</function>
  1744. </para>
  1745. </listitem>
  1746. </itemizedlist>
  1747. </sect1>
  1748. </chapter>
  1749. <chapter id="apiref-mutex">
  1750. <title>Mutex API reference</title>
  1751. !Iinclude/linux/mutex.h
  1752. !Ekernel/locking/mutex.c
  1753. </chapter>
  1754. <chapter id="apiref-futex">
  1755. <title>Futex API reference</title>
  1756. !Ikernel/futex.c
  1757. </chapter>
  1758. <chapter id="references">
  1759. <title>Further reading</title>
  1760. <itemizedlist>
  1761. <listitem>
  1762. <para>
  1763. <filename>Documentation/locking/spinlocks.txt</filename>:
  1764. Linus Torvalds' spinlocking tutorial in the kernel sources.
  1765. </para>
  1766. </listitem>
  1767. <listitem>
  1768. <para>
  1769. Unix Systems for Modern Architectures: Symmetric
  1770. Multiprocessing and Caching for Kernel Programmers:
  1771. </para>
  1772. <para>
  1773. Curt Schimmel's very good introduction to kernel level
  1774. locking (not written for Linux, but nearly everything
  1775. applies). The book is expensive, but really worth every
  1776. penny to understand SMP locking. [ISBN: 0201633388]
  1777. </para>
  1778. </listitem>
  1779. </itemizedlist>
  1780. </chapter>
  1781. <chapter id="thanks">
  1782. <title>Thanks</title>
  1783. <para>
  1784. Thanks to Telsa Gwynne for DocBooking, neatening and adding
  1785. style.
  1786. </para>
  1787. <para>
  1788. Thanks to Martin Pool, Philipp Rumpf, Stephen Rothwell, Paul
  1789. Mackerras, Ruedi Aschwanden, Alan Cox, Manfred Spraul, Tim
  1790. Waugh, Pete Zaitcev, James Morris, Robert Love, Paul McKenney,
  1791. John Ashby for proofreading, correcting, flaming, commenting.
  1792. </para>
  1793. <para>
  1794. Thanks to the cabal for having no influence on this document.
  1795. </para>
  1796. </chapter>
  1797. <glossary id="glossary">
  1798. <title>Glossary</title>
  1799. <glossentry id="gloss-preemption">
  1800. <glossterm>preemption</glossterm>
  1801. <glossdef>
  1802. <para>
  1803. Prior to 2.5, or when <symbol>CONFIG_PREEMPT</symbol> is
  1804. unset, processes in user context inside the kernel would not
  1805. preempt each other (ie. you had that CPU until you gave it up,
  1806. except for interrupts). With the addition of
  1807. <symbol>CONFIG_PREEMPT</symbol> in 2.5.4, this changed: when
  1808. in user context, higher priority tasks can "cut in": spinlocks
  1809. were changed to disable preemption, even on UP.
  1810. </para>
  1811. </glossdef>
  1812. </glossentry>
  1813. <glossentry id="gloss-bh">
  1814. <glossterm>bh</glossterm>
  1815. <glossdef>
  1816. <para>
  1817. Bottom Half: for historical reasons, functions with
  1818. '_bh' in them often now refer to any software interrupt, e.g.
  1819. <function>spin_lock_bh()</function> blocks any software interrupt
  1820. on the current CPU. Bottom halves are deprecated, and will
  1821. eventually be replaced by tasklets. Only one bottom half will be
  1822. running at any time.
  1823. </para>
  1824. </glossdef>
  1825. </glossentry>
  1826. <glossentry id="gloss-hwinterrupt">
  1827. <glossterm>Hardware Interrupt / Hardware IRQ</glossterm>
  1828. <glossdef>
  1829. <para>
  1830. Hardware interrupt request. <function>in_irq()</function> returns
  1831. <returnvalue>true</returnvalue> in a hardware interrupt handler.
  1832. </para>
  1833. </glossdef>
  1834. </glossentry>
  1835. <glossentry id="gloss-interruptcontext">
  1836. <glossterm>Interrupt Context</glossterm>
  1837. <glossdef>
  1838. <para>
  1839. Not user context: processing a hardware irq or software irq.
  1840. Indicated by the <function>in_interrupt()</function> macro
  1841. returning <returnvalue>true</returnvalue>.
  1842. </para>
  1843. </glossdef>
  1844. </glossentry>
  1845. <glossentry id="gloss-smp">
  1846. <glossterm><acronym>SMP</acronym></glossterm>
  1847. <glossdef>
  1848. <para>
  1849. Symmetric Multi-Processor: kernels compiled for multiple-CPU
  1850. machines. (CONFIG_SMP=y).
  1851. </para>
  1852. </glossdef>
  1853. </glossentry>
  1854. <glossentry id="gloss-softirq">
  1855. <glossterm>Software Interrupt / softirq</glossterm>
  1856. <glossdef>
  1857. <para>
  1858. Software interrupt handler. <function>in_irq()</function> returns
  1859. <returnvalue>false</returnvalue>; <function>in_softirq()</function>
  1860. returns <returnvalue>true</returnvalue>. Tasklets and softirqs
  1861. both fall into the category of 'software interrupts'.
  1862. </para>
  1863. <para>
  1864. Strictly speaking a softirq is one of up to 32 enumerated software
  1865. interrupts which can run on multiple CPUs at once.
  1866. Sometimes used to refer to tasklets as
  1867. well (ie. all software interrupts).
  1868. </para>
  1869. </glossdef>
  1870. </glossentry>
  1871. <glossentry id="gloss-tasklet">
  1872. <glossterm>tasklet</glossterm>
  1873. <glossdef>
  1874. <para>
  1875. A dynamically-registrable software interrupt,
  1876. which is guaranteed to only run on one CPU at a time.
  1877. </para>
  1878. </glossdef>
  1879. </glossentry>
  1880. <glossentry id="gloss-timers">
  1881. <glossterm>timer</glossterm>
  1882. <glossdef>
  1883. <para>
  1884. A dynamically-registrable software interrupt, which is run at
  1885. (or close to) a given time. When running, it is just like a
  1886. tasklet (in fact, they are called from the TIMER_SOFTIRQ).
  1887. </para>
  1888. </glossdef>
  1889. </glossentry>
  1890. <glossentry id="gloss-up">
  1891. <glossterm><acronym>UP</acronym></glossterm>
  1892. <glossdef>
  1893. <para>
  1894. Uni-Processor: Non-SMP. (CONFIG_SMP=n).
  1895. </para>
  1896. </glossdef>
  1897. </glossentry>
  1898. <glossentry id="gloss-usercontext">
  1899. <glossterm>User Context</glossterm>
  1900. <glossdef>
  1901. <para>
  1902. The kernel executing on behalf of a particular process (ie. a
  1903. system call or trap) or kernel thread. You can tell which
  1904. process with the <symbol>current</symbol> macro.) Not to
  1905. be confused with userspace. Can be interrupted by software or
  1906. hardware interrupts.
  1907. </para>
  1908. </glossdef>
  1909. </glossentry>
  1910. <glossentry id="gloss-userspace">
  1911. <glossterm>Userspace</glossterm>
  1912. <glossdef>
  1913. <para>
  1914. A process executing its own code outside the kernel.
  1915. </para>
  1916. </glossdef>
  1917. </glossentry>
  1918. </glossary>
  1919. </book>