rt-mutex-design.txt 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. #
  2. # Copyright (c) 2006 Steven Rostedt
  3. # Licensed under the GNU Free Documentation License, Version 1.2
  4. #
  5. RT-mutex implementation design
  6. ------------------------------
  7. This document tries to describe the design of the rtmutex.c implementation.
  8. It doesn't describe the reasons why rtmutex.c exists. For that please see
  9. Documentation/locking/rt-mutex.txt. Although this document does explain problems
  10. that happen without this code, but that is in the concept to understand
  11. what the code actually is doing.
  12. The goal of this document is to help others understand the priority
  13. inheritance (PI) algorithm that is used, as well as reasons for the
  14. decisions that were made to implement PI in the manner that was done.
  15. Unbounded Priority Inversion
  16. ----------------------------
  17. Priority inversion is when a lower priority process executes while a higher
  18. priority process wants to run. This happens for several reasons, and
  19. most of the time it can't be helped. Anytime a high priority process wants
  20. to use a resource that a lower priority process has (a mutex for example),
  21. the high priority process must wait until the lower priority process is done
  22. with the resource. This is a priority inversion. What we want to prevent
  23. is something called unbounded priority inversion. That is when the high
  24. priority process is prevented from running by a lower priority process for
  25. an undetermined amount of time.
  26. The classic example of unbounded priority inversion is where you have three
  27. processes, let's call them processes A, B, and C, where A is the highest
  28. priority process, C is the lowest, and B is in between. A tries to grab a lock
  29. that C owns and must wait and lets C run to release the lock. But in the
  30. meantime, B executes, and since B is of a higher priority than C, it preempts C,
  31. but by doing so, it is in fact preempting A which is a higher priority process.
  32. Now there's no way of knowing how long A will be sleeping waiting for C
  33. to release the lock, because for all we know, B is a CPU hog and will
  34. never give C a chance to release the lock. This is called unbounded priority
  35. inversion.
  36. Here's a little ASCII art to show the problem.
  37. grab lock L1 (owned by C)
  38. |
  39. A ---+
  40. C preempted by B
  41. |
  42. C +----+
  43. B +-------->
  44. B now keeps A from running.
  45. Priority Inheritance (PI)
  46. -------------------------
  47. There are several ways to solve this issue, but other ways are out of scope
  48. for this document. Here we only discuss PI.
  49. PI is where a process inherits the priority of another process if the other
  50. process blocks on a lock owned by the current process. To make this easier
  51. to understand, let's use the previous example, with processes A, B, and C again.
  52. This time, when A blocks on the lock owned by C, C would inherit the priority
  53. of A. So now if B becomes runnable, it would not preempt C, since C now has
  54. the high priority of A. As soon as C releases the lock, it loses its
  55. inherited priority, and A then can continue with the resource that C had.
  56. Terminology
  57. -----------
  58. Here I explain some terminology that is used in this document to help describe
  59. the design that is used to implement PI.
  60. PI chain - The PI chain is an ordered series of locks and processes that cause
  61. processes to inherit priorities from a previous process that is
  62. blocked on one of its locks. This is described in more detail
  63. later in this document.
  64. mutex - In this document, to differentiate from locks that implement
  65. PI and spin locks that are used in the PI code, from now on
  66. the PI locks will be called a mutex.
  67. lock - In this document from now on, I will use the term lock when
  68. referring to spin locks that are used to protect parts of the PI
  69. algorithm. These locks disable preemption for UP (when
  70. CONFIG_PREEMPT is enabled) and on SMP prevents multiple CPUs from
  71. entering critical sections simultaneously.
  72. spin lock - Same as lock above.
  73. waiter - A waiter is a struct that is stored on the stack of a blocked
  74. process. Since the scope of the waiter is within the code for
  75. a process being blocked on the mutex, it is fine to allocate
  76. the waiter on the process's stack (local variable). This
  77. structure holds a pointer to the task, as well as the mutex that
  78. the task is blocked on. It also has rbtree node structures to
  79. place the task in the waiters rbtree of a mutex as well as the
  80. pi_waiters rbtree of a mutex owner task (described below).
  81. waiter is sometimes used in reference to the task that is waiting
  82. on a mutex. This is the same as waiter->task.
  83. waiters - A list of processes that are blocked on a mutex.
  84. top waiter - The highest priority process waiting on a specific mutex.
  85. top pi waiter - The highest priority process waiting on one of the mutexes
  86. that a specific process owns.
  87. Note: task and process are used interchangeably in this document, mostly to
  88. differentiate between two processes that are being described together.
  89. PI chain
  90. --------
  91. The PI chain is a list of processes and mutexes that may cause priority
  92. inheritance to take place. Multiple chains may converge, but a chain
  93. would never diverge, since a process can't be blocked on more than one
  94. mutex at a time.
  95. Example:
  96. Process: A, B, C, D, E
  97. Mutexes: L1, L2, L3, L4
  98. A owns: L1
  99. B blocked on L1
  100. B owns L2
  101. C blocked on L2
  102. C owns L3
  103. D blocked on L3
  104. D owns L4
  105. E blocked on L4
  106. The chain would be:
  107. E->L4->D->L3->C->L2->B->L1->A
  108. To show where two chains merge, we could add another process F and
  109. another mutex L5 where B owns L5 and F is blocked on mutex L5.
  110. The chain for F would be:
  111. F->L5->B->L1->A
  112. Since a process may own more than one mutex, but never be blocked on more than
  113. one, the chains merge.
  114. Here we show both chains:
  115. E->L4->D->L3->C->L2-+
  116. |
  117. +->B->L1->A
  118. |
  119. F->L5-+
  120. For PI to work, the processes at the right end of these chains (or we may
  121. also call it the Top of the chain) must be equal to or higher in priority
  122. than the processes to the left or below in the chain.
  123. Also since a mutex may have more than one process blocked on it, we can
  124. have multiple chains merge at mutexes. If we add another process G that is
  125. blocked on mutex L2:
  126. G->L2->B->L1->A
  127. And once again, to show how this can grow I will show the merging chains
  128. again.
  129. E->L4->D->L3->C-+
  130. +->L2-+
  131. | |
  132. G-+ +->B->L1->A
  133. |
  134. F->L5-+
  135. If process G has the highest priority in the chain, then all the tasks up
  136. the chain (A and B in this example), must have their priorities increased
  137. to that of G.
  138. Mutex Waiters Tree
  139. -----------------
  140. Every mutex keeps track of all the waiters that are blocked on itself. The
  141. mutex has a rbtree to store these waiters by priority. This tree is protected
  142. by a spin lock that is located in the struct of the mutex. This lock is called
  143. wait_lock.
  144. Task PI Tree
  145. ------------
  146. To keep track of the PI chains, each process has its own PI rbtree. This is
  147. a tree of all top waiters of the mutexes that are owned by the process.
  148. Note that this tree only holds the top waiters and not all waiters that are
  149. blocked on mutexes owned by the process.
  150. The top of the task's PI tree is always the highest priority task that
  151. is waiting on a mutex that is owned by the task. So if the task has
  152. inherited a priority, it will always be the priority of the task that is
  153. at the top of this tree.
  154. This tree is stored in the task structure of a process as a rbtree called
  155. pi_waiters. It is protected by a spin lock also in the task structure,
  156. called pi_lock. This lock may also be taken in interrupt context, so when
  157. locking the pi_lock, interrupts must be disabled.
  158. Depth of the PI Chain
  159. ---------------------
  160. The maximum depth of the PI chain is not dynamic, and could actually be
  161. defined. But is very complex to figure it out, since it depends on all
  162. the nesting of mutexes. Let's look at the example where we have 3 mutexes,
  163. L1, L2, and L3, and four separate functions func1, func2, func3 and func4.
  164. The following shows a locking order of L1->L2->L3, but may not actually
  165. be directly nested that way.
  166. void func1(void)
  167. {
  168. mutex_lock(L1);
  169. /* do anything */
  170. mutex_unlock(L1);
  171. }
  172. void func2(void)
  173. {
  174. mutex_lock(L1);
  175. mutex_lock(L2);
  176. /* do something */
  177. mutex_unlock(L2);
  178. mutex_unlock(L1);
  179. }
  180. void func3(void)
  181. {
  182. mutex_lock(L2);
  183. mutex_lock(L3);
  184. /* do something else */
  185. mutex_unlock(L3);
  186. mutex_unlock(L2);
  187. }
  188. void func4(void)
  189. {
  190. mutex_lock(L3);
  191. /* do something again */
  192. mutex_unlock(L3);
  193. }
  194. Now we add 4 processes that run each of these functions separately.
  195. Processes A, B, C, and D which run functions func1, func2, func3 and func4
  196. respectively, and such that D runs first and A last. With D being preempted
  197. in func4 in the "do something again" area, we have a locking that follows:
  198. D owns L3
  199. C blocked on L3
  200. C owns L2
  201. B blocked on L2
  202. B owns L1
  203. A blocked on L1
  204. And thus we have the chain A->L1->B->L2->C->L3->D.
  205. This gives us a PI depth of 4 (four processes), but looking at any of the
  206. functions individually, it seems as though they only have at most a locking
  207. depth of two. So, although the locking depth is defined at compile time,
  208. it still is very difficult to find the possibilities of that depth.
  209. Now since mutexes can be defined by user-land applications, we don't want a DOS
  210. type of application that nests large amounts of mutexes to create a large
  211. PI chain, and have the code holding spin locks while looking at a large
  212. amount of data. So to prevent this, the implementation not only implements
  213. a maximum lock depth, but also only holds at most two different locks at a
  214. time, as it walks the PI chain. More about this below.
  215. Mutex owner and flags
  216. ---------------------
  217. The mutex structure contains a pointer to the owner of the mutex. If the
  218. mutex is not owned, this owner is set to NULL. Since all architectures
  219. have the task structure on at least a two byte alignment (and if this is
  220. not true, the rtmutex.c code will be broken!), this allows for the least
  221. significant bit to be used as a flag. Bit 0 is used as the "Has Waiters"
  222. flag. It's set whenever there are waiters on a mutex.
  223. See Documentation/locking/rt-mutex.txt for further details.
  224. cmpxchg Tricks
  225. --------------
  226. Some architectures implement an atomic cmpxchg (Compare and Exchange). This
  227. is used (when applicable) to keep the fast path of grabbing and releasing
  228. mutexes short.
  229. cmpxchg is basically the following function performed atomically:
  230. unsigned long _cmpxchg(unsigned long *A, unsigned long *B, unsigned long *C)
  231. {
  232. unsigned long T = *A;
  233. if (*A == *B) {
  234. *A = *C;
  235. }
  236. return T;
  237. }
  238. #define cmpxchg(a,b,c) _cmpxchg(&a,&b,&c)
  239. This is really nice to have, since it allows you to only update a variable
  240. if the variable is what you expect it to be. You know if it succeeded if
  241. the return value (the old value of A) is equal to B.
  242. The macro rt_mutex_cmpxchg is used to try to lock and unlock mutexes. If
  243. the architecture does not support CMPXCHG, then this macro is simply set
  244. to fail every time. But if CMPXCHG is supported, then this will
  245. help out extremely to keep the fast path short.
  246. The use of rt_mutex_cmpxchg with the flags in the owner field help optimize
  247. the system for architectures that support it. This will also be explained
  248. later in this document.
  249. Priority adjustments
  250. --------------------
  251. The implementation of the PI code in rtmutex.c has several places that a
  252. process must adjust its priority. With the help of the pi_waiters of a
  253. process this is rather easy to know what needs to be adjusted.
  254. The functions implementing the task adjustments are rt_mutex_adjust_prio
  255. and rt_mutex_setprio. rt_mutex_setprio is only used in rt_mutex_adjust_prio.
  256. rt_mutex_adjust_prio examines the priority of the task, and the highest
  257. priority process that is waiting any of mutexes owned by the task. Since
  258. the pi_waiters of a task holds an order by priority of all the top waiters
  259. of all the mutexes that the task owns, we simply need to compare the top
  260. pi waiter to its own normal/deadline priority and take the higher one.
  261. Then rt_mutex_setprio is called to adjust the priority of the task to the
  262. new priority. Note that rt_mutex_setprio is defined in kernel/sched/core.c
  263. to implement the actual change in priority.
  264. (Note: For the "prio" field in task_struct, the lower the number, the
  265. higher the priority. A "prio" of 5 is of higher priority than a
  266. "prio" of 10.)
  267. It is interesting to note that rt_mutex_adjust_prio can either increase
  268. or decrease the priority of the task. In the case that a higher priority
  269. process has just blocked on a mutex owned by the task, rt_mutex_adjust_prio
  270. would increase/boost the task's priority. But if a higher priority task
  271. were for some reason to leave the mutex (timeout or signal), this same function
  272. would decrease/unboost the priority of the task. That is because the pi_waiters
  273. always contains the highest priority task that is waiting on a mutex owned
  274. by the task, so we only need to compare the priority of that top pi waiter
  275. to the normal priority of the given task.
  276. High level overview of the PI chain walk
  277. ----------------------------------------
  278. The PI chain walk is implemented by the function rt_mutex_adjust_prio_chain.
  279. The implementation has gone through several iterations, and has ended up
  280. with what we believe is the best. It walks the PI chain by only grabbing
  281. at most two locks at a time, and is very efficient.
  282. The rt_mutex_adjust_prio_chain can be used either to boost or lower process
  283. priorities.
  284. rt_mutex_adjust_prio_chain is called with a task to be checked for PI
  285. (de)boosting (the owner of a mutex that a process is blocking on), a flag to
  286. check for deadlocking, the mutex that the task owns, a pointer to a waiter
  287. that is the process's waiter struct that is blocked on the mutex (although this
  288. parameter may be NULL for deboosting), a pointer to the mutex on which the task
  289. is blocked, and a top_task as the top waiter of the mutex.
  290. For this explanation, I will not mention deadlock detection. This explanation
  291. will try to stay at a high level.
  292. When this function is called, there are no locks held. That also means
  293. that the state of the owner and lock can change when entered into this function.
  294. Before this function is called, the task has already had rt_mutex_adjust_prio
  295. performed on it. This means that the task is set to the priority that it
  296. should be at, but the rbtree nodes of the task's waiter have not been updated
  297. with the new priorities, and this task may not be in the proper locations
  298. in the pi_waiters and waiters trees that the task is blocked on. This function
  299. solves all that.
  300. The main operation of this function is summarized by Thomas Gleixner in
  301. rtmutex.c. See the 'Chain walk basics and protection scope' comment for further
  302. details.
  303. Taking of a mutex (The walk through)
  304. ------------------------------------
  305. OK, now let's take a look at the detailed walk through of what happens when
  306. taking a mutex.
  307. The first thing that is tried is the fast taking of the mutex. This is
  308. done when we have CMPXCHG enabled (otherwise the fast taking automatically
  309. fails). Only when the owner field of the mutex is NULL can the lock be
  310. taken with the CMPXCHG and nothing else needs to be done.
  311. If there is contention on the lock, we go about the slow path
  312. (rt_mutex_slowlock).
  313. The slow path function is where the task's waiter structure is created on
  314. the stack. This is because the waiter structure is only needed for the
  315. scope of this function. The waiter structure holds the nodes to store
  316. the task on the waiters tree of the mutex, and if need be, the pi_waiters
  317. tree of the owner.
  318. The wait_lock of the mutex is taken since the slow path of unlocking the
  319. mutex also takes this lock.
  320. We then call try_to_take_rt_mutex. This is where the architecture that
  321. does not implement CMPXCHG would always grab the lock (if there's no
  322. contention).
  323. try_to_take_rt_mutex is used every time the task tries to grab a mutex in the
  324. slow path. The first thing that is done here is an atomic setting of
  325. the "Has Waiters" flag of the mutex's owner field. By setting this flag
  326. now, the current owner of the mutex being contended for can't release the mutex
  327. without going into the slow unlock path, and it would then need to grab the
  328. wait_lock, which this code currently holds. So setting the "Has Waiters" flag
  329. forces the current owner to synchronize with this code.
  330. The lock is taken if the following are true:
  331. 1) The lock has no owner
  332. 2) The current task is the highest priority against all other
  333. waiters of the lock
  334. If the task succeeds to acquire the lock, then the task is set as the
  335. owner of the lock, and if the lock still has waiters, the top_waiter
  336. (highest priority task waiting on the lock) is added to this task's
  337. pi_waiters tree.
  338. If the lock is not taken by try_to_take_rt_mutex(), then the
  339. task_blocks_on_rt_mutex() function is called. This will add the task to
  340. the lock's waiter tree and propagate the pi chain of the lock as well
  341. as the lock's owner's pi_waiters tree. This is described in the next
  342. section.
  343. Task blocks on mutex
  344. --------------------
  345. The accounting of a mutex and process is done with the waiter structure of
  346. the process. The "task" field is set to the process, and the "lock" field
  347. to the mutex. The rbtree node of waiter are initialized to the processes
  348. current priority.
  349. Since the wait_lock was taken at the entry of the slow lock, we can safely
  350. add the waiter to the task waiter tree. If the current process is the
  351. highest priority process currently waiting on this mutex, then we remove the
  352. previous top waiter process (if it exists) from the pi_waiters of the owner,
  353. and add the current process to that tree. Since the pi_waiter of the owner
  354. has changed, we call rt_mutex_adjust_prio on the owner to see if the owner
  355. should adjust its priority accordingly.
  356. If the owner is also blocked on a lock, and had its pi_waiters changed
  357. (or deadlock checking is on), we unlock the wait_lock of the mutex and go ahead
  358. and run rt_mutex_adjust_prio_chain on the owner, as described earlier.
  359. Now all locks are released, and if the current process is still blocked on a
  360. mutex (waiter "task" field is not NULL), then we go to sleep (call schedule).
  361. Waking up in the loop
  362. ---------------------
  363. The task can then wake up for a couple of reasons:
  364. 1) The previous lock owner released the lock, and the task now is top_waiter
  365. 2) we received a signal or timeout
  366. In both cases, the task will try again to acquire the lock. If it
  367. does, then it will take itself off the waiters tree and set itself back
  368. to the TASK_RUNNING state.
  369. In first case, if the lock was acquired by another task before this task
  370. could get the lock, then it will go back to sleep and wait to be woken again.
  371. The second case is only applicable for tasks that are grabbing a mutex
  372. that can wake up before getting the lock, either due to a signal or
  373. a timeout (i.e. rt_mutex_timed_futex_lock()). When woken, it will try to
  374. take the lock again, if it succeeds, then the task will return with the
  375. lock held, otherwise it will return with -EINTR if the task was woken
  376. by a signal, or -ETIMEDOUT if it timed out.
  377. Unlocking the Mutex
  378. -------------------
  379. The unlocking of a mutex also has a fast path for those architectures with
  380. CMPXCHG. Since the taking of a mutex on contention always sets the
  381. "Has Waiters" flag of the mutex's owner, we use this to know if we need to
  382. take the slow path when unlocking the mutex. If the mutex doesn't have any
  383. waiters, the owner field of the mutex would equal the current process and
  384. the mutex can be unlocked by just replacing the owner field with NULL.
  385. If the owner field has the "Has Waiters" bit set (or CMPXCHG is not available),
  386. the slow unlock path is taken.
  387. The first thing done in the slow unlock path is to take the wait_lock of the
  388. mutex. This synchronizes the locking and unlocking of the mutex.
  389. A check is made to see if the mutex has waiters or not. On architectures that
  390. do not have CMPXCHG, this is the location that the owner of the mutex will
  391. determine if a waiter needs to be awoken or not. On architectures that
  392. do have CMPXCHG, that check is done in the fast path, but it is still needed
  393. in the slow path too. If a waiter of a mutex woke up because of a signal
  394. or timeout between the time the owner failed the fast path CMPXCHG check and
  395. the grabbing of the wait_lock, the mutex may not have any waiters, thus the
  396. owner still needs to make this check. If there are no waiters then the mutex
  397. owner field is set to NULL, the wait_lock is released and nothing more is
  398. needed.
  399. If there are waiters, then we need to wake one up.
  400. On the wake up code, the pi_lock of the current owner is taken. The top
  401. waiter of the lock is found and removed from the waiters tree of the mutex
  402. as well as the pi_waiters tree of the current owner. The "Has Waiters" bit is
  403. marked to prevent lower priority tasks from stealing the lock.
  404. Finally we unlock the pi_lock of the pending owner and wake it up.
  405. Contact
  406. -------
  407. For updates on this document, please email Steven Rostedt <rostedt@goodmis.org>
  408. Credits
  409. -------
  410. Author: Steven Rostedt <rostedt@goodmis.org>
  411. Updated: Alex Shi <alex.shi@linaro.org> - 7/6/2017
  412. Original Reviewers: Ingo Molnar, Thomas Gleixner, Thomas Duetsch, and
  413. Randy Dunlap
  414. Update (7/6/2017) Reviewers: Steven Rostedt and Sebastian Siewior
  415. Updates
  416. -------
  417. This document was originally written for 2.6.17-rc3-mm1
  418. was updated on 4.12