locking.rst 52 KB

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