1 /* Copyright (c) 2011-2014 The Regents of the University of California
2 * Barret Rhoden <brho@cs.berkeley.edu>
3 * See LICENSE for details. */
5 #include <ros/arch/membar.h>
6 #include <parlib/arch/atomic.h>
7 #include <parlib/parlib.h>
8 #include <parlib/vcore.h>
9 #include <parlib/uthread.h>
10 #include <parlib/event.h>
12 #include <parlib/assert.h>
13 #include <parlib/stdio.h>
14 #include <parlib/arch/trap.h>
15 #include <parlib/ros_debug.h>
17 __thread struct uthread *current_uthread = 0;
18 /* ev_q for all preempt messages (handled here to keep 2LSs from worrying
19 * extensively about the details. Will call out when necessary. */
20 static struct event_queue *preempt_ev_q;
23 #define UTH_TLSDESC_NOTLS (void*)(-1)
24 static inline bool __uthread_has_tls(struct uthread *uthread);
25 static int __uthread_allocate_tls(struct uthread *uthread);
26 static int __uthread_reinit_tls(struct uthread *uthread);
27 static void __uthread_free_tls(struct uthread *uthread);
28 static void __run_current_uthread_raw(void);
30 static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
32 static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
34 static void __ros_uth_syscall_blockon(struct syscall *sysc);
36 /* Helper, initializes a fresh uthread to be thread0. */
37 static void uthread_init_thread0(struct uthread *uthread)
40 /* Save a pointer to thread0's tls region (the glibc one) into its tcb */
41 uthread->tls_desc = get_tls_desc();
42 /* Save a pointer to the uthread in its own TLS */
43 current_uthread = uthread;
44 /* Thread is currently running (it is 'us') */
45 uthread->state = UT_RUNNING;
46 /* Thread is detached */
47 atomic_set(&uthread->join_ctl.state, UTH_JOIN_DETACHED);
48 /* Reset the signal state */
49 uthread->sigstate.mask = 0;
50 __sigemptyset(&uthread->sigstate.pending);
51 uthread->sigstate.data = NULL;
52 /* utf/as doesn't represent the state of the uthread (we are running) */
53 uthread->flags &= ~(UTHREAD_SAVED | UTHREAD_FPSAVED);
54 /* need to track thread0 for TLS deallocation */
55 uthread->flags |= UTHREAD_IS_THREAD0;
56 uthread->notif_disabled_depth = 0;
57 /* setting the uthread's TLS var. this is idempotent for SCPs (us) */
61 /* Helper, makes VC ctx tracks uthread as its current_uthread in its TLS.
63 * Whether or not uthreads have TLS, thread0 has TLS, given to it by glibc.
64 * This TLS will get set whenever we use thread0, regardless of whether or not
65 * we use TLS for uthreads in general. glibc cares about this TLS and will use
66 * it at exit. We can't simply use that TLS for VC0 either, since we don't know
67 * where thread0 will be running when the program ends. */
68 static void uthread_track_thread0(struct uthread *uthread)
70 set_tls_desc(get_vcpd_tls_desc(0));
71 begin_safe_access_tls_vars();
72 current_uthread = uthread;
73 __vcore_context = TRUE;
74 end_safe_access_tls_vars();
75 set_tls_desc(uthread->tls_desc);
78 /* The real 2LS calls this to transition us into mcp mode. When it
79 * returns, you're in _M mode, still running thread0, on vcore0 */
80 void uthread_mcp_init()
82 /* Prevent this from happening more than once. */
83 parlib_init_once_racy(return);
85 /* Doing this after the init_once check, since we don't want to let the
86 * process/2LS change their mind about being an MCP or not once they have
89 * The reason is that once you set "MCP please" on, you could get
90 * interrupted into VC ctx, say for a syscall completion, and then make
91 * decisions based on the fact that you're an MCP (e.g., unblocking a
92 * uthread, asking for vcores, etc), even though you are not an MCP.
93 * Arguably, these things could happen for signals too, but all of this is
94 * less likely than if we have multiple threads.
96 * Also, we could just abort here, since they shouldn't be calling
97 * mcp_init() if they don't want to be an MCP. */
98 if (!parlib_wants_to_be_mcp)
101 /* Receive preemption events. Note that this merely tells the kernel how to
102 * send the messages, and does not necessarily provide storage space for the
103 * messages. What we're doing is saying that all PREEMPT and CHECK_MSGS
104 * events should be spammed to vcores that are running, preferring whatever
105 * the kernel thinks is appropriate. And IPI them.
107 * It is critical that these are either SPAM_PUB or INDIR|SPAM_INDIR, so
108 * that yielding vcores do not miss the preemption messages. */
109 register_ev_handler(EV_VCORE_PREEMPT, handle_vc_preempt, 0);
110 register_ev_handler(EV_CHECK_MSGS, handle_vc_indir, 0);
111 preempt_ev_q = get_eventq_slim(); /* small ev_q, mostly a vehicle for flags */
112 preempt_ev_q->ev_flags = EVENT_IPI | EVENT_SPAM_PUBLIC | EVENT_VCORE_APPRO |
113 EVENT_VCORE_MUST_RUN | EVENT_WAKEUP;
114 /* Tell the kernel to use the ev_q (it's settings) for the two types. Note
115 * that we still have two separate handlers. We just want the events
116 * delivered in the same way. If we ever want to have a big_event_q with
117 * INDIRs, we could consider using separate ones. */
118 register_kevent_q(preempt_ev_q, EV_VCORE_PREEMPT);
119 register_kevent_q(preempt_ev_q, EV_CHECK_MSGS);
120 printd("[user] registered %08p (flags %08p) for preempt messages\n",
121 preempt_ev_q, preempt_ev_q->ev_flags);
122 /* Get ourselves into _M mode. Could consider doing this elsewhere... */
126 /* Helper: tells the kernel our SCP is capable of going into vcore context on
127 * vcore 0. Pairs with k/s/process.c scp_is_vcctx_ready(). */
128 static void scp_vcctx_ready(void)
130 struct preempt_data *vcpd = vcpd_of(0);
132 /* the CAS is a bit overkill; keeping it around in case people use this
133 * code in other situations. */
135 old_flags = atomic_read(&vcpd->flags);
136 /* Spin if the kernel is mucking with the flags */
137 while (old_flags & VC_K_LOCK)
138 old_flags = atomic_read(&vcpd->flags);
139 } while (!atomic_cas(&vcpd->flags, old_flags,
140 old_flags & ~VC_SCP_NOVCCTX));
143 /* For both of these, VC ctx uses the usual TLS errno/errstr. Uthreads use
144 * their own storage. Since we're called after manage_thread0, we should always
145 * have current_uthread if we are not in vc ctx. */
146 static int *__ros_errno_loc(void)
148 if (in_vcore_context())
149 return __errno_location_tls();
151 return ¤t_uthread->err_no;
154 static char *__ros_errstr_loc(void)
156 if (in_vcore_context())
157 return __errstr_location_tls();
159 return current_uthread->err_str;
162 static void __attribute__((constructor)) uthread_lib_init(void)
164 /* Surprise! Parlib's ctors also run in shared objects. We can't have
165 * multiple versions of parlib (with multiple data structures). */
166 if (__in_fake_parlib())
168 /* Need to make sure the vcore_lib_init() ctor runs first */
170 /* Instead of relying on ctors for the specific 2LS, we make sure they are
171 * called next. They will call uthread_2ls_init().
173 * The potential issue here is that C++ ctors might make use of the GCC/C++
174 * threading callbacks, which require the full 2LS. There's no linkage
175 * dependency between C++ and the specific 2LS, so there's no way to be
176 * sure the 2LS actually turned on before we started calling into it.
178 * Hopefully, the uthread ctor was called in time, since the GCC threading
179 * functions link against parlib. Note that, unlike parlib-compat.c, there
180 * are no stub functions available to GCC that could get called by
181 * accident and prevent the linkage. */
182 sched_ops->sched_init();
185 /* The 2LS calls this, passing in a uthread representing thread0 and its
186 * syscall handling routine. (NULL is fine). The 2LS sched_ops is known
187 * statically (via symbol overrides).
189 * This is where parlib (and whatever 2LS is linked in) takes over control of
190 * scheduling, including handling notifications, having sched_entry() called,
191 * blocking syscalls, and handling syscall completion events. Before this
192 * call, these things are handled by slim functions in glibc (e.g. early
193 * function pointers for ros_blockon) and by the kernel. The kerne's role was
194 * to treat the process specially until we call scp_vcctx_ready(): things like
195 * no __notify, no sched_entry, etc.
197 * We need to be careful to not start using the 2LS before it is fully ready.
198 * For instance, once we change ros_blockon, we could have a blocking syscall
199 * (e.g. for something glibc does) and the rest of the 2LS code expects things
202 * In older versions of this code, we would hop from the thread0 sched to the
203 * real 2LSs sched, which meant we had to be very careful. But now that we
204 * only do this once, we can do all the prep work and then take over from
205 * glibc's early SCP setup. Specifically, notifs are disabled (due to the
206 * early SCP ctx) and syscalls won't use the __ros_uth_syscall_blockon, so we
207 * shouldn't get a syscall event.
209 * Still, if you have things like an outstanding async syscall, then you'll
210 * have issues. Most likely it would complete and you'd never hear about it.
212 * Note that some 2LS ops can be called even before we've initialized the 2LS!
213 * Some ops, like the sync_obj ops, are called when initializing an uncontested
214 * mutex, which could be called from glibc (e.g. malloc). Hopefully that's
215 * fine - we'll see! I imagine a contested mutex would be a disaster (during
216 * the unblock), which shouldn't happen as we are single threaded. */
217 void uthread_2ls_init(struct uthread *uthread,
218 void (*handle_sysc)(struct event_msg *, unsigned int,
222 struct ev_handler *new_h = NULL;
225 new_h = malloc(sizeof(struct ev_handler));
227 new_h->func = handle_sysc;
230 assert(!ev_handlers[EV_SYSCALL]);
231 ev_handlers[EV_SYSCALL] = new_h;
233 uthread_init_thread0(uthread);
234 uthread_track_thread0(uthread);
235 /* Switch our errno/errstr functions to be uthread-aware. See glibc's
236 * errno.c for more info. */
237 ros_errno_loc = __ros_errno_loc;
238 ros_errstr_loc = __ros_errstr_loc;
239 register_ev_handler(EV_EVENT, handle_ev_ev, 0);
241 /* Now that we're ready (I hope) to operate as a full process, we tell the
242 * kernel. We must set vcctx and blockon atomically with respect to
243 * syscalls, meaning no syscalls in between. */
245 /* Change our blockon from glibc's internal one to the regular one, which
246 * uses vcore context and works for SCPs (with or without 2LS) and MCPs.
247 * Now that we told the kernel we are ready to utilize vcore context, we
248 * need our blocking syscalls to utilize it as well. */
249 ros_syscall_blockon = __ros_uth_syscall_blockon;
251 init_posix_signals();
252 /* Accept diagnostic events. Other parts of the program/libraries can
253 * register handlers to run. You can kick these with "notify PID 9". */
254 enable_kevent(EV_FREE_APPLE_PIE, 0, EVENT_IPI | EVENT_WAKEUP |
258 /* 2LSs shouldn't call uthread_vcore_entry directly */
259 void __attribute__((noreturn)) uthread_vcore_entry(void)
261 uint32_t vcoreid = vcore_id();
262 struct preempt_data *vcpd = vcpd_of(vcoreid);
263 /* Should always have notifications disabled when coming in here. */
264 assert(!notif_is_enabled(vcoreid));
265 assert(in_vcore_context());
266 /* If someone is stealing our uthread (from when we were preempted before),
267 * we can't touch our uthread. But we might be the last vcore around, so
268 * we'll handle preemption events (spammed to our public mbox).
270 * It's important that we only check/handle one message per loop, otherwise
271 * we could get stuck in a ping-pong scenario with a recoverer (maybe). */
272 while (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
273 /* Note we're handling INDIRs and other public messages while someone
274 * is stealing our uthread. Remember that those event handlers cannot
275 * touch cur_uth, as it is "vcore business". */
276 handle_one_mbox_msg(&vcpd->ev_mbox_public);
279 /* If we have a current uthread that is DONT_MIGRATE, pop it real quick and
280 * let it disable notifs (like it wants to). Other than dealing with
281 * preemption events (or other INDIRs), we shouldn't do anything in vc_ctx
282 * when we have a DONT_MIGRATE uthread. */
283 if (current_uthread && (current_uthread->flags & UTHREAD_DONT_MIGRATE))
284 __run_current_uthread_raw();
285 /* Check and see if we wanted ourselves to handle a remote VCPD mbox. Want
286 * to do this after we've handled STEALING and DONT_MIGRATE. */
287 try_handle_remote_mbox();
288 /* Otherwise, go about our usual vcore business (messages, etc). */
289 handle_events(vcoreid);
290 __check_preempt_pending(vcoreid);
291 assert(in_vcore_context()); /* double check, in case an event changed it */
292 sched_ops->sched_entry();
293 assert(0); /* 2LS sched_entry should never return */
296 /* Does the uthread initialization of a uthread that the caller created. Call
297 * this whenever you are "starting over" with a thread. */
298 void uthread_init(struct uthread *new_thread, struct uth_thread_attr *attr)
302 new_thread->state = UT_NOT_RUNNING;
303 /* Set the signal state. */
305 new_thread->sigstate.mask = current_uthread->sigstate.mask;
307 new_thread->sigstate.mask = 0;
308 __sigemptyset(&new_thread->sigstate.pending);
309 new_thread->sigstate.data = NULL;
310 /* They should have zero'd the uthread. Let's check critical things: */
311 assert(!new_thread->flags && !new_thread->sysc);
312 /* the utf holds the GP context of the uthread (set by the 2LS earlier).
313 * There is no FP context to be restored yet. We only save the FPU when we
314 * were interrupted off a core. */
315 new_thread->flags |= UTHREAD_SAVED;
316 new_thread->notif_disabled_depth = 0;
317 /* TODO: on a reinit, if they changed whether or not they want TLS, we'll
318 * have issues (checking tls_desc, assert in allocate_tls, maybe more). */
319 if (attr && attr->want_tls) {
320 /* Get a TLS. If we already have one, reallocate/refresh it */
321 if (new_thread->tls_desc)
322 ret = __uthread_reinit_tls(new_thread);
324 ret = __uthread_allocate_tls(new_thread);
326 begin_access_tls_vars(new_thread->tls_desc);
327 current_uthread = new_thread;
328 /* ctypes stores locale info in TLS. we need this only once per TLS, so
329 * we don't have to do it here, but it is convenient since we already
330 * loaded the uthread's TLS. */
331 extern void __ctype_init(void);
333 end_access_tls_vars();
335 new_thread->tls_desc = UTH_TLSDESC_NOTLS;
337 if (attr && attr->detached)
338 atomic_set(&new_thread->join_ctl.state, UTH_JOIN_DETACHED);
340 atomic_set(&new_thread->join_ctl.state, UTH_JOIN_JOINABLE);
343 /* This is a wrapper for the sched_ops thread_runnable, for use by functions
344 * outside the main 2LS. Do not put anything important in this, since the 2LSs
345 * internally call their sched op. This is to improve batch wakeups (barriers,
347 void uthread_runnable(struct uthread *uthread)
349 assert(sched_ops->thread_runnable);
350 sched_ops->thread_runnable(uthread);
353 /* Informs the 2LS that its thread blocked, and it is not under the control of
354 * the 2LS. This is for informational purposes, and some semantic meaning
355 * should be passed by flags (from uthread.h's UTH_EXT_BLK_xxx options).
356 * Eventually, whoever calls this will call uthread_runnable(), giving the
357 * thread back to the 2LS. If the 2LS provide sync ops, it will have a say in
358 * which thread wakes up at a given time.
360 * If code outside the 2LS has blocked a thread (via uthread_yield) and ran its
361 * own callback/yield_func instead of some 2LS code, that callback needs to
364 * AKA: obviously_a_uthread_has_blocked_in_lincoln_park() */
365 void uthread_has_blocked(struct uthread *uthread, int flags)
367 assert(sched_ops->thread_has_blocked);
368 sched_ops->thread_has_blocked(uthread, flags);
371 /* Function indicating an external event has temporarily paused a uthread, but
372 * it is ok to resume it if possible. */
373 void uthread_paused(struct uthread *uthread)
375 /* Call out to the 2LS to let it know the uthread was paused for some
376 * reason, but it is ok to resume it now. */
377 assert(uthread->state == UT_NOT_RUNNING);
378 assert(sched_ops->thread_paused);
379 sched_ops->thread_paused(uthread);
382 /* Need to have this as a separate, non-inlined function since we clobber the
383 * stack pointer before calling it, and don't want the compiler to play games
385 static void __attribute__((noinline, noreturn))
386 __uthread_yield(void)
388 struct uthread *uthread = current_uthread;
389 assert(in_vcore_context());
390 assert(!notif_is_enabled(vcore_id()));
391 /* Note: we no longer care if the thread is exiting, the 2LS will call
392 * uthread_destroy() */
393 uthread->flags &= ~UTHREAD_DONT_MIGRATE;
394 uthread->state = UT_NOT_RUNNING;
395 /* Any locks that were held before the yield must be unlocked in the
396 * callback. That callback won't get a chance to update our disabled depth.
397 * This sets us up for the next time the uthread runs. */
398 assert(uthread->notif_disabled_depth <= 1);
399 uthread->notif_disabled_depth = 0;
400 /* Do whatever the yielder wanted us to do */
401 assert(uthread->yield_func);
402 uthread->yield_func(uthread, uthread->yield_arg);
403 /* Make sure you do not touch uthread after that func call */
404 /* Leave the current vcore completely */
405 /* TODO: if the yield func can return a failure, we can abort the yield */
406 current_uthread = NULL;
407 /* Go back to the entry point, where we can handle notifications or
408 * reschedule someone. */
409 uthread_vcore_entry();
412 /* Calling thread yields for some reason. Set 'save_state' if you want to ever
413 * run the thread again. Once in vcore context in __uthread_yield, yield_func
414 * will get called with the uthread and yield_arg passed to it. This way, you
415 * can do whatever you want when you get into vcore context, which can be
416 * thread_blockon_sysc, unlocking mutexes, joining, whatever.
418 * If you do *not* pass a 2LS sched op or other 2LS function as yield_func,
419 * then you must also call uthread_has_blocked(flags), which will let the 2LS
420 * know a thread blocked beyond its control (and why). */
421 void uthread_yield(bool save_state, void (*yield_func)(struct uthread*, void*),
424 struct uthread *uthread = current_uthread;
425 volatile bool yielding = TRUE; /* signal to short circuit when restarting */
426 assert(!in_vcore_context());
427 assert(uthread->state == UT_RUNNING);
428 /* Pass info to ourselves across the uth_yield -> __uth_yield transition. */
429 uthread->yield_func = yield_func;
430 uthread->yield_arg = yield_arg;
431 /* Don't migrate this thread to another vcore, since it depends on being on
432 * the same vcore throughout (once it disables notifs). The race is that we
433 * read vcoreid, then get interrupted / migrated before disabling notifs. */
434 uthread->flags |= UTHREAD_DONT_MIGRATE;
435 cmb(); /* don't let DONT_MIGRATE write pass the vcoreid read */
436 uint32_t vcoreid = vcore_id();
437 printd("[U] Uthread %08p is yielding on vcore %d\n", uthread, vcoreid);
438 struct preempt_data *vcpd = vcpd_of(vcoreid);
439 /* once we do this, we might miss a notif_pending, so we need to enter vcore
440 * entry later. Need to disable notifs so we don't get in weird loops with
441 * save_user_ctx() and pop_user_ctx(). */
442 disable_notifs(vcoreid);
443 /* take the current state and save it into t->utf when this pthread
444 * restarts, it will continue from right after this, see yielding is false,
445 * and short ciruit the function. Don't do this if we're dying. */
447 /* Need to signal this before we actually save, since save_user_ctx
448 * returns() twice (once now, once when woken up) */
449 uthread->flags |= UTHREAD_SAVED;
450 save_user_ctx(&uthread->u_ctx);
452 cmb(); /* Force reread of yielding. Technically save_user_ctx() suffices*/
453 /* Restart path doesn't matter if we're dying */
455 goto yield_return_path;
456 /* From here on down is only executed on the save path (not the wake up) */
457 yielding = FALSE; /* for when it starts back up */
458 /* TODO: remove this when all arches support SW contexts */
459 if (save_state && (uthread->u_ctx.type != ROS_SW_CTX)) {
460 save_fp_state(&uthread->as);
461 uthread->flags |= UTHREAD_FPSAVED;
463 /* Change to the transition context (both TLS (if applicable) and stack). */
464 if (__uthread_has_tls(uthread)) {
465 set_tls_desc(get_vcpd_tls_desc(vcoreid));
466 begin_safe_access_tls_vars();
467 assert(current_uthread == uthread);
468 /* If this assert fails, see the note in uthread_track_thread0 */
469 assert(in_vcore_context());
470 end_safe_access_tls_vars();
472 /* Since uthreads and vcores share TLS (it's always the vcore's TLS, the
473 * uthread one just bootstraps from it), we need to change our state at
474 * boundaries between the two 'contexts' */
475 __vcore_context = TRUE;
477 /* After this, make sure you don't use local variables. Also, make sure the
478 * compiler doesn't use them without telling you (TODO).
480 * In each arch's set_stack_pointer, make sure you subtract off as much room
481 * as you need to any local vars that might be pushed before calling the
482 * next function, or for whatever other reason the compiler/hardware might
483 * walk up the stack a bit when calling a noreturn function. */
484 set_stack_pointer((void*)vcpd->vcore_stack);
485 /* Finish exiting in another function. */
487 /* Should never get here */
489 /* Will jump here when the uthread's trapframe is restarted/popped. */
491 printd("[U] Uthread %08p returning from a yield!\n", uthread);
494 /* We explicitly don't support sleep(), since old callers of it have
495 * expectations of being woken up by signal handlers. If we need that, we can
496 * build it in to sleep() later. If you just want to sleep for a while, call
498 void uthread_sleep(unsigned int seconds)
500 sys_block(seconds * 1000000); /* usec sleep */
502 /* If we are providing a dummy sleep function, might as well provide the more
503 * accurate/useful one. */
504 void uthread_usleep(unsigned int usecs)
506 sys_block(usecs); /* usec sleep */
509 static void __sleep_forever_cb(struct uthread *uth, void *arg)
511 uthread_has_blocked(uth, UTH_EXT_BLK_MISC);
514 void __attribute__((noreturn)) uthread_sleep_forever(void)
516 uthread_yield(FALSE, __sleep_forever_cb, NULL);
520 /* Cleans up the uthread (the stuff we did in uthread_init()). If you want to
521 * destroy a currently running uthread, you'll want something like
522 * pthread_exit(), which yields, and calls this from its sched_ops yield. */
523 void uthread_cleanup(struct uthread *uthread)
525 printd("[U] thread %08p on vcore %d is DYING!\n", uthread, vcore_id());
526 /* we alloc and manage the TLS, so lets get rid of it, except for thread0.
527 * glibc owns it. might need to keep it around for a full exit() */
528 if (__uthread_has_tls(uthread) && !(uthread->flags & UTHREAD_IS_THREAD0))
529 __uthread_free_tls(uthread);
532 static void __ros_syscall_spinon(struct syscall *sysc)
534 while (!(atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS)))
538 static void __ros_vcore_ctx_syscall_blockon(struct syscall *sysc)
540 if (in_multi_mode()) {
541 /* MCP vcore's don't know what to do yet, so we have to spin */
542 __ros_syscall_spinon(sysc);
544 /* SCPs can use the early blockon, which acts like VC ctx. */
545 __ros_early_syscall_blockon(sysc);
549 /* Attempts to block on sysc, returning when it is done or progress has been
550 * made. Made for initialized processes using uthreads. */
551 static void __ros_uth_syscall_blockon(struct syscall *sysc)
553 if (in_vcore_context()) {
554 __ros_vcore_ctx_syscall_blockon(sysc);
557 /* At this point, we know we're a uthread. If we're a DONT_MIGRATE uthread,
558 * then it's disabled notifs and is basically in vcore context, enough so
559 * that it can't call into the 2LS. */
560 assert(current_uthread);
561 if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
562 assert(!notif_is_enabled(vcore_id())); /* catch bugs */
563 /* if we had a notif_disabled_depth, then we should also have
564 * DONT_MIGRATE set */
565 __ros_vcore_ctx_syscall_blockon(sysc);
568 assert(!current_uthread->notif_disabled_depth);
569 /* double check before doing all this crap */
570 if (atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS))
572 /* for both debugging and syscall cancelling */
573 current_uthread->sysc = sysc;
574 /* yield, calling 2ls-blockon(cur_uth, sysc) on the other side */
575 uthread_yield(TRUE, sched_ops->thread_blockon_sysc, sysc);
578 /* 2LS helper. Run this from vcore context. It will block a uthread on it's
579 * internal syscall struct, which should be an async call. You'd use this in
580 * e.g. thread_refl_fault when the 2LS initiates a syscall on behalf of the
582 void __block_uthread_on_async_sysc(struct uthread *uth)
584 assert(in_vcore_context());
585 uth->sysc = &uth->local_sysc;
586 /* If a DONT_MIGRATE issued a syscall that blocks, we gotta spin, same as
587 * with the usual blockon. */
588 if (uth->flags & UTHREAD_DONT_MIGRATE) {
589 __ros_vcore_ctx_syscall_blockon(uth->sysc);
593 sched_ops->thread_blockon_sysc(uth, uth->sysc);
596 /* Simply sets current uthread to be whatever the value of uthread is. This
597 * can be called from outside of sched_entry() to highjack the current context,
598 * and make sure that the new uthread struct is used to store this context upon
599 * yielding, etc. USE WITH EXTREME CAUTION! */
600 void highjack_current_uthread(struct uthread *uthread)
602 uint32_t vcoreid = vcore_id();
603 assert(uthread != current_uthread);
604 current_uthread->state = UT_NOT_RUNNING;
605 uthread->state = UT_RUNNING;
606 /* Make sure the vcore is tracking the new uthread struct */
607 if (__uthread_has_tls(current_uthread))
608 vcore_set_tls_var(current_uthread, uthread);
610 current_uthread = uthread;
611 /* and make sure we are using the correct TLS for the new uthread */
612 if (__uthread_has_tls(uthread)) {
613 assert(uthread->tls_desc);
614 set_tls_desc(uthread->tls_desc);
615 begin_safe_access_tls_vars();
616 __vcoreid = vcoreid; /* setting the uthread's TLS var */
617 end_safe_access_tls_vars();
621 /* Helper: loads a uthread's TLS on this vcore, if applicable. If our uthreads
622 * do not have their own TLS, we simply switch the __vc_ctx, signalling that the
623 * context running here is (soon to be) a uthread. */
624 static void set_uthread_tls(struct uthread *uthread, uint32_t vcoreid)
626 if (__uthread_has_tls(uthread)) {
627 set_tls_desc(uthread->tls_desc);
628 begin_safe_access_tls_vars();
629 __vcoreid = vcoreid; /* setting the uthread's TLS var */
630 end_safe_access_tls_vars();
632 __vcore_context = FALSE;
636 /* Attempts to handle a fault for uth, etc */
637 static void handle_refl_fault(struct uthread *uth, struct user_context *ctx)
639 sched_ops->thread_refl_fault(uth, ctx);
642 /* 2LS helper: stops the current uthread, saves its state, and returns a pointer
643 * to it. Unlike __uthread_pause, which is called by non-specific 2LS code,
644 * this function is called by a specific 2LS to stop it's current uthread. */
645 struct uthread *stop_current_uthread(void)
648 struct preempt_data *vcpd = vcpd_of(vcore_id());
650 uth = current_uthread;
652 if (!(uth->flags & UTHREAD_SAVED)) {
653 uth->u_ctx = vcpd->uthread_ctx;
654 uth->flags |= UTHREAD_SAVED;
656 if ((uth->u_ctx.type != ROS_SW_CTX) && !(uth->flags & UTHREAD_FPSAVED)) {
657 save_fp_state(&uth->as);
658 uth->flags |= UTHREAD_FPSAVED;
660 uth->state = UT_NOT_RUNNING;
664 /* Run the thread that was current_uthread, from a previous run. Should be
665 * called only when the uthread already was running, and we were interrupted by
666 * the kernel (event, etc). Do not call this to run a fresh uthread, even if
667 * you've set it to be current. */
668 void __attribute__((noreturn)) run_current_uthread(void)
671 uint32_t vcoreid = vcore_id();
672 struct preempt_data *vcpd = vcpd_of(vcoreid);
673 assert(current_uthread);
674 assert(current_uthread->state == UT_RUNNING);
675 /* Uth was already running, should not have been saved */
676 assert(!(current_uthread->flags & UTHREAD_SAVED));
677 assert(!(current_uthread->flags & UTHREAD_FPSAVED));
678 printd("[U] Vcore %d is restarting uthread %08p\n", vcoreid,
680 if (has_refl_fault(&vcpd->uthread_ctx)) {
681 clear_refl_fault(&vcpd->uthread_ctx);
682 /* we preemptively copy out and make non-running, so that there is a
683 * consistent state for the handler. it can then block the uth or
685 uth = stop_current_uthread();
686 handle_refl_fault(uth, &vcpd->uthread_ctx);
687 /* we abort no matter what. up to the 2LS to reschedule the thread */
688 set_stack_pointer((void*)vcpd->vcore_stack);
691 /* Go ahead and start the uthread */
692 set_uthread_tls(current_uthread, vcoreid);
693 /* Run, using the TF in the VCPD. FP state should already be loaded */
694 pop_user_ctx(&vcpd->uthread_ctx, vcoreid);
698 /* Launches the uthread on the vcore. Don't call this on current_uthread.
700 * In previous versions of this, we used to check for events after setting
701 * current_uthread. That is super-dangerous. handle_events() doesn't always
702 * return (which we used to handle), and it may also clear current_uthread. We
703 * needed to save uthread in current_uthread, in case we didn't return. If we
704 * didn't return, the vcore started over at vcore_entry, with current set. When
705 * this happens, we never actually had loaded cur_uth's FP and GP onto the core,
706 * so cur_uth fails. Check out 4602599be for more info.
708 * Ultimately, handling events again in these 'popping helpers' isn't even
709 * necessary (we only must do it once for an entire time in VC ctx, and in
710 * loops), and might have been optimizing a rare event at a cost in both
711 * instructions and complexity. */
712 void __attribute__((noreturn)) run_uthread(struct uthread *uthread)
714 uint32_t vcoreid = vcore_id();
715 struct preempt_data *vcpd = vcpd_of(vcoreid);
716 assert(!current_uthread);
717 assert(uthread->state == UT_NOT_RUNNING);
718 assert(uthread->flags & UTHREAD_SAVED);
719 /* For HW/VM CTX, FPSAVED must match UTH SAVE (and both be on here). For
720 * SW, FP should never be saved. */
721 switch (uthread->u_ctx.type) {
724 assert(uthread->flags & UTHREAD_FPSAVED);
727 assert(!(uthread->flags & UTHREAD_FPSAVED));
730 if (has_refl_fault(&uthread->u_ctx)) {
731 clear_refl_fault(&uthread->u_ctx);
732 handle_refl_fault(uthread, &uthread->u_ctx);
733 /* we abort no matter what. up to the 2LS to reschedule the thread */
734 set_stack_pointer((void*)vcpd->vcore_stack);
737 uthread->state = UT_RUNNING;
738 /* Save a ptr to the uthread we'll run in the transition context's TLS */
739 current_uthread = uthread;
740 if (uthread->flags & UTHREAD_FPSAVED) {
741 uthread->flags &= ~UTHREAD_FPSAVED;
742 restore_fp_state(&uthread->as);
744 set_uthread_tls(uthread, vcoreid);
745 /* the uth's context will soon be in the cpu (or VCPD), no longer saved */
746 uthread->flags &= ~UTHREAD_SAVED;
747 pop_user_ctx(&uthread->u_ctx, vcoreid);
751 /* Runs the uthread, but doesn't care about notif pending. Only call this when
752 * there was a DONT_MIGRATE uthread, or a similar situation where the uthread
753 * will check messages soon (like calling enable_notifs()). */
754 static void __run_current_uthread_raw(void)
756 uint32_t vcoreid = vcore_id();
757 struct preempt_data *vcpd = vcpd_of(vcoreid);
758 if (has_refl_fault(&vcpd->uthread_ctx)) {
759 printf("Raw / DONT_MIGRATE uthread took a fault, exiting.\n");
762 /* We need to manually say we have a notif pending, so we eventually return
763 * to vcore context. (note the kernel turned it off for us) */
764 vcpd->notif_pending = TRUE;
765 assert(!(current_uthread->flags & UTHREAD_SAVED));
766 assert(!(current_uthread->flags & UTHREAD_FPSAVED));
767 set_uthread_tls(current_uthread, vcoreid);
768 pop_user_ctx_raw(&vcpd->uthread_ctx, vcoreid);
772 /* Copies the uthread trapframe and silly state from the vcpd to the uthread,
773 * subject to the uthread's flags and whatnot.
775 * For example: The uthread state might still be in the uthread struct. Imagine
776 * the 2LS decides to run a new uthread and sets it up as current, but doesn't
777 * actually run it yet. The 2LS happened to voluntarily give up the VC (due to
778 * some other event) and then wanted to copy out the thread. This is pretty
779 * rare - the normal case is when an IRQ of some sort hit the core and the
780 * kernel copied the running state into VCPD.
782 * The FP state could also be in VCPD (e.g. preemption being handled remotely),
783 * it could be in the uthread struct (e.g. hasn't started running yet) or even
784 * in the FPU (e.g. took an IRQ/notif and we're handling the preemption of
787 * There are some cases where we'll have a uthread SW ctx that needs to be
788 * copied out: uth syscalls, notif happens, and the core comes back from the
789 * kernel in VC ctx. VC ctx calls copy_out (response to preempt_pending or done
790 * while handling a preemption). */
791 static void copyout_uthread(struct preempt_data *vcpd, struct uthread *uthread,
795 if (uthread->flags & UTHREAD_SAVED) {
796 /* I don't know of scenarios where HW/VM ctxs FP state differs from GP*/
797 switch (uthread->u_ctx.type) {
800 assert(uthread->flags & UTHREAD_FPSAVED);
805 /* If we're copying GP state, it must be in VCPD */
806 uthread->u_ctx = vcpd->uthread_ctx;
807 uthread->flags |= UTHREAD_SAVED;
808 printd("VC %d copying out uthread %08p\n", vcore_id(), uthread);
809 /* Software contexts do not need FP state, nor should we think it has any */
810 if (uthread->u_ctx.type == ROS_SW_CTX) {
811 assert(!(uthread->flags & UTHREAD_FPSAVED));
814 /* HW contexts also should not have it saved either. Should be either in
815 * the VCPD or the FPU. Yes, this is the same assert. */
816 assert(!(uthread->flags & UTHREAD_FPSAVED));
817 /* When we're dealing with the uthread running on our own vcore, the FP
818 * state is in the actual FPU, not VCPD. It might also be in VCPD, but it
819 * will always be in the FPU (the kernel maintains this for us, in the event
820 * we were preempted since the uthread was last running). */
822 save_fp_state(&uthread->as);
824 uthread->as = vcpd->preempt_anc;
825 uthread->flags |= UTHREAD_FPSAVED;
828 /* Helper, packages up and pauses a uthread that was running on vcoreid. Used
829 * by preemption handling (and detection) so far. Careful using this, esp if
830 * it is on another vcore (need to make sure it's not running!). If you are
831 * using it on the local vcore, set vcore_local = TRUE. */
832 static void __uthread_pause(struct preempt_data *vcpd, struct uthread *uthread,
835 assert(!(uthread->flags & UTHREAD_DONT_MIGRATE));
836 copyout_uthread(vcpd, uthread, vcore_local);
837 uthread->state = UT_NOT_RUNNING;
838 /* Call out to the 2LS to package up its uthread */
839 assert(sched_ops->thread_paused);
840 sched_ops->thread_paused(uthread);
843 /* Deals with a pending preemption (checks, responds). If the 2LS registered a
844 * function, it will get run. Returns true if you got preempted. Called
845 * 'check' instead of 'handle', since this isn't an event handler. It's the "Oh
846 * shit a preempt is on its way ASAP".
848 * Be careful calling this: you might not return, so don't call it if you can't
849 * handle that. If you are calling this from an event handler, you'll need to
850 * do things like ev_might_not_return(). If the event can via an INDIR ev_q,
851 * that ev_q must be a NOTHROTTLE.
853 * Finally, don't call this from a place that might have a DONT_MIGRATE
854 * cur_uth. This should be safe for most 2LS code. */
855 bool __check_preempt_pending(uint32_t vcoreid)
858 assert(in_vcore_context());
859 if (__preempt_is_pending(vcoreid)) {
861 if (sched_ops->preempt_pending)
862 sched_ops->preempt_pending();
863 /* If we still have a cur_uth, copy it out and hand it back to the 2LS
864 * before yielding. */
865 if (current_uthread) {
866 __uthread_pause(vcpd_of(vcoreid), current_uthread, TRUE);
869 /* vcore_yield tries to yield, and will pop back up if this was a spurious
870 * preempt_pending or if it handled an event. For now, we'll just keep
871 * trying to yield so long as a preempt is coming in. Eventually, we'll
872 * handle all of our events and yield, or else the preemption will hit
873 * and someone will recover us (at which point we'll break out of the
875 while (__procinfo.vcoremap[vcoreid].preempt_pending) {
883 /* Helper: This is a safe way for code to disable notifs if it *might* be called
884 * from uthread context (like from a notif_safe lock). Pair this with
885 * uth_enable_notifs() unless you know what you're doing. */
886 void uth_disable_notifs(void)
888 if (!in_vcore_context()) {
889 if (current_uthread) {
890 if (current_uthread->notif_disabled_depth++)
892 current_uthread->flags |= UTHREAD_DONT_MIGRATE;
893 cmb(); /* don't issue the flag write before the vcore_id() read */
895 disable_notifs(vcore_id());
898 assert(!notif_is_enabled(vcore_id()));
901 /* Helper: Pair this with uth_disable_notifs(). */
902 void uth_enable_notifs(void)
904 if (!in_vcore_context()) {
905 if (current_uthread) {
906 if (--current_uthread->notif_disabled_depth)
908 current_uthread->flags &= ~UTHREAD_DONT_MIGRATE;
909 cmb(); /* don't enable before ~DONT_MIGRATE */
911 enable_notifs(vcore_id());
915 void assert_can_block(void)
917 if (in_vcore_context())
918 panic("Vcore context tried to block!");
919 if (!current_uthread) {
920 /* Pre-parlib SCPs can do whatever. */
921 if (atomic_read(&vcpd_of(0)->flags) & VC_SCP_NOVCCTX)
923 panic("No current_uthread and tried to block!");
925 if (current_uthread->notif_disabled_depth)
926 panic("Uthread tried to block with notifs disabled!");
927 if (current_uthread->flags & UTHREAD_DONT_MIGRATE)
928 panic("Uthread tried to block with DONT_MIGRATE!");
931 /* Helper: returns TRUE if it succeeded in starting the uth stealing process. */
932 static bool start_uth_stealing(struct preempt_data *vcpd)
936 old_flags = atomic_read(&vcpd->flags);
937 /* Spin if the kernel is mucking with the flags */
938 while (old_flags & VC_K_LOCK)
939 old_flags = atomic_read(&vcpd->flags);
940 /* Someone else is stealing, we failed */
941 if (old_flags & VC_UTHREAD_STEALING)
943 } while (!atomic_cas(&vcpd->flags, old_flags,
944 old_flags | VC_UTHREAD_STEALING));
948 /* Helper: pairs with stop_uth_stealing */
949 static void stop_uth_stealing(struct preempt_data *vcpd)
953 old_flags = atomic_read(&vcpd->flags);
954 assert(old_flags & VC_UTHREAD_STEALING); /* sanity */
955 while (old_flags & VC_K_LOCK)
956 old_flags = atomic_read(&vcpd->flags);
957 } while (!atomic_cas(&vcpd->flags, old_flags,
958 old_flags & ~VC_UTHREAD_STEALING));
961 /* Handles INDIRS for another core (the public mbox). We synchronize with the
962 * kernel (__set_curtf_to_vcoreid). */
963 static void handle_indirs(uint32_t rem_vcoreid)
966 struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
967 /* Turn off their message reception if they are still preempted. If they
968 * are no longer preempted, we do nothing - they will handle their own
969 * messages. Turning off CAN_RCV will route this vcore's messages to
970 * fallback vcores (if those messages were 'spammed'). */
972 old_flags = atomic_read(&rem_vcpd->flags);
973 while (old_flags & VC_K_LOCK)
974 old_flags = atomic_read(&rem_vcpd->flags);
975 if (!(old_flags & VC_PREEMPTED))
977 } while (!atomic_cas(&rem_vcpd->flags, old_flags,
978 old_flags & ~VC_CAN_RCV_MSG));
979 wrmb(); /* don't let the CAN_RCV write pass reads of the mbox status */
980 /* handle all INDIRs of the remote vcore */
981 handle_vcpd_mbox(rem_vcoreid);
984 /* Helper. Will ensure a good attempt at changing vcores, meaning we try again
985 * if we failed for some reason other than the vcore was already running. */
986 static void __change_vcore(uint32_t rem_vcoreid, bool enable_my_notif)
988 /* okay to do a normal spin/relax here, even though we are in vcore
990 while (-EAGAIN == sys_change_vcore(rem_vcoreid, enable_my_notif))
994 /* Helper, used in preemption recovery. When you can freely leave vcore
995 * context and need to change to another vcore, call this. vcpd is the caller,
996 * rem_vcoreid is the remote vcore. This will try to package up your uthread.
997 * It may return, either because the other core already started up (someone else
998 * got it), or in some very rare cases where we had to stay in our vcore
1000 static void change_to_vcore(struct preempt_data *vcpd, uint32_t rem_vcoreid)
1002 bool were_handling_remotes;
1003 /* Unlikely, but if we have no uthread we can just change. This is the
1004 * check, sync, then really check pattern: we can only really be sure about
1005 * current_uthread after we check STEALING. */
1006 if (!current_uthread) {
1007 /* there might be an issue with doing this while someone is recovering.
1008 * once they 0'd it, we should be good to yield. just a bit dangerous.
1010 were_handling_remotes = ev_might_not_return();
1011 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
1012 goto out_we_returned;
1014 /* Note that the reason we need to check STEALING is because we can get into
1015 * vcore context and slip past that check in vcore_entry when we are
1016 * handling a preemption message. Anytime preemption recovery cares about
1017 * the calling vcore's cur_uth, it needs to be careful about STEALING. But
1018 * it is safe to do the check up above (if it's 0, it won't concurrently
1021 * STEALING might be turned on at any time. Whoever turns it on will do
1022 * nothing if we are online or were in vc_ctx. So if it is on, we can't
1023 * touch current_uthread til it is turned off (not sure what state they saw
1024 * us in). We could spin here til they unset STEALING (since they will
1025 * soon), but there is a chance they were preempted, so we need to make
1026 * progress by doing a sys_change_vcore(). */
1027 /* Crap, someone is stealing (unlikely). All we can do is change. */
1028 if (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
1029 __change_vcore(rem_vcoreid, FALSE); /* returns on success */
1033 /* Need to recheck, in case someone stole it and finished before we checked
1034 * VC_UTHREAD_STEALING. */
1035 if (!current_uthread) {
1036 were_handling_remotes = ev_might_not_return();
1037 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
1038 goto out_we_returned;
1040 /* Need to make sure we don't have a DONT_MIGRATE (very rare, someone would
1041 * have to steal from us to get us to handle a preempt message, and then had
1042 * to finish stealing (and fail) fast enough for us to miss the previous
1044 if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
1045 __change_vcore(rem_vcoreid, FALSE); /* returns on success */
1048 /* Now save our uthread and restart them */
1049 assert(current_uthread);
1050 __uthread_pause(vcpd, current_uthread, TRUE);
1051 current_uthread = 0;
1052 were_handling_remotes = ev_might_not_return();
1053 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
1054 /* Fall-through to out_we_returned */
1056 ev_we_returned(were_handling_remotes);
1059 /* This handles a preemption message. When this is done, either we recovered,
1060 * or recovery *for our message* isn't needed. */
1061 static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
1064 uint32_t vcoreid = vcore_id();
1065 struct preempt_data *vcpd = vcpd_of(vcoreid);
1066 uint32_t rem_vcoreid = ev_msg->ev_arg2;
1067 struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
1068 struct uthread *uthread_to_steal = 0;
1069 struct uthread **rem_cur_uth;
1070 bool cant_migrate = FALSE;
1072 assert(in_vcore_context());
1073 /* Just drop messages about ourselves. They are old. If we happen to be
1074 * getting preempted right now, there's another message out there about
1076 if (rem_vcoreid == vcoreid)
1078 printd("Vcore %d was preempted (i'm %d), it's flags %08p!\n",
1079 ev_msg->ev_arg2, vcoreid, rem_vcpd->flags);
1080 /* Spin til the kernel is done with flags. This is how we avoid handling
1081 * the preempt message before the preemption. */
1082 while (atomic_read(&rem_vcpd->flags) & VC_K_LOCK)
1084 /* If they aren't preempted anymore, just return (optimization). */
1085 if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
1087 /* At this point, we need to try to recover */
1088 /* This case handles when the remote core was in vcore context */
1089 if (rem_vcpd->notif_disabled) {
1090 printd("VC %d recovering %d, notifs were disabled\n", vcoreid,
1092 change_to_vcore(vcpd, rem_vcoreid);
1093 return; /* in case it returns. we've done our job recovering */
1095 /* So now it looks like they were not in vcore context. We want to steal
1096 * the uthread. Set stealing, then doublecheck everything. If stealing
1097 * fails, someone else is stealing and we can just leave. That other vcore
1098 * who is stealing will check the VCPD/INDIRs when it is done. */
1099 if (!start_uth_stealing(rem_vcpd))
1101 /* Now we're stealing. Double check everything. A change in preempt status
1102 * or notif_disable status means the vcore has since restarted. The vcore
1103 * may or may not have started after we set STEALING. If it didn't, we'll
1104 * need to bail out (but still check messages, since above we assumed the
1105 * uthread stealer handles the VCPD/INDIRs). Since the vcore is running, we
1106 * don't need to worry about handling the message any further. Future
1107 * preemptions will generate another message, so we can ignore getting the
1108 * uthread or anything like that. */
1109 printd("VC %d recovering %d, trying to steal uthread\n", vcoreid,
1111 if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
1113 /* Might be preempted twice quickly, and the second time had notifs
1116 * Also note that the second preemption event had another
1117 * message sent, which either we or someone else will deal with. And also,
1118 * we don't need to worry about how we are stealing still and plan to
1119 * abort. If another vcore handles that second preemption message, either
1120 * the original vcore is in vc ctx or not. If so, we bail out and the
1121 * second preemption handling needs to change_to. If not, we aren't
1122 * bailing out, and we'll handle the preemption as normal, and the second
1123 * handler will bail when it fails to steal. */
1124 if (rem_vcpd->notif_disabled)
1126 /* At this point, we're clear to try and steal the uthread. We used to
1127 * switch to their TLS to steal the uthread, but we can access their
1128 * current_uthread directly. */
1129 rem_cur_uth = get_tlsvar_linaddr(rem_vcoreid, current_uthread);
1130 uthread_to_steal = *rem_cur_uth;
1131 if (uthread_to_steal) {
1132 /* Extremely rare: they have a uthread, but it can't migrate. So we'll
1133 * need to change to them. */
1134 if (uthread_to_steal->flags & UTHREAD_DONT_MIGRATE) {
1135 printd("VC %d recovering %d, can't migrate uthread!\n", vcoreid,
1137 stop_uth_stealing(rem_vcpd);
1138 change_to_vcore(vcpd, rem_vcoreid);
1139 return; /* in case it returns. we've done our job recovering */
1142 /* we're clear to steal it */
1143 printd("VC %d recovering %d, uthread %08p stolen\n", vcoreid,
1144 rem_vcoreid, uthread_to_steal);
1145 __uthread_pause(rem_vcpd, uthread_to_steal, FALSE);
1146 /* can't let the cur_uth = 0 write and any writes from __uth_pause()
1147 * to pass stop_uth_stealing. */
1153 stop_uth_stealing(rem_vcpd);
1154 handle_indirs(rem_vcoreid);
1157 /* This handles a "check indirs" message. When this is done, either we checked
1158 * their indirs, or the vcore restarted enough so that checking them is
1159 * unnecessary. If that happens and they got preempted quickly, then another
1160 * preempt/check_indirs was sent out. */
1161 static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
1164 uint32_t vcoreid = vcore_id();
1165 uint32_t rem_vcoreid = ev_msg->ev_arg2;
1167 if (rem_vcoreid == vcoreid)
1169 handle_indirs(rem_vcoreid);
1172 static inline bool __uthread_has_tls(struct uthread *uthread)
1174 return uthread->tls_desc != UTH_TLSDESC_NOTLS;
1178 static int __uthread_allocate_tls(struct uthread *uthread)
1180 assert(!uthread->tls_desc);
1181 uthread->tls_desc = allocate_tls();
1182 if (!uthread->tls_desc) {
1189 static int __uthread_reinit_tls(struct uthread *uthread)
1191 uthread->tls_desc = reinit_tls(uthread->tls_desc);
1192 if (!uthread->tls_desc) {
1199 static void __uthread_free_tls(struct uthread *uthread)
1201 free_tls(uthread->tls_desc);
1202 uthread->tls_desc = NULL;
1205 bool uth_2ls_is_multithreaded(void)
1207 /* thread 0 is single threaded. For the foreseeable future, every other 2LS
1208 * will be multithreaded. */
1209 extern struct schedule_ops thread0_2ls_ops;
1211 return sched_ops != &thread0_2ls_ops;
1214 struct uthread *uthread_create(void *(*func)(void *), void *arg)
1216 return sched_ops->thread_create(func, arg);
1219 /* Who does the thread_exited callback (2LS-specific cleanup)? It depends. If
1220 * the thread exits first, then join/detach does it. o/w, the exit path does.
1222 * What are the valid state changes?
1224 * JOINABLE -> DETACHED (only by detach())
1225 * JOINABLE -> HAS_JOINER (only by join())
1226 * JOINABLE -> EXITED (only by uth_2ls_thread_exit())
1228 * That's it. The initial state is either JOINABLE or DETACHED. */
1229 void uthread_detach(struct uthread *uth)
1231 struct uth_join_ctl *jc = &uth->join_ctl;
1235 old_state = atomic_read(&jc->state);
1236 switch (old_state) {
1237 case UTH_JOIN_EXITED:
1238 sched_ops->thread_exited(uth);
1240 case UTH_JOIN_DETACHED:
1241 panic("Uth %p has already been detached!", uth);
1242 case UTH_JOIN_HAS_JOINER:
1243 panic("Uth %p has a pending joiner, can't detach!", uth);
1245 assert(old_state == UTH_JOIN_JOINABLE);
1246 } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_DETACHED));
1249 /* Helper. We have a joiner. So we'll write the retval to the final location
1250 * (the one passed to join() and decref to wake the joiner. This may seem a
1251 * little odd for a normal join, but it works identically a parallel join - and
1252 * there's only one wakeup (hence the kref). */
1253 static void uth_post_and_kick_joiner(struct uthread *uth, void *retval)
1255 struct uth_join_ctl *jc = &uth->join_ctl;
1258 *jc->retval_loc = retval;
1259 /* Note the JC has a pointer to the kicker. There's one kicker for the
1260 * joiner, but there could be many joinees. */
1261 kref_put(&jc->kicker->kref);
1264 /* Callback after the exiting uthread has yielded and is in vcore context. Note
1265 * that the thread_exited callback can be called concurrently (e.g., a racing
1266 * call to detach()), so it's important to not be in the uthread's context. */
1267 static void __uth_2ls_thread_exit_cb(struct uthread *uth, void *retval)
1269 struct uth_join_ctl *jc = &uth->join_ctl;
1273 old_state = atomic_read(&jc->state);
1274 switch (old_state) {
1275 case UTH_JOIN_DETACHED:
1276 sched_ops->thread_exited(uth);
1278 case UTH_JOIN_HAS_JOINER:
1279 uth_post_and_kick_joiner(uth, retval);
1280 sched_ops->thread_exited(uth);
1282 case UTH_JOIN_JOINABLE:
1283 /* This write is harmless and idempotent; we can lose the race and
1284 * still be safe. Assuming we don't, the joiner will look here for
1285 * the retval. It's temporary storage since we don't know the final
1286 * retval location (since join hasn't happened yet). */
1287 jc->retval = retval;
1290 assert(old_state == UTH_JOIN_JOINABLE);
1291 } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_EXITED));
1292 /* We were joinable, now we have exited. A detacher or joiner will trigger
1296 /* 2LSs call this when their threads are exiting. The 2LS will regain control
1297 * of the thread in sched_ops->thread_exited. This will be after the
1298 * join/detach/exit has completed, and might be in vcore context. */
1299 void __attribute__((noreturn)) uth_2ls_thread_exit(void *retval)
1301 uthread_yield(FALSE, __uth_2ls_thread_exit_cb, retval);
1305 /* Helper: Attaches the caller (specifically the jk) to the target uthread.
1306 * When the thread has been joined (either due to the UTH_EXITED case or due to
1307 * __uth_2ls_thread_exit_cb), the join kicker will be decreffed. */
1308 static void join_one(struct uthread *uth, struct uth_join_kicker *jk,
1311 struct uth_join_ctl *jc = &uth->join_ctl;
1314 /* We can safely write to the join_ctl, even if we don't end up setting
1315 * HAS_JOINER. There's only supposed to be one joiner, and if not, we'll
1316 * catch the bad state. */
1317 jc->retval_loc = retval_loc;
1320 old_state = atomic_read(&jc->state);
1321 switch (old_state) {
1322 case UTH_JOIN_EXITED:
1324 *retval_loc = jc->retval;
1325 sched_ops->thread_exited(uth);
1326 kref_put(&jk->kref);
1328 case UTH_JOIN_DETACHED:
1329 panic("Uth %p has been detached, can't join!", uth);
1330 case UTH_JOIN_HAS_JOINER:
1331 panic("Uth %p has another pending joiner!", uth);
1333 assert(old_state == UTH_JOIN_JOINABLE);
1334 } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_HAS_JOINER));
1337 /* Bottom half of the join, in vcore context */
1338 static void __uth_join_cb(struct uthread *uth, void *arg)
1340 struct uth_join_kicker *jk = (struct uth_join_kicker*)arg;
1342 uthread_has_blocked(uth, UTH_EXT_BLK_MISC);
1343 /* After this, and after all threads join, we could be woken up. */
1344 kref_put(&jk->kref);
1347 static void kicker_release(struct kref *k)
1349 struct uth_join_kicker *jk = container_of(k, struct uth_join_kicker, kref);
1351 uthread_runnable(jk->joiner);
1354 void uthread_join_arr(struct uth_join_request reqs[], size_t nr_req)
1356 struct uth_join_kicker jk[1];
1358 jk->joiner = current_uthread;
1359 /* One ref for each target, another for *us*, which we drop in the yield
1360 * callback. As as soon as it is fully decreffed, our thread will be
1361 * restarted. We must block before that (in the yield callback). */
1362 kref_init(&jk->kref, kicker_release, nr_req + 1);
1363 for (int i = 0; i < nr_req; i++)
1364 join_one(reqs[i].uth, jk, reqs[i].retval_loc);
1365 uthread_yield(TRUE, __uth_join_cb, jk);
1368 /* Unlike POSIX, we don't bother with returning error codes. Anything that can
1369 * go wrong is so horrendous that you should crash (the specs say the behavior
1371 void uthread_join(struct uthread *uth, void **retval_loc)
1373 struct uth_join_request req[1];
1376 req->retval_loc = retval_loc;
1377 uthread_join_arr(req, 1);
1380 static void __uth_sched_yield_cb(struct uthread *uth, void *arg)
1382 uthread_has_blocked(uth, UTH_EXT_BLK_YIELD);
1383 uthread_runnable(uth);
1386 void uthread_sched_yield(void)
1388 if (!uth_2ls_is_multithreaded()) {
1389 /* We're an SCP with no other threads, so we want to yield to other
1390 * processes. For SCPs, this will yield to the OS/other procs. */
1391 syscall(SYS_proc_yield, TRUE);
1394 uthread_yield(TRUE, __uth_sched_yield_cb, NULL);
1397 struct uthread *uthread_self(void)
1399 return current_uthread;