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

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

Make futex able to time out.

  • Property mode set to 100644
File size: 17.2 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/** Interrupt the first thread sleeping in the wait queue.
195 *
196 * Note that the caller somehow needs to know that the thread to be interrupted
197 * is sleeping interruptibly.
198 *
199 * @param wq Pointer to wait queue.
200 *
201 */
202void waitq_unsleep(waitq_t *wq)
203{
204 irq_spinlock_lock(&wq->lock, true);
205
206 if (!list_empty(&wq->sleepers)) {
207 thread_t *thread = list_get_instance(list_first(&wq->sleepers),
208 thread_t, wq_link);
209
210 irq_spinlock_lock(&thread->lock, false);
211
212 assert(thread->sleep_interruptible);
213
214 if ((thread->timeout_pending) &&
215 (timeout_unregister(&thread->sleep_timeout)))
216 thread->timeout_pending = false;
217
218 list_remove(&thread->wq_link);
219 thread->saved_context = thread->sleep_interruption_context;
220 thread->sleep_queue = NULL;
221
222 irq_spinlock_unlock(&thread->lock, false);
223 thread_ready(thread);
224 }
225
226 irq_spinlock_unlock(&wq->lock, true);
227}
228
229#define PARAM_NON_BLOCKING(flags, usec) \
230 (((flags) & SYNCH_FLAGS_NON_BLOCKING) && ((usec) == 0))
231
232/** Sleep until either wakeup, timeout or interruption occurs
233 *
234 * This is a sleep implementation which allows itself to time out or to be
235 * interrupted from the sleep, restoring a failover context.
236 *
237 * Sleepers are organised in a FIFO fashion in a structure called wait queue.
238 *
239 * This function is really basic in that other functions as waitq_sleep()
240 * and all the *_timeout() functions use it.
241 *
242 * @param wq Pointer to wait queue.
243 * @param usec Timeout in microseconds.
244 * @param flags Specify mode of the sleep.
245 *
246 * @param[out] blocked On return, regardless of the return code,
247 * `*blocked` is set to `true` iff the thread went to
248 * sleep.
249 *
250 * The sleep can be interrupted only if the
251 * SYNCH_FLAGS_INTERRUPTIBLE bit is specified in flags.
252 *
253 * If usec is greater than zero, regardless of the value of the
254 * SYNCH_FLAGS_NON_BLOCKING bit in flags, the call will not return until either
255 * timeout, interruption or wakeup comes.
256 *
257 * If usec is zero and the SYNCH_FLAGS_NON_BLOCKING bit is not set in flags,
258 * the call will not return until wakeup or interruption comes.
259 *
260 * If usec is zero and the SYNCH_FLAGS_NON_BLOCKING bit is set in flags, the
261 * call will immediately return, reporting either success or failure.
262 *
263 * @return EAGAIN, meaning that the sleep failed because it was requested
264 * as SYNCH_FLAGS_NON_BLOCKING, but there was no pending wakeup.
265 * @return ETIMEOUT, meaning that the sleep timed out.
266 * @return EINTR, meaning that somebody interrupted the sleeping
267 * thread. Check the value of `*blocked` to see if the thread slept,
268 * or if a pending interrupt forced it to return immediately.
269 * @return EOK, meaning that none of the above conditions occured, and the
270 * thread was woken up successfuly by `waitq_wakeup()`. Check
271 * the value of `*blocked` to see if the thread slept or if
272 * the wakeup was already pending.
273 *
274 */
275errno_t waitq_sleep_timeout(waitq_t *wq, uint32_t usec, unsigned int flags, bool *blocked)
276{
277 assert((!PREEMPTION_DISABLED) || (PARAM_NON_BLOCKING(flags, usec)));
278
279 ipl_t ipl = waitq_sleep_prepare(wq);
280 bool nblocked;
281 errno_t rc = waitq_sleep_timeout_unsafe(wq, usec, flags, &nblocked);
282 waitq_sleep_finish(wq, nblocked, ipl);
283
284 if (blocked != NULL) {
285 *blocked = nblocked;
286 }
287 return rc;
288}
289
290/** Prepare to sleep in a waitq.
291 *
292 * This function will return holding the lock of the wait queue
293 * and interrupts disabled.
294 *
295 * @param wq Wait queue.
296 *
297 * @return Interrupt level as it existed on entry to this function.
298 *
299 */
300ipl_t waitq_sleep_prepare(waitq_t *wq)
301{
302 ipl_t ipl;
303
304restart:
305 ipl = interrupts_disable();
306
307 if (THREAD) { /* Needed during system initiailzation */
308 /*
309 * Busy waiting for a delayed timeout.
310 * This is an important fix for the race condition between
311 * a delayed timeout and a next call to waitq_sleep_timeout().
312 * Simply, the thread is not allowed to go to sleep if
313 * there are timeouts in progress.
314 *
315 */
316 irq_spinlock_lock(&THREAD->lock, false);
317
318 if (THREAD->timeout_pending) {
319 irq_spinlock_unlock(&THREAD->lock, false);
320 interrupts_restore(ipl);
321 goto restart;
322 }
323
324 irq_spinlock_unlock(&THREAD->lock, false);
325 }
326
327 irq_spinlock_lock(&wq->lock, false);
328 return ipl;
329}
330
331/** Finish waiting in a wait queue.
332 *
333 * This function restores interrupts to the state that existed prior
334 * to the call to waitq_sleep_prepare(). If necessary, the wait queue
335 * lock is released.
336 *
337 * @param wq Wait queue.
338 * @param blocked Out parameter of waitq_sleep_timeout_unsafe().
339 * @param ipl Interrupt level returned by waitq_sleep_prepare().
340 *
341 */
342void waitq_sleep_finish(waitq_t *wq, bool blocked, ipl_t ipl)
343{
344 if (blocked) {
345 /*
346 * Wait for a waitq_wakeup() or waitq_unsleep() to complete
347 * before returning from waitq_sleep() to the caller. Otherwise
348 * the caller might expect that the wait queue is no longer used
349 * and deallocate it (although the wakeup on a another cpu has
350 * not yet completed and is using the wait queue).
351 *
352 * Note that we have to do this for EOK and EINTR, but not
353 * necessarily for ETIMEOUT where the timeout handler stops
354 * using the waitq before waking us up. To be on the safe side,
355 * ensure the waitq is not in use anymore in this case as well.
356 */
357 waitq_complete_wakeup(wq);
358 } else {
359 irq_spinlock_unlock(&wq->lock, false);
360 }
361
362 interrupts_restore(ipl);
363}
364
365/** Internal implementation of waitq_sleep_timeout().
366 *
367 * This function implements logic of sleeping in a wait queue.
368 * This call must be preceded by a call to waitq_sleep_prepare()
369 * and followed by a call to waitq_sleep_finish().
370 *
371 * @param wq See waitq_sleep_timeout().
372 * @param usec See waitq_sleep_timeout().
373 * @param flags See waitq_sleep_timeout().
374 *
375 * @param[out] blocked See waitq_sleep_timeout().
376 *
377 * @return See waitq_sleep_timeout().
378 *
379 */
380errno_t waitq_sleep_timeout_unsafe(waitq_t *wq, uint32_t usec, unsigned int flags, bool *blocked)
381{
382 *blocked = false;
383
384 /* Checks whether to go to sleep at all */
385 if (wq->missed_wakeups) {
386 wq->missed_wakeups--;
387 return EOK;
388 } else {
389 if (PARAM_NON_BLOCKING(flags, usec)) {
390 /* Return immediately instead of going to sleep */
391 return EAGAIN;
392 }
393 }
394
395 /*
396 * Now we are firmly decided to go to sleep.
397 *
398 */
399 irq_spinlock_lock(&THREAD->lock, false);
400
401 THREAD->sleep_composable = (flags & SYNCH_FLAGS_FUTEX);
402
403 if (flags & SYNCH_FLAGS_INTERRUPTIBLE) {
404 /*
405 * If the thread was already interrupted,
406 * don't go to sleep at all.
407 */
408 if (THREAD->interrupted) {
409 irq_spinlock_unlock(&THREAD->lock, false);
410 return EINTR;
411 }
412
413 /*
414 * Set context that will be restored if the sleep
415 * of this thread is ever interrupted.
416 */
417 THREAD->sleep_interruptible = true;
418 if (!context_save(&THREAD->sleep_interruption_context)) {
419 /* Short emulation of scheduler() return code. */
420 THREAD->last_cycle = get_cycle();
421 irq_spinlock_unlock(&THREAD->lock, false);
422 return EINTR;
423 }
424 } else
425 THREAD->sleep_interruptible = false;
426
427 if (usec) {
428 /* We use the timeout variant. */
429 if (!context_save(&THREAD->sleep_timeout_context)) {
430 /* Short emulation of scheduler() return code. */
431 THREAD->last_cycle = get_cycle();
432 irq_spinlock_unlock(&THREAD->lock, false);
433 return ETIMEOUT;
434 }
435
436 THREAD->timeout_pending = true;
437 timeout_register(&THREAD->sleep_timeout, (uint64_t) usec,
438 waitq_sleep_timed_out, THREAD);
439 }
440
441 list_append(&THREAD->wq_link, &wq->sleepers);
442
443 /*
444 * Suspend execution.
445 *
446 */
447 THREAD->state = Sleeping;
448 THREAD->sleep_queue = wq;
449
450 /*
451 * Must be before entry to scheduler, because there are multiple
452 * return vectors.
453 */
454 *blocked = true;
455
456 irq_spinlock_unlock(&THREAD->lock, false);
457
458 /* wq->lock is released in scheduler_separated_stack() */
459 scheduler();
460
461 return EOK;
462}
463
464/** Wake up first thread sleeping in a wait queue
465 *
466 * Wake up first thread sleeping in a wait queue. This is the SMP- and IRQ-safe
467 * wrapper meant for general use.
468 *
469 * Besides its 'normal' wakeup operation, it attempts to unregister possible
470 * timeout.
471 *
472 * @param wq Pointer to wait queue.
473 * @param mode Wakeup mode.
474 *
475 */
476void waitq_wakeup(waitq_t *wq, wakeup_mode_t mode)
477{
478 irq_spinlock_lock(&wq->lock, true);
479 _waitq_wakeup_unsafe(wq, mode);
480 irq_spinlock_unlock(&wq->lock, true);
481}
482
483/** If there is a wakeup in progress actively waits for it to complete.
484 *
485 * The function returns once the concurrently running waitq_wakeup()
486 * exits. It returns immediately if there are no concurrent wakeups
487 * at the time.
488 *
489 * Interrupts must be disabled.
490 *
491 * Example usage:
492 * @code
493 * void callback(waitq *wq)
494 * {
495 * // Do something and notify wait_for_completion() that we're done.
496 * waitq_wakeup(wq);
497 * }
498 * void wait_for_completion(void)
499 * {
500 * waitq wg;
501 * waitq_initialize(&wq);
502 * // Run callback() in the background, pass it wq.
503 * do_asynchronously(callback, &wq);
504 * // Wait for callback() to complete its work.
505 * waitq_sleep(&wq);
506 * // callback() completed its work, but it may still be accessing
507 * // wq in waitq_wakeup(). Therefore it is not yet safe to return
508 * // from waitq_sleep() or it would clobber up our stack (where wq
509 * // is stored). waitq_sleep() ensures the wait queue is no longer
510 * // in use by invoking waitq_complete_wakeup() internally.
511 *
512 * // waitq_sleep() returned, it is safe to free wq.
513 * }
514 * @endcode
515 *
516 * @param wq Pointer to a wait queue.
517 */
518static void waitq_complete_wakeup(waitq_t *wq)
519{
520 assert(interrupts_disabled());
521
522 irq_spinlock_lock(&wq->lock, false);
523 irq_spinlock_unlock(&wq->lock, false);
524}
525
526
527/** Internal SMP- and IRQ-unsafe version of waitq_wakeup()
528 *
529 * This is the internal SMP- and IRQ-unsafe version of waitq_wakeup(). It
530 * assumes wq->lock is already locked and interrupts are already disabled.
531 *
532 * @param wq Pointer to wait queue.
533 * @param mode If mode is WAKEUP_FIRST, then the longest waiting
534 * thread, if any, is woken up. If mode is WAKEUP_ALL, then
535 * all waiting threads, if any, are woken up. If there are
536 * no waiting threads to be woken up, the missed wakeup is
537 * recorded in the wait queue.
538 *
539 */
540void _waitq_wakeup_unsafe(waitq_t *wq, wakeup_mode_t mode)
541{
542 size_t count = 0;
543
544 assert(interrupts_disabled());
545 assert(irq_spinlock_locked(&wq->lock));
546
547 if (wq->ignore_wakeups > 0) {
548 if (mode == WAKEUP_FIRST) {
549 wq->ignore_wakeups--;
550 return;
551 }
552 wq->ignore_wakeups = 0;
553 }
554
555loop:
556 if (list_empty(&wq->sleepers)) {
557 wq->missed_wakeups++;
558 if ((count) && (mode == WAKEUP_ALL))
559 wq->missed_wakeups--;
560
561 return;
562 }
563
564 count++;
565 thread_t *thread = list_get_instance(list_first(&wq->sleepers),
566 thread_t, wq_link);
567
568 /*
569 * Lock the thread prior to removing it from the wq.
570 * This is not necessary because of mutual exclusion
571 * (the link belongs to the wait queue), but because
572 * of synchronization with waitq_sleep_timed_out()
573 * and thread_interrupt_sleep().
574 *
575 * In order for these two functions to work, the following
576 * invariant must hold:
577 *
578 * thread->sleep_queue != NULL <=> thread sleeps in a wait queue
579 *
580 * For an observer who locks the thread, the invariant
581 * holds only when the lock is held prior to removing
582 * it from the wait queue.
583 *
584 */
585 irq_spinlock_lock(&thread->lock, false);
586 list_remove(&thread->wq_link);
587
588 if ((thread->timeout_pending) &&
589 (timeout_unregister(&thread->sleep_timeout)))
590 thread->timeout_pending = false;
591
592 thread->sleep_queue = NULL;
593 irq_spinlock_unlock(&thread->lock, false);
594
595 thread_ready(thread);
596
597 if (mode == WAKEUP_ALL)
598 goto loop;
599}
600
601/** Get the missed wakeups count.
602 *
603 * @param wq Pointer to wait queue.
604 * @return The wait queue's missed_wakeups count.
605 */
606int waitq_count_get(waitq_t *wq)
607{
608 int cnt;
609
610 irq_spinlock_lock(&wq->lock, true);
611 cnt = wq->missed_wakeups;
612 irq_spinlock_unlock(&wq->lock, true);
613
614 return cnt;
615}
616
617/** Set the missed wakeups count.
618 *
619 * @param wq Pointer to wait queue.
620 * @param val New value of the missed_wakeups count.
621 */
622void waitq_count_set(waitq_t *wq, int val)
623{
624 irq_spinlock_lock(&wq->lock, true);
625 wq->missed_wakeups = val;
626 irq_spinlock_unlock(&wq->lock, true);
627}
628
629/** @}
630 */
Note: See TracBrowser for help on using the repository browser.