source: mainline/kernel/generic/src/synch/waitq.c@ b2aaaa0

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since b2aaaa0 was 96c30c8, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Turn ipc_poke() into a regular wakeup on the waitq.

With prior behavior of ignoring the poke when no thread is blocking,
a thread could go to sleep just after a poke meant for it and sleep
indefinitely despite there being work to do.

After the change, worst case scenario, thread enters ipc wait, exits
immediately due to a previous poke, finds no work to do and enters ipc wait
again (possibly repeating the spurious wakeup a few times).

  • Property mode set to 100644
File size: 16.4 KB
Line 
1/*
2 * Copyright (c) 2001-2004 Jakub Jermar
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 *
9 * - Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * - Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * - The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29/** @addtogroup sync
30 * @{
31 */
32
33/**
34 * @file
35 * @brief Wait queue.
36 *
37 * Wait queue is the basic synchronization primitive upon which all
38 * other synchronization primitives build.
39 *
40 * It allows threads to wait for an event in first-come, first-served
41 * fashion. Conditional operation as well as timeouts and interruptions
42 * are supported.
43 *
44 */
45
46#include <assert.h>
47#include <errno.h>
48#include <synch/waitq.h>
49#include <synch/spinlock.h>
50#include <proc/thread.h>
51#include <proc/scheduler.h>
52#include <arch/asm.h>
53#include <typedefs.h>
54#include <time/timeout.h>
55#include <arch.h>
56#include <context.h>
57#include <adt/list.h>
58#include <arch/cycle.h>
59#include <mem.h>
60
61static void waitq_sleep_timed_out(void *);
62static void waitq_complete_wakeup(waitq_t *);
63
64
65/** Initialize wait queue
66 *
67 * Initialize wait queue.
68 *
69 * @param wq Pointer to wait queue to be initialized.
70 *
71 */
72void waitq_initialize(waitq_t *wq)
73{
74 memsetb(wq, sizeof(*wq), 0);
75 irq_spinlock_initialize(&wq->lock, "wq.lock");
76 list_initialize(&wq->sleepers);
77}
78
79/** Handle timeout during waitq_sleep_timeout() call
80 *
81 * This routine is called when waitq_sleep_timeout() times out.
82 * Interrupts are disabled.
83 *
84 * It is supposed to try to remove 'its' thread from the wait queue;
85 * it can eventually fail to achieve this goal when these two events
86 * overlap. In that case it behaves just as though there was no
87 * timeout at all.
88 *
89 * @param data Pointer to the thread that called waitq_sleep_timeout().
90 *
91 */
92void waitq_sleep_timed_out(void *data)
93{
94 thread_t *thread = (thread_t *) data;
95 bool do_wakeup = false;
96 DEADLOCK_PROBE_INIT(p_wqlock);
97
98 irq_spinlock_lock(&threads_lock, false);
99 if (!thread_exists(thread))
100 goto out;
101
102grab_locks:
103 irq_spinlock_lock(&thread->lock, false);
104
105 waitq_t *wq;
106 if ((wq = thread->sleep_queue)) { /* Assignment */
107 if (!irq_spinlock_trylock(&wq->lock)) {
108 irq_spinlock_unlock(&thread->lock, false);
109 DEADLOCK_PROBE(p_wqlock, DEADLOCK_THRESHOLD);
110 /* Avoid deadlock */
111 goto grab_locks;
112 }
113
114 list_remove(&thread->wq_link);
115 thread->saved_context = thread->sleep_timeout_context;
116 do_wakeup = true;
117 if (thread->sleep_composable)
118 wq->ignore_wakeups++;
119 thread->sleep_queue = NULL;
120 irq_spinlock_unlock(&wq->lock, false);
121 }
122
123 thread->timeout_pending = false;
124 irq_spinlock_unlock(&thread->lock, false);
125
126 if (do_wakeup)
127 thread_ready(thread);
128
129out:
130 irq_spinlock_unlock(&threads_lock, false);
131}
132
133/** Interrupt sleeping thread.
134 *
135 * This routine attempts to interrupt a thread from its sleep in
136 * a waitqueue. If the thread is not found sleeping, no action
137 * is taken.
138 *
139 * The threads_lock must be already held and interrupts must be
140 * disabled upon calling this function.
141 *
142 * @param thread Thread to be interrupted.
143 *
144 */
145void waitq_interrupt_sleep(thread_t *thread)
146{
147 bool do_wakeup = false;
148 DEADLOCK_PROBE_INIT(p_wqlock);
149
150 /*
151 * The thread is quaranteed to exist because
152 * threads_lock is held.
153 */
154
155grab_locks:
156 irq_spinlock_lock(&thread->lock, false);
157
158 waitq_t *wq;
159 if ((wq = thread->sleep_queue)) { /* Assignment */
160 if (!(thread->sleep_interruptible)) {
161 /*
162 * The sleep cannot be interrupted.
163 */
164 irq_spinlock_unlock(&thread->lock, false);
165 return;
166 }
167
168 if (!irq_spinlock_trylock(&wq->lock)) {
169 /* Avoid deadlock */
170 irq_spinlock_unlock(&thread->lock, false);
171 DEADLOCK_PROBE(p_wqlock, DEADLOCK_THRESHOLD);
172 goto grab_locks;
173 }
174
175 if ((thread->timeout_pending) &&
176 (timeout_unregister(&thread->sleep_timeout)))
177 thread->timeout_pending = false;
178
179 list_remove(&thread->wq_link);
180 thread->saved_context = thread->sleep_interruption_context;
181 if (thread->sleep_composable)
182 wq->ignore_wakeups++;
183 do_wakeup = true;
184 thread->sleep_queue = NULL;
185 irq_spinlock_unlock(&wq->lock, false);
186 }
187
188 irq_spinlock_unlock(&thread->lock, false);
189
190 if (do_wakeup)
191 thread_ready(thread);
192}
193
194#define PARAM_NON_BLOCKING(flags, usec) \
195 (((flags) & SYNCH_FLAGS_NON_BLOCKING) && ((usec) == 0))
196
197/** Sleep until either wakeup, timeout or interruption occurs
198 *
199 * This is a sleep implementation which allows itself to time out or to be
200 * interrupted from the sleep, restoring a failover context.
201 *
202 * Sleepers are organised in a FIFO fashion in a structure called wait queue.
203 *
204 * This function is really basic in that other functions as waitq_sleep()
205 * and all the *_timeout() functions use it.
206 *
207 * @param wq Pointer to wait queue.
208 * @param usec Timeout in microseconds.
209 * @param flags Specify mode of the sleep.
210 *
211 * @param[out] blocked On return, regardless of the return code,
212 * `*blocked` is set to `true` iff the thread went to
213 * sleep.
214 *
215 * The sleep can be interrupted only if the
216 * SYNCH_FLAGS_INTERRUPTIBLE bit is specified in flags.
217 *
218 * If usec is greater than zero, regardless of the value of the
219 * SYNCH_FLAGS_NON_BLOCKING bit in flags, the call will not return until either
220 * timeout, interruption or wakeup comes.
221 *
222 * If usec is zero and the SYNCH_FLAGS_NON_BLOCKING bit is not set in flags,
223 * the call will not return until wakeup or interruption comes.
224 *
225 * If usec is zero and the SYNCH_FLAGS_NON_BLOCKING bit is set in flags, the
226 * call will immediately return, reporting either success or failure.
227 *
228 * @return EAGAIN, meaning that the sleep failed because it was requested
229 * as SYNCH_FLAGS_NON_BLOCKING, but there was no pending wakeup.
230 * @return ETIMEOUT, meaning that the sleep timed out.
231 * @return EINTR, meaning that somebody interrupted the sleeping
232 * thread. Check the value of `*blocked` to see if the thread slept,
233 * or if a pending interrupt forced it to return immediately.
234 * @return EOK, meaning that none of the above conditions occured, and the
235 * thread was woken up successfuly by `waitq_wakeup()`. Check
236 * the value of `*blocked` to see if the thread slept or if
237 * the wakeup was already pending.
238 *
239 */
240errno_t waitq_sleep_timeout(waitq_t *wq, uint32_t usec, unsigned int flags, bool *blocked)
241{
242 assert((!PREEMPTION_DISABLED) || (PARAM_NON_BLOCKING(flags, usec)));
243
244 ipl_t ipl = waitq_sleep_prepare(wq);
245 bool nblocked;
246 errno_t rc = waitq_sleep_timeout_unsafe(wq, usec, flags, &nblocked);
247 waitq_sleep_finish(wq, nblocked, ipl);
248
249 if (blocked != NULL) {
250 *blocked = nblocked;
251 }
252 return rc;
253}
254
255/** Prepare to sleep in a waitq.
256 *
257 * This function will return holding the lock of the wait queue
258 * and interrupts disabled.
259 *
260 * @param wq Wait queue.
261 *
262 * @return Interrupt level as it existed on entry to this function.
263 *
264 */
265ipl_t waitq_sleep_prepare(waitq_t *wq)
266{
267 ipl_t ipl;
268
269restart:
270 ipl = interrupts_disable();
271
272 if (THREAD) { /* Needed during system initiailzation */
273 /*
274 * Busy waiting for a delayed timeout.
275 * This is an important fix for the race condition between
276 * a delayed timeout and a next call to waitq_sleep_timeout().
277 * Simply, the thread is not allowed to go to sleep if
278 * there are timeouts in progress.
279 *
280 */
281 irq_spinlock_lock(&THREAD->lock, false);
282
283 if (THREAD->timeout_pending) {
284 irq_spinlock_unlock(&THREAD->lock, false);
285 interrupts_restore(ipl);
286 goto restart;
287 }
288
289 irq_spinlock_unlock(&THREAD->lock, false);
290 }
291
292 irq_spinlock_lock(&wq->lock, false);
293 return ipl;
294}
295
296/** Finish waiting in a wait queue.
297 *
298 * This function restores interrupts to the state that existed prior
299 * to the call to waitq_sleep_prepare(). If necessary, the wait queue
300 * lock is released.
301 *
302 * @param wq Wait queue.
303 * @param blocked Out parameter of waitq_sleep_timeout_unsafe().
304 * @param ipl Interrupt level returned by waitq_sleep_prepare().
305 *
306 */
307void waitq_sleep_finish(waitq_t *wq, bool blocked, ipl_t ipl)
308{
309 if (blocked) {
310 /*
311 * Wait for a waitq_wakeup() or waitq_unsleep() to complete
312 * before returning from waitq_sleep() to the caller. Otherwise
313 * the caller might expect that the wait queue is no longer used
314 * and deallocate it (although the wakeup on a another cpu has
315 * not yet completed and is using the wait queue).
316 *
317 * Note that we have to do this for EOK and EINTR, but not
318 * necessarily for ETIMEOUT where the timeout handler stops
319 * using the waitq before waking us up. To be on the safe side,
320 * ensure the waitq is not in use anymore in this case as well.
321 */
322 waitq_complete_wakeup(wq);
323 } else {
324 irq_spinlock_unlock(&wq->lock, false);
325 }
326
327 interrupts_restore(ipl);
328}
329
330/** Internal implementation of waitq_sleep_timeout().
331 *
332 * This function implements logic of sleeping in a wait queue.
333 * This call must be preceded by a call to waitq_sleep_prepare()
334 * and followed by a call to waitq_sleep_finish().
335 *
336 * @param wq See waitq_sleep_timeout().
337 * @param usec See waitq_sleep_timeout().
338 * @param flags See waitq_sleep_timeout().
339 *
340 * @param[out] blocked See waitq_sleep_timeout().
341 *
342 * @return See waitq_sleep_timeout().
343 *
344 */
345errno_t waitq_sleep_timeout_unsafe(waitq_t *wq, uint32_t usec, unsigned int flags, bool *blocked)
346{
347 *blocked = false;
348
349 /* Checks whether to go to sleep at all */
350 if (wq->missed_wakeups) {
351 wq->missed_wakeups--;
352 return EOK;
353 } else {
354 if (PARAM_NON_BLOCKING(flags, usec)) {
355 /* Return immediately instead of going to sleep */
356 return EAGAIN;
357 }
358 }
359
360 /*
361 * Now we are firmly decided to go to sleep.
362 *
363 */
364 irq_spinlock_lock(&THREAD->lock, false);
365
366 THREAD->sleep_composable = (flags & SYNCH_FLAGS_FUTEX);
367
368 if (flags & SYNCH_FLAGS_INTERRUPTIBLE) {
369 /*
370 * If the thread was already interrupted,
371 * don't go to sleep at all.
372 */
373 if (THREAD->interrupted) {
374 irq_spinlock_unlock(&THREAD->lock, false);
375 return EINTR;
376 }
377
378 /*
379 * Set context that will be restored if the sleep
380 * of this thread is ever interrupted.
381 */
382 THREAD->sleep_interruptible = true;
383 if (!context_save(&THREAD->sleep_interruption_context)) {
384 /* Short emulation of scheduler() return code. */
385 THREAD->last_cycle = get_cycle();
386 irq_spinlock_unlock(&THREAD->lock, false);
387 return EINTR;
388 }
389 } else
390 THREAD->sleep_interruptible = false;
391
392 if (usec) {
393 /* We use the timeout variant. */
394 if (!context_save(&THREAD->sleep_timeout_context)) {
395 /* Short emulation of scheduler() return code. */
396 THREAD->last_cycle = get_cycle();
397 irq_spinlock_unlock(&THREAD->lock, false);
398 return ETIMEOUT;
399 }
400
401 THREAD->timeout_pending = true;
402 timeout_register(&THREAD->sleep_timeout, (uint64_t) usec,
403 waitq_sleep_timed_out, THREAD);
404 }
405
406 list_append(&THREAD->wq_link, &wq->sleepers);
407
408 /*
409 * Suspend execution.
410 *
411 */
412 THREAD->state = Sleeping;
413 THREAD->sleep_queue = wq;
414
415 /*
416 * Must be before entry to scheduler, because there are multiple
417 * return vectors.
418 */
419 *blocked = true;
420
421 irq_spinlock_unlock(&THREAD->lock, false);
422
423 /* wq->lock is released in scheduler_separated_stack() */
424 scheduler();
425
426 return EOK;
427}
428
429/** Wake up first thread sleeping in a wait queue
430 *
431 * Wake up first thread sleeping in a wait queue. This is the SMP- and IRQ-safe
432 * wrapper meant for general use.
433 *
434 * Besides its 'normal' wakeup operation, it attempts to unregister possible
435 * timeout.
436 *
437 * @param wq Pointer to wait queue.
438 * @param mode Wakeup mode.
439 *
440 */
441void waitq_wakeup(waitq_t *wq, wakeup_mode_t mode)
442{
443 irq_spinlock_lock(&wq->lock, true);
444 _waitq_wakeup_unsafe(wq, mode);
445 irq_spinlock_unlock(&wq->lock, true);
446}
447
448/** If there is a wakeup in progress actively waits for it to complete.
449 *
450 * The function returns once the concurrently running waitq_wakeup()
451 * exits. It returns immediately if there are no concurrent wakeups
452 * at the time.
453 *
454 * Interrupts must be disabled.
455 *
456 * Example usage:
457 * @code
458 * void callback(waitq *wq)
459 * {
460 * // Do something and notify wait_for_completion() that we're done.
461 * waitq_wakeup(wq);
462 * }
463 * void wait_for_completion(void)
464 * {
465 * waitq wg;
466 * waitq_initialize(&wq);
467 * // Run callback() in the background, pass it wq.
468 * do_asynchronously(callback, &wq);
469 * // Wait for callback() to complete its work.
470 * waitq_sleep(&wq);
471 * // callback() completed its work, but it may still be accessing
472 * // wq in waitq_wakeup(). Therefore it is not yet safe to return
473 * // from waitq_sleep() or it would clobber up our stack (where wq
474 * // is stored). waitq_sleep() ensures the wait queue is no longer
475 * // in use by invoking waitq_complete_wakeup() internally.
476 *
477 * // waitq_sleep() returned, it is safe to free wq.
478 * }
479 * @endcode
480 *
481 * @param wq Pointer to a wait queue.
482 */
483static void waitq_complete_wakeup(waitq_t *wq)
484{
485 assert(interrupts_disabled());
486
487 irq_spinlock_lock(&wq->lock, false);
488 irq_spinlock_unlock(&wq->lock, false);
489}
490
491
492/** Internal SMP- and IRQ-unsafe version of waitq_wakeup()
493 *
494 * This is the internal SMP- and IRQ-unsafe version of waitq_wakeup(). It
495 * assumes wq->lock is already locked and interrupts are already disabled.
496 *
497 * @param wq Pointer to wait queue.
498 * @param mode If mode is WAKEUP_FIRST, then the longest waiting
499 * thread, if any, is woken up. If mode is WAKEUP_ALL, then
500 * all waiting threads, if any, are woken up. If there are
501 * no waiting threads to be woken up, the missed wakeup is
502 * recorded in the wait queue.
503 *
504 */
505void _waitq_wakeup_unsafe(waitq_t *wq, wakeup_mode_t mode)
506{
507 size_t count = 0;
508
509 assert(interrupts_disabled());
510 assert(irq_spinlock_locked(&wq->lock));
511
512 if (wq->ignore_wakeups > 0) {
513 if (mode == WAKEUP_FIRST) {
514 wq->ignore_wakeups--;
515 return;
516 }
517 wq->ignore_wakeups = 0;
518 }
519
520loop:
521 if (list_empty(&wq->sleepers)) {
522 wq->missed_wakeups++;
523 if ((count) && (mode == WAKEUP_ALL))
524 wq->missed_wakeups--;
525
526 return;
527 }
528
529 count++;
530 thread_t *thread = list_get_instance(list_first(&wq->sleepers),
531 thread_t, wq_link);
532
533 /*
534 * Lock the thread prior to removing it from the wq.
535 * This is not necessary because of mutual exclusion
536 * (the link belongs to the wait queue), but because
537 * of synchronization with waitq_sleep_timed_out()
538 * and thread_interrupt_sleep().
539 *
540 * In order for these two functions to work, the following
541 * invariant must hold:
542 *
543 * thread->sleep_queue != NULL <=> thread sleeps in a wait queue
544 *
545 * For an observer who locks the thread, the invariant
546 * holds only when the lock is held prior to removing
547 * it from the wait queue.
548 *
549 */
550 irq_spinlock_lock(&thread->lock, false);
551 list_remove(&thread->wq_link);
552
553 if ((thread->timeout_pending) &&
554 (timeout_unregister(&thread->sleep_timeout)))
555 thread->timeout_pending = false;
556
557 thread->sleep_queue = NULL;
558 irq_spinlock_unlock(&thread->lock, false);
559
560 thread_ready(thread);
561
562 if (mode == WAKEUP_ALL)
563 goto loop;
564}
565
566/** Get the missed wakeups count.
567 *
568 * @param wq Pointer to wait queue.
569 * @return The wait queue's missed_wakeups count.
570 */
571int waitq_count_get(waitq_t *wq)
572{
573 int cnt;
574
575 irq_spinlock_lock(&wq->lock, true);
576 cnt = wq->missed_wakeups;
577 irq_spinlock_unlock(&wq->lock, true);
578
579 return cnt;
580}
581
582/** Set the missed wakeups count.
583 *
584 * @param wq Pointer to wait queue.
585 * @param val New value of the missed_wakeups count.
586 */
587void waitq_count_set(waitq_t *wq, int val)
588{
589 irq_spinlock_lock(&wq->lock, true);
590 wq->missed_wakeups = val;
591 irq_spinlock_unlock(&wq->lock, true);
592}
593
594/** @}
595 */
Note: See TracBrowser for help on using the repository browser.