akaros/user/parlib/uthread.c
<<
>>
Prefs
   1/* Copyright (c) 2011-2014 The Regents of the University of California
   2 * Barret Rhoden <brho@cs.berkeley.edu>
   3 * See LICENSE for details. */
   4
   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>
  11#include <stdlib.h>
  12#include <parlib/assert.h>
  13#include <parlib/stdio.h>
  14#include <parlib/arch/trap.h>
  15#include <parlib/ros_debug.h>
  16
  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. */
  20static struct event_queue *preempt_ev_q;
  21
  22/* Helpers: */
  23#define UTH_TLSDESC_NOTLS (void*)(-1)
  24static inline bool __uthread_has_tls(struct uthread *uthread);
  25static int __uthread_allocate_tls(struct uthread *uthread);
  26static int __uthread_reinit_tls(struct uthread *uthread);
  27static void __uthread_free_tls(struct uthread *uthread);
  28static void __run_current_uthread_raw(void);
  29
  30static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
  31                              void *data);
  32static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
  33                            void *data);
  34static void __ros_uth_syscall_blockon(struct syscall *sysc);
  35
  36/* Helper, initializes a fresh uthread to be thread0. */
  37static void uthread_init_thread0(struct uthread *uthread)
  38{
  39        assert(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        /* sig alt stack pointer */
  51        uthread->sigstate.sigalt_stacktop = 0;
  52        __sigemptyset(&uthread->sigstate.pending);
  53        uthread->sigstate.data = NULL;
  54        /* utf/as doesn't represent the state of the uthread (we are running) */
  55        uthread->flags &= ~(UTHREAD_SAVED | UTHREAD_FPSAVED);
  56        /* need to track thread0 for TLS deallocation */
  57        uthread->flags |= UTHREAD_IS_THREAD0;
  58        uthread->notif_disabled_depth = 0;
  59        /* setting the uthread's TLS var.  this is idempotent for SCPs (us) */
  60        __vcoreid = 0;
  61}
  62
  63/* Helper, makes VC ctx tracks uthread as its current_uthread in its TLS.
  64 *
  65 * Whether or not uthreads have TLS, thread0 has TLS, given to it by glibc.
  66 * This TLS will get set whenever we use thread0, regardless of whether or not
  67 * we use TLS for uthreads in general.  glibc cares about this TLS and will use
  68 * it at exit.  We can't simply use that TLS for VC0 either, since we don't know
  69 * where thread0 will be running when the program ends. */
  70static void uthread_track_thread0(struct uthread *uthread)
  71{
  72        set_tls_desc(get_vcpd_tls_desc(0));
  73        begin_safe_access_tls_vars();
  74        current_uthread = uthread;
  75        __vcore_context = TRUE;
  76        end_safe_access_tls_vars();
  77        set_tls_desc(uthread->tls_desc);
  78}
  79
  80/* The real 2LS calls this to transition us into mcp mode.  When it
  81 * returns, you're in _M mode, still running thread0, on vcore0 */
  82void uthread_mcp_init()
  83{
  84        /* Prevent this from happening more than once. */
  85        parlib_init_once_racy(return);
  86
  87        /* Doing this after the init_once check, since we don't want to let the
  88         * process/2LS change their mind about being an MCP or not once they
  89         * have multiple threads.
  90         *
  91         * The reason is that once you set "MCP please" on, you could get
  92         * interrupted into VC ctx, say for a syscall completion, and then make
  93         * decisions based on the fact that you're an MCP (e.g., unblocking a
  94         * uthread, asking for vcores, etc), even though you are not an MCP.
  95         * Arguably, these things could happen for signals too, but all of this
  96         * is less likely than if we have multiple threads.
  97         *
  98         * Also, we could just abort here, since they shouldn't be calling
  99         * mcp_init() if they don't want to be an MCP. */
 100        if (!parlib_wants_to_be_mcp)
 101                return;
 102
 103        /* Receive preemption events.  Note that this merely tells the kernel
 104         * how to send the messages, and does not necessarily provide storage
 105         * space for the messages.  What we're doing is saying that all PREEMPT
 106         * and CHECK_MSGS events should be spammed to vcores that are running,
 107         * preferring whatever the kernel thinks is appropriate.  And IPI them.
 108         *
 109         * It is critical that these are either SPAM_PUB or INDIR|SPAM_INDIR, so
 110         * that yielding vcores do not miss the preemption messages. */
 111        register_ev_handler(EV_VCORE_PREEMPT, handle_vc_preempt, 0);
 112        register_ev_handler(EV_CHECK_MSGS, handle_vc_indir, 0);
 113        /* small ev_q, mostly a vehicle for flags */
 114        preempt_ev_q = get_eventq_slim();
 115        preempt_ev_q->ev_flags = EVENT_IPI | EVENT_SPAM_PUBLIC |
 116                                 EVENT_VCORE_APPRO | EVENT_VCORE_MUST_RUN |
 117                                 EVENT_WAKEUP;
 118        /* Tell the kernel to use the ev_q (it's settings) for the two types.
 119         * Note that we still have two separate handlers.  We just want the
 120         * events delivered in the same way.  If we ever want to have a
 121         * big_event_q with INDIRs, we could consider using separate ones. */
 122        register_kevent_q(preempt_ev_q, EV_VCORE_PREEMPT);
 123        register_kevent_q(preempt_ev_q, EV_CHECK_MSGS);
 124        printd("[user] registered %08p (flags %08p) for preempt messages\n",
 125               preempt_ev_q, preempt_ev_q->ev_flags);
 126        /* Get ourselves into _M mode.  Could consider doing this elsewhere. */
 127        vcore_change_to_m();
 128}
 129
 130/* Helper: tells the kernel our SCP is capable of going into vcore context on
 131 * vcore 0.  Pairs with k/s/process.c scp_is_vcctx_ready(). */
 132static void scp_vcctx_ready(void)
 133{
 134        struct preempt_data *vcpd = vcpd_of(0);
 135        long old_flags;
 136
 137        /* the CAS is a bit overkill; keeping it around in case people use this
 138         * code in other situations. */
 139        do {
 140                old_flags = atomic_read(&vcpd->flags);
 141                /* Spin if the kernel is mucking with the flags */
 142                while (old_flags & VC_K_LOCK)
 143                        old_flags = atomic_read(&vcpd->flags);
 144        } while (!atomic_cas(&vcpd->flags, old_flags,
 145                             old_flags & ~VC_SCP_NOVCCTX));
 146}
 147
 148/* For both of these, VC ctx uses the usual TLS errno/errstr.  Uthreads use
 149 * their own storage.  Since we're called after manage_thread0, we should always
 150 * have current_uthread if we are not in vc ctx. */
 151static int *__ros_errno_loc(void)
 152{
 153        if (in_vcore_context())
 154                return __errno_location_tls();
 155        else
 156                return &current_uthread->err_no;
 157}
 158
 159static char *__ros_errstr_loc(void)
 160{
 161        if (in_vcore_context())
 162                return __errstr_location_tls();
 163        else
 164                return current_uthread->err_str;
 165}
 166
 167static void __attribute__((constructor)) uthread_lib_ctor(void)
 168{
 169        /* Surprise!  Parlib's ctors also run in shared objects.  We can't have
 170         * multiple versions of parlib (with multiple data structures). */
 171        if (__in_fake_parlib())
 172                return;
 173        /* Need to make sure vcore_lib_init() runs first */
 174        vcore_lib_init();
 175        /* Instead of relying on ctors for the specific 2LS, we make sure they
 176         * are called next.  They will call uthread_2ls_init().
 177         *
 178         * The potential issue here is that C++ ctors might make use of the
 179         * GCC/C++ threading callbacks, which require the full 2LS.  There's no
 180         * linkage dependency  between C++ and the specific 2LS, so there's no
 181         * way to be sure the 2LS actually turned on before we started calling
 182         * into it.
 183         *
 184         * Hopefully, the uthread ctor was called in time, since the GCC
 185         * threading functions link against parlib.  Note that, unlike
 186         * parlib-compat.c, there are no stub functions available to GCC that
 187         * could get called by accident and prevent the linkage. */
 188        sched_ops->sched_init();
 189}
 190
 191/* The 2LS calls this, passing in a uthread representing thread0 and its
 192 * syscall handling routine.  (NULL is fine).  The 2LS sched_ops is known
 193 * statically (via symbol overrides).
 194 *
 195 * This is where parlib (and whatever 2LS is linked in) takes over control of
 196 * scheduling, including handling notifications, having sched_entry() called,
 197 * blocking syscalls, and handling syscall completion events.  Before this
 198 * call, these things are handled by slim functions in glibc (e.g. early
 199 * function pointers for ros_blockon) and by the kernel.  The kerne's role was
 200 * to treat the process specially until we call scp_vcctx_ready(): things like
 201 * no __notify, no sched_entry, etc.
 202 *
 203 * We need to be careful to not start using the 2LS before it is fully ready.
 204 * For instance, once we change ros_blockon, we could have a blocking syscall
 205 * (e.g. for something glibc does) and the rest of the 2LS code expects things
 206 * to be in place.
 207 *
 208 * In older versions of this code, we would hop from the thread0 sched to the
 209 * real 2LSs sched, which meant we had to be very careful.  But now that we
 210 * only do this once, we can do all the prep work and then take over from
 211 * glibc's early SCP setup.  Specifically, notifs are disabled (due to the
 212 * early SCP ctx) and syscalls won't use the __ros_uth_syscall_blockon, so we
 213 * shouldn't get a syscall event.
 214 *
 215 * Still, if you have things like an outstanding async syscall, then you'll
 216 * have issues.  Most likely it would complete and you'd never hear about it.
 217 *
 218 * Note that some 2LS ops can be called even before we've initialized the 2LS!
 219 * Some ops, like the sync_obj ops, are called when initializing an uncontested
 220 * mutex, which could be called from glibc (e.g. malloc).  Hopefully that's
 221 * fine - we'll see!  I imagine a contested mutex would be a disaster (during
 222 * the unblock), which shouldn't happen as we are single threaded. */
 223void uthread_2ls_init(struct uthread *uthread,
 224                      void (*handle_sysc)(struct event_msg *, unsigned int,
 225                                          void *),
 226                      void *data)
 227{
 228        struct ev_handler *new_h = NULL;
 229
 230        if (handle_sysc) {
 231                new_h = malloc(sizeof(struct ev_handler));
 232                assert(new_h);
 233                new_h->func = handle_sysc;
 234                new_h->data = data;
 235                new_h->next = NULL;
 236                assert(!ev_handlers[EV_SYSCALL]);
 237                ev_handlers[EV_SYSCALL] = new_h;
 238        }
 239        uthread_init_thread0(uthread);
 240        uthread_track_thread0(uthread);
 241        /* Switch our errno/errstr functions to be uthread-aware.  See glibc's
 242         * errno.c for more info. */
 243        ros_errno_loc = __ros_errno_loc;
 244        ros_errstr_loc = __ros_errstr_loc;
 245        register_ev_handler(EV_EVENT, handle_ev_ev, 0);
 246        cmb();
 247        /* Now that we're ready (I hope) to operate as a full process, we tell
 248         * the kernel.  We must set vcctx and blockon atomically with respect to
 249         * syscalls, meaning no syscalls in between. */
 250        scp_vcctx_ready();
 251        /* Change our blockon from glibc's internal one to the regular one,
 252         * which uses vcore context and works for SCPs (with or without 2LS) and
 253         * MCPs.  Now that we told the kernel we are ready to utilize vcore
 254         * context, we need our blocking syscalls to utilize it as well. */
 255        ros_syscall_blockon = __ros_uth_syscall_blockon;
 256        cmb();
 257        init_posix_signals();
 258        /* Accept diagnostic events.  Other parts of the program/libraries can
 259         * register handlers to run.  You can kick these with "notify PID 9". */
 260        enable_kevent(EV_FREE_APPLE_PIE, 0, EVENT_IPI | EVENT_WAKEUP |
 261                                            EVENT_SPAM_PUBLIC);
 262}
 263
 264/* 2LSs shouldn't call uthread_vcore_entry directly */
 265void __attribute__((noreturn)) uthread_vcore_entry(void)
 266{
 267        uint32_t vcoreid = vcore_id();
 268        struct preempt_data *vcpd = vcpd_of(vcoreid);
 269
 270        /* Should always have notifications disabled when coming in here. */
 271        assert(!notif_is_enabled(vcoreid));
 272        assert(in_vcore_context());
 273        /* It's possible to have our FPSAVED already, e.g. any vcore reentry
 274         * (refl fault, some preemption handling, etc) if cur_uth wasn't reset.
 275         * In those cases, the FP state should be the same in the processor and
 276         * in the uth, so we might be able to drop the FPSAVED check/branch. */
 277        if (current_uthread && !(current_uthread->flags & UTHREAD_FPSAVED) &&
 278            !cur_uth_is_sw_ctx()) {
 279                save_fp_state(&current_uthread->as);
 280                current_uthread->flags |= UTHREAD_FPSAVED;
 281        }
 282        /* If someone is stealing our uthread (from when we were preempted
 283         * before), we can't touch our uthread.  But we might be the last vcore
 284         * around, so we'll handle preemption events (spammed to our public
 285         * mbox).
 286         *
 287         * It's important that we only check/handle one message per loop,
 288         * otherwise we could get stuck in a ping-pong scenario with a recoverer
 289         * (maybe). */
 290        while (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
 291                /* Note we're handling INDIRs and other public messages while
 292                 * someone is stealing our uthread.  Remember that those event
 293                 * handlers cannot touch cur_uth, as it is "vcore business". */
 294                handle_one_mbox_msg(&vcpd->ev_mbox_public);
 295                cpu_relax();
 296        }
 297        /* If we have a current uthread that is DONT_MIGRATE, pop it real quick
 298         * and let it disable notifs (like it wants to).  Other than dealing
 299         * with preemption events (or other INDIRs), we shouldn't do anything in
 300         * vc_ctx when we have a DONT_MIGRATE uthread. */
 301        if (current_uthread && (current_uthread->flags & UTHREAD_DONT_MIGRATE))
 302                __run_current_uthread_raw();
 303        /* Check and see if we wanted ourselves to handle a remote VCPD mbox.
 304         * Want to do this after we've handled STEALING and DONT_MIGRATE. */
 305        try_handle_remote_mbox();
 306        /* Otherwise, go about our usual vcore business (messages, etc). */
 307        handle_events(vcoreid);
 308        __check_preempt_pending(vcoreid);
 309        /* double check, in case an event changed it */
 310        assert(in_vcore_context());
 311        sched_ops->sched_entry();
 312        assert(0); /* 2LS sched_entry should never return */
 313}
 314
 315/* Does the uthread initialization of a uthread that the caller created.  Call
 316 * this whenever you are "starting over" with a thread. */
 317void uthread_init(struct uthread *new_thread, struct uth_thread_attr *attr)
 318{
 319        int ret;
 320        assert(new_thread);
 321        new_thread->state = UT_NOT_RUNNING;
 322        /* Set the signal state. */
 323        if (current_uthread)
 324                new_thread->sigstate.mask = current_uthread->sigstate.mask;
 325        else
 326                new_thread->sigstate.mask = 0;
 327        __sigemptyset(&new_thread->sigstate.pending);
 328        new_thread->sigstate.data = NULL;
 329        new_thread->sigstate.sigalt_stacktop = 0;
 330        new_thread->flags = 0;
 331        new_thread->sysc = NULL;
 332        /* the utf holds the GP context of the uthread (set by the 2LS earlier).
 333         * There is no FP context to be restored yet.  We only save the FPU when
 334         * we were interrupted off a core. */
 335        new_thread->flags |= UTHREAD_SAVED;
 336        new_thread->notif_disabled_depth = 0;
 337        /* TODO: on a reinit, if they changed whether or not they want TLS,
 338         * we'll have issues (checking tls_desc, assert in allocate_tls, maybe
 339         * more). */
 340        if (attr && attr->want_tls) {
 341                /* Get a TLS.  If we already have one, reallocate/refresh it */
 342                if (new_thread->tls_desc)
 343                        ret = __uthread_reinit_tls(new_thread);
 344                else
 345                        ret = __uthread_allocate_tls(new_thread);
 346                assert(!ret);
 347                begin_access_tls_vars(new_thread->tls_desc);
 348                current_uthread = new_thread;
 349                /* ctypes stores locale info in TLS.  we need this only once per
 350                 * TLS, so we don't have to do it here, but it is convenient
 351                 * since we already loaded the uthread's TLS. */
 352                extern void __ctype_init(void);
 353                __ctype_init();
 354                end_access_tls_vars();
 355        } else {
 356                new_thread->tls_desc = UTH_TLSDESC_NOTLS;
 357        }
 358        if (attr && attr->detached)
 359                atomic_set(&new_thread->join_ctl.state, UTH_JOIN_DETACHED);
 360        else
 361                atomic_set(&new_thread->join_ctl.state, UTH_JOIN_JOINABLE);
 362}
 363
 364/* This is a wrapper for the sched_ops thread_runnable, for use by functions
 365 * outside the main 2LS.  Do not put anything important in this, since the 2LSs
 366 * internally call their sched op.  This is to improve batch wakeups (barriers,
 367 * etc) */
 368void uthread_runnable(struct uthread *uthread)
 369{
 370        assert(sched_ops->thread_runnable);
 371        sched_ops->thread_runnable(uthread);
 372}
 373
 374/* Informs the 2LS that its thread blocked, and it is not under the control of
 375 * the 2LS.  This is for informational purposes, and some semantic meaning
 376 * should be passed by flags (from uthread.h's UTH_EXT_BLK_xxx options).
 377 * Eventually, whoever calls this will call uthread_runnable(), giving the
 378 * thread back to the 2LS.  If the 2LS provide sync ops, it will have a say in
 379 * which thread wakes up at a given time.
 380 *
 381 * If code outside the 2LS has blocked a thread (via uthread_yield) and ran its
 382 * own callback/yield_func instead of some 2LS code, that callback needs to
 383 * call this.
 384 *
 385 * AKA: obviously_a_uthread_has_blocked_in_lincoln_park() */
 386void uthread_has_blocked(struct uthread *uthread, int flags)
 387{
 388        assert(sched_ops->thread_has_blocked);
 389        sched_ops->thread_has_blocked(uthread, flags);
 390}
 391
 392/* Function indicating an external event has temporarily paused a uthread, but
 393 * it is ok to resume it if possible. */
 394void uthread_paused(struct uthread *uthread)
 395{
 396        /* Call out to the 2LS to let it know the uthread was paused for some
 397         * reason, but it is ok to resume it now. */
 398        assert(uthread->state == UT_NOT_RUNNING);
 399        assert(sched_ops->thread_paused);
 400        sched_ops->thread_paused(uthread);
 401}
 402
 403/* Need to have this as a separate, non-inlined function since we clobber the
 404 * stack pointer before calling it, and don't want the compiler to play games
 405 * with my hart. */
 406static void __attribute__((noinline, noreturn))
 407__uthread_yield(void)
 408{
 409        struct uthread *uthread = current_uthread;
 410        assert(in_vcore_context());
 411        assert(!notif_is_enabled(vcore_id()));
 412        /* Note: we no longer care if the thread is exiting, the 2LS will call
 413         * uthread_destroy() */
 414        uthread->flags &= ~UTHREAD_DONT_MIGRATE;
 415        uthread->state = UT_NOT_RUNNING;
 416        /* Any locks that were held before the yield must be unlocked in the
 417         * callback.  That callback won't get a chance to update our disabled
 418         * depth.  This sets us up for the next time the uthread runs. */
 419        assert(uthread->notif_disabled_depth <= 1);
 420        uthread->notif_disabled_depth = 0;
 421        /* Do whatever the yielder wanted us to do */
 422        assert(uthread->yield_func);
 423        uthread->yield_func(uthread, uthread->yield_arg);
 424        /* Make sure you do not touch uthread after that func call */
 425        /* Leave the current vcore completely */
 426        /* TODO: if the yield func can return a failure, we can abort the yield
 427         */
 428        current_uthread = NULL;
 429        /* Go back to the entry point, where we can handle notifications or
 430         * reschedule someone. */
 431        uthread_vcore_entry();
 432}
 433
 434/* Calling thread yields for some reason.  Set 'save_state' if you want to ever
 435 * run the thread again.  Once in vcore context in __uthread_yield, yield_func
 436 * will get called with the uthread and yield_arg passed to it.  This way, you
 437 * can do whatever you want when you get into vcore context, which can be
 438 * thread_blockon_sysc, unlocking mutexes, joining, whatever.
 439 *
 440 * If you do *not* pass a 2LS sched op or other 2LS function as yield_func,
 441 * then you must also call uthread_has_blocked(flags), which will let the 2LS
 442 * know a thread blocked beyond its control (and why). */
 443void uthread_yield(bool save_state, void (*yield_func)(struct uthread*, void*),
 444                   void *yield_arg)
 445{
 446        struct uthread *uthread = current_uthread;
 447        volatile bool yielding = TRUE; /* signal to short circuit on restart */
 448        assert(!in_vcore_context());
 449        assert(uthread->state == UT_RUNNING);
 450        /* Pass info to ourselves across the uth_yield -> __uth_yield
 451         * transition. */
 452        uthread->yield_func = yield_func;
 453        uthread->yield_arg = yield_arg;
 454        /* Don't migrate this thread to another vcore, since it depends on being
 455         * on the same vcore throughout (once it disables notifs).  The race is
 456         * that we read vcoreid, then get interrupted / migrated before
 457         * disabling notifs. */
 458        uthread->flags |= UTHREAD_DONT_MIGRATE;
 459        cmb();  /* don't let DONT_MIGRATE write pass the vcoreid read */
 460        uint32_t vcoreid = vcore_id();
 461
 462        printd("[U] Uthread %08p is yielding on vcore %d\n", uthread, vcoreid);
 463        struct preempt_data *vcpd = vcpd_of(vcoreid);
 464
 465        /* once we do this, we might miss a notif_pending, so we need to enter
 466         * vcore entry later.  Need to disable notifs so we don't get in weird
 467         * loops with save_user_ctx() and pop_user_ctx(). */
 468        disable_notifs(vcoreid);
 469        /* take the current state and save it into t->utf when this pthread
 470         * restarts, it will continue from right after this, see yielding is
 471         * false, and short ciruit the function.  Don't do this if we're dying.
 472         * */
 473        if (save_state) {
 474                /* Need to signal this before we actually save, since
 475                 * save_user_ctx returns() twice (once now, once when woken up)
 476                 */
 477                uthread->flags |= UTHREAD_SAVED;
 478                save_user_ctx(&uthread->u_ctx);
 479        }
 480        /* Force reread of yielding. Technically save_user_ctx() suffices*/
 481        cmb();
 482        /* Restart path doesn't matter if we're dying */
 483        if (!yielding)
 484                goto yield_return_path;
 485        /* From here on down is only executed on the save path (not the wake up)
 486         */
 487        yielding = FALSE; /* for when it starts back up */
 488        /* TODO: remove this when all arches support SW contexts */
 489        if (save_state && (uthread->u_ctx.type != ROS_SW_CTX)) {
 490                save_fp_state(&uthread->as);
 491                uthread->flags |= UTHREAD_FPSAVED;
 492        }
 493        /* Change to the transition context (both TLS (if applicable) and
 494         * stack). */
 495        if (__uthread_has_tls(uthread)) {
 496                set_tls_desc(get_vcpd_tls_desc(vcoreid));
 497                begin_safe_access_tls_vars();
 498                assert(current_uthread == uthread);
 499                /* If this assert fails, see the note in uthread_track_thread0
 500                 */
 501                assert(in_vcore_context());
 502                end_safe_access_tls_vars();
 503        } else {
 504                /* Since uthreads and vcores share TLS (it's always the vcore's
 505                 * TLS, the uthread one just bootstraps from it), we need to
 506                 * change our state at boundaries between the two 'contexts' */
 507                __vcore_context = TRUE;
 508        }
 509        /* After this, make sure you don't use local variables.  Also, make sure
 510         * the compiler doesn't use them without telling you (TODO).
 511         *
 512         * In each arch's set_stack_pointer, make sure you subtract off as much
 513         * room as you need to any local vars that might be pushed before
 514         * calling the next function, or for whatever other reason the
 515         * compiler/hardware might walk up the stack a bit when calling a
 516         * noreturn function. */
 517        set_stack_pointer((void*)vcpd->vcore_stack);
 518        /* Finish exiting in another function. */
 519        __uthread_yield();
 520        /* Should never get here */
 521        assert(0);
 522        /* Will jump here when the uthread's trapframe is restarted/popped. */
 523yield_return_path:
 524        printd("[U] Uthread %08p returning from a yield!\n", uthread);
 525}
 526
 527/* We explicitly don't support sleep(), since old callers of it have
 528 * expectations of being woken up by signal handlers.  If we need that, we can
 529 * build it in to sleep() later.  If you just want to sleep for a while, call
 530 * this helper. */
 531void uthread_sleep(unsigned int seconds)
 532{
 533        sys_block(seconds * 1000000);   /* usec sleep */
 534}
 535/* If we are providing a dummy sleep function, might as well provide the more
 536 * accurate/useful one. */
 537void uthread_usleep(unsigned int usecs)
 538{
 539        sys_block(usecs);       /* usec sleep */
 540}
 541
 542static void __sleep_forever_cb(struct uthread *uth, void *arg)
 543{
 544        uthread_has_blocked(uth, UTH_EXT_BLK_MISC);
 545}
 546
 547void __attribute__((noreturn)) uthread_sleep_forever(void)
 548{
 549        uthread_yield(FALSE, __sleep_forever_cb, NULL);
 550        assert(0);
 551}
 552
 553/* Cleans up the uthread (the stuff we did in uthread_init()).  If you want to
 554 * destroy a currently running uthread, you'll want something like
 555 * pthread_exit(), which yields, and calls this from its sched_ops yield. */
 556void uthread_cleanup(struct uthread *uthread)
 557{
 558        printd("[U] thread %08p on vcore %d is DYING!\n", uthread, vcore_id());
 559        /* we alloc and manage the TLS, so lets get rid of it, except for
 560         * thread0.  glibc owns it.  might need to keep it around for a full
 561         * exit() */
 562        if (__uthread_has_tls(uthread) && !(uthread->flags & UTHREAD_IS_THREAD0))
 563                __uthread_free_tls(uthread);
 564}
 565
 566static void __ros_syscall_spinon(struct syscall *sysc)
 567{
 568        while (!(atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS)))
 569                cpu_relax();
 570}
 571
 572static void __ros_vcore_ctx_syscall_blockon(struct syscall *sysc)
 573{
 574        if (in_multi_mode()) {
 575                /* MCP vcore's don't know what to do yet, so we have to spin */
 576                __ros_syscall_spinon(sysc);
 577        } else {
 578                /* SCPs can use the early blockon, which acts like VC ctx. */
 579                __ros_early_syscall_blockon(sysc);
 580        }
 581}
 582
 583/* Attempts to block on sysc, returning when it is done or progress has been
 584 * made.  Made for initialized processes using uthreads. */
 585static void __ros_uth_syscall_blockon(struct syscall *sysc)
 586{
 587        if (in_vcore_context()) {
 588                __ros_vcore_ctx_syscall_blockon(sysc);
 589                return;
 590        }
 591        /* At this point, we know we're a uthread.  If we're a DONT_MIGRATE
 592         * uthread, then it's disabled notifs and is basically in vcore context,
 593         * enough so that it can't call into the 2LS. */
 594        assert(current_uthread);
 595        if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
 596                assert(!notif_is_enabled(vcore_id()));  /* catch bugs */
 597                /* if we had a notif_disabled_depth, then we should also have
 598                 * DONT_MIGRATE set */
 599                __ros_vcore_ctx_syscall_blockon(sysc);
 600                return;
 601        }
 602        assert(!current_uthread->notif_disabled_depth);
 603        /* double check before doing all this crap */
 604        if (atomic_read(&sysc->flags) & (SC_DONE | SC_PROGRESS))
 605                return;
 606        /* for both debugging and syscall cancelling */
 607        current_uthread->sysc = sysc;
 608        /* yield, calling 2ls-blockon(cur_uth, sysc) on the other side */
 609        uthread_yield(TRUE, sched_ops->thread_blockon_sysc, sysc);
 610}
 611
 612/* 2LS helper.  Run this from vcore context.  It will block a uthread on it's
 613 * internal syscall struct, which should be an async call.  You'd use this in
 614 * e.g. thread_refl_fault when the 2LS initiates a syscall on behalf of the
 615 * uthread. */
 616void __block_uthread_on_async_sysc(struct uthread *uth)
 617{
 618        assert(in_vcore_context());
 619        uth->sysc = &uth->local_sysc;
 620        /* If a DONT_MIGRATE issued a syscall that blocks, we gotta spin, same
 621         * as with the usual blockon. */
 622        if (uth->flags & UTHREAD_DONT_MIGRATE) {
 623                __ros_vcore_ctx_syscall_blockon(uth->sysc);
 624                uth->sysc = 0;
 625                return;
 626        }
 627        sched_ops->thread_blockon_sysc(uth, uth->sysc);
 628}
 629
 630/* Simply sets current uthread to be whatever the value of uthread is.  This
 631 * can be called from outside of sched_entry() to highjack the current context,
 632 * and make sure that the new uthread struct is used to store this context upon
 633 * yielding, etc. USE WITH EXTREME CAUTION! */
 634void highjack_current_uthread(struct uthread *uthread)
 635{
 636        uint32_t vcoreid = vcore_id();
 637
 638        assert(uthread != current_uthread);
 639        current_uthread->state = UT_NOT_RUNNING;
 640        uthread->state = UT_RUNNING;
 641        /* Make sure the vcore is tracking the new uthread struct */
 642        if (__uthread_has_tls(current_uthread))
 643                vcore_set_tls_var(current_uthread, uthread);
 644        else
 645                current_uthread = uthread;
 646        /* and make sure we are using the correct TLS for the new uthread */
 647        if (__uthread_has_tls(uthread)) {
 648                assert(uthread->tls_desc);
 649                set_tls_desc(uthread->tls_desc);
 650                begin_safe_access_tls_vars();
 651                __vcoreid = vcoreid;    /* setting the uthread's TLS var */
 652                end_safe_access_tls_vars();
 653        }
 654}
 655
 656/* Helper: loads a uthread's TLS on this vcore, if applicable.  If our uthreads
 657 * do not have their own TLS, we simply switch the __vc_ctx, signalling that the
 658 * context running here is (soon to be) a uthread. */
 659static void set_uthread_tls(struct uthread *uthread, uint32_t vcoreid)
 660{
 661        if (__uthread_has_tls(uthread)) {
 662                set_tls_desc(uthread->tls_desc);
 663                begin_safe_access_tls_vars();
 664                __vcoreid = vcoreid;    /* setting the uthread's TLS var */
 665                end_safe_access_tls_vars();
 666        } else {
 667                __vcore_context = FALSE;
 668        }
 669}
 670
 671/* Attempts to handle a fault for uth, etc */
 672static void handle_refl_fault(struct uthread *uth, struct user_context *ctx)
 673{
 674        sched_ops->thread_refl_fault(uth, ctx);
 675}
 676
 677/* 2LS helper: stops the current uthread, saves its state, and returns a pointer
 678 * to it.  Unlike __uthread_pause, which is called by non-specific 2LS code,
 679 * this function is called by a specific 2LS to stop it's current uthread. */
 680struct uthread *stop_current_uthread(void)
 681{
 682        struct uthread *uth;
 683        struct preempt_data *vcpd = vcpd_of(vcore_id());
 684
 685        uth = current_uthread;
 686        current_uthread = 0;
 687        if (!(uth->flags & UTHREAD_SAVED)) {
 688                uth->u_ctx = vcpd->uthread_ctx;
 689                uth->flags |= UTHREAD_SAVED;
 690        }
 691        if ((uth->u_ctx.type != ROS_SW_CTX) && !(uth->flags & UTHREAD_FPSAVED))
 692        {
 693                save_fp_state(&uth->as);
 694                uth->flags |= UTHREAD_FPSAVED;
 695        }
 696        uth->state = UT_NOT_RUNNING;
 697        return uth;
 698}
 699
 700/* Run the thread that was current_uthread, from a previous run.  Should be
 701 * called only when the uthread already was running, and we were interrupted by
 702 * the kernel (event, etc).  Do not call this to run a fresh uthread, even if
 703 * you've set it to be current. */
 704void __attribute__((noreturn)) run_current_uthread(void)
 705{
 706        struct uthread *uth;
 707        uint32_t vcoreid = vcore_id();
 708        struct preempt_data *vcpd = vcpd_of(vcoreid);
 709
 710        assert(current_uthread);
 711        assert(current_uthread->state == UT_RUNNING);
 712        /* Uth was already running, should not have been saved */
 713        assert(!(current_uthread->flags & UTHREAD_SAVED));
 714        /* SW CTX FP wasn't saved, but HW/VM was.  There might be some case
 715         * where a VMTF hadn't run yet, and thus wasn't interrupted, but it
 716         * shouldn't have made it to be current_uthread. */
 717        if (cur_uth_is_sw_ctx())
 718                assert(!(current_uthread->flags & UTHREAD_FPSAVED));
 719        else
 720                assert(current_uthread->flags & UTHREAD_FPSAVED);
 721        printd("[U] Vcore %d is restarting uthread %08p\n", vcoreid,
 722               current_uthread);
 723        if (has_refl_fault(&vcpd->uthread_ctx)) {
 724                clear_refl_fault(&vcpd->uthread_ctx);
 725                /* we preemptively copy out and make non-running, so that there
 726                 * is a consistent state for the handler.  it can then block the
 727                 * uth or whatever. */
 728                uth = stop_current_uthread();
 729                handle_refl_fault(uth, &vcpd->uthread_ctx);
 730                /* we abort no matter what.  up to the 2LS to reschedule the
 731                 * thread */
 732                set_stack_pointer((void*)vcpd->vcore_stack);
 733                vcore_entry();
 734        }
 735        if (current_uthread->flags & UTHREAD_FPSAVED) {
 736                current_uthread->flags &= ~UTHREAD_FPSAVED;
 737                restore_fp_state(&current_uthread->as);
 738        }
 739        set_uthread_tls(current_uthread, vcoreid);
 740        pop_user_ctx(&vcpd->uthread_ctx, vcoreid);
 741        assert(0);
 742}
 743
 744/* Launches the uthread on the vcore.  Don't call this on current_uthread. 
 745 *
 746 * In previous versions of this, we used to check for events after setting
 747 * current_uthread.  That is super-dangerous.  handle_events() doesn't always
 748 * return (which we used to handle), and it may also clear current_uthread.  We
 749 * needed to save uthread in current_uthread, in case we didn't return.  If we
 750 * didn't return, the vcore started over at vcore_entry, with current set.  When
 751 * this happens, we never actually had loaded cur_uth's FP and GP onto the core,
 752 * so cur_uth fails.  Check out 4602599be for more info.
 753 *
 754 * Ultimately, handling events again in these 'popping helpers' isn't even
 755 * necessary (we only must do it once for an entire time in VC ctx, and in
 756 * loops), and might have been optimizing a rare event at a cost in both
 757 * instructions and complexity. */
 758void __attribute__((noreturn)) run_uthread(struct uthread *uthread)
 759{
 760        uint32_t vcoreid = vcore_id();
 761        struct preempt_data *vcpd = vcpd_of(vcoreid);
 762
 763        assert(!current_uthread);
 764        assert(uthread->state == UT_NOT_RUNNING);
 765        assert(uthread->flags & UTHREAD_SAVED);
 766        /* For HW CTX, FPSAVED must match UTH SAVE (and both be on here).  For
 767         * SW, FP should never be saved. */
 768        switch (uthread->u_ctx.type) {
 769        case ROS_HW_CTX:
 770                assert(uthread->flags & UTHREAD_FPSAVED);
 771                break;
 772        case ROS_SW_CTX:
 773                assert(!(uthread->flags & UTHREAD_FPSAVED));
 774                break;
 775        case ROS_VM_CTX:
 776                /* Don't care.  This gives it the state of the vcore when it
 777                 * starts up.  If we care about leaking FPU / XMM state, we can
 778                 * create a new one for every VM TF (or vthread reuse). */
 779                break;
 780        }
 781        if (has_refl_fault(&uthread->u_ctx)) {
 782                clear_refl_fault(&uthread->u_ctx);
 783                handle_refl_fault(uthread, &uthread->u_ctx);
 784                /* we abort no matter what.  up to the 2LS to reschedule the
 785                 * thread */
 786                set_stack_pointer((void*)vcpd->vcore_stack);
 787                vcore_entry();
 788        }
 789        uthread->state = UT_RUNNING;
 790        /* Save a ptr to the uthread we'll run in the transition context's TLS
 791         */
 792        current_uthread = uthread;
 793        if (uthread->flags & UTHREAD_FPSAVED) {
 794                uthread->flags &= ~UTHREAD_FPSAVED;
 795                restore_fp_state(&uthread->as);
 796        }
 797        set_uthread_tls(uthread, vcoreid);
 798        /* the uth's context will soon be in the cpu (or VCPD), no longer saved
 799         */
 800        uthread->flags &= ~UTHREAD_SAVED;
 801        pop_user_ctx(&uthread->u_ctx, vcoreid);
 802        assert(0);
 803}
 804
 805/* Runs the uthread, but doesn't care about notif pending.  Only call this when
 806 * there was a DONT_MIGRATE uthread, or a similar situation where the uthread
 807 * will check messages soon (like calling enable_notifs()). */
 808static void __run_current_uthread_raw(void)
 809{
 810        uint32_t vcoreid = vcore_id();
 811        struct preempt_data *vcpd = vcpd_of(vcoreid);
 812
 813        if (has_refl_fault(&vcpd->uthread_ctx)) {
 814                printf("Raw / DONT_MIGRATE uthread took a fault, exiting.\n");
 815                exit(-1);
 816        }
 817        /* We need to manually say we have a notif pending, so we eventually
 818         * return to vcore context.  (note the kernel turned it off for us) */
 819        vcpd->notif_pending = TRUE;
 820        assert(!(current_uthread->flags & UTHREAD_SAVED));
 821        if (current_uthread->flags & UTHREAD_FPSAVED) {
 822                current_uthread->flags &= ~UTHREAD_FPSAVED;
 823                restore_fp_state(&current_uthread->as);
 824        }
 825        set_uthread_tls(current_uthread, vcoreid);
 826        pop_user_ctx_raw(&vcpd->uthread_ctx, vcoreid);
 827        assert(0);
 828}
 829
 830/* Copies the uthread trapframe and silly state from the vcpd to the uthread,
 831 * subject to the uthread's flags and whatnot.
 832 *
 833 * For example: The uthread state might still be in the uthread struct.  Imagine
 834 * the 2LS decides to run a new uthread and sets it up as current, but doesn't
 835 * actually run it yet.  The 2LS happened to voluntarily give up the VC (due to
 836 * some other event) and then wanted to copy out the thread.  This is pretty
 837 * rare - the normal case is when an IRQ of some sort hit the core and the
 838 * kernel copied the running state into VCPD.
 839 *
 840 * The FP state could also be in VCPD (e.g. preemption being handled remotely),
 841 * it could be in the uthread struct (e.g. hasn't started running yet) or even
 842 * in the FPU (e.g. took an IRQ/notif and we're handling the preemption of
 843 * another vcore).
 844 *
 845 * There are some cases where we'll have a uthread SW ctx that needs to be
 846 * copied out: uth syscalls, notif happens, and the core comes back from the
 847 * kernel in VC ctx.  VC ctx calls copy_out (response to preempt_pending or done
 848 * while handling a preemption). */
 849static void copyout_uthread(struct preempt_data *vcpd, struct uthread *uthread,
 850                            bool vcore_local)
 851{
 852        assert(uthread);
 853        if (uthread->flags & UTHREAD_SAVED) {
 854                /* GP saved -> FP saved, but not iff.  FP could be saved due to
 855                 * aggressive save/restore. */
 856                switch (uthread->u_ctx.type) {
 857                case ROS_HW_CTX:
 858                case ROS_VM_CTX:
 859                        assert(uthread->flags & UTHREAD_FPSAVED);
 860                }
 861                assert(vcore_local);
 862                return;
 863        }
 864        /* If we're copying GP state, it must be in VCPD */
 865        uthread->u_ctx = vcpd->uthread_ctx;
 866        uthread->flags |= UTHREAD_SAVED;
 867        printd("VC %d copying out uthread %08p\n", vcore_id(), uthread);
 868        /* Software contexts do not need FP state, nor should we think it has
 869         * any */
 870        if (uthread->u_ctx.type == ROS_SW_CTX) {
 871                assert(!(uthread->flags & UTHREAD_FPSAVED));
 872                return;
 873        }
 874        /* We might have aggressively saved for non-SW ctx in vc_entry before we
 875         * got to the event handler. */
 876        if (uthread->flags & UTHREAD_FPSAVED) {
 877                /* If this fails, we're remote.  But the target vcore should not
 878                 * be in uth context (which is when we'd be stealing a uthread)
 879                 * with FPSAVED, just like how it shouldn't have GP saved. */
 880                assert(vcore_local);
 881                return;
 882        }
 883        /* When we're dealing with the uthread running on our own vcore, the FP
 884         * state is in the actual FPU, not VCPD.  It might also be in VCPD, but
 885         * it will always be in the FPU (the kernel maintains this for us, in
 886         * the event we were preempted since the uthread was last running). */
 887        if (vcore_local)
 888                save_fp_state(&uthread->as);
 889        else
 890                uthread->as = vcpd->preempt_anc;
 891        uthread->flags |= UTHREAD_FPSAVED;
 892}
 893
 894/* Helper, packages up and pauses a uthread that was running on vcoreid.  Used
 895 * by preemption handling (and detection) so far.  Careful using this, esp if
 896 * it is on another vcore (need to make sure it's not running!).  If you are
 897 * using it on the local vcore, set vcore_local = TRUE. */
 898static void __uthread_pause(struct preempt_data *vcpd, struct uthread *uthread,
 899                            bool vcore_local)
 900{
 901        assert(!(uthread->flags & UTHREAD_DONT_MIGRATE));
 902        copyout_uthread(vcpd, uthread, vcore_local);
 903        uthread->state = UT_NOT_RUNNING;
 904        /* Call out to the 2LS to package up its uthread */
 905        assert(sched_ops->thread_paused);
 906        sched_ops->thread_paused(uthread);
 907}
 908
 909/* Deals with a pending preemption (checks, responds).  If the 2LS registered a
 910 * function, it will get run.  Returns true if you got preempted.  Called
 911 * 'check' instead of 'handle', since this isn't an event handler.  It's the "Oh
 912 * shit a preempt is on its way ASAP".
 913 *
 914 * Be careful calling this: you might not return, so don't call it if you can't
 915 * handle that.  If you are calling this from an event handler, you'll need to
 916 * do things like ev_might_not_return().  If the event can via an INDIR ev_q,
 917 * that ev_q must be a NOTHROTTLE.
 918 *
 919 * Finally, don't call this from a place that might have a DONT_MIGRATE
 920 * cur_uth.  This should be safe for most 2LS code. */
 921bool __check_preempt_pending(uint32_t vcoreid)
 922{
 923        bool retval = FALSE;
 924        assert(in_vcore_context());
 925        if (__preempt_is_pending(vcoreid)) {
 926                retval = TRUE;
 927                if (sched_ops->preempt_pending)
 928                        sched_ops->preempt_pending();
 929                /* If we still have a cur_uth, copy it out and hand it back to
 930                 * the 2LS before yielding. */
 931                if (current_uthread) {
 932                        __uthread_pause(vcpd_of(vcoreid), current_uthread,
 933                                        TRUE);
 934                        current_uthread = 0;
 935                }
 936                /* vcore_yield tries to yield, and will pop back up if this was
 937                 * a spurious preempt_pending or if it handled an event.  For
 938                 * now, we'll just keep trying to yield so long as a preempt is
 939                 * coming in.  Eventually, we'll handle all of our events and
 940                 * yield, or else the preemption will hit and someone will
 941                 * recover us (at which point we'll break out of the loop) */
 942                while (__procinfo.vcoremap[vcoreid].preempt_pending) {
 943                        vcore_yield(TRUE);
 944                        cpu_relax();
 945                }
 946        }
 947        return retval;
 948}
 949
 950/* Helper: This is a safe way for code to disable notifs if it *might* be called
 951 * from uthread context (like from a notif_safe lock).  Pair this with
 952 * uth_enable_notifs() unless you know what you're doing. */
 953void uth_disable_notifs(void)
 954{
 955        if (!in_vcore_context()) {
 956                if (current_uthread) {
 957                        if (current_uthread->notif_disabled_depth++)
 958                                goto out;
 959                        current_uthread->flags |= UTHREAD_DONT_MIGRATE;
 960                        /* don't issue the flag write before the vcore_id() read
 961                         */
 962                        cmb();
 963                }
 964                disable_notifs(vcore_id());
 965        }
 966out:
 967        assert(!notif_is_enabled(vcore_id()));
 968}
 969
 970/* Helper: Pair this with uth_disable_notifs(). */
 971void uth_enable_notifs(void)
 972{
 973        if (!in_vcore_context()) {
 974                if (current_uthread) {
 975                        if (--current_uthread->notif_disabled_depth)
 976                                return;
 977                        current_uthread->flags &= ~UTHREAD_DONT_MIGRATE;
 978                        cmb();  /* don't enable before ~DONT_MIGRATE */
 979                }
 980                enable_notifs(vcore_id());
 981        }
 982}
 983
 984void assert_can_block(void)
 985{
 986        if (in_vcore_context())
 987                panic("Vcore context tried to block!");
 988        if (!current_uthread) {
 989                /* Pre-parlib SCPs can do whatever. */
 990                if (atomic_read(&vcpd_of(0)->flags) & VC_SCP_NOVCCTX)
 991                        return;
 992                panic("No current_uthread and tried to block!");
 993        }
 994        if (current_uthread->notif_disabled_depth)
 995                panic("Uthread tried to block with notifs disabled!");
 996        if (current_uthread->flags & UTHREAD_DONT_MIGRATE)
 997                panic("Uthread tried to block with DONT_MIGRATE!");
 998}
 999
