kernel-locking.tmpl 66 KB

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