Back to home page

OSCL-LXR

 
 

    


0001 ================================================
0002 Completions - "wait for completion" barrier APIs
0003 ================================================
0004 
0005 Introduction:
0006 -------------
0007 
0008 If you have one or more threads that must wait for some kernel activity
0009 to have reached a point or a specific state, completions can provide a
0010 race-free solution to this problem. Semantically they are somewhat like a
0011 pthread_barrier() and have similar use-cases.
0012 
0013 Completions are a code synchronization mechanism which is preferable to any
0014 misuse of locks/semaphores and busy-loops. Any time you think of using
0015 yield() or some quirky msleep(1) loop to allow something else to proceed,
0016 you probably want to look into using one of the wait_for_completion*()
0017 calls and complete() instead.
0018 
0019 The advantage of using completions is that they have a well defined, focused
0020 purpose which makes it very easy to see the intent of the code, but they
0021 also result in more efficient code as all threads can continue execution
0022 until the result is actually needed, and both the waiting and the signalling
0023 is highly efficient using low level scheduler sleep/wakeup facilities.
0024 
0025 Completions are built on top of the waitqueue and wakeup infrastructure of
0026 the Linux scheduler. The event the threads on the waitqueue are waiting for
0027 is reduced to a simple flag in 'struct completion', appropriately called "done".
0028 
0029 As completions are scheduling related, the code can be found in
0030 kernel/sched/completion.c.
0031 
0032 
0033 Usage:
0034 ------
0035 
0036 There are three main parts to using completions:
0037 
0038  - the initialization of the 'struct completion' synchronization object
0039  - the waiting part through a call to one of the variants of wait_for_completion(),
0040  - the signaling side through a call to complete() or complete_all().
0041 
0042 There are also some helper functions for checking the state of completions.
0043 Note that while initialization must happen first, the waiting and signaling
0044 part can happen in any order. I.e. it's entirely normal for a thread
0045 to have marked a completion as 'done' before another thread checks whether
0046 it has to wait for it.
0047 
0048 To use completions you need to #include <linux/completion.h> and
0049 create a static or dynamic variable of type 'struct completion',
0050 which has only two fields::
0051 
0052         struct completion {
0053                 unsigned int done;
0054                 wait_queue_head_t wait;
0055         };
0056 
0057 This provides the ->wait waitqueue to place tasks on for waiting (if any), and
0058 the ->done completion flag for indicating whether it's completed or not.
0059 
0060 Completions should be named to refer to the event that is being synchronized on.
0061 A good example is::
0062 
0063         wait_for_completion(&early_console_added);
0064 
0065         complete(&early_console_added);
0066 
0067 Good, intuitive naming (as always) helps code readability. Naming a completion
0068 'complete' is not helpful unless the purpose is super obvious...
0069 
0070 
0071 Initializing completions:
0072 -------------------------
0073 
0074 Dynamically allocated completion objects should preferably be embedded in data
0075 structures that are assured to be alive for the life-time of the function/driver,
0076 to prevent races with asynchronous complete() calls from occurring.
0077 
0078 Particular care should be taken when using the _timeout() or _killable()/_interruptible()
0079 variants of wait_for_completion(), as it must be assured that memory de-allocation
0080 does not happen until all related activities (complete() or reinit_completion())
0081 have taken place, even if these wait functions return prematurely due to a timeout
0082 or a signal triggering.
0083 
0084 Initializing of dynamically allocated completion objects is done via a call to
0085 init_completion()::
0086 
0087         init_completion(&dynamic_object->done);
0088 
0089 In this call we initialize the waitqueue and set ->done to 0, i.e. "not completed"
0090 or "not done".
0091 
0092 The re-initialization function, reinit_completion(), simply resets the
0093 ->done field to 0 ("not done"), without touching the waitqueue.
0094 Callers of this function must make sure that there are no racy
0095 wait_for_completion() calls going on in parallel.
0096 
0097 Calling init_completion() on the same completion object twice is
0098 most likely a bug as it re-initializes the queue to an empty queue and
0099 enqueued tasks could get "lost" - use reinit_completion() in that case,
0100 but be aware of other races.
0101 
0102 For static declaration and initialization, macros are available.
0103 
0104 For static (or global) declarations in file scope you can use
0105 DECLARE_COMPLETION()::
0106 
0107         static DECLARE_COMPLETION(setup_done);
0108         DECLARE_COMPLETION(setup_done);
0109 
0110 Note that in this case the completion is boot time (or module load time)
0111 initialized to 'not done' and doesn't require an init_completion() call.
0112 
0113 When a completion is declared as a local variable within a function,
0114 then the initialization should always use DECLARE_COMPLETION_ONSTACK()
0115 explicitly, not just to make lockdep happy, but also to make it clear
0116 that limited scope had been considered and is intentional::
0117 
0118         DECLARE_COMPLETION_ONSTACK(setup_done)
0119 
0120 Note that when using completion objects as local variables you must be
0121 acutely aware of the short life time of the function stack: the function
0122 must not return to a calling context until all activities (such as waiting
0123 threads) have ceased and the completion object is completely unused.
0124 
0125 To emphasise this again: in particular when using some of the waiting API variants
0126 with more complex outcomes, such as the timeout or signalling (_timeout(),
0127 _killable() and _interruptible()) variants, the wait might complete
0128 prematurely while the object might still be in use by another thread - and a return
0129 from the wait_on_completion*() caller function will deallocate the function
0130 stack and cause subtle data corruption if a complete() is done in some
0131 other thread. Simple testing might not trigger these kinds of races.
0132 
0133 If unsure, use dynamically allocated completion objects, preferably embedded
0134 in some other long lived object that has a boringly long life time which
0135 exceeds the life time of any helper threads using the completion object,
0136 or has a lock or other synchronization mechanism to make sure complete()
0137 is not called on a freed object.
0138 
0139 A naive DECLARE_COMPLETION() on the stack triggers a lockdep warning.
0140 
0141 Waiting for completions:
0142 ------------------------
0143 
0144 For a thread to wait for some concurrent activity to finish, it
0145 calls wait_for_completion() on the initialized completion structure::
0146 
0147         void wait_for_completion(struct completion *done)
0148 
0149 A typical usage scenario is::
0150 
0151         CPU#1                                   CPU#2
0152 
0153         struct completion setup_done;
0154 
0155         init_completion(&setup_done);
0156         initialize_work(...,&setup_done,...);
0157 
0158         /* run non-dependent code */            /* do setup */
0159 
0160         wait_for_completion(&setup_done);       complete(setup_done);
0161 
0162 This is not implying any particular order between wait_for_completion() and
0163 the call to complete() - if the call to complete() happened before the call
0164 to wait_for_completion() then the waiting side simply will continue
0165 immediately as all dependencies are satisfied; if not, it will block until
0166 completion is signaled by complete().
0167 
0168 Note that wait_for_completion() is calling spin_lock_irq()/spin_unlock_irq(),
0169 so it can only be called safely when you know that interrupts are enabled.
0170 Calling it from IRQs-off atomic contexts will result in hard-to-detect
0171 spurious enabling of interrupts.
0172 
0173 The default behavior is to wait without a timeout and to mark the task as
0174 uninterruptible. wait_for_completion() and its variants are only safe
0175 in process context (as they can sleep) but not in atomic context,
0176 interrupt context, with disabled IRQs, or preemption is disabled - see also
0177 try_wait_for_completion() below for handling completion in atomic/interrupt
0178 context.
0179 
0180 As all variants of wait_for_completion() can (obviously) block for a long
0181 time depending on the nature of the activity they are waiting for, so in
0182 most cases you probably don't want to call this with held mutexes.
0183 
0184 
0185 wait_for_completion*() variants available:
0186 ------------------------------------------
0187 
0188 The below variants all return status and this status should be checked in
0189 most(/all) cases - in cases where the status is deliberately not checked you
0190 probably want to make a note explaining this (e.g. see
0191 arch/arm/kernel/smp.c:__cpu_up()).
0192 
0193 A common problem that occurs is to have unclean assignment of return types,
0194 so take care to assign return-values to variables of the proper type.
0195 
0196 Checking for the specific meaning of return values also has been found
0197 to be quite inaccurate, e.g. constructs like::
0198 
0199         if (!wait_for_completion_interruptible_timeout(...))
0200 
0201 ... would execute the same code path for successful completion and for the
0202 interrupted case - which is probably not what you want::
0203 
0204         int wait_for_completion_interruptible(struct completion *done)
0205 
0206 This function marks the task TASK_INTERRUPTIBLE while it is waiting.
0207 If a signal was received while waiting it will return -ERESTARTSYS; 0 otherwise::
0208 
0209         unsigned long wait_for_completion_timeout(struct completion *done, unsigned long timeout)
0210 
0211 The task is marked as TASK_UNINTERRUPTIBLE and will wait at most 'timeout'
0212 jiffies. If a timeout occurs it returns 0, else the remaining time in
0213 jiffies (but at least 1).
0214 
0215 Timeouts are preferably calculated with msecs_to_jiffies() or usecs_to_jiffies(),
0216 to make the code largely HZ-invariant.
0217 
0218 If the returned timeout value is deliberately ignored a comment should probably explain
0219 why (e.g. see drivers/mfd/wm8350-core.c wm8350_read_auxadc())::
0220 
0221         long wait_for_completion_interruptible_timeout(struct completion *done, unsigned long timeout)
0222 
0223 This function passes a timeout in jiffies and marks the task as
0224 TASK_INTERRUPTIBLE. If a signal was received it will return -ERESTARTSYS;
0225 otherwise it returns 0 if the completion timed out, or the remaining time in
0226 jiffies if completion occurred.
0227 
0228 Further variants include _killable which uses TASK_KILLABLE as the
0229 designated tasks state and will return -ERESTARTSYS if it is interrupted,
0230 or 0 if completion was achieved.  There is a _timeout variant as well::
0231 
0232         long wait_for_completion_killable(struct completion *done)
0233         long wait_for_completion_killable_timeout(struct completion *done, unsigned long timeout)
0234 
0235 The _io variants wait_for_completion_io() behave the same as the non-_io
0236 variants, except for accounting waiting time as 'waiting on IO', which has
0237 an impact on how the task is accounted in scheduling/IO stats::
0238 
0239         void wait_for_completion_io(struct completion *done)
0240         unsigned long wait_for_completion_io_timeout(struct completion *done, unsigned long timeout)
0241 
0242 
0243 Signaling completions:
0244 ----------------------
0245 
0246 A thread that wants to signal that the conditions for continuation have been
0247 achieved calls complete() to signal exactly one of the waiters that it can
0248 continue::
0249 
0250         void complete(struct completion *done)
0251 
0252 ... or calls complete_all() to signal all current and future waiters::
0253 
0254         void complete_all(struct completion *done)
0255 
0256 The signaling will work as expected even if completions are signaled before
0257 a thread starts waiting. This is achieved by the waiter "consuming"
0258 (decrementing) the done field of 'struct completion'. Waiting threads
0259 wakeup order is the same in which they were enqueued (FIFO order).
0260 
0261 If complete() is called multiple times then this will allow for that number
0262 of waiters to continue - each call to complete() will simply increment the
0263 done field. Calling complete_all() multiple times is a bug though. Both
0264 complete() and complete_all() can be called in IRQ/atomic context safely.
0265 
0266 There can only be one thread calling complete() or complete_all() on a
0267 particular 'struct completion' at any time - serialized through the wait
0268 queue spinlock. Any such concurrent calls to complete() or complete_all()
0269 probably are a design bug.
0270 
0271 Signaling completion from IRQ context is fine as it will appropriately
0272 lock with spin_lock_irqsave()/spin_unlock_irqrestore() and it will never
0273 sleep.
0274 
0275 
0276 try_wait_for_completion()/completion_done():
0277 --------------------------------------------
0278 
0279 The try_wait_for_completion() function will not put the thread on the wait
0280 queue but rather returns false if it would need to enqueue (block) the thread,
0281 else it consumes one posted completion and returns true::
0282 
0283         bool try_wait_for_completion(struct completion *done)
0284 
0285 Finally, to check the state of a completion without changing it in any way,
0286 call completion_done(), which returns false if there are no posted
0287 completions that were not yet consumed by waiters (implying that there are
0288 waiters) and true otherwise::
0289 
0290         bool completion_done(struct completion *done)
0291 
0292 Both try_wait_for_completion() and completion_done() are safe to be called in
0293 IRQ or atomic context.