1000/* Helper: returns TRUE if it succeeded in starting the uth stealing process. */
1001static bool start_uth_stealing(struct preempt_data *vcpd)
1002{
1003        long old_flags;
1004        do {
1005                old_flags = atomic_read(&vcpd->flags);
1006                /* Spin if the kernel is mucking with the flags */
1007                while (old_flags & VC_K_LOCK)
1008                        old_flags = atomic_read(&vcpd->flags);
1009                /* Someone else is stealing, we failed */
1010                if (old_flags & VC_UTHREAD_STEALING)
1011                        return FALSE;
1012        } while (!atomic_cas(&vcpd->flags, old_flags,
1013                             old_flags | VC_UTHREAD_STEALING));
1014        return TRUE;
1015}
1016
1017/* Helper: pairs with stop_uth_stealing */
1018static void stop_uth_stealing(struct preempt_data *vcpd)
1019{
1020        long old_flags;
1021        do {
1022                old_flags = atomic_read(&vcpd->flags);
1023                assert(old_flags & VC_UTHREAD_STEALING);        /* sanity */
1024                while (old_flags & VC_K_LOCK)
1025                        old_flags = atomic_read(&vcpd->flags);
1026        } while (!atomic_cas(&vcpd->flags, old_flags,
1027                             old_flags & ~VC_UTHREAD_STEALING));
1028}
1029
1030/* Handles INDIRS for another core (the public mbox).  We synchronize with the
1031 * kernel (__set_curtf_to_vcoreid). */
1032static void handle_indirs(uint32_t rem_vcoreid)
1033{
1034        long old_flags;
1035        struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
1036        /* Turn off their message reception if they are still preempted.  If
1037         * they are no longer preempted, we do nothing - they will handle their
1038         * own messages.  Turning off CAN_RCV will route this vcore's messages
1039         * to fallback vcores (if those messages were 'spammed'). */
1040        do {
1041                old_flags = atomic_read(&rem_vcpd->flags);
1042                while (old_flags & VC_K_LOCK)
1043                        old_flags = atomic_read(&rem_vcpd->flags);
1044                if (!(old_flags & VC_PREEMPTED))
1045                        return;
1046        } while (!atomic_cas(&rem_vcpd->flags, old_flags,
1047                             old_flags & ~VC_CAN_RCV_MSG));
1048        wrmb(); /* don't let the CAN_RCV write pass reads of the mbox status */
1049        /* handle all INDIRs of the remote vcore */
1050        handle_vcpd_mbox(rem_vcoreid);
1051}
1052
1053/* Helper.  Will ensure a good attempt at changing vcores, meaning we try again
1054 * if we failed for some reason other than the vcore was already running. */
1055static void __change_vcore(uint32_t rem_vcoreid, bool enable_my_notif)
1056{
1057        /* okay to do a normal spin/relax here, even though we are in vcore
1058         * context. */
1059        while (-EAGAIN == sys_change_vcore(rem_vcoreid, enable_my_notif))
1060                cpu_relax();
1061}
1062
1063/* Helper, used in preemption recovery.  When you can freely leave vcore
1064 * context and need to change to another vcore, call this.  vcpd is the caller,
1065 * rem_vcoreid is the remote vcore.  This will try to package up your uthread.
1066 * It may return, either because the other core already started up (someone else
1067 * got it), or in some very rare cases where we had to stay in our vcore
1068 * context */
1069static void change_to_vcore(struct preempt_data *vcpd, uint32_t rem_vcoreid)
1070{
1071        bool were_handling_remotes;
1072
1073        /* Unlikely, but if we have no uthread we can just change.  This is the
1074         * check, sync, then really check pattern: we can only really be sure
1075         * about current_uthread after we check STEALING. */
1076        if (!current_uthread) {
1077                /* there might be an issue with doing this while someone is
1078                 * recovering.  once they 0'd it, we should be good to yield.
1079                 * just a bit dangerous. */
1080                were_handling_remotes = ev_might_not_return();
1081                __change_vcore(rem_vcoreid, TRUE);/* noreturn on success */
1082                goto out_we_returned;
1083        }
1084        /* Note that the reason we need to check STEALING is because we can get
1085         * into vcore context and slip past that check in vcore_entry when we
1086         * are handling a preemption message.  Anytime preemption recovery cares
1087         * about the calling vcore's cur_uth, it needs to be careful about
1088         * STEALING.  But it is safe to do the check up above (if it's 0, it
1089         * won't concurrently become non-zero).
1090         *
1091         * STEALING might be turned on at any time.  Whoever turns it on will do
1092         * nothing if we are online or were in vc_ctx.  So if it is on, we can't
1093         * touch current_uthread til it is turned off (not sure what state they
1094         * saw us in).  We could spin here til they unset STEALING (since they
1095         * will soon), but there is a chance they were preempted, so we need to
1096         * make progress by doing a sys_change_vcore(). */
1097        /* Crap, someone is stealing (unlikely).  All we can do is change. */
1098        if (atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING) {
1099                __change_vcore(rem_vcoreid, FALSE);     /* returns on success */
1100                return;
1101        }
1102        cmb();
1103        /* Need to recheck, in case someone stole it and finished before we
1104         * checked VC_UTHREAD_STEALING. */
1105        if (!current_uthread) {
1106                were_handling_remotes = ev_might_not_return();
1107                __change_vcore(rem_vcoreid, TRUE);      /* noreturn on success*/
1108                goto out_we_returned;
1109        }
1110        /* Need to make sure we don't have a DONT_MIGRATE (very rare, someone
1111         * would have to steal from us to get us to handle a preempt message,
1112         * and then had to finish stealing (and fail) fast enough for us to miss
1113         * the previous check). */
1114        if (current_uthread->flags & UTHREAD_DONT_MIGRATE) {
1115                __change_vcore(rem_vcoreid, FALSE);     /* returns on success */
1116                return;
1117        }
1118        /* Now save our uthread and restart them */
1119        assert(current_uthread);
1120        __uthread_pause(vcpd, current_uthread, TRUE);
1121        current_uthread = 0;
1122        were_handling_remotes = ev_might_not_return();
1123        __change_vcore(rem_vcoreid, TRUE);              /* noreturn on success*/
1124        /* Fall-through to out_we_returned */
1125out_we_returned:
1126        ev_we_returned(were_handling_remotes);
1127}
1128
1129/* This handles a preemption message.  When this is done, either we recovered,
1130 * or recovery *for our message* isn't needed. */
1131static void handle_vc_preempt(struct event_msg *ev_msg, unsigned int ev_type,
1132                              void *data)
1133{
1134        uint32_t vcoreid = vcore_id();
1135        struct preempt_data *vcpd = vcpd_of(vcoreid);
1136        uint32_t rem_vcoreid = ev_msg->ev_arg2;
1137        struct preempt_data *rem_vcpd = vcpd_of(rem_vcoreid);
1138        struct uthread *uthread_to_steal = 0;
1139        struct uthread **rem_cur_uth;
1140        bool cant_migrate = FALSE;
1141
1142        assert(in_vcore_context());
1143        /* Just drop messages about ourselves.  They are old.  If we happen to
1144         * be getting preempted right now, there's another message out there
1145         * about that. */
1146        if (rem_vcoreid == vcoreid)
1147                return;
1148        printd("Vcore %d was preempted (i'm %d), it's flags %08p!\n",
1149               ev_msg->ev_arg2, vcoreid, rem_vcpd->flags);
1150        /* Spin til the kernel is done with flags.  This is how we avoid
1151         * handling the preempt message before the preemption. */
1152        while (atomic_read(&rem_vcpd->flags) & VC_K_LOCK)
1153                cpu_relax();
1154        /* If they aren't preempted anymore, just return (optimization). */
1155        if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
1156                return;
1157        /* At this point, we need to try to recover */
1158        /* This case handles when the remote core was in vcore context */
1159        if (rem_vcpd->notif_disabled) {
1160                printd("VC %d recovering %d, notifs were disabled\n", vcoreid,
1161                       rem_vcoreid);
1162                change_to_vcore(vcpd, rem_vcoreid);
1163                return; /* in case it returns.  we've done our job recovering */
1164        }
1165        /* So now it looks like they were not in vcore context.  We want to
1166         * steal the uthread.  Set stealing, then doublecheck everything.  If
1167         * stealing fails, someone else is stealing and we can just leave.  That
1168         * other vcore who is stealing will check the VCPD/INDIRs when it is
1169         * done. */
1170        if (!start_uth_stealing(rem_vcpd))
1171                return;
1172        /* Now we're stealing.  Double check everything.  A change in preempt
1173         * status or notif_disable status means the vcore has since restarted.
1174         * The vcore may or may not have started after we set STEALING.  If it
1175         * didn't, we'll need to bail out (but still check messages, since above
1176         * we assumed the uthread stealer handles the VCPD/INDIRs).  Since the
1177         * vcore is running, we don't need to worry about handling the message
1178         * any further.  Future preemptions will generate another message, so we
1179         * can ignore getting the uthread or anything like that. */
1180        printd("VC %d recovering %d, trying to steal uthread\n", vcoreid,
1181               rem_vcoreid);
1182        if (!(atomic_read(&rem_vcpd->flags) & VC_PREEMPTED))
1183                goto out_stealing;
1184        /* Might be preempted twice quickly, and the second time had notifs
1185         * disabled.
1186         *
1187         * Also note that the second preemption event had another message sent,
1188         * which either we or someone else will deal with.  And also, we don't
1189         * need to worry about how we are stealing still and plan to abort.  If
1190         * another vcore handles that second preemption message, either the
1191         * original vcore is in vc ctx or not.  If so, we bail out and the
1192         * second preemption handling needs to change_to.  If not, we aren't
1193         * bailing out, and we'll handle the preemption as normal, and the
1194         * second handler will bail when it fails to steal. */
1195        if (rem_vcpd->notif_disabled)
1196                goto out_stealing;
1197        /* At this point, we're clear to try and steal the uthread.  We used to
1198         * switch to their TLS to steal the uthread, but we can access their
1199         * current_uthread directly. */
1200        rem_cur_uth = get_tlsvar_linaddr(rem_vcoreid, current_uthread);
1201        uthread_to_steal = *rem_cur_uth;
1202        if (uthread_to_steal) {
1203                /* Extremely rare: they have a uthread, but it can't migrate.
1204                 * So we'll need to change to them. */
1205                if (uthread_to_steal->flags & UTHREAD_DONT_MIGRATE) {
1206                        printd("VC %d recovering %d, can't migrate uthread!\n",
1207                               vcoreid, rem_vcoreid);
1208                        stop_uth_stealing(rem_vcpd);
1209                        change_to_vcore(vcpd, rem_vcoreid);
1210                        /* in case it returns.  we've done our job recovering */
1211                        return;
1212                } else {
1213                        *rem_cur_uth = 0;
1214                        /* we're clear to steal it */
1215                        printd("VC %d recovering %d, uthread %08p stolen\n",
1216                               vcoreid, rem_vcoreid, uthread_to_steal);
1217                        __uthread_pause(rem_vcpd, uthread_to_steal, FALSE);
1218                        /* can't let the cur_uth = 0 write and any writes from
1219                         * __uth_pause() to pass stop_uth_stealing. */
1220                        wmb();
1221                }
1222        }
1223        /* Fallthrough */
1224out_stealing:
1225        stop_uth_stealing(rem_vcpd);
1226        handle_indirs(rem_vcoreid);
1227}
1228
1229/* This handles a "check indirs" message.  When this is done, either we checked
1230 * their indirs, or the vcore restarted enough so that checking them is
1231 * unnecessary.  If that happens and they got preempted quickly, then another
1232 * preempt/check_indirs was sent out. */
1233static void handle_vc_indir(struct event_msg *ev_msg, unsigned int ev_type,
1234                            void *data)
1235{
1236        uint32_t vcoreid = vcore_id();
1237        uint32_t rem_vcoreid = ev_msg->ev_arg2;
1238
1239        if (rem_vcoreid == vcoreid)
1240                return;
1241        handle_indirs(rem_vcoreid);
1242}
1243
1244static inline bool __uthread_has_tls(struct uthread *uthread)
1245{
1246        return uthread->tls_desc != UTH_TLSDESC_NOTLS;
1247}
1248
1249/* TLS helpers */
1250static int __uthread_allocate_tls(struct uthread *uthread)
1251{
1252        assert(!uthread->tls_desc);
1253        uthread->tls_desc = allocate_tls();
1254        if (!uthread->tls_desc) {
1255                errno = ENOMEM;
1256                return -1;
1257        }
1258        return 0;
1259}
1260
1261static int __uthread_reinit_tls(struct uthread *uthread)
1262{
1263        uthread->tls_desc = reinit_tls(uthread->tls_desc);
1264        if (!uthread->tls_desc) {
1265                errno = ENOMEM;
1266                return -1;
1267        }
1268        return 0;
1269}
1270
1271static void __uthread_free_tls(struct uthread *uthread)
1272{
1273        free_tls(uthread->tls_desc);
1274        uthread->tls_desc = NULL;
1275}
1276
1277bool uth_2ls_is_multithreaded(void)
1278{
1279        /* thread 0 is single threaded.  For the foreseeable future, every other
1280         * 2LS will be multithreaded. */
1281        extern struct schedule_ops thread0_2ls_ops;
1282
1283        return sched_ops != &thread0_2ls_ops;
1284}
1285
1286struct uthread *uthread_create(void *(*func)(void *), void *arg)
1287{
1288        return sched_ops->thread_create(func, arg);
1289}
1290
1291/* Who does the thread_exited callback (2LS-specific cleanup)?  It depends.  If
1292 * the thread exits first, then join/detach does it.  o/w, the exit path does.
1293 *
1294 * What are the valid state changes?
1295 *
1296 *      JOINABLE   -> DETACHED (only by detach())
1297 *      JOINABLE   -> HAS_JOINER (only by join())
1298 *      JOINABLE   -> EXITED (only by uth_2ls_thread_exit())
1299 *
1300 * That's it.  The initial state is either JOINABLE or DETACHED. */
1301void uthread_detach(struct uthread *uth)
1302{
1303        struct uth_join_ctl *jc = &uth->join_ctl;
1304        long old_state;
1305
1306        do {
1307                old_state = atomic_read(&jc->state);
1308                switch (old_state) {
1309                case UTH_JOIN_EXITED:
1310                        sched_ops->thread_exited(uth);
1311                        return;
1312                case UTH_JOIN_DETACHED:
1313                        panic("Uth %p has already been detached!", uth);
1314                case UTH_JOIN_HAS_JOINER:
1315                        panic("Uth %p has a pending joiner, can't detach!",
1316                              uth);
1317                };
1318                assert(old_state == UTH_JOIN_JOINABLE);
1319        } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_DETACHED));
1320}
1321
1322/* Helper.  We have a joiner.  So we'll write the retval to the final location
1323 * (the one passed to join() and decref to wake the joiner.  This may seem a
1324 * little odd for a normal join, but it works identically a parallel join - and
1325 * there's only one wakeup (hence the kref). */
1326static void uth_post_and_kick_joiner(struct uthread *uth, void *retval)
1327{
1328        struct uth_join_ctl *jc = &uth->join_ctl;
1329
1330        if (jc->retval_loc)
1331                *jc->retval_loc = retval;
1332        /* Note the JC has a pointer to the kicker.  There's one kicker for the
1333         * joiner, but there could be many joinees. */
1334        kref_put(&jc->kicker->kref);
1335}
1336
1337/* Callback after the exiting uthread has yielded and is in vcore context.  Note
1338 * that the thread_exited callback can be called concurrently (e.g., a racing
1339 * call to detach()), so it's important to not be in the uthread's context. */
1340static void __uth_2ls_thread_exit_cb(struct uthread *uth, void *retval)
1341{
1342        struct uth_join_ctl *jc = &uth->join_ctl;
1343        long old_state;
1344
1345        do {
1346                old_state = atomic_read(&jc->state);
1347                switch (old_state) {
1348                case UTH_JOIN_DETACHED:
1349                        sched_ops->thread_exited(uth);
1350                        return;
1351                case UTH_JOIN_HAS_JOINER:
1352                        uth_post_and_kick_joiner(uth, retval);
1353                        sched_ops->thread_exited(uth);
1354                        return;
1355                case UTH_JOIN_JOINABLE:
1356                        /* This write is harmless and idempotent; we can lose
1357                         * the race and still be safe.  Assuming we don't, the
1358                         * joiner will look here for the retval.  It's temporary
1359                         * storage since we don't know the final retval location
1360                         * (since join hasn't happened yet). */
1361                        jc->retval = retval;
1362                        break;
1363                };
1364                assert(old_state == UTH_JOIN_JOINABLE);
1365        } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_EXITED));
1366        /* We were joinable, now we have exited.  A detacher or joiner will
1367         * trigger thread_exited. */
1368}
1369
1370/* 2LSs call this when their threads are exiting.  The 2LS will regain control
1371 * of the thread in sched_ops->thread_exited.  This will be after the
1372 * join/detach/exit has completed, and might be in vcore context. */
1373void __attribute__((noreturn)) uth_2ls_thread_exit(void *retval)
1374{
1375        uthread_yield(FALSE, __uth_2ls_thread_exit_cb, retval);
1376        assert(0);
1377}
1378
1379/* Helper: Attaches the caller (specifically the jk) to the target uthread.
1380 * When the thread has been joined (either due to the UTH_EXITED case or due to
1381 * __uth_2ls_thread_exit_cb), the join kicker will be decreffed. */
1382static void join_one(struct uthread *uth, struct uth_join_kicker *jk,
1383                     void **retval_loc)
1384{
1385        struct uth_join_ctl *jc = &uth->join_ctl;
1386        long old_state;
1387
1388        /* We can safely write to the join_ctl, even if we don't end up setting
1389         * HAS_JOINER.  There's only supposed to be one joiner, and if not,
1390         * we'll catch the bad state. */
1391        jc->retval_loc = retval_loc;
1392        jc->kicker = jk;
1393        do {
1394                old_state = atomic_read(&jc->state);
1395                switch (old_state) {
1396                case UTH_JOIN_EXITED:
1397                        if (retval_loc)
1398                                *retval_loc = jc->retval;
1399                        sched_ops->thread_exited(uth);
1400                        kref_put(&jk->kref);
1401                        return;
1402                case UTH_JOIN_DETACHED:
1403                        panic("Uth %p has been detached, can't join!", uth);
1404                case UTH_JOIN_HAS_JOINER:
1405                        panic("Uth %p has another pending joiner!", uth);
1406                };
1407                assert(old_state == UTH_JOIN_JOINABLE);
1408        } while (!atomic_cas(&jc->state, old_state, UTH_JOIN_HAS_JOINER));
1409}
1410
1411/* Bottom half of the join, in vcore context */
1412static void __uth_join_cb(struct uthread *uth, void *arg)
1413{
1414        struct uth_join_kicker *jk = (struct uth_join_kicker*)arg;
1415
1416        uthread_has_blocked(uth, UTH_EXT_BLK_MISC);
1417        /* After this, and after all threads join, we could be woken up. */
1418        kref_put(&jk->kref);
1419}
1420
1421static void kicker_release(struct kref *k)
1422{
1423        struct uth_join_kicker *jk = container_of(k, struct uth_join_kicker,
1424                                                  kref);
1425
1426        uthread_runnable(jk->joiner);
1427}
1428
1429void uthread_join_arr(struct uth_join_request reqs[], size_t nr_req)
1430{
1431        struct uth_join_kicker jk[1];
1432
1433        jk->joiner = current_uthread;
1434        /* One ref for each target, another for *us*, which we drop in the yield
1435         * callback.  As as soon as it is fully decreffed, our thread will be
1436         * restarted.  We must block before that (in the yield callback). */
1437        kref_init(&jk->kref, kicker_release, nr_req + 1);
1438        for (int i = 0; i < nr_req; i++)
1439                join_one(reqs[i].uth, jk, reqs[i].retval_loc);
1440        uthread_yield(TRUE, __uth_join_cb, jk);
1441}
1442
1443/* Unlike POSIX, we don't bother with returning error codes.  Anything that can
1444 * go wrong is so horrendous that you should crash (the specs say the behavior
1445 * is undefined). */
1446void uthread_join(struct uthread *uth, void **retval_loc)
1447{
1448        struct uth_join_request req[1];
1449
1450        req->uth = uth;
1451        req->retval_loc = retval_loc;
1452        uthread_join_arr(req, 1);
1453}
1454
1455static void __uth_sched_yield_cb(struct uthread *uth, void *arg)
1456{
1457        uthread_has_blocked(uth, UTH_EXT_BLK_YIELD);
1458        uthread_runnable(uth);
1459}
1460
1461void uthread_sched_yield(void)
1462{
1463        if (!uth_2ls_is_multithreaded()) {
1464                /* We're an SCP with no other threads, so we want to yield to
1465                 * other processes.  For SCPs, this will yield to the OS/other
1466                 * procs. */
1467                syscall(SYS_proc_yield, TRUE);
1468                return;
1469        }
1470        uthread_yield(TRUE, __uth_sched_yield_cb, NULL);
1471}
1472
1473struct uthread *uthread_self(void)
1474{
1475        return current_uthread;
1476}
1477