locking.rst 53 KB

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