source: mainline/uspace/lib/c/generic/thread/fibril.c@ 508b0df1

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

Remove uspace <atomic.h>, use <stdatomic.h> instead

  • Property mode set to 100644
File size: 21.5 KB
Line 
1/*
2 * Copyright (c) 2006 Ondrej Palkovsky
3 * Copyright (c) 2007 Jakub Jermar
4 * Copyright (c) 2018 CZ.NIC, z.s.p.o.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/** @addtogroup libc
32 * @{
33 */
34/** @file
35 */
36
37#include <adt/list.h>
38#include <fibril.h>
39#include <stack.h>
40#include <tls.h>
41#include <stdlib.h>
42#include <as.h>
43#include <context.h>
44#include <assert.h>
45
46#include <mem.h>
47#include <str.h>
48#include <ipc/ipc.h>
49#include <libarch/faddr.h>
50
51#include "../private/thread.h"
52#include "../private/futex.h"
53#include "../private/fibril.h"
54#include "../private/libc.h"
55
56#define DPRINTF(...) ((void)0)
57#undef READY_DEBUG
58
59/** Member of timeout_list. */
60typedef struct {
61 link_t link;
62 struct timespec expires;
63 fibril_event_t *event;
64} _timeout_t;
65
66typedef struct {
67 errno_t rc;
68 link_t link;
69 ipc_call_t *call;
70 fibril_event_t event;
71} _ipc_waiter_t;
72
73typedef struct {
74 errno_t rc;
75 link_t link;
76 ipc_call_t call;
77} _ipc_buffer_t;
78
79typedef enum {
80 SWITCH_FROM_DEAD,
81 SWITCH_FROM_HELPER,
82 SWITCH_FROM_YIELD,
83 SWITCH_FROM_BLOCKED,
84} _switch_type_t;
85
86static bool multithreaded = false;
87
88/* This futex serializes access to global data. */
89static futex_t fibril_futex = FUTEX_INITIALIZER;
90static futex_t ready_semaphore;
91static long ready_st_count;
92
93static LIST_INITIALIZE(ready_list);
94static LIST_INITIALIZE(fibril_list);
95static LIST_INITIALIZE(timeout_list);
96
97static futex_t ipc_lists_futex = FUTEX_INITIALIZER;
98static LIST_INITIALIZE(ipc_waiter_list);
99static LIST_INITIALIZE(ipc_buffer_list);
100static LIST_INITIALIZE(ipc_buffer_free_list);
101
102/* Only used as unique markers for triggered events. */
103static fibril_t _fibril_event_triggered;
104static fibril_t _fibril_event_timed_out;
105#define _EVENT_INITIAL (NULL)
106#define _EVENT_TRIGGERED (&_fibril_event_triggered)
107#define _EVENT_TIMED_OUT (&_fibril_event_timed_out)
108
109static inline void _ready_debug_check(void)
110{
111#ifdef READY_DEBUG
112 assert(!multithreaded);
113 long count = (long) list_count(&ready_list) +
114 (long) list_count(&ipc_buffer_free_list);
115 assert(ready_st_count == count);
116#endif
117}
118
119static inline void _ready_up(void)
120{
121 if (multithreaded) {
122 futex_up(&ready_semaphore);
123 } else {
124 ready_st_count++;
125 _ready_debug_check();
126 }
127}
128
129static inline errno_t _ready_down(const struct timespec *expires)
130{
131 if (multithreaded)
132 return futex_down_timeout(&ready_semaphore, expires);
133
134 _ready_debug_check();
135 ready_st_count--;
136 return EOK;
137}
138
139static atomic_int threads_in_ipc_wait;
140
141/** Function that spans the whole life-cycle of a fibril.
142 *
143 * Each fibril begins execution in this function. Then the function implementing
144 * the fibril logic is called. After its return, the return value is saved.
145 * The fibril then switches to another fibril, which cleans up after it.
146 *
147 */
148static void _fibril_main(void)
149{
150 /* fibril_futex is locked when a fibril is started. */
151 futex_unlock(&fibril_futex);
152
153 fibril_t *fibril = fibril_self();
154
155 /* Call the implementing function. */
156 fibril_exit(fibril->func(fibril->arg));
157
158 /* Not reached */
159}
160
161/** Allocate a fibril structure and TCB, but don't do anything else with it. */
162fibril_t *fibril_alloc(void)
163{
164 tcb_t *tcb = tls_make(__progsymbols.elfstart);
165 if (!tcb)
166 return NULL;
167
168 fibril_t *fibril = calloc(1, sizeof(fibril_t));
169 if (!fibril) {
170 tls_free(tcb);
171 return NULL;
172 }
173
174 tcb->fibril_data = fibril;
175 fibril->tcb = tcb;
176 fibril->is_freeable = true;
177
178 fibril_setup(fibril);
179 return fibril;
180}
181
182/**
183 * Put the fibril into fibril_list.
184 */
185void fibril_setup(fibril_t *f)
186{
187 futex_lock(&fibril_futex);
188 list_append(&f->all_link, &fibril_list);
189 futex_unlock(&fibril_futex);
190}
191
192void fibril_teardown(fibril_t *fibril)
193{
194 futex_lock(&fibril_futex);
195 list_remove(&fibril->all_link);
196 futex_unlock(&fibril_futex);
197
198 if (fibril->is_freeable) {
199 tls_free(fibril->tcb);
200 free(fibril);
201 }
202}
203
204/**
205 * Event notification with a given reason.
206 *
207 * @param reason Reason of the notification.
208 * Can be either _EVENT_TRIGGERED or _EVENT_TIMED_OUT.
209 */
210static fibril_t *_fibril_trigger_internal(fibril_event_t *event, fibril_t *reason)
211{
212 assert(reason != _EVENT_INITIAL);
213 assert(reason == _EVENT_TIMED_OUT || reason == _EVENT_TRIGGERED);
214
215 futex_assert_is_locked(&fibril_futex);
216
217 if (event->fibril == _EVENT_INITIAL) {
218 event->fibril = reason;
219 return NULL;
220 }
221
222 if (event->fibril == _EVENT_TIMED_OUT) {
223 assert(reason == _EVENT_TRIGGERED);
224 event->fibril = reason;
225 return NULL;
226 }
227
228 if (event->fibril == _EVENT_TRIGGERED) {
229 /* Already triggered. Nothing to do. */
230 return NULL;
231 }
232
233 fibril_t *f = event->fibril;
234 event->fibril = reason;
235
236 assert(f->sleep_event == event);
237 return f;
238}
239
240static errno_t _ipc_wait(ipc_call_t *call, const struct timespec *expires)
241{
242 if (!expires)
243 return ipc_wait(call, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NONE);
244
245 if (expires->tv_sec == 0)
246 return ipc_wait(call, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NON_BLOCKING);
247
248 struct timespec now;
249 getuptime(&now);
250
251 if (ts_gteq(&now, expires))
252 return ipc_wait(call, SYNCH_NO_TIMEOUT, SYNCH_FLAGS_NON_BLOCKING);
253
254 return ipc_wait(call, NSEC2USEC(ts_sub_diff(expires, &now)),
255 SYNCH_FLAGS_NONE);
256}
257
258/*
259 * Waits until a ready fibril is added to the list, or an IPC message arrives.
260 * Returns NULL on timeout and may also return NULL if returning from IPC
261 * wait after new ready fibrils are added.
262 */
263static fibril_t *_ready_list_pop(const struct timespec *expires, bool locked)
264{
265 if (locked) {
266 futex_assert_is_locked(&fibril_futex);
267 assert(expires);
268 /* Must be nonblocking. */
269 assert(expires->tv_sec == 0);
270 } else {
271 futex_assert_is_not_locked(&fibril_futex);
272 }
273
274 errno_t rc = _ready_down(expires);
275 if (rc != EOK)
276 return NULL;
277
278 /*
279 * Once we acquire a token from ready_semaphore, there are two options.
280 * Either there is a ready fibril in the list, or it's our turn to
281 * call `ipc_wait_cycle()`. There is one extra token on the semaphore
282 * for each entry of the call buffer.
283 */
284
285
286 if (!locked)
287 futex_lock(&fibril_futex);
288 fibril_t *f = list_pop(&ready_list, fibril_t, link);
289 if (!f)
290 atomic_fetch_add_explicit(&threads_in_ipc_wait, 1,
291 memory_order_relaxed);
292 if (!locked)
293 futex_unlock(&fibril_futex);
294
295 if (f)
296 return f;
297
298 if (!multithreaded)
299 assert(list_empty(&ipc_buffer_list));
300
301 /* No fibril is ready, IPC wait it is. */
302 ipc_call_t call = { 0 };
303 rc = _ipc_wait(&call, expires);
304
305 atomic_fetch_sub_explicit(&threads_in_ipc_wait, 1,
306 memory_order_relaxed);
307
308 if (rc != EOK && rc != ENOENT) {
309 /* Return token. */
310 _ready_up();
311 return NULL;
312 }
313
314 /*
315 * We might get ENOENT due to a poke.
316 * In that case, we propagate the null call out of fibril_ipc_wait(),
317 * because poke must result in that call returning.
318 */
319
320 /*
321 * If a fibril is already waiting for IPC, we wake up the fibril,
322 * and return the token to ready_semaphore.
323 * If there is no fibril waiting, we pop a buffer bucket and
324 * put our call there. The token then returns when the bucket is
325 * returned.
326 */
327
328 if (!locked)
329 futex_lock(&fibril_futex);
330
331 futex_lock(&ipc_lists_futex);
332
333
334 _ipc_waiter_t *w = list_pop(&ipc_waiter_list, _ipc_waiter_t, link);
335 if (w) {
336 *w->call = call;
337 w->rc = rc;
338 /* We switch to the woken up fibril immediately if possible. */
339 f = _fibril_trigger_internal(&w->event, _EVENT_TRIGGERED);
340
341 /* Return token. */
342 _ready_up();
343 } else {
344 _ipc_buffer_t *buf = list_pop(&ipc_buffer_free_list, _ipc_buffer_t, link);
345 assert(buf);
346 *buf = (_ipc_buffer_t) { .call = call, .rc = rc };
347 list_append(&buf->link, &ipc_buffer_list);
348 }
349
350 futex_unlock(&ipc_lists_futex);
351
352 if (!locked)
353 futex_unlock(&fibril_futex);
354
355 return f;
356}
357
358static fibril_t *_ready_list_pop_nonblocking(bool locked)
359{
360 struct timespec tv = { .tv_sec = 0, .tv_nsec = 0 };
361 return _ready_list_pop(&tv, locked);
362}
363
364static void _ready_list_push(fibril_t *f)
365{
366 if (!f)
367 return;
368
369 futex_assert_is_locked(&fibril_futex);
370
371 /* Enqueue in ready_list. */
372 list_append(&f->link, &ready_list);
373 _ready_up();
374
375 if (atomic_load_explicit(&threads_in_ipc_wait, memory_order_relaxed)) {
376 DPRINTF("Poking.\n");
377 /* Wakeup one thread sleeping in SYS_IPC_WAIT. */
378 ipc_poke();
379 }
380}
381
382/* Blocks the current fibril until an IPC call arrives. */
383static errno_t _wait_ipc(ipc_call_t *call, const struct timespec *expires)
384{
385 futex_assert_is_not_locked(&fibril_futex);
386
387 futex_lock(&ipc_lists_futex);
388 _ipc_buffer_t *buf = list_pop(&ipc_buffer_list, _ipc_buffer_t, link);
389 if (buf) {
390 *call = buf->call;
391 errno_t rc = buf->rc;
392
393 /* Return to freelist. */
394 list_append(&buf->link, &ipc_buffer_free_list);
395 /* Return IPC wait token. */
396 _ready_up();
397
398 futex_unlock(&ipc_lists_futex);
399 return rc;
400 }
401
402 _ipc_waiter_t w = { .call = call };
403 list_append(&w.link, &ipc_waiter_list);
404 futex_unlock(&ipc_lists_futex);
405
406 errno_t rc = fibril_wait_timeout(&w.event, expires);
407 if (rc == EOK)
408 return w.rc;
409
410 futex_lock(&ipc_lists_futex);
411 if (link_in_use(&w.link))
412 list_remove(&w.link);
413 else
414 rc = w.rc;
415 futex_unlock(&ipc_lists_futex);
416 return rc;
417}
418
419/** Fire all timeouts that expired. */
420static struct timespec *_handle_expired_timeouts(struct timespec *next_timeout)
421{
422 struct timespec ts;
423 getuptime(&ts);
424
425 futex_lock(&fibril_futex);
426
427 while (!list_empty(&timeout_list)) {
428 link_t *cur = list_first(&timeout_list);
429 _timeout_t *to = list_get_instance(cur, _timeout_t, link);
430
431 if (ts_gt(&to->expires, &ts)) {
432 *next_timeout = to->expires;
433 futex_unlock(&fibril_futex);
434 return next_timeout;
435 }
436
437 list_remove(&to->link);
438
439 _ready_list_push(_fibril_trigger_internal(
440 to->event, _EVENT_TIMED_OUT));
441 }
442
443 futex_unlock(&fibril_futex);
444 return NULL;
445}
446
447/**
448 * Clean up after a dead fibril from which we restored context, if any.
449 * Called after a switch is made and fibril_futex is unlocked.
450 */
451static void _fibril_cleanup_dead(void)
452{
453 fibril_t *srcf = fibril_self();
454 if (!srcf->clean_after_me)
455 return;
456
457 void *stack = srcf->clean_after_me->stack;
458 assert(stack);
459 as_area_destroy(stack);
460 fibril_teardown(srcf->clean_after_me);
461 srcf->clean_after_me = NULL;
462}
463
464/** Switch to a fibril. */
465static void _fibril_switch_to(_switch_type_t type, fibril_t *dstf, bool locked)
466{
467 assert(fibril_self()->rmutex_locks == 0);
468
469 if (!locked)
470 futex_lock(&fibril_futex);
471 else
472 futex_assert_is_locked(&fibril_futex);
473
474 fibril_t *srcf = fibril_self();
475 assert(srcf);
476 assert(dstf);
477
478 switch (type) {
479 case SWITCH_FROM_YIELD:
480 _ready_list_push(srcf);
481 break;
482 case SWITCH_FROM_DEAD:
483 dstf->clean_after_me = srcf;
484 break;
485 case SWITCH_FROM_HELPER:
486 case SWITCH_FROM_BLOCKED:
487 break;
488 }
489
490 dstf->thread_ctx = srcf->thread_ctx;
491 srcf->thread_ctx = NULL;
492
493 /* Just some bookkeeping to allow better debugging of futex locks. */
494 futex_give_to(&fibril_futex, dstf);
495
496 /* Swap to the next fibril. */
497 context_swap(&srcf->ctx, &dstf->ctx);
498
499 assert(srcf == fibril_self());
500 assert(srcf->thread_ctx);
501
502 if (!locked) {
503 /* Must be after context_swap()! */
504 futex_unlock(&fibril_futex);
505 _fibril_cleanup_dead();
506 }
507}
508
509/**
510 * Main function for a helper fibril.
511 * The helper fibril executes on threads in the lightweight fibril pool when
512 * there is no fibril ready to run. Its only purpose is to block until
513 * another fibril is ready, or a timeout expires, or an IPC message arrives.
514 *
515 * There is at most one helper fibril per thread.
516 *
517 */
518static errno_t _helper_fibril_fn(void *arg)
519{
520 /* Set itself as the thread's own context. */
521 fibril_self()->thread_ctx = fibril_self();
522
523 (void) arg;
524
525 struct timespec next_timeout;
526 while (true) {
527 struct timespec *to = _handle_expired_timeouts(&next_timeout);
528 fibril_t *f = _ready_list_pop(to, false);
529 if (f) {
530 _fibril_switch_to(SWITCH_FROM_HELPER, f, false);
531 }
532 }
533
534 return EOK;
535}
536
537/** Create a new fibril.
538 *
539 * @param func Implementing function of the new fibril.
540 * @param arg Argument to pass to func.
541 * @param stksz Stack size in bytes.
542 *
543 * @return 0 on failure or TLS of the new fibril.
544 *
545 */
546fid_t fibril_create_generic(errno_t (*func)(void *), void *arg, size_t stksz)
547{
548 fibril_t *fibril;
549
550 fibril = fibril_alloc();
551 if (fibril == NULL)
552 return 0;
553
554 fibril->stack_size = (stksz == FIBRIL_DFLT_STK_SIZE) ?
555 stack_size_get() : stksz;
556 fibril->stack = as_area_create(AS_AREA_ANY, fibril->stack_size,
557 AS_AREA_READ | AS_AREA_WRITE | AS_AREA_CACHEABLE | AS_AREA_GUARD |
558 AS_AREA_LATE_RESERVE, AS_AREA_UNPAGED);
559 if (fibril->stack == AS_MAP_FAILED) {
560 fibril_teardown(fibril);
561 return 0;
562 }
563
564 fibril->func = func;
565 fibril->arg = arg;
566
567 context_create_t sctx = {
568 .fn = _fibril_main,
569 .stack_base = fibril->stack,
570 .stack_size = fibril->stack_size,
571 .tls = fibril->tcb,
572 };
573
574 context_create(&fibril->ctx, &sctx);
575 return (fid_t) fibril;
576}
577
578/** Delete a fibril that has never run.
579 *
580 * Free resources of a fibril that has been created with fibril_create()
581 * but never started using fibril_start().
582 *
583 * @param fid Pointer to the fibril structure of the fibril to be
584 * added.
585 */
586void fibril_destroy(fid_t fid)
587{
588 fibril_t *fibril = (fibril_t *) fid;
589
590 assert(!fibril->is_running);
591 assert(fibril->stack);
592 as_area_destroy(fibril->stack);
593 fibril_teardown(fibril);
594}
595
596static void _insert_timeout(_timeout_t *timeout)
597{
598 futex_assert_is_locked(&fibril_futex);
599 assert(timeout);
600
601 link_t *tmp = timeout_list.head.next;
602 while (tmp != &timeout_list.head) {
603 _timeout_t *cur = list_get_instance(tmp, _timeout_t, link);
604
605 if (ts_gteq(&cur->expires, &timeout->expires))
606 break;
607
608 tmp = tmp->next;
609 }
610
611 list_insert_before(&timeout->link, tmp);
612}
613
614/**
615 * Same as `fibril_wait_for()`, except with a timeout.
616 *
617 * It is guaranteed that timing out cannot cause another thread's
618 * `fibril_notify()` to be lost. I.e. the function returns success if and
619 * only if `fibril_notify()` was called after the last call to
620 * wait/wait_timeout returned, and before the call timed out.
621 *
622 * @return ETIMEOUT if timed out. EOK otherwise.
623 */
624errno_t fibril_wait_timeout(fibril_event_t *event,
625 const struct timespec *expires)
626{
627 assert(fibril_self()->rmutex_locks == 0);
628
629 DPRINTF("### Fibril %p sleeping on event %p.\n", fibril_self(), event);
630
631 if (!fibril_self()->thread_ctx) {
632 fibril_self()->thread_ctx =
633 fibril_create_generic(_helper_fibril_fn, NULL, PAGE_SIZE);
634 if (!fibril_self()->thread_ctx)
635 return ENOMEM;
636 }
637
638 futex_lock(&fibril_futex);
639
640 if (event->fibril == _EVENT_TRIGGERED) {
641 DPRINTF("### Already triggered. Returning. \n");
642 event->fibril = _EVENT_INITIAL;
643 futex_unlock(&fibril_futex);
644 return EOK;
645 }
646
647 assert(event->fibril == _EVENT_INITIAL);
648
649 fibril_t *srcf = fibril_self();
650 fibril_t *dstf = NULL;
651
652 /*
653 * We cannot block here waiting for another fibril becoming
654 * ready, since that would require unlocking the fibril_futex,
655 * and that in turn would allow another thread to restore
656 * the source fibril before this thread finished switching.
657 *
658 * Instead, we switch to an internal "helper" fibril whose only
659 * job is to wait for an event, freeing the source fibril for
660 * wakeups. There is always one for each running thread.
661 */
662
663 dstf = _ready_list_pop_nonblocking(true);
664 if (!dstf) {
665 // XXX: It is possible for the _ready_list_pop_nonblocking() to
666 // check for IPC, find a pending message, and trigger the
667 // event on which we are currently trying to sleep.
668 if (event->fibril == _EVENT_TRIGGERED) {
669 event->fibril = _EVENT_INITIAL;
670 futex_unlock(&fibril_futex);
671 return EOK;
672 }
673
674 dstf = srcf->thread_ctx;
675 assert(dstf);
676 }
677
678 _timeout_t timeout = { 0 };
679 if (expires) {
680 timeout.expires = *expires;
681 timeout.event = event;
682 _insert_timeout(&timeout);
683 }
684
685 assert(srcf);
686
687 event->fibril = srcf;
688 srcf->sleep_event = event;
689
690 assert(event->fibril != _EVENT_INITIAL);
691
692 _fibril_switch_to(SWITCH_FROM_BLOCKED, dstf, true);
693
694 assert(event->fibril != srcf);
695 assert(event->fibril != _EVENT_INITIAL);
696 assert(event->fibril == _EVENT_TIMED_OUT || event->fibril == _EVENT_TRIGGERED);
697
698 list_remove(&timeout.link);
699 errno_t rc = (event->fibril == _EVENT_TIMED_OUT) ? ETIMEOUT : EOK;
700 event->fibril = _EVENT_INITIAL;
701
702 futex_unlock(&fibril_futex);
703 _fibril_cleanup_dead();
704 return rc;
705}
706
707void fibril_wait_for(fibril_event_t *event)
708{
709 assert(fibril_self()->rmutex_locks == 0);
710
711 (void) fibril_wait_timeout(event, NULL);
712}
713
714/**
715 * Wake up the fibril waiting for the given event.
716 * Up to one wakeup is remembered if the fibril is not currently waiting.
717 *
718 * This function is safe for use under restricted mutex lock.
719 */
720void fibril_notify(fibril_event_t *event)
721{
722 futex_lock(&fibril_futex);
723 _ready_list_push(_fibril_trigger_internal(event, _EVENT_TRIGGERED));
724 futex_unlock(&fibril_futex);
725}
726
727/** Start a fibril that has not been running yet. */
728void fibril_start(fibril_t *fibril)
729{
730 futex_lock(&fibril_futex);
731 assert(!fibril->is_running);
732 fibril->is_running = true;
733
734 if (!link_in_use(&fibril->all_link))
735 list_append(&fibril->all_link, &fibril_list);
736
737 _ready_list_push(fibril);
738
739 futex_unlock(&fibril_futex);
740}
741
742/** Start a fibril that has not been running yet. (obsolete) */
743void fibril_add_ready(fibril_t *fibril)
744{
745 fibril_start(fibril);
746}
747
748/** @return the currently running fibril. */
749fibril_t *fibril_self(void)
750{
751 assert(__tcb_is_set());
752 tcb_t *tcb = __tcb_get();
753 assert(tcb->fibril_data);
754 return tcb->fibril_data;
755}
756
757/**
758 * Obsolete, use fibril_self().
759 *
760 * @return ID of the currently running fibril.
761 */
762fid_t fibril_get_id(void)
763{
764 return (fid_t) fibril_self();
765}
766
767/**
768 * Switch to another fibril, if one is ready to run.
769 * Has no effect on a heavy fibril.
770 */
771void fibril_yield(void)
772{
773 if (fibril_self()->rmutex_locks > 0)
774 return;
775
776 fibril_t *f = _ready_list_pop_nonblocking(false);
777 if (f)
778 _fibril_switch_to(SWITCH_FROM_YIELD, f, false);
779}
780
781static void _runner_fn(void *arg)
782{
783 _helper_fibril_fn(arg);
784}
785
786/**
787 * Spawn a given number of runners (i.e. OS threads) immediately, and
788 * unconditionally. This is meant to be used for tests and debugging.
789 * Regular programs should just use `fibril_enable_multithreaded()`.
790 *
791 * @param n Number of runners to spawn.
792 * @return Number of runners successfully spawned.
793 */
794int fibril_test_spawn_runners(int n)
795{
796 assert(fibril_self()->rmutex_locks == 0);
797
798 if (!multithreaded) {
799 _ready_debug_check();
800 futex_initialize(&ready_semaphore, ready_st_count);
801 multithreaded = true;
802 }
803
804 errno_t rc;
805
806 for (int i = 0; i < n; i++) {
807 thread_id_t tid;
808 rc = thread_create(_runner_fn, NULL, "fibril runner", &tid);
809 if (rc != EOK)
810 return i;
811 thread_detach(tid);
812 }
813
814 return n;
815}
816
817/**
818 * Opt-in to have more than one runner thread.
819 *
820 * Currently, a task only ever runs in one thread because multithreading
821 * might break some existing code.
822 *
823 * Eventually, the number of runner threads for a given task should become
824 * configurable in the environment and this function becomes no-op.
825 */
826void fibril_enable_multithreaded(void)
827{
828 // TODO: Implement better.
829 // For now, 4 total runners is a sensible default.
830 if (!multithreaded) {
831 fibril_test_spawn_runners(3);
832 }
833}
834
835/**
836 * Detach a fibril.
837 */
838void fibril_detach(fid_t f)
839{
840 // TODO: Currently all fibrils are detached by default, but they
841 // won't always be. Code that explicitly spawns fibrils with
842 // limited lifetime should call this function.
843}
844
845/**
846 * Exit a fibril. Never returns.
847 *
848 * @param retval Value to return from fibril_join() called on this fibril.
849 */
850_Noreturn void fibril_exit(long retval)
851{
852 // TODO: implement fibril_join() and remember retval
853 (void) retval;
854
855 fibril_t *f = _ready_list_pop_nonblocking(false);
856 if (!f)
857 f = fibril_self()->thread_ctx;
858
859 _fibril_switch_to(SWITCH_FROM_DEAD, f, false);
860 __builtin_unreachable();
861}
862
863void __fibrils_init(void)
864{
865 /*
866 * We allow a fixed, small amount of parallelism for IPC reads, but
867 * since IPC is currently serialized in kernel, there's not much
868 * we can get from more threads reading messages.
869 */
870
871#define IPC_BUFFER_COUNT 1024
872 static _ipc_buffer_t buffers[IPC_BUFFER_COUNT];
873
874 for (int i = 0; i < IPC_BUFFER_COUNT; i++) {
875 list_append(&buffers[i].link, &ipc_buffer_free_list);
876 _ready_up();
877 }
878}
879
880void fibril_usleep(usec_t timeout)
881{
882 struct timespec expires;
883 getuptime(&expires);
884 ts_add_diff(&expires, USEC2NSEC(timeout));
885
886 fibril_event_t event = FIBRIL_EVENT_INIT;
887 fibril_wait_timeout(&event, &expires);
888}
889
890void fibril_sleep(sec_t sec)
891{
892 struct timespec expires;
893 getuptime(&expires);
894 expires.tv_sec += sec;
895
896 fibril_event_t event = FIBRIL_EVENT_INIT;
897 fibril_wait_timeout(&event, &expires);
898}
899
900void fibril_ipc_poke(void)
901{
902 DPRINTF("Poking.\n");
903 /* Wakeup one thread sleeping in SYS_IPC_WAIT. */
904 ipc_poke();
905}
906
907errno_t fibril_ipc_wait(ipc_call_t *call, const struct timespec *expires)
908{
909 return _wait_ipc(call, expires);
910}
911
912/** @}
913 */
Note: See TracBrowser for help on using the repository browser.