요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
초기화와 object lifetime
completion.rst:71-140정적 object에는 DECLARE_COMPLETION, 동적 object field에는 init_completion()을 사용합니다. reinit_completion()은 wait queue를 다시 만들지 않고 done만 0으로 되돌리므로 이전 round의 waiter와 signaler가 완전히 끝났다는 외부 보장이 필요합니다.
Stack completion을 timeout wait와 함께 사용할 때 wait가 반환한 직후 stack을 없애면 늦게 도착한 signaler가 freed stack을 complete할 수 있습니다. Signaler 종료까지 보장하거나 object lifetime이 더 긴 storage를 사용합니다.
wait_for_completion 계열
completion.rst:141-242| API | 중단 조건 | 반환 처리 |
|---|---|---|
| wait_for_completion | 완료까지 uninterruptible | 반환값 없음 |
| wait_for_completion_interruptible | signal 가능 | 0 또는 -ERESTARTSYS |
| wait_for_completion_killable | fatal signal | 0 또는 음수 errno |
| wait_for_completion_timeout | jiffies timeout | 0 timeout, 양수 remaining |
| wait_for_completion_interruptible_timeout | signal 또는 timeout | 음수 signal, 0 timeout, 양수 remaining |
| wait_for_completion_io | I/O wait accounting | 기본 wait와 유사 |
Wait 함수는 sleep하므로 atomic context, IRQ-disabled 구간과 spinlock 보유 중 호출할 수 없습니다. Timeout variant의 반환값은 boolean이 아니며 음수, 0, 양수를 모두 구분해야 합니다.
complete와 complete_all
completion.rst:243-294complete()는 waiter 하나를 깨우고 done token 하나를 제공합니다. complete_all()은 현재와 이후 waiter 모두가 통과할 수 있는 완료 상태를 만들며 다음 세대에서 다시 사용하려면 모든 이전 사용자가 끝난 뒤 reinit_completion()해야 합니다.
try_wait_for_completion()은 sleep하지 않고 token을 소비해 성공 여부를 반환합니다. completion_done()은 token 존재 여부를 관찰하지만 그 뒤 상태가 바뀔 수 있으므로 synchronization 자체를 대신하지 않습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
================================================
Completions - "wait for completion" barrier APIs
================================================
Introduction:
-------------
If you have one or more threads that must wait for some kernel activity
to have reached a point or a specific state, completions can provide a
race-free solution to this problem. Semantically they are somewhat like a
pthread_barrier() and have similar use-cases.
Completions are a code synchronization mechanism which is preferable to any
misuse of locks/semaphores and busy-loops. Any time you think of using
yield() or some quirky msleep(1) loop to allow something else to proceed,
you probably want to look into using one of the wait_for_completion*()
calls and complete() instead.
The advantage of using completions is that they have a well defined, focused
purpose which makes it very easy to see the intent of the code, but they
also result in more efficient code as all threads can continue execution
until the result is actually needed, and both the waiting and the signalling
is highly efficient using low level scheduler sleep/wakeup facilities.
Completions are built on top of the waitqueue and wakeup infrastructure of
the Linux scheduler. The event the threads on the waitqueue are waiting for
is reduced to a simple flag in 'struct completion', appropriately called "done".
As completions are scheduling related, the code can be found in
kernel/sched/completion.c.
Usage:
------
There are three main parts to using completions:
- the initialization of the 'struct completion' synchronization object
- the waiting part through a call to one of the variants of wait_for_completion(),
- the signaling side through a call to complete() or complete_all().
There are also some helper functions for checking the state of completions.
Note that while initialization must happen first, the waiting and signaling
part can happen in any order. I.e. it's entirely normal for a thread
to have marked a completion as 'done' before another thread checks whether
it has to wait for it.
To use completions you need to #include <linux/completion.h> and
create a static or dynamic variable of type 'struct completion',
which has only two fields::
struct completion {
unsigned int done;
struct swait_queue_head wait;
};
This provides the ->wait waitqueue to place tasks on for waiting (if any), and
the ->done completion flag for indicating whether it's completed or not.
Completions should be named to refer to the event that is being synchronized on.
A good example is::
wait_for_completion(&early_console_added);
complete(&early_console_added);
Good, intuitive naming (as always) helps code readability. Naming a completion
'complete' is not helpful unless the purpose is super obvious...
Initializing completions:
-------------------------
Dynamically allocated completion objects should preferably be embedded in data
structures that are assured to be alive for the life-time of the function/driver,
to prevent races with asynchronous complete() calls from occurring.
Particular care should be taken when using the _timeout() or _killable()/_interruptible()
variants of wait_for_completion(), as it must be assured that memory de-allocation
does not happen until all related activities (complete() or reinit_completion())
have taken place, even if these wait functions return prematurely due to a timeout
or a signal triggering.
Initializing of dynamically allocated completion objects is done via a call to
init_completion()::
init_completion(&dynamic_object->done);
In this call we initialize the waitqueue and set ->done to 0, i.e. "not completed"
or "not done".
The re-initialization function, reinit_completion(), simply resets the
->done field to 0 ("not done"), without touching the waitqueue.
Callers of this function must make sure that there are no racy
wait_for_completion() calls going on in parallel.
Calling init_completion() on the same completion object twice is
most likely a bug as it re-initializes the queue to an empty queue and
enqueued tasks could get "lost" - use reinit_completion() in that case,
but be aware of other races.
For static declaration and initialization, macros are available.
For static (or global) declarations in file scope you can use
DECLARE_COMPLETION()::
static DECLARE_COMPLETION(setup_done);
DECLARE_COMPLETION(setup_done);
Note that in this case the completion is boot time (or module load time)
initialized to 'not done' and doesn't require an init_completion() call.
When a completion is declared as a local variable within a function,
then the initialization should always use DECLARE_COMPLETION_ONSTACK()
explicitly, not just to make lockdep happy, but also to make it clear
that limited scope had been considered and is intentional::
DECLARE_COMPLETION_ONSTACK(setup_done)
Note that when using completion objects as local variables you must be
acutely aware of the short life time of the function stack: the function
must not return to a calling context until all activities (such as waiting
threads) have ceased and the completion object is completely unused.
To emphasise this again: in particular when using some of the waiting API variants
with more complex outcomes, such as the timeout or signalling (_timeout(),
_killable() and _interruptible()) variants, the wait might complete
prematurely while the object might still be in use by another thread - and a return
from the wait_on_completion*() caller function will deallocate the function
stack and cause subtle data corruption if a complete() is done in some
other thread. Simple testing might not trigger these kinds of races.
If unsure, use dynamically allocated completion objects, preferably embedded
in some other long lived object that has a boringly long life time which
exceeds the life time of any helper threads using the completion object,
or has a lock or other synchronization mechanism to make sure complete()
is not called on a freed object.
A naive DECLARE_COMPLETION() on the stack triggers a lockdep warning.
Waiting for completions:
------------------------
For a thread to wait for some concurrent activity to finish, it
calls wait_for_completion() on the initialized completion structure::
void wait_for_completion(struct completion *done)
A typical usage scenario is::
CPU#1 CPU#2
struct completion setup_done;
init_completion(&setup_done);
initialize_work(...,&setup_done,...);
/* run non-dependent code */ /* do setup */
wait_for_completion(&setup_done); complete(&setup_done);
This is not implying any particular order between wait_for_completion() and
the call to complete() - if the call to complete() happened before the call
to wait_for_completion() then the waiting side simply will continue
immediately as all dependencies are satisfied; if not, it will block until
completion is signaled by complete().
Note that wait_for_completion() is calling spin_lock_irq()/spin_unlock_irq(),
so it can only be called safely when you know that interrupts are enabled.
Calling it from IRQs-off atomic contexts will result in hard-to-detect
spurious enabling of interrupts.
The default behavior is to wait without a timeout and to mark the task as
uninterruptible. wait_for_completion() and its variants are only safe
in process context (as they can sleep) but not in atomic context,
interrupt context, with disabled IRQs, or preemption is disabled - see also
try_wait_for_completion() below for handling completion in atomic/interrupt
context.
As all variants of wait_for_completion() can (obviously) block for a long
time depending on the nature of the activity they are waiting for, so in
most cases you probably don't want to call this with held mutexes.
wait_for_completion*() variants available:
------------------------------------------
The below variants all return status and this status should be checked in
most(/all) cases - in cases where the status is deliberately not checked you
probably want to make a note explaining this (e.g. see
arch/arm/kernel/smp.c:__cpu_up()).
A common problem that occurs is to have unclean assignment of return types,
so take care to assign return-values to variables of the proper type.
Checking for the specific meaning of return values also has been found
to be quite inaccurate, e.g. constructs like::
if (!wait_for_completion_interruptible_timeout(...))
... would execute the same code path for successful completion and for the
interrupted case - which is probably not what you want::
int wait_for_completion_interruptible(struct completion *done)
This function marks the task TASK_INTERRUPTIBLE while it is waiting.
If a signal was received while waiting it will return -ERESTARTSYS; 0 otherwise::
unsigned long wait_for_completion_timeout(struct completion *done, unsigned long timeout)
The task is marked as TASK_UNINTERRUPTIBLE and will wait at most 'timeout'
jiffies. If a timeout occurs it returns 0, else the remaining time in
jiffies (but at least 1).
Timeouts are preferably calculated with msecs_to_jiffies() or usecs_to_jiffies(),
to make the code largely HZ-invariant.
If the returned timeout value is deliberately ignored a comment should probably explain
why (e.g. see drivers/mfd/wm8350-core.c wm8350_read_auxadc())::
long wait_for_completion_interruptible_timeout(struct completion *done, unsigned long timeout)
This function passes a timeout in jiffies and marks the task as
TASK_INTERRUPTIBLE. If a signal was received it will return -ERESTARTSYS;
otherwise it returns 0 if the completion timed out, or the remaining time in
jiffies if completion occurred.
Further variants include _killable which uses TASK_KILLABLE as the
designated tasks state and will return -ERESTARTSYS if it is interrupted,
or 0 if completion was achieved. There is a _timeout variant as well::
long wait_for_completion_killable(struct completion *done)
long wait_for_completion_killable_timeout(struct completion *done, unsigned long timeout)
The _io variants wait_for_completion_io() behave the same as the non-_io
variants, except for accounting waiting time as 'waiting on IO', which has
an impact on how the task is accounted in scheduling/IO stats::
void wait_for_completion_io(struct completion *done)
unsigned long wait_for_completion_io_timeout(struct completion *done, unsigned long timeout)
Signaling completions:
----------------------
A thread that wants to signal that the conditions for continuation have been
achieved calls complete() to signal exactly one of the waiters that it can
continue::
void complete(struct completion *done)
... or calls complete_all() to signal all current and future waiters::
void complete_all(struct completion *done)
The signaling will work as expected even if completions are signaled before
a thread starts waiting. This is achieved by the waiter "consuming"
(decrementing) the done field of 'struct completion'. Waiting threads
wakeup order is the same in which they were enqueued (FIFO order).
If complete() is called multiple times then this will allow for that number
of waiters to continue - each call to complete() will simply increment the
done field. Calling complete_all() multiple times is a bug though. Both
complete() and complete_all() can be called in IRQ/atomic context safely.
There can only be one thread calling complete() or complete_all() on a
particular 'struct completion' at any time - serialized through the wait
queue spinlock. Any such concurrent calls to complete() or complete_all()
probably are a design bug.
Signaling completion from IRQ context is fine as it will appropriately
lock with spin_lock_irqsave()/spin_unlock_irqrestore() and it will never
sleep.
try_wait_for_completion()/completion_done():
--------------------------------------------
The try_wait_for_completion() function will not put the thread on the wait
queue but rather returns false if it would need to enqueue (block) the thread,
else it consumes one posted completion and returns true::
bool try_wait_for_completion(struct completion *done)
Finally, to check the state of a completion without changing it in any way,
call completion_done(), which returns false if there are no posted
completions that were not yet consumed by waiters (implying that there are
waiters) and true otherwise::
bool completion_done(struct completion *done)
Both try_wait_for_completion() and completion_done() are safe to be called in
IRQ or atomic context.
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
Completion barrier가 필요한 이유
1-30하나 이상의 thread가 kernel activity가 특정 지점이나 상태에 도달하기를 기다려야 할 때 completion은 race 없는 해결책을 제공한다. 의미상 pthread_barrier()와 어느 정도 비슷하고 사용 사례도 유사하다.
Completion은 lock이나 semaphore의 오용, busy loop보다 선호되는 code synchronization mechanism이다. 다른 작업이 진행되게 하려고 yield() 또는 임의의 msleep(1) loop를 생각하고 있다면 wait_for_completion*()과 complete()를 검토해야 한다.
Completion은 목적이 명확해 code의 의도를 쉽게 알 수 있다. 결과가 실제로 필요할 때까지 모든 thread가 실행을 계속할 수 있고, wait와 signal 모두 scheduler의 저수준 sleep/wakeup facility를 사용하므로 효율적이다.
Completion은 Linux scheduler의 waitqueue와 wakeup infrastructure 위에 구현한다. Waitqueue의 thread가 기다리는 event는 struct completion의 done이라는 단순한 flag로 축약된다. 관련 code는 kernel/sched/completion.c에 있다.
세 구성 요소와 struct completion
33-68- struct completion synchronization object 초기화
- wait_for_completion() variant 중 하나를 호출하는 wait side
- complete() 또는 complete_all()을 호출하는 signal side
Completion 상태를 검사하는 helper도 있다. 초기화는 반드시 먼저 해야 하지만 wait와 signal의 순서는 어느 쪽이 먼저여도 된다. 한 thread가 wait 여부를 검사하기 전에 다른 thread가 completion을 done으로 표시하는 것은 완전히 정상적인 동작이다.
사용하려면 <linux/completion.h>를 include하고 static 또는 dynamic struct completion 변수를 만든다. Structure에는 두 field만 있다.
struct completion {
unsigned int done;
struct swait_queue_head wait;
};
wait는 기다릴 task를 넣는 waitqueue이고 done은 완료 여부를 나타내는 flag다. Completion 이름은 동기화 대상 event를 나타내야 한다.
wait_for_completion(&early_console_added);
complete(&early_console_added);
이처럼 직관적인 이름은 가독성을 높인다. 목적이 아주 명백한 경우가 아니라면 completion object를 complete라고 이름 짓는 것은 도움이 되지 않는다.
Dynamic object 초기화와 lifetime
71-100Dynamic allocation한 completion은 가능하면 function 또는 driver의 전체 lifetime 동안 살아 있음이 보장되는 data structure 안에 넣어야 한다. 그래야 asynchronous complete() 호출과 object 해제 사이의 race를 막을 수 있다.
wait_for_completion()의 _timeout(), _killable(), _interruptible() variant는 특히 주의해야 한다. Timeout 또는 signal 때문에 wait가 일찍 return하더라도 관련 complete()와 reinit_completion() activity가 모두 끝날 때까지 memory를 해제해서는 안 된다.
init_completion(&dynamic_object->done);
init_completion()은 waitqueue를 초기화하고 done을 0, 즉 not completed 상태로 만든다. reinit_completion()은 waitqueue를 건드리지 않고 done만 0으로 reset한다. 호출자는 동시에 진행 중인 wait_for_completion()과 race하지 않도록 보장해야 한다.
같은 object에 init_completion()을 두 번 호출하면 queue를 빈 queue로 다시 초기화하여 이미 enqueue된 task를 잃을 수 있으므로 대부분 bug다. 재사용에는 reinit_completion()을 쓰되 다른 race도 고려해야 한다.
Static 및 stack object 초기화
102-140File scope의 static 또는 global declaration에는 DECLARE_COMPLETION()을 사용한다.
static DECLARE_COMPLETION(setup_done);
DECLARE_COMPLETION(setup_done);
이 경우 boot 또는 module load 시 not done 상태로 초기화되므로 init_completion()을 따로 호출하지 않는다.
Function local variable로 선언할 때에는 DECLARE_COMPLETION_ONSTACK()을 명시적으로 사용해야 한다. Lockdep을 만족시키는 것뿐 아니라 제한된 scope를 의도적으로 검토했음을 드러낸다.
DECLARE_COMPLETION_ONSTACK(setup_done)
Stack object는 function stack의 lifetime이 짧다는 점을 엄격히 고려해야 한다. 기다리는 thread를 포함한 모든 activity가 끝나고 object를 아무도 사용하지 않을 때까지 function이 caller로 return해서는 안 된다.
특히 _timeout(), _killable(), _interruptible()은 object를 다른 thread가 여전히 사용하는데 wait만 먼저 끝날 수 있다. Caller가 return하여 stack을 해제한 뒤 다른 thread가 complete()를 호출하면 찾기 어려운 data corruption이 생긴다. 단순한 test에서는 이런 race가 드러나지 않을 수 있다.
확신할 수 없다면 helper thread보다 lifetime이 충분히 긴 object 안에 dynamic completion을 넣거나, 해제된 object에 complete()가 호출되지 않도록 lock 또는 다른 synchronization mechanism을 둔다. Stack에서 단순 DECLARE_COMPLETION()을 사용하면 lockdep warning이 발생한다.
wait_for_completion() 동작과 context 제약
141-182void wait_for_completion(struct completion *done)
동시에 수행되는 activity가 끝나기를 기다리는 thread는 초기화된 completion에 wait_for_completion()을 호출한다. 원문의 두 CPU ASCII 예시는 다음 단계로 정리할 수 있다.
| 단계 | CPU #1: wait side | CPU #2: signal side |
|---|---|---|
| 1 | struct completion setup_done 선언 | setup 작업 대기 |
| 2 | init_completion(&setup_done) | 아직 접근하지 않음 |
| 3 | initialize_work(..., &setup_done, ...) | setup 수행 |
| 4 | completion과 무관한 code 실행 | setup 계속 수행 |
| 5 | wait_for_completion(&setup_done) | complete(&setup_done) |
이 도식은 두 호출의 순서를 강제하지 않는다. complete()가 먼저 실행되었다면 dependency가 이미 충족되었으므로 wait side는 즉시 계속한다. 그렇지 않으면 complete()가 signal할 때까지 block된다.
wait_for_completion()은 spin_lock_irq()와 spin_unlock_irq()를 호출하므로 interrupt가 enable되어 있음을 아는 상황에서만 안전하다. IRQ-off atomic context에서 호출하면 찾기 어려운 방식으로 interrupt를 잘못 enable할 수 있다.
기본 동작은 timeout 없이 task를 TASK_UNINTERRUPTIBLE로 두고 기다리는 것이다. Sleep할 수 있으므로 wait_for_completion()과 variant는 process context에서만 안전하다. Atomic context, interrupt context, IRQ disabled 상태, preemption disabled 상태에서는 사용할 수 없다. Atomic 또는 interrupt context에서는 아래의 try_wait_for_completion()을 검토한다.
모든 wait_for_completion() variant는 대상 activity에 따라 오래 block될 수 있으므로 대부분의 경우 mutex를 잡은 채 호출해서는 안 된다.
wait_for_completion*() variant와 return value
185-240아래 variant는 status를 return하므로 대부분 또는 모든 경우 이를 검사해야 한다. 의도적으로 무시한다면 이유를 comment로 남기는 편이 좋다. Return value는 정확한 type의 변수에 받아야 한다.
Return value 의미를 부정확하게 검사하는 흔한 오류가 있다.
if (!wait_for_completion_interruptible_timeout(...))
이 형태는 성공적 completion과 signal로 interrupt된 경우를 같은 code path로 처리할 수 있어 의도와 다를 가능성이 높다.
| API | task state 및 return value |
|---|---|
| int wait_for_completion_interruptible(struct completion *done) | 대기 중 TASK_INTERRUPTIBLE. Signal을 받으면 -ERESTARTSYS, 아니면 0. |
| unsigned long wait_for_completion_timeout(struct completion *done, unsigned long timeout) | TASK_UNINTERRUPTIBLE로 최대 timeout jiffies 대기. Timeout이면 0, 완료되면 남은 jiffies를 최소 1로 return. |
| long wait_for_completion_interruptible_timeout(struct completion *done, unsigned long timeout) | TASK_INTERRUPTIBLE. Signal이면 -ERESTARTSYS, timeout이면 0, 완료되면 남은 jiffies. |
| long wait_for_completion_killable(struct completion *done) | TASK_KILLABLE. Interrupt되면 -ERESTARTSYS, 완료되면 0. |
| long wait_for_completion_killable_timeout(struct completion *done, unsigned long timeout) | TASK_KILLABLE에 timeout을 더한 variant. |
| void wait_for_completion_io(struct completion *done) | 일반 variant와 같지만 대기 시간을 waiting on IO로 accounting. |
| unsigned long wait_for_completion_io_timeout(struct completion *done, unsigned long timeout) | IO wait accounting과 timeout을 함께 적용. |
Timeout은 code가 CONFIG_HZ에 거의 독립적이도록 msecs_to_jiffies() 또는 usecs_to_jiffies()로 계산하는 편이 좋다. Return된 timeout 값을 의도적으로 무시한다면 그 이유를 comment로 설명해야 한다. _io variant의 waiting on IO accounting은 scheduling 및 I/O 통계에서 task를 계산하는 방식에 영향을 준다.
complete()와 complete_all()
243-273계속 실행할 조건이 충족되었음을 알리는 thread는 complete()로 waiter 하나만 깨우거나 complete_all()로 현재와 미래의 모든 waiter를 깨운다.
void complete(struct completion *done)
void complete_all(struct completion *done)
Thread가 wait를 시작하기 전에 signal해도 정상 동작한다. Waiter가 struct completion의 done을 감소시키며 게시된 completion 하나를 소비하기 때문이다. Waiting thread는 enqueue된 FIFO 순서로 깨어난다.
complete()를 여러 번 호출하면 호출할 때마다 done이 증가하여 그 횟수만큼 waiter가 계속 실행할 수 있다. 반면 complete_all()을 여러 번 호출하는 것은 bug다. complete()와 complete_all()은 IRQ 또는 atomic context에서 안전하게 호출할 수 있다.
특정 struct completion에 대해 한 순간에는 thread 하나만 complete() 또는 complete_all()을 호출해야 하며 waitqueue spinlock으로 serialize된다. Concurrent signal 호출이 필요해 보인다면 설계 bug일 가능성이 높다.
IRQ context에서 completion을 signal하는 것은 안전하다. spin_lock_irqsave()와 spin_unlock_irqrestore()로 적절히 lock하며 절대 sleep하지 않는다.
try_wait_for_completion()과 completion_done()
276-293bool try_wait_for_completion(struct completion *done)
bool completion_done(struct completion *done)
try_wait_for_completion()은 thread를 waitqueue에 넣지 않는다. Enqueue하여 block해야 하는 상태면 false를 return한다. 게시되어 아직 소비되지 않은 completion이 있으면 하나를 소비하고 true를 return한다.
completion_done()은 completion 상태를 바꾸지 않고 검사한다. Waiter가 아직 소비하지 않은 게시된 completion이 하나도 없으면 false를, 있으면 true를 return한다. 두 function 모두 IRQ 또는 atomic context에서 호출해도 안전하다.
Event를 기다리는 one-way synchronization
completion.rst:5-70Completion은 shared data를 상호 배제하는 lock이 아니라 특정 작업이 끝났다는 event를 전달하는 barrier입니다. Waiter는 condition polling 대신 wait queue에서 sleep하고 signaler가 complete()를 호출하면 runnable이 됩니다.
Completion 내부의 done count는 signal token을 나타냅니다. complete() 한 번은 waiter 하나를 진행시키고 아직 waiter가 없으면 다음 wait가 소비할 token으로 남습니다. 따라서 단순 wakeup과 달리 signal-before-wait를 잃지 않습니다.