← Documents Documentation/scheduler/completion.rst GitHub 원문 ↗

Linux 6.18.37 · Scheduler

Kernel completion 동기화

한 실행 흐름이 비동기 작업 완료를 기다리는 completion의 초기화, lifetime, wait variant와 complete·complete_all semantics를 설명합니다.

Source pathDocumentation/scheduler/completion.rst
Source versionLinux v6.18.37
TranslationDUJINLABS 전문 번역 + 해설

요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.

1. 요약·해설

원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.

Event를 기다리는 one-way synchronization

completion.rst:5-70

Completion은 shared data를 상호 배제하는 lock이 아니라 특정 작업이 끝났다는 event를 전달하는 barrier입니다. Waiter는 condition polling 대신 wait queue에서 sleep하고 signaler가 complete()를 호출하면 runnable이 됩니다.

struct request {
    struct completion done;
};

init_completion(&req->done);
submit_async(req);
wait_for_completion(&req->done);
/* signaler가 publish한 결과를 이제 읽을 수 있다. */

Completion 내부의 done count는 signal token을 나타냅니다. complete() 한 번은 waiter 하나를 진행시키고 아직 waiter가 없으면 다음 wait가 소비할 token으로 남습니다. 따라서 단순 wakeup과 달리 signal-before-wait를 잃지 않습니다.

초기화와 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_interruptiblesignal 가능0 또는 -ERESTARTSYS
wait_for_completion_killablefatal signal0 또는 음수 errno
wait_for_completion_timeoutjiffies timeout0 timeout, 양수 remaining
wait_for_completion_interruptible_timeoutsignal 또는 timeout음수 signal, 0 timeout, 양수 remaining
wait_for_completion_ioI/O wait accounting기본 wait와 유사

Wait 함수는 sleep하므로 atomic context, IRQ-disabled 구간과 spinlock 보유 중 호출할 수 없습니다. Timeout variant의 반환값은 boolean이 아니며 음수, 0, 양수를 모두 구분해야 합니다.

complete와 complete_all

completion.rst:243-294

complete()는 waiter 하나를 깨우고 done token 하나를 제공합니다. complete_all()은 현재와 이후 waiter 모두가 통과할 수 있는 완료 상태를 만들며 다음 세대에서 다시 사용하려면 모든 이전 사용자가 끝난 뒤 reinit_completion()해야 합니다.

try_wait_for_completion()은 sleep하지 않고 token을 소비해 성공 여부를 반환합니다. completion_done()은 token 존재 여부를 관찰하지만 그 뒤 상태가 바뀔 수 있으므로 synchronization 자체를 대신하지 않습니다.

2. 영어 원문 전체

번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.

