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>
14 /* SCPs have a default 2LS that only manages thread 0. Any other 2LS, such as
15 * pthreads, should override sched_ops in its init code. */
16 extern struct schedule_ops thread0_2ls_ops;
17 struct schedule_ops *sched_ops = &thread0_2ls_ops;
19 __thread struct uthread *current_uthread = 0;
20 /* ev_q for all preempt messages (handled here to keep 2LSs from worrying
21 * extensively about the details. Will call out when necessary. */
22 static struct event_queue *preempt_ev_q;
25 #define UTH_TLSDESC_NOTLS (void*)(-1)
26 static inline bool __uthread_has_tls(struct uthread *uthread);
27 static int __uthread_allocate_tls(struct uthread *uthread);
28 static int __uthread_reinit_tls(struct uthread *uthread);
29 static void __uthread_free_tls(struct uthread *uthread);
30 static void __run_current_uthread_raw(void);
32 static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
34 static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
36 static void __ros_uth_syscall_blockon(struct syscall *sysc);
38 /* Helper, initializes a fresh uthread to be thread0. */
39 static void uthread_init_thread0(struct uthread *uthread)
42 /* Save a pointer to thread0's tls region (the glibc one) into its tcb */
43 uthread->tls_desc = get_tls_desc();
44 /* Save a pointer to the uthread in its own TLS */
45 current_uthread = uthread;
46 /* Thread is currently running (it is 'us') */
47 uthread->state = UT_RUNNING;
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 /* We might have a basic uthread already installed (from a prior call), so
73 * free it before installing the new one. */
75 free(current_uthread);
76 current_uthread = uthread;
77 /* We may not be an MCP at this point (and thus not really working with
78 * vcores), but there is still the notion of something vcore_context-like
79 * even when running as an SCP (i.e. its more of a scheduler_context than a
80 * vcore_context). Threfore we need to set __vcore_context to TRUE here to
81 * represent this (otherwise we will hit some asserts of not being in
82 * vcore_context when running in scheduler_context for the SCP. */
83 __vcore_context = TRUE;
84 end_safe_access_tls_vars();
85 set_tls_desc(uthread->tls_desc);
88 /* The real 2LS calls this to transition us into mcp mode. When it
89 * returns, you're in _M mode, still running thread0, on vcore0 */
90 void uthread_mcp_init()
92 /* Prevent this from happening more than once. */
93 init_once_racy(return);
95 /* Doing this after the init_once check, since we don't want to let the
96 * process/2LS change their mind about being an MCP or not once they have
99 * The reason is that once you set "MCP please" on, you could get
100 * interrupted into VC ctx, say for a syscall completion, and then make
101 * decisions based on the fact that you're an MCP (e.g., unblocking a
102 * uthread, asking for vcores, etc), even though you are not an MCP.
103 * Arguably, these things could happen for signals too, but all of this is
104 * less likely than if we have multiple threads.
106 * Also, we could just abort here, since they shouldn't be calling
107 * mcp_init() if they don't want to be an MCP. */
108 if (!parlib_wants_to_be_mcp)
111 /* Receive preemption events. Note that this merely tells the kernel how to
112 * send the messages, and does not necessarily provide storage space for the
113 * messages. What we're doing is saying that all PREEMPT and CHECK_MSGS
114 * events should be spammed to vcores that are running, preferring whatever
115 * the kernel thinks is appropriate. And IPI them.
117 * It is critical that these are either SPAM_PUB or INDIR|SPAM_INDIR, so
118 * that yielding vcores do not miss the preemption messages. */
119 register_ev_handler(EV_VCORE_PREEMPT, handle_vc_preempt, 0);
120 register_ev_handler(EV_CHECK_MSGS, handle_vc_indir, 0);
121 preempt_ev_q = get_eventq_slim(); /* small ev_q, mostly a vehicle for flags */
122 preempt_ev_q->ev_flags = EVENT_IPI | EVENT_SPAM_PUBLIC | EVENT_VCORE_APPRO |
123 EVENT_VCORE_MUST_RUN | EVENT_WAKEUP;
124 /* Tell the kernel to use the ev_q (it's settings) for the two types. Note
125 * that we still have two separate handlers. We just want the events
126 * delivered in the same way. If we ever want to have a big_event_q with
127 * INDIRs, we could consider using separate ones. */
128 register_kevent_q(preempt_ev_q, EV_VCORE_PREEMPT);
129 register_kevent_q(preempt_ev_q, EV_CHECK_MSGS);
130 printd("[user] registered %08p (flags %08p) for preempt messages\n",
131 preempt_ev_q, preempt_ev_q->ev_flags);
132 /* Get ourselves into _M mode. Could consider doing this elsewhere... */
136 /* The real 2LS calls this, passing in a uthread representing thread0. */
137 void uthread_2ls_init(struct uthread *uthread, struct schedule_ops *ops)
139 uthread_init_thread0(uthread);
140 /* We need to *atomically* change the current_uthread and the schedule_ops
141 * to the new 2LSs thread0 and ops, such that there is no moment when only
142 * one is changed and that we call a sched_ops. There are sources of
143 * implicit calls to sched_ops. Two big ones are sched_entry, called
144 * whenever we receive a notif (so we need to disable notifs), and
145 * syscall_blockon, called whenver we had a syscall that blocked (so we say
146 * tell the *uthread* that *it* is in vc ctx (TLS var).
148 * When disabling notifs, don't use a helper. We're changing
149 * current_uthread under the hood, which messes with the helpers. When
150 * setting __vcore_context, we're in thread0's TLS. Even when we change
151 * current_uthread, we're still in the *same* TLS. */
153 __vcore_context = TRUE;
155 /* Under the hood, this function will free any previously allocated uthread
156 * structs representing thread0 (e.g. the one set up by uthread_lib_init()
158 uthread_track_thread0(uthread);
161 __vcore_context = FALSE;
162 enable_notifs(0); /* will trigger a self_notif if we missed a notif */
165 /* Helper: tells the kernel our SCP is capable of going into vcore context on
166 * vcore 0. Pairs with k/s/process.c scp_is_vcctx_ready(). */
167 static void scp_vcctx_ready(void)
169 struct preempt_data *vcpd = vcpd_of(0);
171 /* the CAS is a bit overkill; keeping it around in case people use this
172 * code in other situations. */
174 old_flags = atomic_read(&vcpd->flags);
175 /* Spin if the kernel is mucking with the flags */
176 while (old_flags & VC_K_LOCK)
177 old_flags = atomic_read(&vcpd->flags);
178 } while (!atomic_cas(&vcpd->flags, old_flags,
179 old_flags & ~VC_SCP_NOVCCTX));
182 /* For both of these, VC ctx uses the usual TLS errno/errstr. Uthreads use
183 * their own storage. Since we're called after manage_thread0, we should always
184 * have current_uthread if we are not in vc ctx. */
185 static int *__ros_errno_loc(void)
187 if (in_vcore_context())
188 return __errno_location_tls();
190 return ¤t_uthread->err_no;
193 static char *__ros_errstr_loc(void)
195 if (in_vcore_context())
196 return __errstr_location_tls();
198 return current_uthread->err_str;
201 /* Sets up basic uthreading for when we are in _S mode and before we set up the
202 * 2LS. Some apps may not have a 2LS and thus never do the full
203 * vcore/2LS/uthread init. */
204 void __attribute__((constructor)) uthread_lib_init(void)
206 /* Use the thread0 sched's uth */
207 extern struct uthread *thread0_uth;
208 extern void thread0_lib_init(void);
211 /* Only run once, but make sure that vcore_lib_init() has run already. */
212 init_once_racy(return);
215 ret = posix_memalign((void**)&thread0_uth, __alignof__(struct uthread),
216 sizeof(struct uthread));
218 memset(thread0_uth, 0, sizeof(struct uthread)); /* aggressively 0 for bugs*/
219 /* Init the 2LS, which sets up current_uthread, before thread0 lib */
220 uthread_2ls_init(thread0_uth, &thread0_2ls_ops);
223 /* Change our blockon from glibc's internal one to the regular one, which
224 * uses vcore context and works for SCPs (with or without 2LS) and MCPs.
225 * Once we tell the kernel we are ready to utilize vcore context, we need
226 * our blocking syscalls to utilize it as well. */
227 ros_syscall_blockon = __ros_uth_syscall_blockon;
229 init_posix_signals();
230 /* Switch our errno/errstr functions to be uthread-aware. See glibc's
231 * errno.c for more info. */
232 ros_errno_loc = __ros_errno_loc;
233 ros_errstr_loc = __ros_errstr_loc;
234 register_ev_handler(EV_EVENT, handle_ev_ev, 0);
237 /* 2LSs shouldn't call uthread_vcore_entry directly */
238 void __attribute__((noreturn)) uthread_vcore_entry(void)
240 uint32_t vcoreid = vcore_id();
241 struct preempt_data *vcpd = vcpd_of(vcoreid);
242 /* Should always have notifications disabled when coming in here. */
243 assert(!notif_is_enabled(vcoreid));
244 assert(in_vcore_context());
245 /* If someone is stealing our uthread (from when we were preempted before),
246 * we can't touch our uthread. But we might be the last vcore around, so
247 * we'll handle preemption events (spammed to our public mbox).
249 * It's important that we only check/handle one message per loop, otherwise
250 * we could get stuck in a ping-pong scenario with a recoverer (maybe). */
251 while (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
252 /* Note we're handling INDIRs and other public messages while someone
253 * is stealing our uthread. Remember that those event handlers cannot
254 * touch cur_uth, as it is "vcore business". */
255 handle_one_mbox_msg(&vcpd->ev_mbox_public);
258 /* If we have a current uthread that is DONT_MIGRATE, pop it real quick and
259 * let it disable notifs (like it wants to). Other than dealing with
260 * preemption events (or other INDIRs), we shouldn't do anything in vc_ctx
261 * when we have a DONT_MIGRATE uthread. */
262 if (current_uthread && (current_uthread->flags & UTHREAD_DONT_MIGRATE))
263 __run_current_uthread_raw();
264 /* Check and see if we wanted ourselves to handle a remote VCPD mbox. Want
265 * to do this after we've handled STEALING and DONT_MIGRATE. */
266 try_handle_remote_mbox();
267 /* Otherwise, go about our usual vcore business (messages, etc). */
268 handle_events(vcoreid);
269 __check_preempt_pending(vcoreid);
270 assert(in_vcore_context()); /* double check, in case an event changed it */
271 sched_ops->sched_entry();
272 assert(0); /* 2LS sched_entry should never return */
275 /* Does the uthread initialization of a uthread that the caller created. Call
276 * this whenever you are "starting over" with a thread. */
277 void uthread_init(struct uthread *new_thread, struct uth_thread_attr *attr)
281 new_thread->state = UT_NOT_RUNNING;
282 /* Set the signal state. */
283 new_thread->sigstate.mask = current_uthread->sigstate.mask;
284 __sigemptyset(&new_thread->sigstate.pending);
285 new_thread->sigstate.data = NULL;
286 /* They should have zero'd the uthread. Let's check critical things: */
287 assert(!new_thread->flags && !new_thread->sysc);
288 /* the utf holds the GP context of the uthread (set by the 2LS earlier).
289 * There is no FP context to be restored yet. We only save the FPU when we
290 * were interrupted off a core. */
291 new_thread->flags |= UTHREAD_SAVED;
292 new_thread->notif_disabled_depth = 0;
293 if (attr && attr->want_tls) {
294 /* Get a TLS. If we already have one, reallocate/refresh it */
295 if (new_thread->tls_desc)
296 ret = __uthread_reinit_tls(new_thread);
298 ret = __uthread_allocate_tls(new_thread);
300 begin_access_tls_vars(new_thread->tls_desc);
301 current_uthread = new_thread;
302 /* ctypes stores locale info in TLS. we need this only once per TLS, so
303 * we don't have to do it here, but it is convenient since we already
304 * loaded the uthread's TLS. */
305 extern void __ctype_init(void);
307 end_access_tls_vars();
309 new_thread->tls_desc = UTH_TLSDESC_NOTLS;
313 /* This is a wrapper for the sched_ops thread_runnable, for use by functions
314 * outside the main 2LS. Do not put anything important in this, since the 2LSs
315 * internally call their sched op. This is to improve batch wakeups (barriers,
317 void uthread_runnable(struct uthread *uthread)
319 assert(sched_ops->thread_runnable);
320 sched_ops->thread_runnable(uthread);
323 /* Informs the 2LS that its thread blocked, and it is not under the control of
324 * the 2LS. This is for informational purposes, and some semantic meaning
325 * should be passed by flags (from uthread.h's UTH_EXT_BLK_xxx options).
326 * Eventually, whoever calls this will call uthread_runnable(), giving the
327 * thread back to the 2LS.
329 * If code outside the 2LS has blocked a thread (via uthread_yield) and ran its
330 * own callback/yield_func instead of some 2LS code, that callback needs to
333 * AKA: obviously_a_uthread_has_blocked_in_lincoln_park() */
334 void uthread_has_blocked(struct uthread *uthread, int flags)
336 assert(sched_ops->thread_has_blocked);
337 sched_ops->thread_has_blocked(uthread, flags);
340 /* Function indicating an external event has temporarily paused a uthread, but
341 * it is ok to resume it if possible. */
342 void uthread_paused(struct uthread *uthread)
344 /* Call out to the 2LS to let it know the uthread was paused for some
345 * reason, but it is ok to resume it now. */
346 assert(uthread->state == UT_NOT_RUNNING);
347 assert(sched_ops->thread_paused);
348 sched_ops->thread_paused(uthread);
351 /* Need to have this as a separate, non-inlined function since we clobber the
352 * stack pointer before calling it, and don't want the compiler to play games
354 static void __attribute__((noinline, noreturn))
355 __uthread_yield(void)
357 struct uthread *uthread = current_uthread;
358 assert(in_vcore_context());
359 assert(!notif_is_enabled(vcore_id()));
360 /* Note: we no longer care if the thread is exiting, the 2LS will call
361 * uthread_destroy() */
362 uthread->flags &= ~UTHREAD_DONT_MIGRATE;
363 uthread->state = UT_NOT_RUNNING;
364 /* Any locks that were held before the yield must be unlocked in the
365 * callback. That callback won't get a chance to update our disabled depth.
366 * This sets us up for the next time the uthread runs. */
367 uthread->notif_disabled_depth = 0;
368 /* Do whatever the yielder wanted us to do */
369 assert(uthread->yield_func);
370 uthread->yield_func(uthread, uthread->yield_arg);
371 /* Make sure you do not touch uthread after that func call */
372 /* Leave the current vcore completely */
373 /* TODO: if the yield func can return a failure, we can abort the yield */
374 current_uthread = NULL;
375 /* Go back to the entry point, where we can handle notifications or
376 * reschedule someone. */
377 uthread_vcore_entry();
380 /* Calling thread yields for some reason. Set 'save_state' if you want to ever
381 * run the thread again. Once in vcore context in __uthread_yield, yield_func
382 * will get called with the uthread and yield_arg passed to it. This way, you
383 * can do whatever you want when you get into vcore context, which can be
384 * thread_blockon_sysc, unlocking mutexes, joining, whatever.
386 * If you do *not* pass a 2LS sched op or other 2LS function as yield_func,
387 * then you must also call uthread_has_blocked(flags), which will let the 2LS
388 * know a thread blocked beyond its control (and why). */
389 void uthread_yield(bool save_state, void (*yield_func)(struct uthread*, void*),
392 struct uthread *uthread = current_uthread;
393 volatile bool yielding = TRUE; /* signal to short circuit when restarting */
394 assert(!in_vcore_context());
395 assert(uthread->state == UT_RUNNING);
396 /* Pass info to ourselves across the uth_yield -> __uth_yield transition. */
397 uthread->yield_func = yield_func;
398 uthread->yield_arg = yield_arg;
399 /* Don't migrate this thread to another vcore, since it depends on being on
400 * the same vcore throughout (once it disables notifs). The race is that we
401 * read vcoreid, then get interrupted / migrated before disabling notifs. */
402 uthread->flags |= UTHREAD_DONT_MIGRATE;
403 cmb(); /* don't let DONT_MIGRATE write pass the vcoreid read */
404 uint32_t vcoreid = vcore_id();
405 printd("[U] Uthread %08p is yielding on vcore %d\n", uthread, vcoreid);
406 struct preempt_data *vcpd = vcpd_of(vcoreid);
407 /* once we do this, we might miss a notif_pending, so we need to enter vcore
408 * entry later. Need to disable notifs so we don't get in weird loops with
409 * save_user_ctx() and pop_user_ctx(). */
410 disable_notifs(vcoreid);
411 /* take the current state and save it into t->utf when this pthread
412 * restarts, it will continue from right after this, see yielding is false,
413 * and short ciruit the function. Don't do this if we're dying. */
415 /* Need to signal this before we actually save, since save_user_ctx
416 * returns() twice (once now, once when woken up) */
417 uthread->flags |= UTHREAD_SAVED;
418 save_user_ctx(&uthread->u_ctx);
420 cmb(); /* Force reread of yielding. Technically save_user_ctx() suffices*/
421 /* Restart path doesn't matter if we're dying */
423 goto yield_return_path;
424 /* From here on down is only executed on the save path (not the wake up) */
425 yielding = FALSE; /* for when it starts back up */
426 /* TODO: remove this when all arches support SW contexts */
427 if (save_state && (uthread->u_ctx.type != ROS_SW_CTX)) {
428 save_fp_state(&uthread->as);
429 uthread->flags |= UTHREAD_FPSAVED;
431 /* Change to the transition context (both TLS (if applicable) and stack). */
432 if (__uthread_has_tls(uthread)) {
433 set_tls_desc(get_vcpd_tls_desc(vcoreid));
434 begin_safe_access_tls_vars();
435 assert(current_uthread == uthread);
436 /* If this assert fails, see the note in uthread_track_thread0 */
437 assert(in_vcore_context());
438 end_safe_access_tls_vars();
440 /* Since uthreads and vcores share TLS (it's always the vcore's TLS, the
441 * uthread one just bootstraps from it), we need to change our state at
442 * boundaries between the two 'contexts' */
443 __vcore_context = TRUE;
445 /* After this, make sure you don't use local variables. Also, make sure the
446 * compiler doesn't use them without telling you (TODO).
448 * In each arch's set_stack_pointer, make sure you subtract off as much room
449 * as you need to any local vars that might be pushed before calling the
450 * next function, or for whatever other reason the compiler/hardware might
451 * walk up the stack a bit when calling a noreturn function. */
452 set_stack_pointer((void*)vcpd->vcore_stack);
453 /* Finish exiting in another function. */
455 /* Should never get here */
457 /* Will jump here when the uthread's trapframe is restarted/popped. */
459 printd("[U] Uthread %08p returning from a yield!\n", uthread);
462 /* We explicitly don't support sleep(), since old callers of it have
463 * expectations of being woken up by signal handlers. If we need that, we can
464 * build it in to sleep() later. If you just want to sleep for a while, call
466 void uthread_sleep(unsigned int seconds)
468 sys_block(seconds * 1000000); /* usec sleep */
470 /* If we are providing a dummy sleep function, might as well provide the more
471 * accurate/useful one. */
472 void uthread_usleep(unsigned int usecs)
474 sys_block(usecs); /* usec sleep */
477 /* Cleans up the uthread (the stuff we did in uthread_init()). If you want to
478 * destroy a currently running uthread, you'll want something like
479 * pthread_exit(), which yields, and calls this from its sched_ops yield. */
480 void uthread_cleanup(struct uthread *uthread)
482 printd("[U] thread %08p on vcore %d is DYING!\n", uthread, vcore_id());
483 /* we alloc and manage the TLS, so lets get rid of it, except for thread0.
484 * glibc owns it. might need to keep it around for a full exit() */
485 if (__uthread_has_tls(uthread) && !(uthread->flags & UTHREAD_IS_THREAD0))
486 __uthread_free_tls(uthread);
489 static void __ros_syscall_spinon(struct syscall *sysc)
491 while (!(atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS)))
495 static void __ros_vcore_ctx_syscall_blockon(struct syscall *sysc)
497 if (in_multi_mode()) {
498 /* MCP vcore's don't know what to do yet, so we have to spin */
499 __ros_syscall_spinon(sysc);
501 /* SCPs can use the early blockon, which acts like VC ctx. */
502 __ros_early_syscall_blockon(sysc);
506 /* Attempts to block on sysc, returning when it is done or progress has been
507 * made. Made for initialized processes using uthreads. */
508 static void __ros_uth_syscall_blockon(struct syscall *sysc)
510 if (in_vcore_context()) {
511 __ros_vcore_ctx_syscall_blockon(sysc);
514 /* At this point, we know we're a uthread. If we're a DONT_MIGRATE uthread,
515 * then it's disabled notifs and is basically in vcore context, enough so
516 * that it can't call into the 2LS. */
517 assert(current_uthread);
518 if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
519 assert(!notif_is_enabled(vcore_id())); /* catch bugs */
520 /* if we had a notif_disabled_depth, then we should also have
521 * DONT_MIGRATE set */
522 __ros_vcore_ctx_syscall_blockon(sysc);
525 assert(!current_uthread->notif_disabled_depth);
526 /* double check before doing all this crap */
527 if (atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS))
529 /* for both debugging and syscall cancelling */
530 current_uthread->sysc = sysc;
531 /* yield, calling 2ls-blockon(cur_uth, sysc) on the other side */
532 uthread_yield(TRUE, sched_ops->thread_blockon_sysc, sysc);
535 /* Simply sets current uthread to be whatever the value of uthread is. This
536 * can be called from outside of sched_entry() to highjack the current context,
537 * and make sure that the new uthread struct is used to store this context upon
538 * yielding, etc. USE WITH EXTREME CAUTION! */
539 void highjack_current_uthread(struct uthread *uthread)
541 uint32_t vcoreid = vcore_id();
542 assert(uthread != current_uthread);
543 current_uthread->state = UT_NOT_RUNNING;
544 uthread->state = UT_RUNNING;
545 /* Make sure the vcore is tracking the new uthread struct */
546 if (__uthread_has_tls(current_uthread))
547 vcore_set_tls_var(current_uthread, uthread);
549 current_uthread = uthread;
550 /* and make sure we are using the correct TLS for the new uthread */
551 if (__uthread_has_tls(uthread)) {
552 assert(uthread->tls_desc);
553 set_tls_desc(uthread->tls_desc);
554 begin_safe_access_tls_vars();
555 __vcoreid = vcoreid; /* setting the uthread's TLS var */
556 end_safe_access_tls_vars();
560 /* Helper: loads a uthread's TLS on this vcore, if applicable. If our uthreads
561 * do not have their own TLS, we simply switch the __vc_ctx, signalling that the
562 * context running here is (soon to be) a uthread. */
563 static void set_uthread_tls(struct uthread *uthread, uint32_t vcoreid)
565 if (__uthread_has_tls(uthread)) {
566 set_tls_desc(uthread->tls_desc);
567 begin_safe_access_tls_vars();
568 __vcoreid = vcoreid; /* setting the uthread's TLS var */
569 end_safe_access_tls_vars();
571 __vcore_context = FALSE;
575 /* Attempts to handle a fault for uth, etc */
576 static void handle_refl_fault(struct uthread *uth, struct user_context *ctx)
578 sched_ops->thread_refl_fault(uth, __arch_refl_get_nr(ctx),
579 __arch_refl_get_err(ctx),
580 __arch_refl_get_aux(ctx));
583 /* Run the thread that was current_uthread, from a previous run. Should be
584 * called only when the uthread already was running, and we were interrupted by
585 * the kernel (event, etc). Do not call this to run a fresh uthread, even if
586 * you've set it to be current. */
587 void run_current_uthread(void)
590 uint32_t vcoreid = vcore_id();
591 struct preempt_data *vcpd = vcpd_of(vcoreid);
592 assert(current_uthread);
593 assert(current_uthread->state == UT_RUNNING);
594 /* Uth was already running, should not have been saved */
595 assert(!(current_uthread->flags & UTHREAD_SAVED));
596 assert(!(current_uthread->flags & UTHREAD_FPSAVED));
597 printd("[U] Vcore %d is restarting uthread %08p\n", vcoreid,
599 if (has_refl_fault(&vcpd->uthread_ctx)) {
600 clear_refl_fault(&vcpd->uthread_ctx);
601 /* we preemptively copy out and make non-running, so that there is a
602 * consistent state for the handler. it can then block the uth or
604 uth = current_uthread;
606 uth->u_ctx = vcpd->uthread_ctx;
607 save_fp_state(&uth->as);
608 uth->state = UT_NOT_RUNNING;
609 uth->flags |= UTHREAD_SAVED | UTHREAD_FPSAVED;
610 handle_refl_fault(uth, &vcpd->uthread_ctx);
611 /* we abort no matter what. up to the 2LS to reschedule the thread */
612 set_stack_pointer((void*)vcpd->vcore_stack);
615 /* Go ahead and start the uthread */
616 set_uthread_tls(current_uthread, vcoreid);
617 /* Run, using the TF in the VCPD. FP state should already be loaded */
618 pop_user_ctx(&vcpd->uthread_ctx, vcoreid);
622 /* Launches the uthread on the vcore. Don't call this on current_uthread.
624 * In previous versions of this, we used to check for events after setting
625 * current_uthread. That is super-dangerous. handle_events() doesn't always
626 * return (which we used to handle), and it may also clear current_uthread. We
627 * needed to save uthread in current_uthread, in case we didn't return. If we
628 * didn't return, the vcore started over at vcore_entry, with current set. When
629 * this happens, we never actually had loaded cur_uth's FP and GP onto the core,
630 * so cur_uth fails. Check out 4602599be for more info.
632 * Ultimately, handling events again in these 'popping helpers' isn't even
633 * necessary (we only must do it once for an entire time in VC ctx, and in
634 * loops), and might have been optimizing a rare event at a cost in both
635 * instructions and complexity. */
636 void run_uthread(struct uthread *uthread)
638 uint32_t vcoreid = vcore_id();
639 struct preempt_data *vcpd = vcpd_of(vcoreid);
640 assert(!current_uthread);
641 assert(uthread->state == UT_NOT_RUNNING);
642 assert(uthread->flags & UTHREAD_SAVED);
643 /* For HW/VM CTX, FPSAVED must match UTH SAVE (and both be on here). For
644 * SW, FP should never be saved. */
645 switch (uthread->u_ctx.type) {
648 assert(uthread->flags & UTHREAD_FPSAVED);
651 assert(!(uthread->flags & UTHREAD_FPSAVED));
654 if (has_refl_fault(&uthread->u_ctx)) {
655 clear_refl_fault(&uthread->u_ctx);
656 handle_refl_fault(uthread, &uthread->u_ctx);
657 /* we abort no matter what. up to the 2LS to reschedule the thread */
658 set_stack_pointer((void*)vcpd->vcore_stack);
661 uthread->state = UT_RUNNING;
662 /* Save a ptr to the uthread we'll run in the transition context's TLS */
663 current_uthread = uthread;
664 if (uthread->flags & UTHREAD_FPSAVED) {
665 uthread->flags &= ~UTHREAD_FPSAVED;
666 restore_fp_state(&uthread->as);
668 set_uthread_tls(uthread, vcoreid);
669 /* the uth's context will soon be in the cpu (or VCPD), no longer saved */
670 uthread->flags &= ~UTHREAD_SAVED;
671 pop_user_ctx(&uthread->u_ctx, vcoreid);
675 /* Runs the uthread, but doesn't care about notif pending. Only call this when
676 * there was a DONT_MIGRATE uthread, or a similar situation where the uthread
677 * will check messages soon (like calling enable_notifs()). */
678 static void __run_current_uthread_raw(void)
680 uint32_t vcoreid = vcore_id();
681 struct preempt_data *vcpd = vcpd_of(vcoreid);
682 if (has_refl_fault(&vcpd->uthread_ctx)) {
683 printf("Raw / DONT_MIGRATE uthread took a fault, exiting.\n");
686 /* We need to manually say we have a notif pending, so we eventually return
687 * to vcore context. (note the kernel turned it off for us) */
688 vcpd->notif_pending = TRUE;
689 assert(!(current_uthread->flags & UTHREAD_SAVED));
690 assert(!(current_uthread->flags & UTHREAD_FPSAVED));
691 set_uthread_tls(current_uthread, vcoreid);
692 pop_user_ctx_raw(&vcpd->uthread_ctx, vcoreid);
696 /* Copies the uthread trapframe and silly state from the vcpd to the uthread,
697 * subject to the uthread's flags and whatnot.
699 * For example: The uthread state might still be in the uthread struct. Imagine
700 * the 2LS decides to run a new uthread and sets it up as current, but doesn't
701 * actually run it yet. The 2LS happened to voluntarily give up the VC (due to
702 * some other event) and then wanted to copy out the thread. This is pretty
703 * rare - the normal case is when an IRQ of some sort hit the core and the
704 * kernel copied the running state into VCPD.
706 * The FP state could also be in VCPD (e.g. preemption being handled remotely),
707 * it could be in the uthread struct (e.g. hasn't started running yet) or even
708 * in the FPU (e.g. took an IRQ/notif and we're handling the preemption of
711 * There are some cases where we'll have a uthread SW ctx that needs to be
712 * copied out: uth syscalls, notif happens, and the core comes back from the
713 * kernel in VC ctx. VC ctx calls copy_out (response to preempt_pending or done
714 * while handling a preemption). */
715 static void copyout_uthread(struct preempt_data *vcpd, struct uthread *uthread,
719 if (uthread->flags & UTHREAD_SAVED) {
720 /* I don't know of scenarios where HW/VM ctxs FP state differs from GP*/
721 switch (uthread->u_ctx.type) {
724 assert(uthread->flags & UTHREAD_FPSAVED);
729 /* If we're copying GP state, it must be in VCPD */
730 uthread->u_ctx = vcpd->uthread_ctx;
731 uthread->flags |= UTHREAD_SAVED;
732 printd("VC %d copying out uthread %08p\n", vcore_id(), uthread);
733 /* Software contexts do not need FP state, nor should we think it has any */
734 if (uthread->u_ctx.type == ROS_SW_CTX) {
735 assert(!(uthread->flags & UTHREAD_FPSAVED));
738 /* HW contexts also should not have it saved either. Should be either in
739 * the VCPD or the FPU. Yes, this is the same assert. */
740 assert(!(uthread->flags & UTHREAD_FPSAVED));
741 /* When we're dealing with the uthread running on our own vcore, the FP
742 * state is in the actual FPU, not VCPD. It might also be in VCPD, but it
743 * will always be in the FPU (the kernel maintains this for us, in the event
744 * we were preempted since the uthread was last running). */
746 save_fp_state(&uthread->as);
748 uthread->as = vcpd->preempt_anc;
749 uthread->flags |= UTHREAD_FPSAVED;
752 /* Helper, packages up and pauses a uthread that was running on vcoreid. Used
753 * by preemption handling (and detection) so far. Careful using this, esp if
754 * it is on another vcore (need to make sure it's not running!). If you are
755 * using it on the local vcore, set vcore_local = TRUE. */
756 static void __uthread_pause(struct preempt_data *vcpd, struct uthread *uthread,
759 assert(!(uthread->flags & UTHREAD_DONT_MIGRATE));
760 copyout_uthread(vcpd, uthread, vcore_local);
761 uthread->state = UT_NOT_RUNNING;
762 /* Call out to the 2LS to package up its uthread */
763 assert(sched_ops->thread_paused);
764 sched_ops->thread_paused(uthread);
767 /* Deals with a pending preemption (checks, responds). If the 2LS registered a
768 * function, it will get run. Returns true if you got preempted. Called
769 * 'check' instead of 'handle', since this isn't an event handler. It's the "Oh
770 * shit a preempt is on its way ASAP".
772 * Be careful calling this: you might not return, so don't call it if you can't
773 * handle that. If you are calling this from an event handler, you'll need to
774 * do things like ev_might_not_return(). If the event can via an INDIR ev_q,
775 * that ev_q must be a NOTHROTTLE.
777 * Finally, don't call this from a place that might have a DONT_MIGRATE
778 * cur_uth. This should be safe for most 2LS code. */
779 bool __check_preempt_pending(uint32_t vcoreid)
782 assert(in_vcore_context());
783 if (__preempt_is_pending(vcoreid)) {
785 if (sched_ops->preempt_pending)
786 sched_ops->preempt_pending();
787 /* If we still have a cur_uth, copy it out and hand it back to the 2LS
788 * before yielding. */
789 if (current_uthread) {
790 __uthread_pause(vcpd_of(vcoreid), current_uthread, TRUE);
793 /* vcore_yield tries to yield, and will pop back up if this was a spurious
794 * preempt_pending or if it handled an event. For now, we'll just keep
795 * trying to yield so long as a preempt is coming in. Eventually, we'll
796 * handle all of our events and yield, or else the preemption will hit
797 * and someone will recover us (at which point we'll break out of the
799 while (__procinfo.vcoremap[vcoreid].preempt_pending) {
807 /* Helper: This is a safe way for code to disable notifs if it *might* be called
808 * from uthread context (like from a notif_safe lock). Pair this with
809 * uth_enable_notifs() unless you know what you're doing. */
810 void uth_disable_notifs(void)
812 if (!in_vcore_context()) {
813 assert(current_uthread);
814 if (current_uthread->notif_disabled_depth++)
816 current_uthread->flags |= UTHREAD_DONT_MIGRATE;
817 cmb(); /* don't issue the flag write before the vcore_id() read */
818 disable_notifs(vcore_id());
821 assert(!notif_is_enabled(vcore_id()));
824 /* Helper: Pair this with uth_disable_notifs(). */
825 void uth_enable_notifs(void)
827 if (!in_vcore_context()) {
828 assert(current_uthread);
829 if (--current_uthread->notif_disabled_depth)
831 current_uthread->flags &= ~UTHREAD_DONT_MIGRATE;
832 cmb(); /* don't enable before ~DONT_MIGRATE */
833 enable_notifs(vcore_id());
837 /* Helper: returns TRUE if it succeeded in starting the uth stealing process. */
838 static bool start_uth_stealing(struct preempt_data *vcpd)
842 old_flags = atomic_read(&vcpd->flags);
843 /* Spin if the kernel is mucking with the flags */
844 while (old_flags & VC_K_LOCK)
845 old_flags = atomic_read(&vcpd->flags);
846 /* Someone else is stealing, we failed */
847 if (old_flags & VC_UTHREAD_STEALING)
849 } while (!atomic_cas(&vcpd->flags, old_flags,
850 old_flags | VC_UTHREAD_STEALING));
854 /* Helper: pairs with stop_uth_stealing */
855 static void stop_uth_stealing(struct preempt_data *vcpd)
859 old_flags = atomic_read(&vcpd->flags);
860 assert(old_flags & VC_UTHREAD_STEALING); /* sanity */
861 while (old_flags & VC_K_LOCK)
862 old_flags = atomic_read(&vcpd->flags);
863 } while (!atomic_cas(&vcpd->flags, old_flags,
864 old_flags & ~VC_UTHREAD_STEALING));
867 /* Handles INDIRS for another core (the public mbox). We synchronize with the
868 * kernel (__set_curtf_to_vcoreid). */
869 static void handle_indirs(uint32_t rem_vcoreid)
872 struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
873 /* Turn off their message reception if they are still preempted. If they
874 * are no longer preempted, we do nothing - they will handle their own
875 * messages. Turning off CAN_RCV will route this vcore's messages to
876 * fallback vcores (if those messages were 'spammed'). */
878 old_flags = atomic_read(&rem_vcpd->flags);
879 while (old_flags & VC_K_LOCK)
880 old_flags = atomic_read(&rem_vcpd->flags);
881 if (!(old_flags & VC_PREEMPTED))
883 } while (!atomic_cas(&rem_vcpd->flags, old_flags,
884 old_flags & ~VC_CAN_RCV_MSG));
885 wrmb(); /* don't let the CAN_RCV write pass reads of the mbox status */
886 /* handle all INDIRs of the remote vcore */
887 handle_vcpd_mbox(rem_vcoreid);
890 /* Helper. Will ensure a good attempt at changing vcores, meaning we try again
891 * if we failed for some reason other than the vcore was already running. */
892 static void __change_vcore(uint32_t rem_vcoreid, bool enable_my_notif)
894 /* okay to do a normal spin/relax here, even though we are in vcore
896 while (-EAGAIN == sys_change_vcore(rem_vcoreid, enable_my_notif))
900 /* Helper, used in preemption recovery. When you can freely leave vcore
901 * context and need to change to another vcore, call this. vcpd is the caller,
902 * rem_vcoreid is the remote vcore. This will try to package up your uthread.
903 * It may return, either because the other core already started up (someone else
904 * got it), or in some very rare cases where we had to stay in our vcore
906 static void change_to_vcore(struct preempt_data *vcpd, uint32_t rem_vcoreid)
908 bool were_handling_remotes;
909 /* Unlikely, but if we have no uthread we can just change. This is the
910 * check, sync, then really check pattern: we can only really be sure about
911 * current_uthread after we check STEALING. */
912 if (!current_uthread) {
913 /* there might be an issue with doing this while someone is recovering.
914 * once they 0'd it, we should be good to yield. just a bit dangerous.
916 were_handling_remotes = ev_might_not_return();
917 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
918 goto out_we_returned;
920 /* Note that the reason we need to check STEALING is because we can get into
921 * vcore context and slip past that check in vcore_entry when we are
922 * handling a preemption message. Anytime preemption recovery cares about
923 * the calling vcore's cur_uth, it needs to be careful about STEALING. But
924 * it is safe to do the check up above (if it's 0, it won't concurrently
927 * STEALING might be turned on at any time. Whoever turns it on will do
928 * nothing if we are online or were in vc_ctx. So if it is on, we can't
929 * touch current_uthread til it is turned off (not sure what state they saw
930 * us in). We could spin here til they unset STEALING (since they will
931 * soon), but there is a chance they were preempted, so we need to make
932 * progress by doing a sys_change_vcore(). */
933 /* Crap, someone is stealing (unlikely). All we can do is change. */
934 if (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
935 __change_vcore(rem_vcoreid, FALSE); /* returns on success */
939 /* Need to recheck, in case someone stole it and finished before we checked
940 * VC_UTHREAD_STEALING. */
941 if (!current_uthread) {
942 were_handling_remotes = ev_might_not_return();
943 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
944 goto out_we_returned;
946 /* Need to make sure we don't have a DONT_MIGRATE (very rare, someone would
947 * have to steal from us to get us to handle a preempt message, and then had
948 * to finish stealing (and fail) fast enough for us to miss the previous
950 if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
951 __change_vcore(rem_vcoreid, FALSE); /* returns on success */
954 /* Now save our uthread and restart them */
955 assert(current_uthread);
956 __uthread_pause(vcpd, current_uthread, TRUE);
958 were_handling_remotes = ev_might_not_return();
959 __change_vcore(rem_vcoreid, TRUE); /* noreturn on success */
960 /* Fall-through to out_we_returned */
962 ev_we_returned(were_handling_remotes);
965 /* This handles a preemption message. When this is done, either we recovered,
966 * or recovery *for our message* isn't needed. */
967 static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
970 uint32_t vcoreid = vcore_id();
971 struct preempt_data *vcpd = vcpd_of(vcoreid);
972 uint32_t rem_vcoreid = ev_msg->ev_arg2;
973 struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
974 struct uthread *uthread_to_steal = 0;
975 struct uthread **rem_cur_uth;
976 bool cant_migrate = FALSE;
978 assert(in_vcore_context());
979 /* Just drop messages about ourselves. They are old. If we happen to be
980 * getting preempted right now, there's another message out there about
982 if (rem_vcoreid == vcoreid)
984 printd("Vcore %d was preempted (i'm %d), it's flags %08p!\n",
985 ev_msg->ev_arg2, vcoreid, rem_vcpd->flags);
986 /* Spin til the kernel is done with flags. This is how we avoid handling
987 * the preempt message before the preemption. */
988 while (atomic_read(&rem_vcpd->flags) & VC_K_LOCK)
990 /* If they aren't preempted anymore, just return (optimization). */
991 if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
993 /* At this point, we need to try to recover */
994 /* This case handles when the remote core was in vcore context */
995 if (rem_vcpd->notif_disabled) {
996 printd("VC %d recovering %d, notifs were disabled\n", vcoreid,
998 change_to_vcore(vcpd, rem_vcoreid);
999 return; /* in case it returns. we've done our job recovering */
1001 /* So now it looks like they were not in vcore context. We want to steal
1002 * the uthread. Set stealing, then doublecheck everything. If stealing
1003 * fails, someone else is stealing and we can just leave. That other vcore
1004 * who is stealing will check the VCPD/INDIRs when it is done. */
1005 if (!start_uth_stealing(rem_vcpd))
1007 /* Now we're stealing. Double check everything. A change in preempt status
1008 * or notif_disable status means the vcore has since restarted. The vcore
1009 * may or may not have started after we set STEALING. If it didn't, we'll
1010 * need to bail out (but still check messages, since above we assumed the
1011 * uthread stealer handles the VCPD/INDIRs). Since the vcore is running, we
1012 * don't need to worry about handling the message any further. Future
1013 * preemptions will generate another message, so we can ignore getting the
1014 * uthread or anything like that. */
1015 printd("VC %d recovering %d, trying to steal uthread\n", vcoreid,
1017 if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
1019 /* Might be preempted twice quickly, and the second time had notifs
1022 * Also note that the second preemption event had another
1023 * message sent, which either we or someone else will deal with. And also,
1024 * we don't need to worry about how we are stealing still and plan to
1025 * abort. If another vcore handles that second preemption message, either
1026 * the original vcore is in vc ctx or not. If so, we bail out and the
1027 * second preemption handling needs to change_to. If not, we aren't
1028 * bailing out, and we'll handle the preemption as normal, and the second
1029 * handler will bail when it fails to steal. */
1030 if (rem_vcpd->notif_disabled)
1032 /* At this point, we're clear to try and steal the uthread. We used to
1033 * switch to their TLS to steal the uthread, but we can access their
1034 * current_uthread directly. */
1035 rem_cur_uth = get_tlsvar_linaddr(rem_vcoreid, current_uthread);
1036 uthread_to_steal = *rem_cur_uth;
1037 if (uthread_to_steal) {
1038 /* Extremely rare: they have a uthread, but it can't migrate. So we'll
1039 * need to change to them. */
1040 if (uthread_to_steal->flags & UTHREAD_DONT_MIGRATE) {
1041 printd("VC %d recovering %d, can't migrate uthread!\n", vcoreid,
1043 stop_uth_stealing(rem_vcpd);
1044 change_to_vcore(vcpd, rem_vcoreid);
1045 return; /* in case it returns. we've done our job recovering */
1048 /* we're clear to steal it */
1049 printd("VC %d recovering %d, uthread %08p stolen\n", vcoreid,
1050 rem_vcoreid, uthread_to_steal);
1051 __uthread_pause(rem_vcpd, uthread_to_steal, FALSE);
1052 /* can't let the cur_uth = 0 write and any writes from __uth_pause()
1053 * to pass stop_uth_stealing. */
1059 stop_uth_stealing(rem_vcpd);
1060 handle_indirs(rem_vcoreid);
1063 /* This handles a "check indirs" message. When this is done, either we checked
1064 * their indirs, or the vcore restarted enough so that checking them is
1065 * unnecessary. If that happens and they got preempted quickly, then another
1066 * preempt/check_indirs was sent out. */
1067 static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
1070 uint32_t vcoreid = vcore_id();
1071 uint32_t rem_vcoreid = ev_msg->ev_arg2;
1073 if (rem_vcoreid == vcoreid)
1075 handle_indirs(rem_vcoreid);
1078 static inline bool __uthread_has_tls(struct uthread *uthread)
1080 return uthread->tls_desc != UTH_TLSDESC_NOTLS;
1084 static int __uthread_allocate_tls(struct uthread *uthread)
1086 assert(!uthread->tls_desc);
1087 uthread->tls_desc = allocate_tls();
1088 if (!uthread->tls_desc) {
1095 static int __uthread_reinit_tls(struct uthread *uthread)
1097 uthread->tls_desc = reinit_tls(uthread->tls_desc);
1098 if (!uthread->tls_desc) {
1105 static void __uthread_free_tls(struct uthread *uthread)
1107 free_tls(uthread->tls_desc);
1108 uthread->tls_desc = NULL;