요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
Priority inheritance
rt-mutex-design.rst:58-127PI에서는 A가 C의 lock에서 막히는 순간 C가 A의 priority를 상속합니다. 이제 B는 boost된 C를 선점할 수 없고, C가 L1을 놓으면 상속 priority를 반납한 뒤 A가 실행됩니다. PI는 대기를 없애는 것이 아니라 관계없는 중간 priority workload가 대기를 무한히 늘리는 것을 막습니다.
| 용어 | 정확한 의미 |
|---|---|
| waiter | 막힌 task의 stack에 만들어지는 구조체. task, mutex, 두 RB-tree node를 보유 |
| waiters | 특정 mutex에서 막힌 task 집합 |
| top waiter | 그 mutex를 기다리는 task 중 priority가 가장 높은 task |
| top PI waiter | 한 task가 보유한 모든 mutex의 top waiter 중 가장 높은 priority task |
| PI chain | waiter, mutex, owner가 이어지며 priority 상속이 전파되는 경로 |
PI chain의 결합 구조
rt-mutex-design.rst:128-195화살표는 waiter에서 자신이 기다리는 lock, 다시 그 lock의 owner로 이동합니다. E의 경로와 F의 경로는 B에서 합쳐지지만 B가 동시에 두 lock을 기다리는 것이 아니므로 B에서 바깥쪽으로 갈라지지는 않습니다.
L2 앞에는 C와 G가 함께 기다릴 수 있지만 B의 task PI tree에는 L2의 모든 waiter가 아니라 L2의 top waiter만 연결됩니다. B가 보유한 L5의 top waiter F와 L2의 top waiter를 다시 비교해 B가 상속할 최종 priority를 정하고, 필요하면 그 값이 L1 owner A까지 전파됩니다.
Task는 여러 mutex를 보유할 수 있지만 동시에 둘 이상의 mutex에서 block될 수는 없으므로 chain은 합쳐질 수 있어도 한 task에서 두 갈래로 분기하지 않습니다. Chain의 왼쪽에 더 높은 priority waiter가 나타나면 오른쪽 끝 owner까지 필요한 모든 task가 그 priority로 boost되어야 합니다.
동일 mutex에 waiter가 여러 명이면 상속에 직접 영향을 주는 것은 그중 top waiter입니다. Top waiter가 timeout이나 signal로 빠지거나 더 높은 waiter가 들어오면 owner가 상속할 priority도 다시 계산해야 합니다.
Mutex waiter tree와 task PI tree
rt-mutex-design.rst:196-223| 자료 구조 | 포함하는 node | 보호 lock | root의 의미 |
|---|---|---|---|
| mutex waiters RB-tree | 그 mutex를 기다리는 모든 waiter | mutex->wait_lock | 해당 mutex의 최고 priority waiter |
| task pi_waiters RB-tree | task가 보유한 각 mutex의 top waiter만 | task->pi_lock | task가 상속해야 할 최고 priority |
하나의 waiter 구조체는 두 tree에 들어갈 node를 모두 가집니다. Mutex tree는 다음 owner 후보를 고르는 데 쓰이고, owner task의 PI tree는 여러 보유 lock에서 들어오는 boost 요구 중 가장 높은 것을 고르는 데 쓰입니다. pi_lock은 interrupt context에서도 획득될 수 있어 IRQ를 disable한 상태로 잡아야 합니다.
PI chain 깊이와 lock 보유 제한
rt-mutex-design.rst:224-299각 함수의 정적 lock nesting 깊이가 2여도 여러 task가 서로 다른 함수에서 막히면 A->L1->B->L2->C->L3->D처럼 더 깊은 PI chain이 만들어질 수 있습니다. User space가 futex를 통해 chain을 만들 수도 있으므로 깊이를 무제한 허용하면 긴 chain walk가 spinlock을 보유한 채 실행되는 DoS가 됩니다.
구현은 최대 chain depth를 제한하고, chain을 따라갈 때 동시에 서로 다른 spinlock을 최대 두 개만 보유합니다. 전체 chain을 한 번에 잠그지 않고 검증과 재시도를 반복하여 bounded atomic section을 유지합니다.
Owner pointer bit와 cmpxchg fastpath
rt-mutex-design.rst:301-345rt_mutex owner field는 task_struct pointer를 저장합니다. Pointer 정렬로 비어 있는 bit 0은 Has Waiters flag로 사용합니다. Owner가 NULL이고 flag도 없다면 cmpxchg로 current pointer를 넣어 lock을 즉시 획득할 수 있습니다.
old = cmpxchg(&lock->owner, NULL, current);
if (old == NULL)
return; /* uncontended fast acquire */
/* waiter bit 또는 owner가 있으면 slow path */
Architecture가 CMPXCHG를 제공하지 않으면 fastpath macro는 항상 실패하고 wait_lock으로 보호되는 slowpath가 상태를 갱신합니다. 기능의 정확성은 같고 uncontended path의 instruction 수만 달라집니다.
Priority 계산과 chain walk
rt-mutex-design.rst:346-416rt_mutex_adjust_prio()는 task 자신의 normal/deadline priority와 pi_waiters root의 priority를 비교해 더 높은 쪽을 유효 priority로 선택합니다. Linux의 task_struct prio는 숫자가 작을수록 높다는 점에 주의해야 합니다. 실제 scheduler priority 변경은 kernel/sched/core.c의 rt_mutex_setprio()가 수행합니다.
새 high-priority waiter가 들어오면 boost하고, top waiter가 timeout 또는 signal로 떠나면 deboost합니다. rt_mutex_adjust_prio_chain()은 owner가 다시 다른 mutex에서 막힌 경우 waiter node의 priority와 두 RB-tree 위치를 chain 위쪽으로 갱신합니다.
Chain walk 함수 진입 시 lock을 보유하지 않으므로 owner와 waiter 상태가 바뀔 수 있습니다. 구현은 각 보호 범위에서 상태를 다시 확인하며 최대 두 lock만 잡아 race와 장시간 IRQ-off 구간을 함께 피합니다.
Mutex 획득 slow path
rt-mutex-design.rst:417-513- 1. owner가 NULL이면 cmpxchg fastpath로 current를 기록한다.
- 2. 실패하면 stack에 waiter를 만들고 mutex->wait_lock을 획득한다.
- 3. owner field의 Has Waiters bit를 먼저 세워 unlock caller도 slowpath와 wait_lock을 거치게 한다.
- 4. owner가 없고 current가 모든 waiter 중 최고 priority이면 lock을 획득한다.
- 5. 획득하지 못하면 waiter를 mutex waiters tree에 넣고, top waiter라면 owner의 pi_waiters tree를 갱신한다.
- 6. Owner priority를 조정하고 owner도 block 중이면 PI chain walk를 전파한다.
- 7. 모든 내부 lock을 놓은 뒤 waiter가 여전히 mutex에 연결되어 있으면 schedule()로 잠든다.
Task가 깨어나는 이유는 이전 owner의 unlock, signal, timeout입니다. 매번 lock 획득을 다시 시도합니다. 다른 task가 먼저 가져갔다면 다시 sleep하고, interruptible 또는 timed futex path라면 실패 시 -EINTR 또는 -ETIMEDOUT을 반환합니다.
Mutex 해제와 다음 waiter 선택
rt-mutex-design.rst:514-550Waiter bit가 없고 owner가 current와 정확히 같으면 cmpxchg로 owner를 NULL로 바꾸는 fast unlock이 가능합니다. Waiter bit가 있거나 CMPXCHG가 없으면 wait_lock을 잡는 slow unlock으로 갑니다.
Slowpath에서는 wait_lock을 획득한 뒤 waiter가 실제로 남아 있는지 다시 확인합니다. Fastpath 실패와 wait_lock 획득 사이에 signal 또는 timeout으로 마지막 waiter가 빠질 수 있기 때문입니다. 아무도 없으면 owner를 NULL로 만들고 끝냅니다.
Waiter가 있으면 current owner의 pi_lock을 잡고 mutex tree의 top waiter를 제거하며 owner의 pi_waiters tree에서도 대응 node를 뺍니다. 낮은 priority task가 lock을 가로채지 못하도록 waiter bit를 유지한 뒤 선택된 pending owner를 깨웁니다.
문서의 적용 범위
rt-mutex-design.rst:551-575이 설계 문서는 2.6.17-rc3-mm1 시기에 작성되고 4.12에서 갱신된 역사적 설명입니다. Linux v6.18.37의 정확한 field와 helper는 현재 kernel/locking/rtmutex.c와 include/linux/rtmutex.h를 함께 확인해야 하지만, 두 RB-tree와 PI chain walk라는 중심 모델은 구현을 읽는 기본 좌표로 유효합니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
==============================
RT-mutex implementation design
==============================
Copyright (c) 2006 Steven Rostedt
Licensed under the GNU Free Documentation License, Version 1.2
This document tries to describe the design of the rtmutex.c implementation.
It doesn't describe the reasons why rtmutex.c exists. For that please see
Documentation/locking/rt-mutex.rst. Although this document does explain problems
that happen without this code, but that is in the concept to understand
what the code actually is doing.
The goal of this document is to help others understand the priority
inheritance (PI) algorithm that is used, as well as reasons for the
decisions that were made to implement PI in the manner that was done.
Unbounded Priority Inversion
----------------------------
Priority inversion is when a lower priority process executes while a higher
priority process wants to run. This happens for several reasons, and
most of the time it can't be helped. Anytime a high priority process wants
to use a resource that a lower priority process has (a mutex for example),
the high priority process must wait until the lower priority process is done
with the resource. This is a priority inversion. What we want to prevent
is something called unbounded priority inversion. That is when the high
priority process is prevented from running by a lower priority process for
an undetermined amount of time.
The classic example of unbounded priority inversion is where you have three
processes, let's call them processes A, B, and C, where A is the highest
priority process, C is the lowest, and B is in between. A tries to grab a lock
that C owns and must wait and lets C run to release the lock. But in the
meantime, B executes, and since B is of a higher priority than C, it preempts C,
but by doing so, it is in fact preempting A which is a higher priority process.
Now there's no way of knowing how long A will be sleeping waiting for C
to release the lock, because for all we know, B is a CPU hog and will
never give C a chance to release the lock. This is called unbounded priority
inversion.
Here's a little ASCII art to show the problem::
grab lock L1 (owned by C)
|
A ---+
C preempted by B
|
C +----+
B +-------->
B now keeps A from running.
Priority Inheritance (PI)
-------------------------
There are several ways to solve this issue, but other ways are out of scope
for this document. Here we only discuss PI.
PI is where a process inherits the priority of another process if the other
process blocks on a lock owned by the current process. To make this easier
to understand, let's use the previous example, with processes A, B, and C again.
This time, when A blocks on the lock owned by C, C would inherit the priority
of A. So now if B becomes runnable, it would not preempt C, since C now has
the high priority of A. As soon as C releases the lock, it loses its
inherited priority, and A then can continue with the resource that C had.
Terminology
-----------
Here I explain some terminology that is used in this document to help describe
the design that is used to implement PI.
PI chain
- The PI chain is an ordered series of locks and processes that cause
processes to inherit priorities from a previous process that is
blocked on one of its locks. This is described in more detail
later in this document.
mutex
- In this document, to differentiate from locks that implement
PI and spin locks that are used in the PI code, from now on
the PI locks will be called a mutex.
lock
- In this document from now on, I will use the term lock when
referring to spin locks that are used to protect parts of the PI
algorithm. These locks disable preemption for UP (when
CONFIG_PREEMPT is enabled) and on SMP prevents multiple CPUs from
entering critical sections simultaneously.
spin lock
- Same as lock above.
waiter
- A waiter is a struct that is stored on the stack of a blocked
process. Since the scope of the waiter is within the code for
a process being blocked on the mutex, it is fine to allocate
the waiter on the process's stack (local variable). This
structure holds a pointer to the task, as well as the mutex that
the task is blocked on. It also has rbtree node structures to
place the task in the waiters rbtree of a mutex as well as the
pi_waiters rbtree of a mutex owner task (described below).
waiter is sometimes used in reference to the task that is waiting
on a mutex. This is the same as waiter->task.
waiters
- A list of processes that are blocked on a mutex.
top waiter
- The highest priority process waiting on a specific mutex.
top pi waiter
- The highest priority process waiting on one of the mutexes
that a specific process owns.
Note:
task and process are used interchangeably in this document, mostly to
differentiate between two processes that are being described together.
PI chain
--------
The PI chain is a list of processes and mutexes that may cause priority
inheritance to take place. Multiple chains may converge, but a chain
would never diverge, since a process can't be blocked on more than one
mutex at a time.
Example::
Process: A, B, C, D, E
Mutexes: L1, L2, L3, L4
A owns: L1
B blocked on L1
B owns L2
C blocked on L2
C owns L3
D blocked on L3
D owns L4
E blocked on L4
The chain would be::
E->L4->D->L3->C->L2->B->L1->A
To show where two chains merge, we could add another process F and
another mutex L5 where B owns L5 and F is blocked on mutex L5.
The chain for F would be::
F->L5->B->L1->A
Since a process may own more than one mutex, but never be blocked on more than
one, the chains merge.
Here we show both chains::
E->L4->D->L3->C->L2-+
|
+->B->L1->A
|
F->L5-+
For PI to work, the processes at the right end of these chains (or we may
also call it the Top of the chain) must be equal to or higher in priority
than the processes to the left or below in the chain.
Also since a mutex may have more than one process blocked on it, we can
have multiple chains merge at mutexes. If we add another process G that is
blocked on mutex L2::
G->L2->B->L1->A
And once again, to show how this can grow I will show the merging chains
again::
E->L4->D->L3->C-+
+->L2-+
| |
G-+ +->B->L1->A
|
F->L5-+
If process G has the highest priority in the chain, then all the tasks up
the chain (A and B in this example), must have their priorities increased
to that of G.
Mutex Waiters Tree
------------------
Every mutex keeps track of all the waiters that are blocked on itself. The
mutex has a rbtree to store these waiters by priority. This tree is protected
by a spin lock that is located in the struct of the mutex. This lock is called
wait_lock.
Task PI Tree
------------
To keep track of the PI chains, each process has its own PI rbtree. This is
a tree of all top waiters of the mutexes that are owned by the process.
Note that this tree only holds the top waiters and not all waiters that are
blocked on mutexes owned by the process.
The top of the task's PI tree is always the highest priority task that
is waiting on a mutex that is owned by the task. So if the task has
inherited a priority, it will always be the priority of the task that is
at the top of this tree.
This tree is stored in the task structure of a process as a rbtree called
pi_waiters. It is protected by a spin lock also in the task structure,
called pi_lock. This lock may also be taken in interrupt context, so when
locking the pi_lock, interrupts must be disabled.
Depth of the PI Chain
---------------------
The maximum depth of the PI chain is not dynamic, and could actually be
defined. But is very complex to figure it out, since it depends on all
the nesting of mutexes. Let's look at the example where we have 3 mutexes,
L1, L2, and L3, and four separate functions func1, func2, func3 and func4.
The following shows a locking order of L1->L2->L3, but may not actually
be directly nested that way::
void func1(void)
{
mutex_lock(L1);
/* do anything */
mutex_unlock(L1);
}
void func2(void)
{
mutex_lock(L1);
mutex_lock(L2);
/* do something */
mutex_unlock(L2);
mutex_unlock(L1);
}
void func3(void)
{
mutex_lock(L2);
mutex_lock(L3);
/* do something else */
mutex_unlock(L3);
mutex_unlock(L2);
}
void func4(void)
{
mutex_lock(L3);
/* do something again */
mutex_unlock(L3);
}
Now we add 4 processes that run each of these functions separately.
Processes A, B, C, and D which run functions func1, func2, func3 and func4
respectively, and such that D runs first and A last. With D being preempted
in func4 in the "do something again" area, we have a locking that follows::
D owns L3
C blocked on L3
C owns L2
B blocked on L2
B owns L1
A blocked on L1
And thus we have the chain A->L1->B->L2->C->L3->D.
This gives us a PI depth of 4 (four processes), but looking at any of the
functions individually, it seems as though they only have at most a locking
depth of two. So, although the locking depth is defined at compile time,
it still is very difficult to find the possibilities of that depth.
Now since mutexes can be defined by user-land applications, we don't want a DOS
type of application that nests large amounts of mutexes to create a large
PI chain, and have the code holding spin locks while looking at a large
amount of data. So to prevent this, the implementation not only implements
a maximum lock depth, but also only holds at most two different locks at a
time, as it walks the PI chain. More about this below.
Mutex owner and flags
---------------------
The mutex structure contains a pointer to the owner of the mutex. If the
mutex is not owned, this owner is set to NULL. Since all architectures
have the task structure on at least a two byte alignment (and if this is
not true, the rtmutex.c code will be broken!), this allows for the least
significant bit to be used as a flag. Bit 0 is used as the "Has Waiters"
flag. It's set whenever there are waiters on a mutex.
See Documentation/locking/rt-mutex.rst for further details.
cmpxchg Tricks
--------------
Some architectures implement an atomic cmpxchg (Compare and Exchange). This
is used (when applicable) to keep the fast path of grabbing and releasing
mutexes short.
cmpxchg is basically the following function performed atomically::
unsigned long _cmpxchg(unsigned long *A, unsigned long *B, unsigned long *C)
{
unsigned long T = *A;
if (*A == *B) {
*A = *C;
}
return T;
}
#define cmpxchg(a,b,c) _cmpxchg(&a,&b,&c)
This is really nice to have, since it allows you to only update a variable
if the variable is what you expect it to be. You know if it succeeded if
the return value (the old value of A) is equal to B.
The macro rt_mutex_cmpxchg is used to try to lock and unlock mutexes. If
the architecture does not support CMPXCHG, then this macro is simply set
to fail every time. But if CMPXCHG is supported, then this will
help out extremely to keep the fast path short.
The use of rt_mutex_cmpxchg with the flags in the owner field help optimize
the system for architectures that support it. This will also be explained
later in this document.
Priority adjustments
--------------------
The implementation of the PI code in rtmutex.c has several places that a
process must adjust its priority. With the help of the pi_waiters of a
process this is rather easy to know what needs to be adjusted.
The functions implementing the task adjustments are rt_mutex_adjust_prio
and rt_mutex_setprio. rt_mutex_setprio is only used in rt_mutex_adjust_prio.
rt_mutex_adjust_prio examines the priority of the task, and the highest
priority process that is waiting any of mutexes owned by the task. Since
the pi_waiters of a task holds an order by priority of all the top waiters
of all the mutexes that the task owns, we simply need to compare the top
pi waiter to its own normal/deadline priority and take the higher one.
Then rt_mutex_setprio is called to adjust the priority of the task to the
new priority. Note that rt_mutex_setprio is defined in kernel/sched/core.c
to implement the actual change in priority.
Note:
For the "prio" field in task_struct, the lower the number, the
higher the priority. A "prio" of 5 is of higher priority than a
"prio" of 10.
It is interesting to note that rt_mutex_adjust_prio can either increase
or decrease the priority of the task. In the case that a higher priority
process has just blocked on a mutex owned by the task, rt_mutex_adjust_prio
would increase/boost the task's priority. But if a higher priority task
were for some reason to leave the mutex (timeout or signal), this same function
would decrease/unboost the priority of the task. That is because the pi_waiters
always contains the highest priority task that is waiting on a mutex owned
by the task, so we only need to compare the priority of that top pi waiter
to the normal priority of the given task.
High level overview of the PI chain walk
----------------------------------------
The PI chain walk is implemented by the function rt_mutex_adjust_prio_chain.
The implementation has gone through several iterations, and has ended up
with what we believe is the best. It walks the PI chain by only grabbing
at most two locks at a time, and is very efficient.
The rt_mutex_adjust_prio_chain can be used either to boost or lower process
priorities.
rt_mutex_adjust_prio_chain is called with a task to be checked for PI
(de)boosting (the owner of a mutex that a process is blocking on), a flag to
check for deadlocking, the mutex that the task owns, a pointer to a waiter
that is the process's waiter struct that is blocked on the mutex (although this
parameter may be NULL for deboosting), a pointer to the mutex on which the task
is blocked, and a top_task as the top waiter of the mutex.
For this explanation, I will not mention deadlock detection. This explanation
will try to stay at a high level.
When this function is called, there are no locks held. That also means
that the state of the owner and lock can change when entered into this function.
Before this function is called, the task has already had rt_mutex_adjust_prio
performed on it. This means that the task is set to the priority that it
should be at, but the rbtree nodes of the task's waiter have not been updated
with the new priorities, and this task may not be in the proper locations
in the pi_waiters and waiters trees that the task is blocked on. This function
solves all that.
The main operation of this function is summarized by Thomas Gleixner in
rtmutex.c. See the 'Chain walk basics and protection scope' comment for further
details.
Taking of a mutex (The walk through)
------------------------------------
OK, now let's take a look at the detailed walk through of what happens when
taking a mutex.
The first thing that is tried is the fast taking of the mutex. This is
done when we have CMPXCHG enabled (otherwise the fast taking automatically
fails). Only when the owner field of the mutex is NULL can the lock be
taken with the CMPXCHG and nothing else needs to be done.
If there is contention on the lock, we go about the slow path
(rt_mutex_slowlock).
The slow path function is where the task's waiter structure is created on
the stack. This is because the waiter structure is only needed for the
scope of this function. The waiter structure holds the nodes to store
the task on the waiters tree of the mutex, and if need be, the pi_waiters
tree of the owner.
The wait_lock of the mutex is taken since the slow path of unlocking the
mutex also takes this lock.
We then call try_to_take_rt_mutex. This is where the architecture that
does not implement CMPXCHG would always grab the lock (if there's no
contention).
try_to_take_rt_mutex is used every time the task tries to grab a mutex in the
slow path. The first thing that is done here is an atomic setting of
the "Has Waiters" flag of the mutex's owner field. By setting this flag
now, the current owner of the mutex being contended for can't release the mutex
without going into the slow unlock path, and it would then need to grab the
wait_lock, which this code currently holds. So setting the "Has Waiters" flag
forces the current owner to synchronize with this code.
The lock is taken if the following are true:
1) The lock has no owner
2) The current task is the highest priority against all other
waiters of the lock
If the task succeeds to acquire the lock, then the task is set as the
owner of the lock, and if the lock still has waiters, the top_waiter
(highest priority task waiting on the lock) is added to this task's
pi_waiters tree.
If the lock is not taken by try_to_take_rt_mutex(), then the
task_blocks_on_rt_mutex() function is called. This will add the task to
the lock's waiter tree and propagate the pi chain of the lock as well
as the lock's owner's pi_waiters tree. This is described in the next
section.
Task blocks on mutex
--------------------
The accounting of a mutex and process is done with the waiter structure of
the process. The "task" field is set to the process, and the "lock" field
to the mutex. The rbtree node of waiter are initialized to the processes
current priority.
Since the wait_lock was taken at the entry of the slow lock, we can safely
add the waiter to the task waiter tree. If the current process is the
highest priority process currently waiting on this mutex, then we remove the
previous top waiter process (if it exists) from the pi_waiters of the owner,
and add the current process to that tree. Since the pi_waiter of the owner
has changed, we call rt_mutex_adjust_prio on the owner to see if the owner
should adjust its priority accordingly.
If the owner is also blocked on a lock, and had its pi_waiters changed
(or deadlock checking is on), we unlock the wait_lock of the mutex and go ahead
and run rt_mutex_adjust_prio_chain on the owner, as described earlier.
Now all locks are released, and if the current process is still blocked on a
mutex (waiter "task" field is not NULL), then we go to sleep (call schedule).
Waking up in the loop
---------------------
The task can then wake up for a couple of reasons:
1) The previous lock owner released the lock, and the task now is top_waiter
2) we received a signal or timeout
In both cases, the task will try again to acquire the lock. If it
does, then it will take itself off the waiters tree and set itself back
to the TASK_RUNNING state.
In first case, if the lock was acquired by another task before this task
could get the lock, then it will go back to sleep and wait to be woken again.
The second case is only applicable for tasks that are grabbing a mutex
that can wake up before getting the lock, either due to a signal or
a timeout (i.e. rt_mutex_timed_futex_lock()). When woken, it will try to
take the lock again, if it succeeds, then the task will return with the
lock held, otherwise it will return with -EINTR if the task was woken
by a signal, or -ETIMEDOUT if it timed out.
Unlocking the Mutex
-------------------
The unlocking of a mutex also has a fast path for those architectures with
CMPXCHG. Since the taking of a mutex on contention always sets the
"Has Waiters" flag of the mutex's owner, we use this to know if we need to
take the slow path when unlocking the mutex. If the mutex doesn't have any
waiters, the owner field of the mutex would equal the current process and
the mutex can be unlocked by just replacing the owner field with NULL.
If the owner field has the "Has Waiters" bit set (or CMPXCHG is not available),
the slow unlock path is taken.
The first thing done in the slow unlock path is to take the wait_lock of the
mutex. This synchronizes the locking and unlocking of the mutex.
A check is made to see if the mutex has waiters or not. On architectures that
do not have CMPXCHG, this is the location that the owner of the mutex will
determine if a waiter needs to be awoken or not. On architectures that
do have CMPXCHG, that check is done in the fast path, but it is still needed
in the slow path too. If a waiter of a mutex woke up because of a signal
or timeout between the time the owner failed the fast path CMPXCHG check and
the grabbing of the wait_lock, the mutex may not have any waiters, thus the
owner still needs to make this check. If there are no waiters then the mutex
owner field is set to NULL, the wait_lock is released and nothing more is
needed.
If there are waiters, then we need to wake one up.
On the wake up code, the pi_lock of the current owner is taken. The top
waiter of the lock is found and removed from the waiters tree of the mutex
as well as the pi_waiters tree of the current owner. The "Has Waiters" bit is
marked to prevent lower priority tasks from stealing the lock.
Finally we unlock the pi_lock of the pending owner and wake it up.
Contact
-------
For updates on this document, please email Steven Rostedt <[email protected]>
Credits
-------
Author: Steven Rostedt <[email protected]>
Updated: Alex Shi <[email protected]> - 7/6/2017
Original Reviewers:
Ingo Molnar, Thomas Gleixner, Thomas Duetsch, and
Randy Dunlap
Update (7/6/2017) Reviewers: Steven Rostedt and Sebastian Siewior
Updates
-------
This document was originally written for 2.6.17-rc3-mm1
was updated on 4.12
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
문서의 목적과 unbounded priority inversion
1-57이 문서는 rtmutex.c 구현 설계를 설명한다. rtmutex.c가 존재하는 이유 자체는 Documentation/locking/rt-mutex.rst를 참고한다. 다만 code가 실제로 하는 일을 이해하기 위한 개념으로 이 code가 없을 때 생기는 문제도 설명한다.
목표는 사용된 priority inheritance(PI) algorithm과 PI를 현재 방식으로 구현한 설계 결정을 이해하도록 돕는 것이다. 원문 copyright는 2006 Steven Rostedt이며 GNU Free Documentation License 1.2로 제공된다.
Priority inversion은 high-priority process가 실행되기를 원하지만 low-priority process가 실행되는 상황이다. High-priority process가 low-priority process가 보유한 mutex 같은 resource를 필요로 하면 resource release까지 기다려야 하므로 어느 정도의 inversion은 피할 수 없다.
막아야 하는 것은 unbounded priority inversion이다. Low-priority process 때문에 high-priority process가 언제 끝날지 알 수 없는 시간 동안 실행되지 못하는 경우다.
Classic example에서 A가 가장 높은 priority, C가 가장 낮고 B는 중간이다. A가 C 소유 lock L1을 얻으려다 block되어 C가 release하기를 기다린다. 그 사이 B가 runnable이 되면 C보다 priority가 높아 C를 preempt한다. 결과적으로 B는 C를 통해 자신보다 priority가 높은 A까지 간접적으로 막는다. B가 CPU를 계속 사용하면 C가 L1을 release할 기회를 언제 얻을지 알 수 없다.
A는 C가 가진 L1을 기다린다. 중간 priority B가 C를 preempt하면 C는 lock을 release할 수 없고 A의 대기 시간도 제한할 수 없게 된다.
Priority inheritance와 핵심 용어
58-126PI에서는 다른 process가 current process 소유 lock에서 block하면 current process가 그 process의 priority를 상속한다. 앞의 예에서 A가 C 소유 lock에 block하면 C가 A의 높은 priority를 상속한다. B가 runnable이 되어도 C를 preempt하지 못하고, C가 lock을 release하면 inherited priority를 잃으며 A가 resource를 사용할 수 있다.
| 용어 | 의미 |
|---|---|
| PI chain | Lock과 process가 순서대로 이어져 앞에서 block한 process의 priority를 뒤쪽 process가 상속하게 만드는 chain |
| mutex | 이 문서에서 PI를 구현하는 lock. PI code 내부 보호용 spinlock과 구분하기 위한 명칭 |
| lock / spin lock | PI algorithm 일부를 보호하는 spinlock. UP에서는 CONFIG_PREEMPT일 때 preemption을 disable하고 SMP에서는 여러 CPU의 동시 critical-section 진입을 막음 |
| waiter | Block된 process stack에 놓이는 struct. task와 대기 mutex pointer, mutex waiters rbtree와 owner task pi_waiters rbtree용 node를 보유 |
| waiters | 한 mutex에서 block된 process 목록 |
| top waiter | 특정 mutex를 기다리는 가장 높은 priority process |
| top pi waiter | 특정 process가 소유한 모든 mutex의 waiter 중 가장 높은 priority process |
Waiter object의 scope는 process가 mutex에서 block되는 code 안이므로 local variable로 task stack에 allocate해도 안전하다. 문맥에 따라 waiter라는 말이 기다리는 task, 즉 waiter->task를 가리키기도 한다. 이 문서는 task와 process를 같은 뜻으로 사용한다.
PI chain의 수렴과 priority 전파
128-194PI chain은 priority inheritance를 만들 수 있는 process와 mutex의 list다. 한 process는 동시에 하나의 mutex에만 block될 수 있으므로 chain은 갈라지지 않지만, 한 process가 여러 mutex를 소유할 수 있어 여러 chain은 합쳐질 수 있다.
A가 L1을 소유하고 B가 L1을 기다리며, B가 L2를 소유하고 C가 기다리는 식으로 E까지 이어지면 chain은 E→L4→D→L3→C→L2→B→L1→A가 된다.
B는 L1을 기다리면서 L2와 L5를 소유할 수 있다. E에서 시작한 긴 chain과 F에서 시작한 chain이 B에서 합쳐져 A까지 하나의 priority inheritance 경로를 만든다.
PI가 동작하려면 chain 오른쪽 끝, 또는 top의 process priority가 왼쪽이나 아래쪽 process와 같거나 더 높아야 한다.
Mutex에는 여러 process가 block될 수 있으므로 mutex 지점에서도 chain이 합쳐진다. G가 L2를 기다리면 G→L2→B→L1→A chain이 추가된다.
E 쪽 chain과 G가 L2에서 합쳐지고, 다시 F 쪽 chain이 B에서 합쳐진다. G가 가장 높은 priority라면 위쪽 A와 B도 G priority까지 boost되어야 한다.
G가 전체 chain에서 가장 높은 priority라면 chain 위쪽 task인 B와 A의 priority를 G까지 올려야 한다.
Mutex waiters tree와 task PI tree
196-221각 mutex는 자신에게 block된 모든 waiter를 priority 순서 rbtree에 저장한다. Mutex struct 안의 spinlock인 wait_lock이 이 tree를 보호한다.
PI chain을 추적하기 위해 각 process에는 독립 PI rbtree가 있다. 이 tree에는 process가 소유한 각 mutex의 top waiter만 들어가며 모든 waiter를 넣지는 않는다.
Task PI tree의 top은 그 task가 소유한 mutex 중 하나를 기다리는 가장 높은 priority task다. Owner task가 priority를 상속했다면 항상 이 top task의 priority를 상속한다.
이 tree는 task structure의 pi_waiters rbtree에 저장되고 같은 task structure의 pi_lock spinlock이 보호한다. pi_lock은 interrupt context에서도 획득될 수 있으므로 lock을 잡을 때 interrupt를 disable해야 한다.
| Tree | 포함하는 node | 보호 lock |
|---|---|---|
| mutex waiters | 해당 mutex에서 block된 모든 waiter, priority order | mutex->wait_lock |
| task pi_waiters | task가 소유한 각 mutex의 top waiter만 | task->pi_lock, IRQ disabled |
PI chain depth는 함수 nesting만 보고 알 수 없다
224-298Maximum PI chain depth는 dynamic하지 않아 이론상 정의할 수 있지만 모든 mutex nesting에 의존해 계산이 매우 복잡하다. L1, L2, L3와 네 function의 예를 보자.
void func1(void)
{
mutex_lock(L1);
/* do anything */
mutex_unlock(L1);
}
void func2(void)
{
mutex_lock(L1);
mutex_lock(L2);
/* do something */
mutex_unlock(L2);
mutex_unlock(L1);
}
void func3(void)
{
mutex_lock(L2);
mutex_lock(L3);
/* do something else */
mutex_unlock(L3);
mutex_unlock(L2);
}
void func4(void)
{
mutex_lock(L3);
/* do something again */
mutex_unlock(L3);
}
Process A·B·C·D가 각각 func1·func2·func3·func4를 실행하고 D가 먼저, A가 마지막에 실행된다고 하자. D가 func4 critical section에서 preempt되면 D owns L3, C blocked on L3 and owns L2, B blocked on L2 and owns L1, A blocked on L1 관계가 생긴다.
A -> L1 -> B -> L2 -> C -> L3 -> D
각 function의 lock nesting depth는 최대 2처럼 보이지만 process 네 개의 PI depth는 4가 된다. Compile-time locking depth가 정해져 있어도 가능한 chain depth를 찾기 어려운 이유다.
User-space application도 mutex를 정의할 수 있으므로 매우 많은 mutex를 nesting해 거대한 PI chain을 만들고 kernel이 spinlock을 가진 채 대량 data를 순회하게 하는 DOS를 막아야 한다. 구현은 maximum lock depth를 제한할 뿐 아니라 PI chain을 걷는 동안 동시에 최대 두 lock만 보유한다.
Owner pointer flag와 cmpxchg fast path
301-343Mutex struct는 owner task pointer를 갖고 소유자가 없으면 NULL이다. 모든 architecture에서 task structure가 최소 2-byte aligned이므로 least significant bit를 flag로 쓸 수 있다. Bit 0은 Has Waiters flag이며 mutex에 waiter가 있으면 설정한다. 자세한 내용은 Documentation/locking/rt-mutex.rst에 있다.
일부 architecture는 atomic cmpxchg(Compare and Exchange)를 구현한다. 가능한 경우 mutex 획득·release fast path를 짧게 만드는 데 사용한다. 개념적으로 다음 operation을 atomic하게 수행한다.
unsigned long _cmpxchg(unsigned long *A, unsigned long *B,
unsigned long *C)
{
unsigned long T = *A;
if (*A == *B) {
*A = *C;
}
return T;
}
#define cmpxchg(a,b,c) _cmpxchg(&a,&b,&c)
Variable이 expected value일 때만 update하며 return한 old A가 B와 같으면 성공한 것이다. rt_mutex_cmpxchg macro가 mutex lock·unlock을 시도한다. Architecture가 CMPXCHG를 지원하지 않으면 항상 fail하도록 정의되어 slow path로 가고, 지원하면 owner field flag와 함께 fast path를 크게 최적화한다.
pi_waiters top으로 priority를 boost·deboost
346-378rtmutex.c PI code에는 process priority를 조정해야 하는 곳이 여러 군데 있다. Task의 pi_waiters 덕분에 필요한 조정을 쉽게 알 수 있다.
Task adjustment function은 rt_mutex_adjust_prio와 rt_mutex_setprio다. rt_mutex_setprio는 rt_mutex_adjust_prio에서만 사용되며 실제 priority 변경은 kernel/sched/core.c에 정의된 rt_mutex_setprio가 수행한다.
rt_mutex_adjust_prio는 task own priority와 task 소유 mutex 전체를 기다리는 process 중 가장 높은 priority를 비교한다. pi_waiters는 각 mutex top waiter를 priority 순으로 보유하므로 top pi waiter와 task의 normal/deadline priority 중 높은 쪽을 고르면 된다.
task_struct의 prio field는 숫자가 작을수록 priority가 높다. prio 5가 prio 10보다 높은 priority다.
Higher-priority process가 task 소유 mutex에 block되면 rt_mutex_adjust_prio가 task를 boost한다. 반대로 그 waiter가 timeout 또는 signal로 떠나면 같은 함수가 task를 deboost한다. pi_waiters top과 normal priority만 비교하면 두 방향을 모두 처리할 수 있다.
rt_mutex_adjust_prio_chain의 고수준 동작
381-415PI chain walk는 rt_mutex_adjust_prio_chain이 구현한다. 여러 iteration을 거쳐 동시에 최대 두 lock만 잡고 chain을 걷는 효율적인 형태가 되었다. Process priority를 boost하거나 낮추는 양쪽에 사용한다.
Input에는 PI boost/deboost를 검사할 task, deadlock 검사 flag, task가 소유한 mutex, 그 mutex에 block된 process의 waiter pointer(deboost 때 NULL일 수 있음), task가 block된 mutex pointer, mutex의 top waiter인 top_task가 들어간다.
이 설명은 deadlock detection을 제외하고 high level에 집중한다. Function 진입 시 보유한 lock이 없으므로 진입하는 동안 owner와 lock state가 바뀔 수 있다.
호출 전에 task에는 이미 rt_mutex_adjust_prio가 실행되어 필요한 priority로 설정되어 있다. 하지만 task waiter의 rbtree node priority와 pi_waiters·waiters tree 위치는 아직 갱신되지 않았을 수 있다. rt_mutex_adjust_prio_chain이 이를 바로잡는다. 더 자세한 요약은 rtmutex.c의 Chain walk basics and protection scope comment에 있다.
Mutex 획득 fast path와 slow path
417-467Mutex 획득은 먼저 fast path를 시도한다. CMPXCHG가 enable되어 있고 owner field가 NULL일 때만 atomic exchange로 lock을 얻으며 추가 작업은 필요 없다. CMPXCHG가 없으면 fast attempt는 자동으로 실패한다.
Contention이 있으면 rt_mutex_slowlock slow path로 간다. 이 function에서 waiter struct를 stack에 만든다. Waiter는 이 function scope에서만 필요하며 mutex waiters tree와 필요 시 owner pi_waiters tree에 task를 넣을 node를 보유한다.
Mutex slow unlock path도 사용하는 wait_lock을 획득해 locking과 unlocking을 동기화한다. 그 뒤 try_to_take_rt_mutex를 호출한다. CMPXCHG가 없는 architecture에서는 contention이 없을 때 이 경로에서 lock을 얻게 된다.
Slow path에서 매 획득 시도마다 try_to_take_rt_mutex를 사용한다. 먼저 owner field의 Has Waiters flag를 atomically 설정한다. 그러면 current owner는 slow unlock path로 들어가 현재 code가 가진 wait_lock을 잡아야 하므로 이 경로와 반드시 synchronize한다.
Lock owner가 없고 current task가 모든 waiter 중 highest priority일 때만 lock을 획득한다. 성공하면 current task를 owner로 설정하고 waiter가 더 있으면 top_waiter를 새 owner task의 pi_waiters tree에 추가한다.
try_to_take_rt_mutex()가 실패하면 task_blocks_on_rt_mutex()를 호출한다. Task를 mutex waiters tree에 추가하고 owner pi_waiters tree와 lock PI chain에 priority를 전파한다.
Task block accounting과 wakeup loop
469-511Mutex와 process의 관계는 process waiter struct로 기록한다. task field는 process, lock field는 mutex를 가리키며 waiter rbtree node를 current process priority로 초기화한다.
Slow lock 진입 때 wait_lock을 획득했으므로 waiter를 mutex waiter tree에 안전하게 넣을 수 있다. Current process가 mutex의 새 highest-priority waiter라면 기존 top waiter를 owner pi_waiters에서 제거하고 current process를 추가한다. Owner pi_waiter가 바뀌었으므로 rt_mutex_adjust_prio로 owner priority 조정 여부를 확인한다.
Owner도 다른 lock에 block되어 있고 pi_waiters가 바뀌었거나 deadlock check가 켜져 있으면 mutex wait_lock을 풀고 owner에 대해 rt_mutex_adjust_prio_chain을 실행한다.
모든 lock을 release한 뒤 current process가 여전히 mutex에 block되어 있다면, 즉 waiter task field가 NULL이 아니면 schedule()로 sleep한다.
Task가 깨는 이유는 이전 owner가 release하여 task가 top_waiter가 되었거나 signal·timeout을 받은 경우다. 두 경우 모두 lock 획득을 다시 시도한다. 성공하면 waiters tree에서 자신을 제거하고 TASK_RUNNING으로 돌아간다.
첫 경우 다른 task가 먼저 lock을 얻었다면 다시 sleep하여 다음 wakeup을 기다린다. 두 번째는 rt_mutex_timed_futex_lock()처럼 signal 또는 timeout으로 lock 전에 깰 수 있는 mutex에만 해당한다. 재시도 성공 시 lock을 보유한 채 return하고 실패하면 signal은 -EINTR, timeout은 -ETIMEDOUT을 반환한다.
Unlock fast path, slow path와 pending owner wakeup
514-548CMPXCHG architecture에서는 unlock도 fast path가 있다. Contended acquisition이 항상 owner field의 Has Waiters flag를 설정하므로 unlock 시 slow path 필요 여부를 알 수 있다. Waiter가 없으면 owner field가 current process와 같고 이를 NULL로 바꾸기만 하면 된다.
Owner field에 Has Waiters bit가 있거나 CMPXCHG가 없으면 slow unlock으로 간다. 먼저 mutex wait_lock을 잡아 lock·unlock path를 동기화한다.
그 뒤 waiter 존재 여부를 다시 검사한다. CMPXCHG가 없는 architecture는 여기서 깨울 waiter를 결정한다. CMPXCHG가 있어도 slow path에는 재검사가 필요하다. Owner가 fast CMPXCHG check에 실패한 뒤 wait_lock을 잡기 전 사이에 waiter가 signal 또는 timeout으로 떠났을 수 있기 때문이다. Waiter가 없으면 owner=NULL로 만들고 wait_lock을 release한 뒤 끝낸다.
Waiter가 있으면 하나를 깨운다. Wakeup code는 current owner의 pi_lock을 잡고 mutex top waiter를 찾아 mutex waiters tree와 current owner pi_waiters tree에서 제거한다. Lower-priority task가 lock을 steal하지 못하도록 Has Waiters bit를 표시한다. 마지막으로 pending owner의 pi_lock을 풀고 그 task를 wake up한다.
문서 연락처와 이력
551-574문서 update 연락처는 Steven Rostedt <[email protected]>다. Author는 Steven Rostedt이고 Alex Shi가 2017년 7월 6일 update했다.
Original reviewer는 Ingo Molnar, Thomas Gleixner, Thomas Duetsch, Randy Dunlap이며 2017년 update reviewer는 Steven Rostedt와 Sebastian Siewior다.
이 문서는 원래 2.6.17-rc3-mm1을 위해 작성되었고 4.12에서 update되었다.
Unbounded priority inversion
rt-mutex-design.rst:10-57높은 priority A가 낮은 priority C가 보유한 L1을 기다리는 것은 resource dependency가 만든 정상적인 priority inversion입니다. 문제는 중간 priority B가 C를 계속 선점하여 C가 L1을 놓지 못하고, 결과적으로 B가 자신보다 높은 A의 진행까지 간접적으로 무기한 막는 unbounded inversion입니다.
A가 기다리는 직접 원인은 C의 L1 보유이지만, 실제 대기 상한을 없애는 주체는 L1과 무관한 B입니다. B가 계속 runnable이면 C는 unlock까지 도달하지 못합니다. PI는 A가 막히는 순간 C를 A의 priority로 boost해 이 간접 차단을 제거합니다.