원문 전체 펼치기
1 ================================================
2 Completions - "wait for completion" barrier APIs
3 ================================================
4
5 Introduction:
6 -------------
7
8 If you have one or more threads that must wait for some kernel activity
9 to have reached a point or a specific state, completions can provide a
10 race-free solution to this problem. Semantically they are somewhat like a
11 pthread_barrier() and have similar use-cases.
12
13 Completions are a code synchronization mechanism which is preferable to any
14 misuse of locks/semaphores and busy-loops. Any time you think of using
15 yield() or some quirky msleep(1) loop to allow something else to proceed,
16 you probably want to look into using one of the wait_for_completion*()
17 calls and complete() instead.
18
19 The advantage of using completions is that they have a well defined, focused
20 purpose which makes it very easy to see the intent of the code, but they
21 also result in more efficient code as all threads can continue execution
22 until the result is actually needed, and both the waiting and the signalling
23 is highly efficient using low level scheduler sleep/wakeup facilities.
24
25 Completions are built on top of the waitqueue and wakeup infrastructure of
26 the Linux scheduler. The event the threads on the waitqueue are waiting for
27 is reduced to a simple flag in 'struct completion', appropriately called "done".
28
29 As completions are scheduling related, the code can be found in
30 kernel/sched/completion.c.
31
32
33 Usage:
34 ------
35
36 There are three main parts to using completions:
37
38 - the initialization of the 'struct completion' synchronization object
39 - the waiting part through a call to one of the variants of wait_for_completion(),
40 - the signaling side through a call to complete() or complete_all().
41
42 There are also some helper functions for checking the state of completions.
43 Note that while initialization must happen first, the waiting and signaling
44 part can happen in any order. I.e. it's entirely normal for a thread
45 to have marked a completion as 'done' before another thread checks whether
46 it has to wait for it.
47
48 To use completions you need to #include <linux/completion.h> and
49 create a static or dynamic variable of type 'struct completion',
50 which has only two fields::
51
52 struct completion {
53 unsigned int done;
54 struct swait_queue_head wait;
55 };
56
57 This provides the ->wait waitqueue to place tasks on for waiting (if any), and
58 the ->done completion flag for indicating whether it's completed or not.
59
60 Completions should be named to refer to the event that is being synchronized on.
61 A good example is::
62
63 wait_for_completion(&early_console_added);
64
65 complete(&early_console_added);
66
67 Good, intuitive naming (as always) helps code readability. Naming a completion
68 'complete' is not helpful unless the purpose is super obvious...
69
70
71 Initializing completions:
72 -------------------------
73
74 Dynamically allocated completion objects should preferably be embedded in data
75 structures that are assured to be alive for the life-time of the function/driver,
76 to prevent races with asynchronous complete() calls from occurring.
77
78 Particular care should be taken when using the _timeout() or _killable()/_interruptible()
79 variants of wait_for_completion(), as it must be assured that memory de-allocation
80 does not happen until all related activities (complete() or reinit_completion())
81 have taken place, even if these wait functions return prematurely due to a timeout
82 or a signal triggering.
83
84 Initializing of dynamically allocated completion objects is done via a call to
85 init_completion()::
86
87 init_completion(&dynamic_object->done);
88
89 In this call we initialize the waitqueue and set ->done to 0, i.e. "not completed"
90 or "not done".
91
92 The re-initialization function, reinit_completion(), simply resets the
93 ->done field to 0 ("not done"), without touching the waitqueue.
94 Callers of this function must make sure that there are no racy
95 wait_for_completion() calls going on in parallel.
96
97 Calling init_completion() on the same completion object twice is
98 most likely a bug as it re-initializes the queue to an empty queue and
99 enqueued tasks could get "lost" - use reinit_completion() in that case,
100 but be aware of other races.
101
102 For static declaration and initialization, macros are available.
103
104 For static (or global) declarations in file scope you can use
105 DECLARE_COMPLETION()::
106
107 static DECLARE_COMPLETION(setup_done);
108 DECLARE_COMPLETION(setup_done);
109
110 Note that in this case the completion is boot time (or module load time)
111 initialized to 'not done' and doesn't require an init_completion() call.
112
113 When a completion is declared as a local variable within a function,
114 then the initialization should always use DECLARE_COMPLETION_ONSTACK()
115 explicitly, not just to make lockdep happy, but also to make it clear
116 that limited scope had been considered and is intentional::
117
118 DECLARE_COMPLETION_ONSTACK(setup_done)
119
120 Note that when using completion objects as local variables you must be
121 acutely aware of the short life time of the function stack: the function
122 must not return to a calling context until all activities (such as waiting
123 threads) have ceased and the completion object is completely unused.
124
125 To emphasise this again: in particular when using some of the waiting API variants
126 with more complex outcomes, such as the timeout or signalling (_timeout(),
127 _killable() and _interruptible()) variants, the wait might complete
128 prematurely while the object might still be in use by another thread - and a return
129 from the wait_on_completion*() caller function will deallocate the function
130 stack and cause subtle data corruption if a complete() is done in some
131 other thread. Simple testing might not trigger these kinds of races.
132
133 If unsure, use dynamically allocated completion objects, preferably embedded
134 in some other long lived object that has a boringly long life time which
135 exceeds the life time of any helper threads using the completion object,
136 or has a lock or other synchronization mechanism to make sure complete()
137 is not called on a freed object.
138
139 A naive DECLARE_COMPLETION() on the stack triggers a lockdep warning.
140
141 Waiting for completions:
142 ------------------------
143
144 For a thread to wait for some concurrent activity to finish, it
145 calls wait_for_completion() on the initialized completion structure::
146
147 void wait_for_completion(struct completion *done)
148
149 A typical usage scenario is::
150
151 CPU#1 CPU#2
152
153 struct completion setup_done;
154
155 init_completion(&setup_done);
156 initialize_work(...,&setup_done,...);
157
158 /* run non-dependent code */ /* do setup */
159
160 wait_for_completion(&setup_done); complete(&setup_done);
161
162 This is not implying any particular order between wait_for_completion() and
163 the call to complete() - if the call to complete() happened before the call
164 to wait_for_completion() then the waiting side simply will continue
165 immediately as all dependencies are satisfied; if not, it will block until
166 completion is signaled by complete().
167
168 Note that wait_for_completion() is calling spin_lock_irq()/spin_unlock_irq(),
169 so it can only be called safely when you know that interrupts are enabled.
170 Calling it from IRQs-off atomic contexts will result in hard-to-detect
171 spurious enabling of interrupts.
172
173 The default behavior is to wait without a timeout and to mark the task as
174 uninterruptible. wait_for_completion() and its variants are only safe
175 in process context (as they can sleep) but not in atomic context,
176 interrupt context, with disabled IRQs, or preemption is disabled - see also
177 try_wait_for_completion() below for handling completion in atomic/interrupt
178 context.
179
180 As all variants of wait_for_completion() can (obviously) block for a long
181 time depending on the nature of the activity they are waiting for, so in
182 most cases you probably don't want to call this with held mutexes.
183
184
185 wait_for_completion*() variants available:
186 ------------------------------------------
187
188 The below variants all return status and this status should be checked in
189 most(/all) cases - in cases where the status is deliberately not checked you
190 probably want to make a note explaining this (e.g. see
191 arch/arm/kernel/smp.c:__cpu_up()).
192
193 A common problem that occurs is to have unclean assignment of return types,
194 so take care to assign return-values to variables of the proper type.
195
196 Checking for the specific meaning of return values also has been found
197 to be quite inaccurate, e.g. constructs like::
198
199 if (!wait_for_completion_interruptible_timeout(...))
200
201 ... would execute the same code path for successful completion and for the
202 interrupted case - which is probably not what you want::
203
204 int wait_for_completion_interruptible(struct completion *done)
205
206 This function marks the task TASK_INTERRUPTIBLE while it is waiting.
207 If a signal was received while waiting it will return -ERESTARTSYS; 0 otherwise::
208
209 unsigned long wait_for_completion_timeout(struct completion *done, unsigned long timeout)
210
211 The task is marked as TASK_UNINTERRUPTIBLE and will wait at most 'timeout'
212 jiffies. If a timeout occurs it returns 0, else the remaining time in
213 jiffies (but at least 1).
214
215 Timeouts are preferably calculated with msecs_to_jiffies() or usecs_to_jiffies(),
216 to make the code largely HZ-invariant.
217
218 If the returned timeout value is deliberately ignored a comment should probably explain
219 why (e.g. see drivers/mfd/wm8350-core.c wm8350_read_auxadc())::
220
221 long wait_for_completion_interruptible_timeout(struct completion *done, unsigned long timeout)
222
223 This function passes a timeout in jiffies and marks the task as
224 TASK_INTERRUPTIBLE. If a signal was received it will return -ERESTARTSYS;
225 otherwise it returns 0 if the completion timed out, or the remaining time in
226 jiffies if completion occurred.
227
228 Further variants include _killable which uses TASK_KILLABLE as the
229 designated tasks state and will return -ERESTARTSYS if it is interrupted,
230 or 0 if completion was achieved. There is a _timeout variant as well::
231
232 long wait_for_completion_killable(struct completion *done)
233 long wait_for_completion_killable_timeout(struct completion *done, unsigned long timeout)
234
235 The _io variants wait_for_completion_io() behave the same as the non-_io
236 variants, except for accounting waiting time as 'waiting on IO', which has
237 an impact on how the task is accounted in scheduling/IO stats::
238
239 void wait_for_completion_io(struct completion *done)
240 unsigned long wait_for_completion_io_timeout(struct completion *done, unsigned long timeout)
241
242
243 Signaling completions:
244 ----------------------
245
246 A thread that wants to signal that the conditions for continuation have been
247 achieved calls complete() to signal exactly one of the waiters that it can
248 continue::
249
250 void complete(struct completion *done)
251
252 ... or calls complete_all() to signal all current and future waiters::
253
254 void complete_all(struct completion *done)
255
256 The signaling will work as expected even if completions are signaled before
257 a thread starts waiting. This is achieved by the waiter "consuming"
258 (decrementing) the done field of 'struct completion'. Waiting threads
259 wakeup order is the same in which they were enqueued (FIFO order).
260
261 If complete() is called multiple times then this will allow for that number
262 of waiters to continue - each call to complete() will simply increment the
263 done field. Calling complete_all() multiple times is a bug though. Both
264 complete() and complete_all() can be called in IRQ/atomic context safely.
265
266 There can only be one thread calling complete() or complete_all() on a
267 particular 'struct completion' at any time - serialized through the wait
268 queue spinlock. Any such concurrent calls to complete() or complete_all()
269 probably are a design bug.
270
271 Signaling completion from IRQ context is fine as it will appropriately
272 lock with spin_lock_irqsave()/spin_unlock_irqrestore() and it will never
273 sleep.
274
275
276 try_wait_for_completion()/completion_done():
277 --------------------------------------------
278
279 The try_wait_for_completion() function will not put the thread on the wait
280 queue but rather returns false if it would need to enqueue (block) the thread,
281 else it consumes one posted completion and returns true::
282
283 bool try_wait_for_completion(struct completion *done)
284
285 Finally, to check the state of a completion without changing it in any way,
286 call completion_done(), which returns false if there are no posted
287 completions that were not yet consumed by waiters (implying that there are
288 waiters) and true otherwise::
289
290 bool completion_done(struct completion *done)
291
292 Both try_wait_for_completion() and completion_done() are safe to be called in
293 IRQ or atomic context.
294

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-100

Dynamic 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-140

File 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-182
void wait_for_completion(struct completion *done)

동시에 수행되는 activity가 끝나기를 기다리는 thread는 초기화된 completion에 wait_for_completion()을 호출한다. 원문의 두 CPU ASCII 예시는 다음 단계로 정리할 수 있다.

단계CPU #1: wait sideCPU #2: signal side
1struct completion setup_done 선언setup 작업 대기
2init_completion(&setup_done)아직 접근하지 않음
3initialize_work(..., &setup_done, ...)setup 수행
4completion과 무관한 code 실행setup 계속 수행
5wait_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로 처리할 수 있어 의도와 다를 가능성이 높다.

APItask 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-293
bool 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에서 호출해도 안전하다.