0001 ==============================
0002 RT-mutex implementation design
0003 ==============================
0004
0005 Copyright (c) 2006 Steven Rostedt
0006
0007 Licensed under the GNU Free Documentation License, Version 1.2
0008
0009
0010 This document tries to describe the design of the rtmutex.c implementation.
0011 It doesn't describe the reasons why rtmutex.c exists. For that please see
0012 Documentation/locking/rt-mutex.rst. Although this document does explain problems
0013 that happen without this code, but that is in the concept to understand
0014 what the code actually is doing.
0015
0016 The goal of this document is to help others understand the priority
0017 inheritance (PI) algorithm that is used, as well as reasons for the
0018 decisions that were made to implement PI in the manner that was done.
0019
0020
0021 Unbounded Priority Inversion
0022 ----------------------------
0023
0024 Priority inversion is when a lower priority process executes while a higher
0025 priority process wants to run. This happens for several reasons, and
0026 most of the time it can't be helped. Anytime a high priority process wants
0027 to use a resource that a lower priority process has (a mutex for example),
0028 the high priority process must wait until the lower priority process is done
0029 with the resource. This is a priority inversion. What we want to prevent
0030 is something called unbounded priority inversion. That is when the high
0031 priority process is prevented from running by a lower priority process for
0032 an undetermined amount of time.
0033
0034 The classic example of unbounded priority inversion is where you have three
0035 processes, let's call them processes A, B, and C, where A is the highest
0036 priority process, C is the lowest, and B is in between. A tries to grab a lock
0037 that C owns and must wait and lets C run to release the lock. But in the
0038 meantime, B executes, and since B is of a higher priority than C, it preempts C,
0039 but by doing so, it is in fact preempting A which is a higher priority process.
0040 Now there's no way of knowing how long A will be sleeping waiting for C
0041 to release the lock, because for all we know, B is a CPU hog and will
0042 never give C a chance to release the lock. This is called unbounded priority
0043 inversion.
0044
0045 Here's a little ASCII art to show the problem::
0046
0047 grab lock L1 (owned by C)
0048 |
0049 A ---+
0050 C preempted by B
0051 |
0052 C +----+
0053
0054 B +-------->
0055 B now keeps A from running.
0056
0057
0058 Priority Inheritance (PI)
0059 -------------------------
0060
0061 There are several ways to solve this issue, but other ways are out of scope
0062 for this document. Here we only discuss PI.
0063
0064 PI is where a process inherits the priority of another process if the other
0065 process blocks on a lock owned by the current process. To make this easier
0066 to understand, let's use the previous example, with processes A, B, and C again.
0067
0068 This time, when A blocks on the lock owned by C, C would inherit the priority
0069 of A. So now if B becomes runnable, it would not preempt C, since C now has
0070 the high priority of A. As soon as C releases the lock, it loses its
0071 inherited priority, and A then can continue with the resource that C had.
0072
0073 Terminology
0074 -----------
0075
0076 Here I explain some terminology that is used in this document to help describe
0077 the design that is used to implement PI.
0078
0079 PI chain
0080 - The PI chain is an ordered series of locks and processes that cause
0081 processes to inherit priorities from a previous process that is
0082 blocked on one of its locks. This is described in more detail
0083 later in this document.
0084
0085 mutex
0086 - In this document, to differentiate from locks that implement
0087 PI and spin locks that are used in the PI code, from now on
0088 the PI locks will be called a mutex.
0089
0090 lock
0091 - In this document from now on, I will use the term lock when
0092 referring to spin locks that are used to protect parts of the PI
0093 algorithm. These locks disable preemption for UP (when
0094 CONFIG_PREEMPT is enabled) and on SMP prevents multiple CPUs from
0095 entering critical sections simultaneously.
0096
0097 spin lock
0098 - Same as lock above.
0099
0100 waiter
0101 - A waiter is a struct that is stored on the stack of a blocked
0102 process. Since the scope of the waiter is within the code for
0103 a process being blocked on the mutex, it is fine to allocate
0104 the waiter on the process's stack (local variable). This
0105 structure holds a pointer to the task, as well as the mutex that
0106 the task is blocked on. It also has rbtree node structures to
0107 place the task in the waiters rbtree of a mutex as well as the
0108 pi_waiters rbtree of a mutex owner task (described below).
0109
0110 waiter is sometimes used in reference to the task that is waiting
0111 on a mutex. This is the same as waiter->task.
0112
0113 waiters
0114 - A list of processes that are blocked on a mutex.
0115
0116 top waiter
0117 - The highest priority process waiting on a specific mutex.
0118
0119 top pi waiter
0120 - The highest priority process waiting on one of the mutexes
0121 that a specific process owns.
0122
0123 Note:
0124 task and process are used interchangeably in this document, mostly to
0125 differentiate between two processes that are being described together.
0126
0127
0128 PI chain
0129 --------
0130
0131 The PI chain is a list of processes and mutexes that may cause priority
0132 inheritance to take place. Multiple chains may converge, but a chain
0133 would never diverge, since a process can't be blocked on more than one
0134 mutex at a time.
0135
0136 Example::
0137
0138 Process: A, B, C, D, E
0139 Mutexes: L1, L2, L3, L4
0140
0141 A owns: L1
0142 B blocked on L1
0143 B owns L2
0144 C blocked on L2
0145 C owns L3
0146 D blocked on L3
0147 D owns L4
0148 E blocked on L4
0149
0150 The chain would be::
0151
0152 E->L4->D->L3->C->L2->B->L1->A
0153
0154 To show where two chains merge, we could add another process F and
0155 another mutex L5 where B owns L5 and F is blocked on mutex L5.
0156
0157 The chain for F would be::
0158
0159 F->L5->B->L1->A
0160
0161 Since a process may own more than one mutex, but never be blocked on more than
0162 one, the chains merge.
0163
0164 Here we show both chains::
0165
0166 E->L4->D->L3->C->L2-+
0167 |
0168 +->B->L1->A
0169 |
0170 F->L5-+
0171
0172 For PI to work, the processes at the right end of these chains (or we may
0173 also call it the Top of the chain) must be equal to or higher in priority
0174 than the processes to the left or below in the chain.
0175
0176 Also since a mutex may have more than one process blocked on it, we can
0177 have multiple chains merge at mutexes. If we add another process G that is
0178 blocked on mutex L2::
0179
0180 G->L2->B->L1->A
0181
0182 And once again, to show how this can grow I will show the merging chains
0183 again::
0184
0185 E->L4->D->L3->C-+
0186 +->L2-+
0187 | |
0188 G-+ +->B->L1->A
0189 |
0190 F->L5-+
0191
0192 If process G has the highest priority in the chain, then all the tasks up
0193 the chain (A and B in this example), must have their priorities increased
0194 to that of G.
0195
0196 Mutex Waiters Tree
0197 ------------------
0198
0199 Every mutex keeps track of all the waiters that are blocked on itself. The
0200 mutex has a rbtree to store these waiters by priority. This tree is protected
0201 by a spin lock that is located in the struct of the mutex. This lock is called
0202 wait_lock.
0203
0204
0205 Task PI Tree
0206 ------------
0207
0208 To keep track of the PI chains, each process has its own PI rbtree. This is
0209 a tree of all top waiters of the mutexes that are owned by the process.
0210 Note that this tree only holds the top waiters and not all waiters that are
0211 blocked on mutexes owned by the process.
0212
0213 The top of the task's PI tree is always the highest priority task that
0214 is waiting on a mutex that is owned by the task. So if the task has
0215 inherited a priority, it will always be the priority of the task that is
0216 at the top of this tree.
0217
0218 This tree is stored in the task structure of a process as a rbtree called
0219 pi_waiters. It is protected by a spin lock also in the task structure,
0220 called pi_lock. This lock may also be taken in interrupt context, so when
0221 locking the pi_lock, interrupts must be disabled.
0222
0223
0224 Depth of the PI Chain
0225 ---------------------
0226
0227 The maximum depth of the PI chain is not dynamic, and could actually be
0228 defined. But is very complex to figure it out, since it depends on all
0229 the nesting of mutexes. Let's look at the example where we have 3 mutexes,
0230 L1, L2, and L3, and four separate functions func1, func2, func3 and func4.
0231 The following shows a locking order of L1->L2->L3, but may not actually
0232 be directly nested that way::
0233
0234 void func1(void)
0235 {
0236 mutex_lock(L1);
0237
0238 /* do anything */
0239
0240 mutex_unlock(L1);
0241 }
0242
0243 void func2(void)
0244 {
0245 mutex_lock(L1);
0246 mutex_lock(L2);
0247
0248 /* do something */
0249
0250 mutex_unlock(L2);
0251 mutex_unlock(L1);
0252 }
0253
0254 void func3(void)
0255 {
0256 mutex_lock(L2);
0257 mutex_lock(L3);
0258
0259 /* do something else */
0260
0261 mutex_unlock(L3);
0262 mutex_unlock(L2);
0263 }
0264
0265 void func4(void)
0266 {
0267 mutex_lock(L3);
0268
0269 /* do something again */
0270
0271 mutex_unlock(L3);
0272 }
0273
0274 Now we add 4 processes that run each of these functions separately.
0275 Processes A, B, C, and D which run functions func1, func2, func3 and func4
0276 respectively, and such that D runs first and A last. With D being preempted
0277 in func4 in the "do something again" area, we have a locking that follows::
0278
0279 D owns L3
0280 C blocked on L3
0281 C owns L2
0282 B blocked on L2
0283 B owns L1
0284 A blocked on L1
0285
0286 And thus we have the chain A->L1->B->L2->C->L3->D.
0287
0288 This gives us a PI depth of 4 (four processes), but looking at any of the
0289 functions individually, it seems as though they only have at most a locking
0290 depth of two. So, although the locking depth is defined at compile time,
0291 it still is very difficult to find the possibilities of that depth.
0292
0293 Now since mutexes can be defined by user-land applications, we don't want a DOS
0294 type of application that nests large amounts of mutexes to create a large
0295 PI chain, and have the code holding spin locks while looking at a large
0296 amount of data. So to prevent this, the implementation not only implements
0297 a maximum lock depth, but also only holds at most two different locks at a
0298 time, as it walks the PI chain. More about this below.
0299
0300
0301 Mutex owner and flags
0302 ---------------------
0303
0304 The mutex structure contains a pointer to the owner of the mutex. If the
0305 mutex is not owned, this owner is set to NULL. Since all architectures
0306 have the task structure on at least a two byte alignment (and if this is
0307 not true, the rtmutex.c code will be broken!), this allows for the least
0308 significant bit to be used as a flag. Bit 0 is used as the "Has Waiters"
0309 flag. It's set whenever there are waiters on a mutex.
0310
0311 See Documentation/locking/rt-mutex.rst for further details.
0312
0313 cmpxchg Tricks
0314 --------------
0315
0316 Some architectures implement an atomic cmpxchg (Compare and Exchange). This
0317 is used (when applicable) to keep the fast path of grabbing and releasing
0318 mutexes short.
0319
0320 cmpxchg is basically the following function performed atomically::
0321
0322 unsigned long _cmpxchg(unsigned long *A, unsigned long *B, unsigned long *C)
0323 {
0324 unsigned long T = *A;
0325 if (*A == *B) {
0326 *A = *C;
0327 }
0328 return T;
0329 }
0330 #define cmpxchg(a,b,c) _cmpxchg(&a,&b,&c)
0331
0332 This is really nice to have, since it allows you to only update a variable
0333 if the variable is what you expect it to be. You know if it succeeded if
0334 the return value (the old value of A) is equal to B.
0335
0336 The macro rt_mutex_cmpxchg is used to try to lock and unlock mutexes. If
0337 the architecture does not support CMPXCHG, then this macro is simply set
0338 to fail every time. But if CMPXCHG is supported, then this will
0339 help out extremely to keep the fast path short.
0340
0341 The use of rt_mutex_cmpxchg with the flags in the owner field help optimize
0342 the system for architectures that support it. This will also be explained
0343 later in this document.
0344
0345
0346 Priority adjustments
0347 --------------------
0348
0349 The implementation of the PI code in rtmutex.c has several places that a
0350 process must adjust its priority. With the help of the pi_waiters of a
0351 process this is rather easy to know what needs to be adjusted.
0352
0353 The functions implementing the task adjustments are rt_mutex_adjust_prio
0354 and rt_mutex_setprio. rt_mutex_setprio is only used in rt_mutex_adjust_prio.
0355
0356 rt_mutex_adjust_prio examines the priority of the task, and the highest
0357 priority process that is waiting any of mutexes owned by the task. Since
0358 the pi_waiters of a task holds an order by priority of all the top waiters
0359 of all the mutexes that the task owns, we simply need to compare the top
0360 pi waiter to its own normal/deadline priority and take the higher one.
0361 Then rt_mutex_setprio is called to adjust the priority of the task to the
0362 new priority. Note that rt_mutex_setprio is defined in kernel/sched/core.c
0363 to implement the actual change in priority.
0364
0365 Note:
0366 For the "prio" field in task_struct, the lower the number, the
0367 higher the priority. A "prio" of 5 is of higher priority than a
0368 "prio" of 10.
0369
0370 It is interesting to note that rt_mutex_adjust_prio can either increase
0371 or decrease the priority of the task. In the case that a higher priority
0372 process has just blocked on a mutex owned by the task, rt_mutex_adjust_prio
0373 would increase/boost the task's priority. But if a higher priority task
0374 were for some reason to leave the mutex (timeout or signal), this same function
0375 would decrease/unboost the priority of the task. That is because the pi_waiters
0376 always contains the highest priority task that is waiting on a mutex owned
0377 by the task, so we only need to compare the priority of that top pi waiter
0378 to the normal priority of the given task.
0379
0380
0381 High level overview of the PI chain walk
0382 ----------------------------------------
0383
0384 The PI chain walk is implemented by the function rt_mutex_adjust_prio_chain.
0385
0386 The implementation has gone through several iterations, and has ended up
0387 with what we believe is the best. It walks the PI chain by only grabbing
0388 at most two locks at a time, and is very efficient.
0389
0390 The rt_mutex_adjust_prio_chain can be used either to boost or lower process
0391 priorities.
0392
0393 rt_mutex_adjust_prio_chain is called with a task to be checked for PI
0394 (de)boosting (the owner of a mutex that a process is blocking on), a flag to
0395 check for deadlocking, the mutex that the task owns, a pointer to a waiter
0396 that is the process's waiter struct that is blocked on the mutex (although this
0397 parameter may be NULL for deboosting), a pointer to the mutex on which the task
0398 is blocked, and a top_task as the top waiter of the mutex.
0399
0400 For this explanation, I will not mention deadlock detection. This explanation
0401 will try to stay at a high level.
0402
0403 When this function is called, there are no locks held. That also means
0404 that the state of the owner and lock can change when entered into this function.
0405
0406 Before this function is called, the task has already had rt_mutex_adjust_prio
0407 performed on it. This means that the task is set to the priority that it
0408 should be at, but the rbtree nodes of the task's waiter have not been updated
0409 with the new priorities, and this task may not be in the proper locations
0410 in the pi_waiters and waiters trees that the task is blocked on. This function
0411 solves all that.
0412
0413 The main operation of this function is summarized by Thomas Gleixner in
0414 rtmutex.c. See the 'Chain walk basics and protection scope' comment for further
0415 details.
0416
0417 Taking of a mutex (The walk through)
0418 ------------------------------------
0419
0420 OK, now let's take a look at the detailed walk through of what happens when
0421 taking a mutex.
0422
0423 The first thing that is tried is the fast taking of the mutex. This is
0424 done when we have CMPXCHG enabled (otherwise the fast taking automatically
0425 fails). Only when the owner field of the mutex is NULL can the lock be
0426 taken with the CMPXCHG and nothing else needs to be done.
0427
0428 If there is contention on the lock, we go about the slow path
0429 (rt_mutex_slowlock).
0430
0431 The slow path function is where the task's waiter structure is created on
0432 the stack. This is because the waiter structure is only needed for the
0433 scope of this function. The waiter structure holds the nodes to store
0434 the task on the waiters tree of the mutex, and if need be, the pi_waiters
0435 tree of the owner.
0436
0437 The wait_lock of the mutex is taken since the slow path of unlocking the
0438 mutex also takes this lock.
0439
0440 We then call try_to_take_rt_mutex. This is where the architecture that
0441 does not implement CMPXCHG would always grab the lock (if there's no
0442 contention).
0443
0444 try_to_take_rt_mutex is used every time the task tries to grab a mutex in the
0445 slow path. The first thing that is done here is an atomic setting of
0446 the "Has Waiters" flag of the mutex's owner field. By setting this flag
0447 now, the current owner of the mutex being contended for can't release the mutex
0448 without going into the slow unlock path, and it would then need to grab the
0449 wait_lock, which this code currently holds. So setting the "Has Waiters" flag
0450 forces the current owner to synchronize with this code.
0451
0452 The lock is taken if the following are true:
0453
0454 1) The lock has no owner
0455 2) The current task is the highest priority against all other
0456 waiters of the lock
0457
0458 If the task succeeds to acquire the lock, then the task is set as the
0459 owner of the lock, and if the lock still has waiters, the top_waiter
0460 (highest priority task waiting on the lock) is added to this task's
0461 pi_waiters tree.
0462
0463 If the lock is not taken by try_to_take_rt_mutex(), then the
0464 task_blocks_on_rt_mutex() function is called. This will add the task to
0465 the lock's waiter tree and propagate the pi chain of the lock as well
0466 as the lock's owner's pi_waiters tree. This is described in the next
0467 section.
0468
0469 Task blocks on mutex
0470 --------------------
0471
0472 The accounting of a mutex and process is done with the waiter structure of
0473 the process. The "task" field is set to the process, and the "lock" field
0474 to the mutex. The rbtree node of waiter are initialized to the processes
0475 current priority.
0476
0477 Since the wait_lock was taken at the entry of the slow lock, we can safely
0478 add the waiter to the task waiter tree. If the current process is the
0479 highest priority process currently waiting on this mutex, then we remove the
0480 previous top waiter process (if it exists) from the pi_waiters of the owner,
0481 and add the current process to that tree. Since the pi_waiter of the owner
0482 has changed, we call rt_mutex_adjust_prio on the owner to see if the owner
0483 should adjust its priority accordingly.
0484
0485 If the owner is also blocked on a lock, and had its pi_waiters changed
0486 (or deadlock checking is on), we unlock the wait_lock of the mutex and go ahead
0487 and run rt_mutex_adjust_prio_chain on the owner, as described earlier.
0488
0489 Now all locks are released, and if the current process is still blocked on a
0490 mutex (waiter "task" field is not NULL), then we go to sleep (call schedule).
0491
0492 Waking up in the loop
0493 ---------------------
0494
0495 The task can then wake up for a couple of reasons:
0496 1) The previous lock owner released the lock, and the task now is top_waiter
0497 2) we received a signal or timeout
0498
0499 In both cases, the task will try again to acquire the lock. If it
0500 does, then it will take itself off the waiters tree and set itself back
0501 to the TASK_RUNNING state.
0502
0503 In first case, if the lock was acquired by another task before this task
0504 could get the lock, then it will go back to sleep and wait to be woken again.
0505
0506 The second case is only applicable for tasks that are grabbing a mutex
0507 that can wake up before getting the lock, either due to a signal or
0508 a timeout (i.e. rt_mutex_timed_futex_lock()). When woken, it will try to
0509 take the lock again, if it succeeds, then the task will return with the
0510 lock held, otherwise it will return with -EINTR if the task was woken
0511 by a signal, or -ETIMEDOUT if it timed out.
0512
0513
0514 Unlocking the Mutex
0515 -------------------
0516
0517 The unlocking of a mutex also has a fast path for those architectures with
0518 CMPXCHG. Since the taking of a mutex on contention always sets the
0519 "Has Waiters" flag of the mutex's owner, we use this to know if we need to
0520 take the slow path when unlocking the mutex. If the mutex doesn't have any
0521 waiters, the owner field of the mutex would equal the current process and
0522 the mutex can be unlocked by just replacing the owner field with NULL.
0523
0524 If the owner field has the "Has Waiters" bit set (or CMPXCHG is not available),
0525 the slow unlock path is taken.
0526
0527 The first thing done in the slow unlock path is to take the wait_lock of the
0528 mutex. This synchronizes the locking and unlocking of the mutex.
0529
0530 A check is made to see if the mutex has waiters or not. On architectures that
0531 do not have CMPXCHG, this is the location that the owner of the mutex will
0532 determine if a waiter needs to be awoken or not. On architectures that
0533 do have CMPXCHG, that check is done in the fast path, but it is still needed
0534 in the slow path too. If a waiter of a mutex woke up because of a signal
0535 or timeout between the time the owner failed the fast path CMPXCHG check and
0536 the grabbing of the wait_lock, the mutex may not have any waiters, thus the
0537 owner still needs to make this check. If there are no waiters then the mutex
0538 owner field is set to NULL, the wait_lock is released and nothing more is
0539 needed.
0540
0541 If there are waiters, then we need to wake one up.
0542
0543 On the wake up code, the pi_lock of the current owner is taken. The top
0544 waiter of the lock is found and removed from the waiters tree of the mutex
0545 as well as the pi_waiters tree of the current owner. The "Has Waiters" bit is
0546 marked to prevent lower priority tasks from stealing the lock.
0547
0548 Finally we unlock the pi_lock of the pending owner and wake it up.
0549
0550
0551 Contact
0552 -------
0553
0554 For updates on this document, please email Steven Rostedt <rostedt@goodmis.org>
0555
0556
0557 Credits
0558 -------
0559
0560 Author: Steven Rostedt <rostedt@goodmis.org>
0561
0562 Updated: Alex Shi <alex.shi@linaro.org> - 7/6/2017
0563
0564 Original Reviewers:
0565 Ingo Molnar, Thomas Gleixner, Thomas Duetsch, and
0566 Randy Dunlap
0567
0568 Update (7/6/2017) Reviewers: Steven Rostedt and Sebastian Siewior
0569
0570 Updates
0571 -------
0572
0573 This document was originally written for 2.6.17-rc3-mm1
0574 was updated on 4.12