locking.rst 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. ===========================
  2. Unreliable Guide To Locking
  3. ===========================
  4. :Author: Rusty Russell
  5. Introduction
  6. ============
  7. Welcome, to Rusty's Remarkably Unreliable Guide to Kernel Locking
  8. issues. This document describes the locking systems in the Linux Kernel
  9. in 2.6.
  10. With the wide availability of HyperThreading, and preemption in the
  11. Linux Kernel, everyone hacking on the kernel needs to know the
  12. fundamentals of concurrency and locking for SMP.
  13. The Problem With Concurrency
  14. ============================
  15. (Skip this if you know what a Race Condition is).
  16. In a normal program, you can increment a counter like so:
  17. ::
  18. very_important_count++;
  19. This is what they would expect to happen:
  20. .. table:: Expected Results
  21. +------------------------------------+------------------------------------+
  22. | Instance 1 | Instance 2 |
  23. +====================================+====================================+
  24. | read very_important_count (5) | |
  25. +------------------------------------+------------------------------------+
  26. | add 1 (6) | |
  27. +------------------------------------+------------------------------------+
  28. | write very_important_count (6) | |
  29. +------------------------------------+------------------------------------+
  30. | | read very_important_count (6) |
  31. +------------------------------------+------------------------------------+
  32. | | add 1 (7) |
  33. +------------------------------------+------------------------------------+
  34. | | write very_important_count (7) |
  35. +------------------------------------+------------------------------------+
  36. This is what might happen:
  37. .. table:: Possible Results
  38. +------------------------------------+------------------------------------+
  39. | Instance 1 | Instance 2 |
  40. +====================================+====================================+
  41. | read very_important_count (5) | |
  42. +------------------------------------+------------------------------------+
  43. | | read very_important_count (5) |
  44. +------------------------------------+------------------------------------+
  45. | add 1 (6) | |
  46. +------------------------------------+------------------------------------+
  47. | | add 1 (6) |
  48. +------------------------------------+------------------------------------+
  49. | write very_important_count (6) | |
  50. +------------------------------------+------------------------------------+
  51. | | write very_important_count (6) |
  52. +------------------------------------+------------------------------------+
  53. Race Conditions and Critical Regions
  54. ------------------------------------
  55. This overlap, where the result depends on the relative timing of
  56. multiple tasks, is called a race condition. The piece of code containing
  57. the concurrency issue is called a critical region. And especially since
  58. Linux starting running on SMP machines, they became one of the major
  59. issues in kernel design and implementation.
  60. Preemption can have the same effect, even if there is only one CPU: by
  61. preempting one task during the critical region, we have exactly the same
  62. race condition. In this case the thread which preempts might run the
  63. critical region itself.
  64. The solution is to recognize when these simultaneous accesses occur, and
  65. use locks to make sure that only one instance can enter the critical
  66. region at any time. There are many friendly primitives in the Linux
  67. kernel to help you do this. And then there are the unfriendly
  68. primitives, but I'll pretend they don't exist.
  69. Locking in the Linux Kernel
  70. ===========================
  71. If I could give you one piece of advice: never sleep with anyone crazier
  72. than yourself. But if I had to give you advice on locking: **keep it
  73. simple**.
  74. Be reluctant to introduce new locks.
  75. Strangely enough, this last one is the exact reverse of my advice when
  76. you **have** slept with someone crazier than yourself. And you should
  77. think about getting a big dog.
  78. Two Main Types of Kernel Locks: Spinlocks and Mutexes
  79. -----------------------------------------------------
  80. There are two main types of kernel locks. The fundamental type is the
  81. spinlock (``include/asm/spinlock.h``), which is a very simple
  82. single-holder lock: if you can't get the spinlock, you keep trying
  83. (spinning) until you can. Spinlocks are very small and fast, and can be
  84. used anywhere.
  85. The second type is a mutex (``include/linux/mutex.h``): it is like a
  86. spinlock, but you may block holding a mutex. If you can't lock a mutex,
  87. your task will suspend itself, and be woken up when the mutex is
  88. released. This means the CPU can do something else while you are
  89. waiting. There are many cases when you simply can't sleep (see
  90. `What Functions Are Safe To Call From Interrupts? <#sleeping-things>`__),
  91. and so have to use a spinlock instead.
  92. Neither type of lock is recursive: see
  93. `Deadlock: Simple and Advanced <#deadlock>`__.
  94. Locks and Uniprocessor Kernels
  95. ------------------------------
  96. For kernels compiled without ``CONFIG_SMP``, and without
  97. ``CONFIG_PREEMPT`` spinlocks do not exist at all. This is an excellent
  98. design decision: when no-one else can run at the same time, there is no
  99. reason to have a lock.
  100. If the kernel is compiled without ``CONFIG_SMP``, but ``CONFIG_PREEMPT``
  101. is set, then spinlocks simply disable preemption, which is sufficient to
  102. prevent any races. For most purposes, we can think of preemption as
  103. equivalent to SMP, and not worry about it separately.
  104. You should always test your locking code with ``CONFIG_SMP`` and
  105. ``CONFIG_PREEMPT`` enabled, even if you don't have an SMP test box,
  106. because it will still catch some kinds of locking bugs.
  107. Mutexes still exist, because they are required for synchronization
  108. between user contexts, as we will see below.
  109. Locking Only In User Context
  110. ----------------------------
  111. If you have a data structure which is only ever accessed from user
  112. context, then you can use a simple mutex (``include/linux/mutex.h``) to
  113. protect it. This is the most trivial case: you initialize the mutex.
  114. Then you can call :c:func:`mutex_lock_interruptible()` to grab the
  115. mutex, and :c:func:`mutex_unlock()` to release it. There is also a
  116. :c:func:`mutex_lock()`, which should be avoided, because it will
  117. not return if a signal is received.
  118. Example: ``net/netfilter/nf_sockopt.c`` allows registration of new
  119. :c:func:`setsockopt()` and :c:func:`getsockopt()` calls, with
  120. :c:func:`nf_register_sockopt()`. Registration and de-registration
  121. are only done on module load and unload (and boot time, where there is
  122. no concurrency), and the list of registrations is only consulted for an
  123. unknown :c:func:`setsockopt()` or :c:func:`getsockopt()` system
  124. call. The ``nf_sockopt_mutex`` is perfect to protect this, especially
  125. since the setsockopt and getsockopt calls may well sleep.
  126. Locking Between User Context and Softirqs
  127. -----------------------------------------
  128. If a softirq shares data with user context, you have two problems.
  129. Firstly, the current user context can be interrupted by a softirq, and
  130. secondly, the critical region could be entered from another CPU. This is
  131. where :c:func:`spin_lock_bh()` (``include/linux/spinlock.h``) is
  132. used. It disables softirqs on that CPU, then grabs the lock.
  133. :c:func:`spin_unlock_bh()` does the reverse. (The '_bh' suffix is
  134. a historical reference to "Bottom Halves", the old name for software
  135. interrupts. It should really be called spin_lock_softirq()' in a
  136. perfect world).
  137. Note that you can also use :c:func:`spin_lock_irq()` or
  138. :c:func:`spin_lock_irqsave()` here, which stop hardware interrupts
  139. as well: see `Hard IRQ Context <#hardirq-context>`__.
  140. This works perfectly for UP as well: the spin lock vanishes, and this
  141. macro simply becomes :c:func:`local_bh_disable()`
  142. (``include/linux/interrupt.h``), which protects you from the softirq
  143. being run.
  144. Locking Between User Context and Tasklets
  145. -----------------------------------------
  146. This is exactly the same as above, because tasklets are actually run
  147. from a softirq.
  148. Locking Between User Context and Timers
  149. ---------------------------------------
  150. This, too, is exactly the same as above, because timers are actually run
  151. from a softirq. From a locking point of view, tasklets and timers are
  152. identical.
  153. Locking Between Tasklets/Timers
  154. -------------------------------
  155. Sometimes a tasklet or timer might want to share data with another
  156. tasklet or timer.
  157. The Same Tasklet/Timer
  158. ~~~~~~~~~~~~~~~~~~~~~~
  159. Since a tasklet is never run on two CPUs at once, you don't need to
  160. worry about your tasklet being reentrant (running twice at once), even
  161. on SMP.
  162. Different Tasklets/Timers
  163. ~~~~~~~~~~~~~~~~~~~~~~~~~
  164. If another tasklet/timer wants to share data with your tasklet or timer
  165. , you will both need to use :c:func:`spin_lock()` and
  166. :c:func:`spin_unlock()` calls. :c:func:`spin_lock_bh()` is
  167. unnecessary here, as you are already in a tasklet, and none will be run
  168. on the same CPU.
  169. Locking Between Softirqs
  170. ------------------------
  171. Often a softirq might want to share data with itself or a tasklet/timer.
  172. The Same Softirq
  173. ~~~~~~~~~~~~~~~~
  174. The same softirq can run on the other CPUs: you can use a per-CPU array
  175. (see `Per-CPU Data <#per-cpu>`__) for better performance. If you're
  176. going so far as to use a softirq, you probably care about scalable
  177. performance enough to justify the extra complexity.
  178. You'll need to use :c:func:`spin_lock()` and
  179. :c:func:`spin_unlock()` for shared data.
  180. Different Softirqs
  181. ~~~~~~~~~~~~~~~~~~
  182. You'll need to use :c:func:`spin_lock()` and
  183. :c:func:`spin_unlock()` for shared data, whether it be a timer,
  184. tasklet, different softirq or the same or another softirq: any of them
  185. could be running on a different CPU.
  186. Hard IRQ Context
  187. ================
  188. Hardware interrupts usually communicate with a tasklet or softirq.
  189. Frequently this involves putting work in a queue, which the softirq will
  190. take out.
  191. Locking Between Hard IRQ and Softirqs/Tasklets
  192. ----------------------------------------------
  193. If a hardware irq handler shares data with a softirq, you have two
  194. concerns. Firstly, the softirq processing can be interrupted by a
  195. hardware interrupt, and secondly, the critical region could be entered
  196. by a hardware interrupt on another CPU. This is where
  197. :c:func:`spin_lock_irq()` is used. It is defined to disable
  198. interrupts on that cpu, then grab the lock.
  199. :c:func:`spin_unlock_irq()` does the reverse.
  200. The irq handler does not to use :c:func:`spin_lock_irq()`, because
  201. the softirq cannot run while the irq handler is running: it can use
  202. :c:func:`spin_lock()`, which is slightly faster. The only exception
  203. would be if a different hardware irq handler uses the same lock:
  204. :c:func:`spin_lock_irq()` will stop that from interrupting us.
  205. This works perfectly for UP as well: the spin lock vanishes, and this
  206. macro simply becomes :c:func:`local_irq_disable()`
  207. (``include/asm/smp.h``), which protects you from the softirq/tasklet/BH
  208. being run.
  209. :c:func:`spin_lock_irqsave()` (``include/linux/spinlock.h``) is a
  210. variant which saves whether interrupts were on or off in a flags word,
  211. which is passed to :c:func:`spin_unlock_irqrestore()`. This means
  212. that the same code can be used inside an hard irq handler (where
  213. interrupts are already off) and in softirqs (where the irq disabling is
  214. required).
  215. Note that softirqs (and hence tasklets and timers) are run on return
  216. from hardware interrupts, so :c:func:`spin_lock_irq()` also stops
  217. these. In that sense, :c:func:`spin_lock_irqsave()` is the most
  218. general and powerful locking function.
  219. Locking Between Two Hard IRQ Handlers
  220. -------------------------------------
  221. It is rare to have to share data between two IRQ handlers, but if you
  222. do, :c:func:`spin_lock_irqsave()` should be used: it is
  223. architecture-specific whether all interrupts are disabled inside irq
  224. handlers themselves.
  225. Cheat Sheet For Locking
  226. =======================
  227. Pete Zaitcev gives the following summary:
  228. - If you are in a process context (any syscall) and want to lock other
  229. process out, use a mutex. You can take a mutex and sleep
  230. (``copy_from_user*(`` or ``kmalloc(x,GFP_KERNEL)``).
  231. - Otherwise (== data can be touched in an interrupt), use
  232. :c:func:`spin_lock_irqsave()` and
  233. :c:func:`spin_unlock_irqrestore()`.
  234. - Avoid holding spinlock for more than 5 lines of code and across any
  235. function call (except accessors like :c:func:`readb()`).
  236. Table of Minimum Requirements
  237. -----------------------------
  238. The following table lists the **minimum** locking requirements between
  239. various contexts. In some cases, the same context can only be running on
  240. one CPU at a time, so no locking is required for that context (eg. a
  241. particular thread can only run on one CPU at a time, but if it needs
  242. shares data with another thread, locking is required).
  243. Remember the advice above: you can always use
  244. :c:func:`spin_lock_irqsave()`, which is a superset of all other
  245. spinlock primitives.
  246. ============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
  247. . IRQ Handler A IRQ Handler B Softirq A Softirq B Tasklet A Tasklet B Timer A Timer B User Context A User Context B
  248. ============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
  249. IRQ Handler A None
  250. IRQ Handler B SLIS None
  251. Softirq A SLI SLI SL
  252. Softirq B SLI SLI SL SL
  253. Tasklet A SLI SLI SL SL None
  254. Tasklet B SLI SLI SL SL SL None
  255. Timer A SLI SLI SL SL SL SL None
  256. Timer B SLI SLI SL SL SL SL SL None
  257. User Context A SLI SLI SLBH SLBH SLBH SLBH SLBH SLBH None
  258. User Context B SLI SLI SLBH SLBH SLBH SLBH SLBH SLBH MLI None
  259. ============== ============= ============= ========= ========= ========= ========= ======= ======= ============== ==============
  260. Table: Table of Locking Requirements
  261. +--------+----------------------------+
  262. | SLIS | spin_lock_irqsave |
  263. +--------+----------------------------+
  264. | SLI | spin_lock_irq |
  265. +--------+----------------------------+
  266. | SL | spin_lock |
  267. +--------+----------------------------+
  268. | SLBH | spin_lock_bh |
  269. +--------+----------------------------+
  270. | MLI | mutex_lock_interruptible |
  271. +--------+----------------------------+
  272. Table: Legend for Locking Requirements Table
  273. The trylock Functions
  274. =====================
  275. There are functions that try to acquire a lock only once and immediately
  276. return a value telling about success or failure to acquire the lock.
  277. They can be used if you need no access to the data protected with the
  278. lock when some other thread is holding the lock. You should acquire the
  279. lock later if you then need access to the data protected with the lock.
  280. :c:func:`spin_trylock()` does not spin but returns non-zero if it
  281. acquires the spinlock on the first try or 0 if not. This function can be
  282. used in all contexts like :c:func:`spin_lock()`: you must have
  283. disabled the contexts that might interrupt you and acquire the spin
  284. lock.
  285. :c:func:`mutex_trylock()` does not suspend your task but returns
  286. non-zero if it could lock the mutex on the first try or 0 if not. This
  287. function cannot be safely used in hardware or software interrupt
  288. contexts despite not sleeping.
  289. Common Examples
  290. ===============
  291. Let's step through a simple example: a cache of number to name mappings.
  292. The cache keeps a count of how often each of the objects is used, and
  293. when it gets full, throws out the least used one.
  294. All In User Context
  295. -------------------
  296. For our first example, we assume that all operations are in user context
  297. (ie. from system calls), so we can sleep. This means we can use a mutex
  298. to protect the cache and all the objects within it. Here's the code::
  299. #include <linux/list.h>
  300. #include <linux/slab.h>
  301. #include <linux/string.h>
  302. #include <linux/mutex.h>
  303. #include <asm/errno.h>
  304. struct object
  305. {
  306. struct list_head list;
  307. int id;
  308. char name[32];
  309. int popularity;
  310. };
  311. /* Protects the cache, cache_num, and the objects within it */
  312. static DEFINE_MUTEX(cache_lock);
  313. static LIST_HEAD(cache);
  314. static unsigned int cache_num = 0;
  315. #define MAX_CACHE_SIZE 10
  316. /* Must be holding cache_lock */
  317. static struct object *__cache_find(int id)
  318. {
  319. struct object *i;
  320. list_for_each_entry(i, &cache, list)
  321. if (i->id == id) {
  322. i->popularity++;
  323. return i;
  324. }
  325. return NULL;
  326. }
  327. /* Must be holding cache_lock */
  328. static void __cache_delete(struct object *obj)
  329. {
  330. BUG_ON(!obj);
  331. list_del(&obj->list);
  332. kfree(obj);
  333. cache_num--;
  334. }
  335. /* Must be holding cache_lock */
  336. static void __cache_add(struct object *obj)
  337. {
  338. list_add(&obj->list, &cache);
  339. if (++cache_num > MAX_CACHE_SIZE) {
  340. struct object *i, *outcast = NULL;
  341. list_for_each_entry(i, &cache, list) {
  342. if (!outcast || i->popularity < outcast->popularity)
  343. outcast = i;
  344. }
  345. __cache_delete(outcast);
  346. }
  347. }
  348. int cache_add(int id, const char *name)
  349. {
  350. struct object *obj;
  351. if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
  352. return -ENOMEM;
  353. strlcpy(obj->name, name, sizeof(obj->name));
  354. obj->id = id;
  355. obj->popularity = 0;
  356. mutex_lock(&cache_lock);
  357. __cache_add(obj);
  358. mutex_unlock(&cache_lock);
  359. return 0;
  360. }
  361. void cache_delete(int id)
  362. {
  363. mutex_lock(&cache_lock);
  364. __cache_delete(__cache_find(id));
  365. mutex_unlock(&cache_lock);
  366. }
  367. int cache_find(int id, char *name)
  368. {
  369. struct object *obj;
  370. int ret = -ENOENT;
  371. mutex_lock(&cache_lock);
  372. obj = __cache_find(id);
  373. if (obj) {
  374. ret = 0;
  375. strcpy(name, obj->name);
  376. }
  377. mutex_unlock(&cache_lock);
  378. return ret;
  379. }
  380. Note that we always make sure we have the cache_lock when we add,
  381. delete, or look up the cache: both the cache infrastructure itself and
  382. the contents of the objects are protected by the lock. In this case it's
  383. easy, since we copy the data for the user, and never let them access the
  384. objects directly.
  385. There is a slight (and common) optimization here: in
  386. :c:func:`cache_add()` we set up the fields of the object before
  387. grabbing the lock. This is safe, as no-one else can access it until we
  388. put it in cache.
  389. Accessing From Interrupt Context
  390. --------------------------------
  391. Now consider the case where :c:func:`cache_find()` can be called
  392. from interrupt context: either a hardware interrupt or a softirq. An
  393. example would be a timer which deletes object from the cache.
  394. The change is shown below, in standard patch format: the ``-`` are lines
  395. which are taken away, and the ``+`` are lines which are added.
  396. ::
  397. --- cache.c.usercontext 2003-12-09 13:58:54.000000000 +1100
  398. +++ cache.c.interrupt 2003-12-09 14:07:49.000000000 +1100
  399. @@ -12,7 +12,7 @@
  400. int popularity;
  401. };
  402. -static DEFINE_MUTEX(cache_lock);
  403. +static DEFINE_SPINLOCK(cache_lock);
  404. static LIST_HEAD(cache);
  405. static unsigned int cache_num = 0;
  406. #define MAX_CACHE_SIZE 10
  407. @@ -55,6 +55,7 @@
  408. int cache_add(int id, const char *name)
  409. {
  410. struct object *obj;
  411. + unsigned long flags;
  412. if ((obj = kmalloc(sizeof(*obj), GFP_KERNEL)) == NULL)
  413. return -ENOMEM;
  414. @@ -63,30 +64,33 @@
  415. obj->id = id;
  416. obj->popularity = 0;
  417. - mutex_lock(&cache_lock);
  418. + spin_lock_irqsave(&cache_lock, flags);
  419. __cache_add(obj);
  420. - mutex_unlock(&cache_lock);
  421. + spin_unlock_irqrestore(&cache_lock, flags);
  422. return 0;
  423. }
  424. void cache_delete(int id)
  425. {
  426. - mutex_lock(&cache_lock);
  427. + unsigned long flags;
  428. +
  429. + spin_lock_irqsave(&cache_lock, flags);
  430. __cache_delete(__cache_find(id));
  431. - mutex_unlock(&cache_lock);
  432. + spin_unlock_irqrestore(&cache_lock, flags);
  433. }
  434. int cache_find(int id, char *name)
  435. {
  436. struct object *obj;
  437. int ret = -ENOENT;
  438. + unsigned long flags;
  439. - mutex_lock(&cache_lock);
  440. + spin_lock_irqsave(&cache_lock, flags);
  441. obj = __cache_find(id);
  442. if (obj) {
  443. ret = 0;
  444. strcpy(name, obj->name);
  445. }
  446. - mutex_unlock(&cache_lock);
  447. + spin_unlock_irqrestore(&cache_lock, flags);
  448. return ret;
  449. }
  450. Note that the :c:func:`spin_lock_irqsave()` will turn off
  451. interrupts if they are on, otherwise does nothing (if we are already in
  452. an interrupt handler), hence these functions are safe to call from any
  453. context.
  454. Unfortunately, :c:func:`cache_add()` calls :c:func:`kmalloc()`
  455. with the ``GFP_KERNEL`` flag, which is only legal in user context. I
  456. have assumed that :c:func:`cache_add()` is still only called in
  457. user context, otherwise this should become a parameter to
  458. :c:func:`cache_add()`.
  459. Exposing Objects Outside This File
  460. ----------------------------------
  461. If our objects contained more information, it might not be sufficient to
  462. copy the information in and out: other parts of the code might want to
  463. keep pointers to these objects, for example, rather than looking up the
  464. id every time. This produces two problems.
  465. The first problem is that we use the ``cache_lock`` to protect objects:
  466. we'd need to make this non-static so the rest of the code can use it.
  467. This makes locking trickier, as it is no longer all in one place.
  468. The second problem is the lifetime problem: if another structure keeps a
  469. pointer to an object, it presumably expects that pointer to remain
  470. valid. Unfortunately, this is only guaranteed while you hold the lock,
  471. otherwise someone might call :c:func:`cache_delete()` and even
  472. worse, add another object, re-using the same address.
  473. As there is only one lock, you can't hold it forever: no-one else would
  474. get any work done.
  475. The solution to this problem is to use a reference count: everyone who
  476. has a pointer to the object increases it when they first get the object,
  477. and drops the reference count when they're finished with it. Whoever
  478. drops it to zero knows it is unused, and can actually delete it.
  479. Here is the code::
  480. --- cache.c.interrupt 2003-12-09 14:25:43.000000000 +1100
  481. +++ cache.c.refcnt 2003-12-09 14:33:05.000000000 +1100
  482. @@ -7,6 +7,7 @@
  483. struct object
  484. {
  485. struct list_head list;
  486. + unsigned int refcnt;
  487. int id;
  488. char name[32];
  489. int popularity;
  490. @@ -17,6 +18,35 @@
  491. static unsigned int cache_num = 0;
  492. #define MAX_CACHE_SIZE 10
  493. +static void __object_put(struct object *obj)
  494. +{
  495. + if (--obj->refcnt == 0)
  496. + kfree(obj);
  497. +}
  498. +
  499. +static void __object_get(struct object *obj)
  500. +{
  501. + obj->refcnt++;
  502. +}
  503. +
  504. +void object_put(struct object *obj)
  505. +{
  506. + unsigned long flags;
  507. +
  508. + spin_lock_irqsave(&cache_lock, flags);
  509. + __object_put(obj);
  510. + spin_unlock_irqrestore(&cache_lock, flags);
  511. +}
  512. +
  513. +void object_get(struct object *obj)
  514. +{
  515. + unsigned long flags;
  516. +
  517. + spin_lock_irqsave(&cache_lock, flags);
  518. + __object_get(obj);
  519. + spin_unlock_irqrestore(&cache_lock, flags);
  520. +}
  521. +
  522. /* Must be holding cache_lock */
  523. static struct object *__cache_find(int id)
  524. {
  525. @@ -35,6 +65,7 @@
  526. {
  527. BUG_ON(!obj);
  528. list_del(&obj->list);
  529. + __object_put(obj);
  530. cache_num--;
  531. }
  532. @@ -63,6 +94,7 @@
  533. strlcpy(obj->name, name, sizeof(obj->name));
  534. obj->id = id;
  535. obj->popularity = 0;
  536. + obj->refcnt = 1; /* The cache holds a reference */
  537. spin_lock_irqsave(&cache_lock, flags);
  538. __cache_add(obj);
  539. @@ -79,18 +111,15 @@
  540. spin_unlock_irqrestore(&cache_lock, flags);
  541. }
  542. -int cache_find(int id, char *name)
  543. +struct object *cache_find(int id)
  544. {
  545. struct object *obj;
  546. - int ret = -ENOENT;
  547. unsigned long flags;
  548. spin_lock_irqsave(&cache_lock, flags);
  549. obj = __cache_find(id);
  550. - if (obj) {
  551. - ret = 0;
  552. - strcpy(name, obj->name);
  553. - }
  554. + if (obj)
  555. + __object_get(obj);
  556. spin_unlock_irqrestore(&cache_lock, flags);
  557. - return ret;
  558. + return obj;
  559. }
  560. We encapsulate the reference counting in the standard 'get' and 'put'
  561. functions. Now we can return the object itself from
  562. :c:func:`cache_find()` which has the advantage that the user can
  563. now sleep holding the object (eg. to :c:func:`copy_to_user()` to
  564. name to userspace).
  565. The other point to note is that I said a reference should be held for
  566. every pointer to the object: thus the reference count is 1 when first
  567. inserted into the cache. In some versions the framework does not hold a
  568. reference count, but they are more complicated.
  569. Using Atomic Operations For The Reference Count
  570. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  571. In practice, :c:type:`atomic_t` would usually be used for refcnt. There are a
  572. number of atomic operations defined in ``include/asm/atomic.h``: these
  573. are guaranteed to be seen atomically from all CPUs in the system, so no
  574. lock is required. In this case, it is simpler than using spinlocks,
  575. although for anything non-trivial using spinlocks is clearer. The
  576. :c:func:`atomic_inc()` and :c:func:`atomic_dec_and_test()`
  577. are used instead of the standard increment and decrement operators, and
  578. the lock is no longer used to protect the reference count itself.
  579. ::
  580. --- cache.c.refcnt 2003-12-09 15:00:35.000000000 +1100
  581. +++ cache.c.refcnt-atomic 2003-12-11 15:49:42.000000000 +1100
  582. @@ -7,7 +7,7 @@
  583. struct object
  584. {
  585. struct list_head list;
  586. - unsigned int refcnt;
  587. + atomic_t refcnt;
  588. int id;
  589. char name[32];
  590. int popularity;
  591. @@ -18,33 +18,15 @@
  592. static unsigned int cache_num = 0;
  593. #define MAX_CACHE_SIZE 10
  594. -static void __object_put(struct object *obj)
  595. -{
  596. - if (--obj->refcnt == 0)
  597. - kfree(obj);
  598. -}
  599. -
  600. -static void __object_get(struct object *obj)
  601. -{
  602. - obj->refcnt++;
  603. -}
  604. -
  605. void object_put(struct object *obj)
  606. {
  607. - unsigned long flags;
  608. -
  609. - spin_lock_irqsave(&cache_lock, flags);
  610. - __object_put(obj);
  611. - spin_unlock_irqrestore(&cache_lock, flags);
  612. + if (atomic_dec_and_test(&obj->refcnt))
  613. + kfree(obj);
  614. }
  615. void object_get(struct object *obj)
  616. {
  617. - unsigned long flags;
  618. -
  619. - spin_lock_irqsave(&cache_lock, flags);
  620. - __object_get(obj);
  621. - spin_unlock_irqrestore(&cache_lock, flags);
  622. + atomic_inc(&obj->refcnt);
  623. }
  624. /* Must be holding cache_lock */
  625. @@ -65,7 +47,7 @@
  626. {
  627. BUG_ON(!obj);
  628. list_del(&obj->list);
  629. - __object_put(obj);
  630. + object_put(obj);
  631. cache_num--;
  632. }
  633. @@ -94,7 +76,7 @@
  634. strlcpy(obj->name, name, sizeof(obj->name));
  635. obj->id = id;
  636. obj->popularity = 0;
  637. - obj->refcnt = 1; /* The cache holds a reference */
  638. + atomic_set(&obj->refcnt, 1); /* The cache holds a reference */
  639. spin_lock_irqsave(&cache_lock, flags);
  640. __cache_add(obj);
  641. @@ -119,7 +101,7 @@
  642. spin_lock_irqsave(&cache_lock, flags);
  643. obj = __cache_find(id);
  644. if (obj)
  645. - __object_get(obj);
  646. + object_get(obj);
  647. spin_unlock_irqrestore(&cache_lock, flags);
  648. return obj;
  649. }
  650. Protecting The Objects Themselves
  651. ---------------------------------
  652. In these examples, we assumed that the objects (except the reference
  653. counts) never changed once they are created. If we wanted to allow the
  654. name to change, there are three possibilities:
  655. - You can make ``cache_lock`` non-static, and tell people to grab that
  656. lock before changing the name in any object.
  657. - You can provide a :c:func:`cache_obj_rename()` which grabs this
  658. lock and changes the name for the caller, and tell everyone to use
  659. that function.
  660. - You can make the ``cache_lock`` protect only the cache itself, and
  661. use another lock to protect the name.
  662. Theoretically, you can make the locks as fine-grained as one lock for
  663. every field, for every object. In practice, the most common variants
  664. are:
  665. - One lock which protects the infrastructure (the ``cache`` list in
  666. this example) and all the objects. This is what we have done so far.
  667. - One lock which protects the infrastructure (including the list
  668. pointers inside the objects), and one lock inside the object which
  669. protects the rest of that object.
  670. - Multiple locks to protect the infrastructure (eg. one lock per hash
  671. chain), possibly with a separate per-object lock.
  672. Here is the "lock-per-object" implementation:
  673. ::
  674. --- cache.c.refcnt-atomic 2003-12-11 15:50:54.000000000 +1100
  675. +++ cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
  676. @@ -6,11 +6,17 @@
  677. struct object
  678. {
  679. + /* These two protected by cache_lock. */
  680. struct list_head list;
  681. + int popularity;
  682. +
  683. atomic_t refcnt;
  684. +
  685. + /* Doesn't change once created. */
  686. int id;
  687. +
  688. + spinlock_t lock; /* Protects the name */
  689. char name[32];
  690. - int popularity;
  691. };
  692. static DEFINE_SPINLOCK(cache_lock);
  693. @@ -77,6 +84,7 @@
  694. obj->id = id;
  695. obj->popularity = 0;
  696. atomic_set(&obj->refcnt, 1); /* The cache holds a reference */
  697. + spin_lock_init(&obj->lock);
  698. spin_lock_irqsave(&cache_lock, flags);
  699. __cache_add(obj);
  700. Note that I decide that the popularity count should be protected by the
  701. ``cache_lock`` rather than the per-object lock: this is because it (like
  702. the :c:type:`struct list_head <list_head>` inside the object)
  703. is logically part of the infrastructure. This way, I don't need to grab
  704. the lock of every object in :c:func:`__cache_add()` when seeking
  705. the least popular.
  706. I also decided that the id member is unchangeable, so I don't need to
  707. grab each object lock in :c:func:`__cache_find()` to examine the
  708. id: the object lock is only used by a caller who wants to read or write
  709. the name field.
  710. Note also that I added a comment describing what data was protected by
  711. which locks. This is extremely important, as it describes the runtime
  712. behavior of the code, and can be hard to gain from just reading. And as
  713. Alan Cox says, “Lock data, not code”.
  714. Common Problems
  715. ===============
  716. Deadlock: Simple and Advanced
  717. -----------------------------
  718. There is a coding bug where a piece of code tries to grab a spinlock
  719. twice: it will spin forever, waiting for the lock to be released
  720. (spinlocks, rwlocks and mutexes are not recursive in Linux). This is
  721. trivial to diagnose: not a
  722. stay-up-five-nights-talk-to-fluffy-code-bunnies kind of problem.
  723. For a slightly more complex case, imagine you have a region shared by a
  724. softirq and user context. If you use a :c:func:`spin_lock()` call
  725. to protect it, it is possible that the user context will be interrupted
  726. by the softirq while it holds the lock, and the softirq will then spin
  727. forever trying to get the same lock.
  728. Both of these are called deadlock, and as shown above, it can occur even
  729. with a single CPU (although not on UP compiles, since spinlocks vanish
  730. on kernel compiles with ``CONFIG_SMP``\ =n. You'll still get data
  731. corruption in the second example).
  732. This complete lockup is easy to diagnose: on SMP boxes the watchdog
  733. timer or compiling with ``DEBUG_SPINLOCK`` set
  734. (``include/linux/spinlock.h``) will show this up immediately when it
  735. happens.
  736. A more complex problem is the so-called 'deadly embrace', involving two
  737. or more locks. Say you have a hash table: each entry in the table is a
  738. spinlock, and a chain of hashed objects. Inside a softirq handler, you
  739. sometimes want to alter an object from one place in the hash to another:
  740. you grab the spinlock of the old hash chain and the spinlock of the new
  741. hash chain, and delete the object from the old one, and insert it in the
  742. new one.
  743. There are two problems here. First, if your code ever tries to move the
  744. object to the same chain, it will deadlock with itself as it tries to
  745. lock it twice. Secondly, if the same softirq on another CPU is trying to
  746. move another object in the reverse direction, the following could
  747. happen:
  748. +-----------------------+-----------------------+
  749. | CPU 1 | CPU 2 |
  750. +=======================+=======================+
  751. | Grab lock A -> OK | Grab lock B -> OK |
  752. +-----------------------+-----------------------+
  753. | Grab lock B -> spin | Grab lock A -> spin |
  754. +-----------------------+-----------------------+
  755. Table: Consequences
  756. The two CPUs will spin forever, waiting for the other to give up their
  757. lock. It will look, smell, and feel like a crash.
  758. Preventing Deadlock
  759. -------------------
  760. Textbooks will tell you that if you always lock in the same order, you
  761. will never get this kind of deadlock. Practice will tell you that this
  762. approach doesn't scale: when I create a new lock, I don't understand
  763. enough of the kernel to figure out where in the 5000 lock hierarchy it
  764. will fit.
  765. The best locks are encapsulated: they never get exposed in headers, and
  766. are never held around calls to non-trivial functions outside the same
  767. file. You can read through this code and see that it will never
  768. deadlock, because it never tries to grab another lock while it has that
  769. one. People using your code don't even need to know you are using a
  770. lock.
  771. A classic problem here is when you provide callbacks or hooks: if you
  772. call these with the lock held, you risk simple deadlock, or a deadly
  773. embrace (who knows what the callback will do?). Remember, the other
  774. programmers are out to get you, so don't do this.
  775. Overzealous Prevention Of Deadlocks
  776. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  777. Deadlocks are problematic, but not as bad as data corruption. Code which
  778. grabs a read lock, searches a list, fails to find what it wants, drops
  779. the read lock, grabs a write lock and inserts the object has a race
  780. condition.
  781. If you don't see why, please stay the fuck away from my code.
  782. Racing Timers: A Kernel Pastime
  783. -------------------------------
  784. Timers can produce their own special problems with races. Consider a
  785. collection of objects (list, hash, etc) where each object has a timer
  786. which is due to destroy it.
  787. If you want to destroy the entire collection (say on module removal),
  788. you might do the following::
  789. /* THIS CODE BAD BAD BAD BAD: IF IT WAS ANY WORSE IT WOULD USE
  790. HUNGARIAN NOTATION */
  791. spin_lock_bh(&list_lock);
  792. while (list) {
  793. struct foo *next = list->next;
  794. del_timer(&list->timer);
  795. kfree(list);
  796. list = next;
  797. }
  798. spin_unlock_bh(&list_lock);
  799. Sooner or later, this will crash on SMP, because a timer can have just
  800. gone off before the :c:func:`spin_lock_bh()`, and it will only get
  801. the lock after we :c:func:`spin_unlock_bh()`, and then try to free
  802. the element (which has already been freed!).
  803. This can be avoided by checking the result of
  804. :c:func:`del_timer()`: if it returns 1, the timer has been deleted.
  805. If 0, it means (in this case) that it is currently running, so we can
  806. do::
  807. retry:
  808. spin_lock_bh(&list_lock);
  809. while (list) {
  810. struct foo *next = list->next;
  811. if (!del_timer(&list->timer)) {
  812. /* Give timer a chance to delete this */
  813. spin_unlock_bh(&list_lock);
  814. goto retry;
  815. }
  816. kfree(list);
  817. list = next;
  818. }
  819. spin_unlock_bh(&list_lock);
  820. Another common problem is deleting timers which restart themselves (by
  821. calling :c:func:`add_timer()` at the end of their timer function).
  822. Because this is a fairly common case which is prone to races, you should
  823. use :c:func:`del_timer_sync()` (``include/linux/timer.h``) to
  824. handle this case. It returns the number of times the timer had to be
  825. deleted before we finally stopped it from adding itself back in.
  826. Locking Speed
  827. =============
  828. There are three main things to worry about when considering speed of
  829. some code which does locking. First is concurrency: how many things are
  830. going to be waiting while someone else is holding a lock. Second is the
  831. time taken to actually acquire and release an uncontended lock. Third is
  832. using fewer, or smarter locks. I'm assuming that the lock is used fairly
  833. often: otherwise, you wouldn't be concerned about efficiency.
  834. Concurrency depends on how long the lock is usually held: you should
  835. hold the lock for as long as needed, but no longer. In the cache
  836. example, we always create the object without the lock held, and then
  837. grab the lock only when we are ready to insert it in the list.
  838. Acquisition times depend on how much damage the lock operations do to
  839. the pipeline (pipeline stalls) and how likely it is that this CPU was
  840. the last one to grab the lock (ie. is the lock cache-hot for this CPU):
  841. on a machine with more CPUs, this likelihood drops fast. Consider a
  842. 700MHz Intel Pentium III: an instruction takes about 0.7ns, an atomic
  843. increment takes about 58ns, a lock which is cache-hot on this CPU takes
  844. 160ns, and a cacheline transfer from another CPU takes an additional 170
  845. to 360ns. (These figures from Paul McKenney's `Linux Journal RCU
  846. article <http://www.linuxjournal.com/article.php?sid=6993>`__).
  847. These two aims conflict: holding a lock for a short time might be done
  848. by splitting locks into parts (such as in our final per-object-lock
  849. example), but this increases the number of lock acquisitions, and the
  850. results are often slower than having a single lock. This is another
  851. reason to advocate locking simplicity.
  852. The third concern is addressed below: there are some methods to reduce
  853. the amount of locking which needs to be done.
  854. Read/Write Lock Variants
  855. ------------------------
  856. Both spinlocks and mutexes have read/write variants: ``rwlock_t`` and
  857. :c:type:`struct rw_semaphore <rw_semaphore>`. These divide
  858. users into two classes: the readers and the writers. If you are only
  859. reading the data, you can get a read lock, but to write to the data you
  860. need the write lock. Many people can hold a read lock, but a writer must
  861. be sole holder.
  862. If your code divides neatly along reader/writer lines (as our cache code
  863. does), and the lock is held by readers for significant lengths of time,
  864. using these locks can help. They are slightly slower than the normal
  865. locks though, so in practice ``rwlock_t`` is not usually worthwhile.
  866. Avoiding Locks: Read Copy Update
  867. --------------------------------
  868. There is a special method of read/write locking called Read Copy Update.
  869. Using RCU, the readers can avoid taking a lock altogether: as we expect
  870. our cache to be read more often than updated (otherwise the cache is a
  871. waste of time), it is a candidate for this optimization.
  872. How do we get rid of read locks? Getting rid of read locks means that
  873. writers may be changing the list underneath the readers. That is
  874. actually quite simple: we can read a linked list while an element is
  875. being added if the writer adds the element very carefully. For example,
  876. adding ``new`` to a single linked list called ``list``::
  877. new->next = list->next;
  878. wmb();
  879. list->next = new;
  880. The :c:func:`wmb()` is a write memory barrier. It ensures that the
  881. first operation (setting the new element's ``next`` pointer) is complete
  882. and will be seen by all CPUs, before the second operation is (putting
  883. the new element into the list). This is important, since modern
  884. compilers and modern CPUs can both reorder instructions unless told
  885. otherwise: we want a reader to either not see the new element at all, or
  886. see the new element with the ``next`` pointer correctly pointing at the
  887. rest of the list.
  888. Fortunately, there is a function to do this for standard
  889. :c:type:`struct list_head <list_head>` lists:
  890. :c:func:`list_add_rcu()` (``include/linux/list.h``).
  891. Removing an element from the list is even simpler: we replace the
  892. pointer to the old element with a pointer to its successor, and readers
  893. will either see it, or skip over it.
  894. ::
  895. list->next = old->next;
  896. There is :c:func:`list_del_rcu()` (``include/linux/list.h``) which
  897. does this (the normal version poisons the old object, which we don't
  898. want).
  899. The reader must also be careful: some CPUs can look through the ``next``
  900. pointer to start reading the contents of the next element early, but
  901. don't realize that the pre-fetched contents is wrong when the ``next``
  902. pointer changes underneath them. Once again, there is a
  903. :c:func:`list_for_each_entry_rcu()` (``include/linux/list.h``)
  904. to help you. Of course, writers can just use
  905. :c:func:`list_for_each_entry()`, since there cannot be two
  906. simultaneous writers.
  907. Our final dilemma is this: when can we actually destroy the removed
  908. element? Remember, a reader might be stepping through this element in
  909. the list right now: if we free this element and the ``next`` pointer
  910. changes, the reader will jump off into garbage and crash. We need to
  911. wait until we know that all the readers who were traversing the list
  912. when we deleted the element are finished. We use
  913. :c:func:`call_rcu()` to register a callback which will actually
  914. destroy the object once all pre-existing readers are finished.
  915. Alternatively, :c:func:`synchronize_rcu()` may be used to block
  916. until all pre-existing are finished.
  917. But how does Read Copy Update know when the readers are finished? The
  918. method is this: firstly, the readers always traverse the list inside
  919. :c:func:`rcu_read_lock()`/:c:func:`rcu_read_unlock()` pairs:
  920. these simply disable preemption so the reader won't go to sleep while
  921. reading the list.
  922. RCU then waits until every other CPU has slept at least once: since
  923. readers cannot sleep, we know that any readers which were traversing the
  924. list during the deletion are finished, and the callback is triggered.
  925. The real Read Copy Update code is a little more optimized than this, but
  926. this is the fundamental idea.
  927. ::
  928. --- cache.c.perobjectlock 2003-12-11 17:15:03.000000000 +1100
  929. +++ cache.c.rcupdate 2003-12-11 17:55:14.000000000 +1100
  930. @@ -1,15 +1,18 @@
  931. #include <linux/list.h>
  932. #include <linux/slab.h>
  933. #include <linux/string.h>
  934. +#include <linux/rcupdate.h>
  935. #include <linux/mutex.h>
  936. #include <asm/errno.h>
  937. struct object
  938. {
  939. - /* These two protected by cache_lock. */
  940. + /* This is protected by RCU */
  941. struct list_head list;
  942. int popularity;
  943. + struct rcu_head rcu;
  944. +
  945. atomic_t refcnt;
  946. /* Doesn't change once created. */
  947. @@ -40,7 +43,7 @@
  948. {
  949. struct object *i;
  950. - list_for_each_entry(i, &cache, list) {
  951. + list_for_each_entry_rcu(i, &cache, list) {
  952. if (i->id == id) {
  953. i->popularity++;
  954. return i;
  955. @@ -49,19 +52,25 @@
  956. return NULL;
  957. }
  958. +/* Final discard done once we know no readers are looking. */
  959. +static void cache_delete_rcu(void *arg)
  960. +{
  961. + object_put(arg);
  962. +}
  963. +
  964. /* Must be holding cache_lock */
  965. static void __cache_delete(struct object *obj)
  966. {
  967. BUG_ON(!obj);
  968. - list_del(&obj->list);
  969. - object_put(obj);
  970. + list_del_rcu(&obj->list);
  971. cache_num--;
  972. + call_rcu(&obj->rcu, cache_delete_rcu);
  973. }
  974. /* Must be holding cache_lock */
  975. static void __cache_add(struct object *obj)
  976. {
  977. - list_add(&obj->list, &cache);
  978. + list_add_rcu(&obj->list, &cache);
  979. if (++cache_num > MAX_CACHE_SIZE) {
  980. struct object *i, *outcast = NULL;
  981. list_for_each_entry(i, &cache, list) {
  982. @@ -104,12 +114,11 @@
  983. struct object *cache_find(int id)
  984. {
  985. struct object *obj;
  986. - unsigned long flags;
  987. - spin_lock_irqsave(&cache_lock, flags);
  988. + rcu_read_lock();
  989. obj = __cache_find(id);
  990. if (obj)
  991. object_get(obj);
  992. - spin_unlock_irqrestore(&cache_lock, flags);
  993. + rcu_read_unlock();
  994. return obj;
  995. }
  996. Note that the reader will alter the popularity member in
  997. :c:func:`__cache_find()`, and now it doesn't hold a lock. One
  998. solution would be to make it an ``atomic_t``, but for this usage, we
  999. don't really care about races: an approximate result is good enough, so
  1000. I didn't change it.
  1001. The result is that :c:func:`cache_find()` requires no
  1002. synchronization with any other functions, so is almost as fast on SMP as
  1003. it would be on UP.
  1004. There is a further optimization possible here: remember our original
  1005. cache code, where there were no reference counts and the caller simply
  1006. held the lock whenever using the object? This is still possible: if you
  1007. hold the lock, no one can delete the object, so you don't need to get
  1008. and put the reference count.
  1009. Now, because the 'read lock' in RCU is simply disabling preemption, a
  1010. caller which always has preemption disabled between calling
  1011. :c:func:`cache_find()` and :c:func:`object_put()` does not
  1012. need to actually get and put the reference count: we could expose
  1013. :c:func:`__cache_find()` by making it non-static, and such
  1014. callers could simply call that.
  1015. The benefit here is that the reference count is not written to: the
  1016. object is not altered in any way, which is much faster on SMP machines
  1017. due to caching.
  1018. Per-CPU Data
  1019. ------------
  1020. Another technique for avoiding locking which is used fairly widely is to
  1021. duplicate information for each CPU. For example, if you wanted to keep a
  1022. count of a common condition, you could use a spin lock and a single
  1023. counter. Nice and simple.
  1024. If that was too slow (it's usually not, but if you've got a really big
  1025. machine to test on and can show that it is), you could instead use a
  1026. counter for each CPU, then none of them need an exclusive lock. See
  1027. :c:func:`DEFINE_PER_CPU()`, :c:func:`get_cpu_var()` and
  1028. :c:func:`put_cpu_var()` (``include/linux/percpu.h``).
  1029. Of particular use for simple per-cpu counters is the ``local_t`` type,
  1030. and the :c:func:`cpu_local_inc()` and related functions, which are
  1031. more efficient than simple code on some architectures
  1032. (``include/asm/local.h``).
  1033. Note that there is no simple, reliable way of getting an exact value of
  1034. such a counter, without introducing more locks. This is not a problem
  1035. for some uses.
  1036. Data Which Mostly Used By An IRQ Handler
  1037. ----------------------------------------
  1038. If data is always accessed from within the same IRQ handler, you don't
  1039. need a lock at all: the kernel already guarantees that the irq handler
  1040. will not run simultaneously on multiple CPUs.
  1041. Manfred Spraul points out that you can still do this, even if the data
  1042. is very occasionally accessed in user context or softirqs/tasklets. The
  1043. irq handler doesn't use a lock, and all other accesses are done as so::
  1044. spin_lock(&lock);
  1045. disable_irq(irq);
  1046. ...
  1047. enable_irq(irq);
  1048. spin_unlock(&lock);
  1049. The :c:func:`disable_irq()` prevents the irq handler from running
  1050. (and waits for it to finish if it's currently running on other CPUs).
  1051. The spinlock prevents any other accesses happening at the same time.
  1052. Naturally, this is slower than just a :c:func:`spin_lock_irq()`
  1053. call, so it only makes sense if this type of access happens extremely
  1054. rarely.
  1055. What Functions Are Safe To Call From Interrupts?
  1056. ================================================
  1057. Many functions in the kernel sleep (ie. call schedule()) directly or
  1058. indirectly: you can never call them while holding a spinlock, or with
  1059. preemption disabled. This also means you need to be in user context:
  1060. calling them from an interrupt is illegal.
  1061. Some Functions Which Sleep
  1062. --------------------------
  1063. The most common ones are listed below, but you usually have to read the
  1064. code to find out if other calls are safe. If everyone else who calls it
  1065. can sleep, you probably need to be able to sleep, too. In particular,
  1066. registration and deregistration functions usually expect to be called
  1067. from user context, and can sleep.
  1068. - Accesses to userspace:
  1069. - :c:func:`copy_from_user()`
  1070. - :c:func:`copy_to_user()`
  1071. - :c:func:`get_user()`
  1072. - :c:func:`put_user()`
  1073. - :c:func:`kmalloc(GFP_KERNEL) <kmalloc>`
  1074. - :c:func:`mutex_lock_interruptible()` and
  1075. :c:func:`mutex_lock()`
  1076. There is a :c:func:`mutex_trylock()` which does not sleep.
  1077. Still, it must not be used inside interrupt context since its
  1078. implementation is not safe for that. :c:func:`mutex_unlock()`
  1079. will also never sleep. It cannot be used in interrupt context either
  1080. since a mutex must be released by the same task that acquired it.
  1081. Some Functions Which Don't Sleep
  1082. --------------------------------
  1083. Some functions are safe to call from any context, or holding almost any
  1084. lock.
  1085. - :c:func:`printk()`
  1086. - :c:func:`kfree()`
  1087. - :c:func:`add_timer()` and :c:func:`del_timer()`
  1088. Mutex API reference
  1089. ===================
  1090. .. kernel-doc:: include/linux/mutex.h
  1091. :internal:
  1092. .. kernel-doc:: kernel/locking/mutex.c
  1093. :export:
  1094. Futex API reference
  1095. ===================
  1096. .. kernel-doc:: kernel/futex.c
  1097. :internal:
  1098. Further reading
  1099. ===============
  1100. - ``Documentation/locking/spinlocks.txt``: Linus Torvalds' spinlocking
  1101. tutorial in the kernel sources.
  1102. - Unix Systems for Modern Architectures: Symmetric Multiprocessing and
  1103. Caching for Kernel Programmers:
  1104. Curt Schimmel's very good introduction to kernel level locking (not
  1105. written for Linux, but nearly everything applies). The book is
  1106. expensive, but really worth every penny to understand SMP locking.
  1107. [ISBN: 0201633388]
  1108. Thanks
  1109. ======
  1110. Thanks to Telsa Gwynne for DocBooking, neatening and adding style.
  1111. Thanks to Martin Pool, Philipp Rumpf, Stephen Rothwell, Paul Mackerras,
  1112. Ruedi Aschwanden, Alan Cox, Manfred Spraul, Tim Waugh, Pete Zaitcev,
  1113. James Morris, Robert Love, Paul McKenney, John Ashby for proofreading,
  1114. correcting, flaming, commenting.
  1115. Thanks to the cabal for having no influence on this document.
  1116. Glossary
  1117. ========
  1118. preemption
  1119. Prior to 2.5, or when ``CONFIG_PREEMPT`` is unset, processes in user
  1120. context inside the kernel would not preempt each other (ie. you had that
  1121. CPU until you gave it up, except for interrupts). With the addition of
  1122. ``CONFIG_PREEMPT`` in 2.5.4, this changed: when in user context, higher
  1123. priority tasks can "cut in": spinlocks were changed to disable
  1124. preemption, even on UP.
  1125. bh
  1126. Bottom Half: for historical reasons, functions with '_bh' in them often
  1127. now refer to any software interrupt, e.g. :c:func:`spin_lock_bh()`
  1128. blocks any software interrupt on the current CPU. Bottom halves are
  1129. deprecated, and will eventually be replaced by tasklets. Only one bottom
  1130. half will be running at any time.
  1131. Hardware Interrupt / Hardware IRQ
  1132. Hardware interrupt request. :c:func:`in_irq()` returns true in a
  1133. hardware interrupt handler.
  1134. Interrupt Context
  1135. Not user context: processing a hardware irq or software irq. Indicated
  1136. by the :c:func:`in_interrupt()` macro returning true.
  1137. SMP
  1138. Symmetric Multi-Processor: kernels compiled for multiple-CPU machines.
  1139. (``CONFIG_SMP=y``).
  1140. Software Interrupt / softirq
  1141. Software interrupt handler. :c:func:`in_irq()` returns false;
  1142. :c:func:`in_softirq()` returns true. Tasklets and softirqs both
  1143. fall into the category of 'software interrupts'.
  1144. Strictly speaking a softirq is one of up to 32 enumerated software
  1145. interrupts which can run on multiple CPUs at once. Sometimes used to
  1146. refer to tasklets as well (ie. all software interrupts).
  1147. tasklet
  1148. A dynamically-registrable software interrupt, which is guaranteed to
  1149. only run on one CPU at a time.
  1150. timer
  1151. A dynamically-registrable software interrupt, which is run at (or close
  1152. to) a given time. When running, it is just like a tasklet (in fact, they
  1153. are called from the ``TIMER_SOFTIRQ``).
  1154. UP
  1155. Uni-Processor: Non-SMP. (``CONFIG_SMP=n``).
  1156. User Context
  1157. The kernel executing on behalf of a particular process (ie. a system
  1158. call or trap) or kernel thread. You can tell which process with the
  1159. ``current`` macro.) Not to be confused with userspace. Can be
  1160. interrupted by software or hardware interrupts.
  1161. Userspace
  1162. A process executing its own code outside the kernel.