akaros/kern/src/process.c
<<
>>
Prefs
   1/* Copyright (c) 2009, 2010 The Regents of the University of California
   2 * Barret Rhoden <brho@cs.berkeley.edu>
   3 * See LICENSE for details. */
   4
   5#include <event.h>
   6#include <arch/arch.h>
   7#include <bitmask.h>
   8#include <process.h>
   9#include <atomic.h>
  10#include <smp.h>
  11#include <pmap.h>
  12#include <trap.h>
  13#include <umem.h>
  14#include <schedule.h>
  15#include <manager.h>
  16#include <stdio.h>
  17#include <assert.h>
  18#include <time.h>
  19#include <hashtable.h>
  20#include <slab.h>
  21#include <sys/queue.h>
  22#include <monitor.h>
  23#include <elf.h>
  24#include <arsc_server.h>
  25#include <kmalloc.h>
  26#include <ros/procinfo.h>
  27#include <init.h>
  28#include <rcu.h>
  29
  30struct kmem_cache *proc_cache;
  31
  32/* Other helpers, implemented later. */
  33static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid);
  34static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid);
  35static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid);
  36static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid);
  37static void __proc_free(struct kref *kref);
  38static bool scp_is_vcctx_ready(struct preempt_data *vcpd);
  39static void save_vc_fp_state(struct preempt_data *vcpd);
  40static void restore_vc_fp_state(struct preempt_data *vcpd);
  41
  42/* PID management. */
  43#define PID_MAX 32767 // goes from 0 to 32767, with 0 reserved
  44static DECL_BITMASK(pid_bmask, PID_MAX + 1);
  45spinlock_t pid_bmask_lock = SPINLOCK_INITIALIZER;
  46struct hashtable *pid_hash;
  47spinlock_t pid_hash_lock; // initialized in proc_init
  48
  49/* Finds the next free entry (zero) entry in the pid_bitmask.  Set means busy.
  50 * PID 0 is reserved (in proc_init).  A return value of 0 is a failure (and
  51 * you'll also see a warning, for now).  Consider doing this with atomics. */
  52static pid_t get_free_pid(void)
  53{
  54        static pid_t next_free_pid = 1;
  55        pid_t my_pid = 0;
  56
  57        spin_lock(&pid_bmask_lock);
  58        // atomically (can lock for now, then change to atomic_and_return
  59        FOR_CIRC_BUFFER(next_free_pid, PID_MAX + 1, i) {
  60                // always points to the next to test
  61                next_free_pid = (next_free_pid + 1) % (PID_MAX + 1);
  62                if (!GET_BITMASK_BIT(pid_bmask, i)) {
  63                        SET_BITMASK_BIT(pid_bmask, i);
  64                        my_pid = i;
  65                        break;
  66                }
  67        }
  68        spin_unlock(&pid_bmask_lock);
  69        if (!my_pid)
  70                warn("Unable to find a PID!  You need to deal with this!\n");
  71        return my_pid;
  72}
  73
  74/* Return a pid to the pid bitmask */
  75static void put_free_pid(pid_t pid)
  76{
  77        spin_lock(&pid_bmask_lock);
  78        CLR_BITMASK_BIT(pid_bmask, pid);
  79        spin_unlock(&pid_bmask_lock);
  80}
  81
  82/* 'resume' is the time int ticks of the most recent onlining.  'total' is the
  83 * amount of time in ticks consumed up to and including the current offlining.
  84 *
  85 * We could move these to the map and unmap of vcores, though not every place
  86 * uses that (SCPs, in particular).  However, maps/unmaps happen remotely;
  87 * something to consider.  If we do it remotely, we can batch them up and do one
  88 * rdtsc() for all of them.  For now, I want to do them on the core, around when
  89 * we do the context change.  It'll also parallelize the accounting a bit. */
  90void vcore_account_online(struct proc *p, uint32_t vcoreid)
  91{
  92        struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
  93
  94        vc->resume_ticks = read_tsc();
  95}
  96
  97void vcore_account_offline(struct proc *p, uint32_t vcoreid)
  98{
  99        struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
 100        vc->total_ticks += read_tsc() - vc->resume_ticks;
 101}
 102
 103uint64_t vcore_account_gettotal(struct proc *p, uint32_t vcoreid)
 104{
 105        struct vcore *vc = &p->procinfo->vcoremap[vcoreid];
 106
 107        return vc->total_ticks;
 108}
 109
 110/* While this could be done with just an assignment, this gives us the
 111 * opportunity to check for bad transitions.  Might compile these out later, so
 112 * we shouldn't rely on them for sanity checking from userspace.  */
 113int __proc_set_state(struct proc *p, uint32_t state)
 114{
 115        uint32_t curstate = p->state;
 116        /* Valid transitions:
 117         * C   -> RBS
 118         * C   -> D
 119         * RBS -> RGS
 120         * RGS -> RBS
 121         * RGS -> W
 122         * RGM -> W
 123         * W   -> RBS
 124         * W   -> RGS
 125         * W   -> RBM
 126         * W   -> D
 127         * RGS -> RBM
 128         * RBM -> RGM
 129         * RGM -> RBM
 130         * RGM -> RBS
 131         * RGS -> D
 132         * RGM -> D
 133         * D   -> DA
 134         *
 135         * These ought to be implemented later (allowed, not thought through
 136         * yet).
 137         * RBS -> D
 138         * RBM -> D
 139         */
 140        #if 1 // some sort of correctness flag
 141        switch (curstate) {
 142        case PROC_CREATED:
 143                if (!(state & (PROC_RUNNABLE_S | PROC_DYING)))
 144                        goto invalid_state_transition;
 145                break;
 146        case PROC_RUNNABLE_S:
 147                if (!(state & (PROC_RUNNING_S | PROC_DYING)))
 148                        goto invalid_state_transition;
 149                break;
 150        case PROC_RUNNING_S:
 151                if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING
 152                               | PROC_DYING)))
 153                        goto invalid_state_transition;
 154                break;
 155        case PROC_WAITING:
 156                if (!(state & (PROC_RUNNABLE_S | PROC_RUNNING_S |
 157                               PROC_RUNNABLE_M | PROC_DYING)))
 158                        goto invalid_state_transition;
 159                break;
 160        case PROC_DYING:
 161                if (state != PROC_DYING_ABORT)
 162                        goto invalid_state_transition;
 163                break;
 164        case PROC_DYING_ABORT:
 165                goto invalid_state_transition;
 166        case PROC_RUNNABLE_M:
 167                if (!(state & (PROC_RUNNING_M | PROC_DYING)))
 168                        goto invalid_state_transition;
 169                break;
 170        case PROC_RUNNING_M:
 171                if (!(state & (PROC_RUNNABLE_S | PROC_RUNNABLE_M | PROC_WAITING
 172                               | PROC_DYING)))
 173                        goto invalid_state_transition;
 174                break;
 175invalid_state_transition:
 176                panic("Invalid State Transition! %s to %02x",
 177                      procstate2str(state), state);
 178        }
 179        #endif
 180        p->state = state;
 181        return 0;
 182}
 183
 184/* Returns a pointer to the proc with the given pid, or 0 if there is none.
 185 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
 186 * process is dying and we should not have the ref (and thus return 0).  We need
 187 * to lock to protect us from getting p, (someone else removes and frees p),
 188 * then get_not_zero() on p.
 189 * Don't push the locking into the hashtable without dealing with this. */
 190struct proc *pid2proc(pid_t pid)
 191{
 192        spin_lock(&pid_hash_lock);
 193        struct proc *p = hashtable_search(pid_hash, (void*)(long)pid);
 194
 195        if (p)
 196                if (!kref_get_not_zero(&p->p_kref, 1))
 197                        p = 0;
 198        spin_unlock(&pid_hash_lock);
 199        return p;
 200}
 201
 202/* Used by devproc for successive reads of the proc table.
 203 * Returns a pointer to the nth proc, or 0 if there is none.
 204 * This uses get_not_zero, since it is possible the refcnt is 0, which means the
 205 * process is dying and we should not have the ref (and thus return 0).  We need
 206 * to lock to protect us from getting p, (someone else removes and frees p),
 207 * then get_not_zero() on p.
 208 * Don't push the locking into the hashtable without dealing with this. */
 209struct proc *pid_nth(unsigned int n)
 210{
 211        struct proc *p;
 212        spin_lock(&pid_hash_lock);
 213        if (!hashtable_count(pid_hash)) {
 214                spin_unlock(&pid_hash_lock);
 215                return NULL;
 216        }
 217        struct hashtable_itr *iter = hashtable_iterator(pid_hash);
 218        p = hashtable_iterator_value(iter);
 219
 220        while (p) {
 221                /* if this process is not valid, it doesn't count,
 222                 * so continue
 223                 */
 224
 225                if (kref_get_not_zero(&p->p_kref, 1)) {
 226                        /* this one counts */
 227                        if (! n){
 228                                printd("pid_nth: at end, p %p\n", p);
 229                                break;
 230                        }
 231                        kref_put(&p->p_kref);
 232                        n--;
 233                }
 234                if (!hashtable_iterator_advance(iter)) {
 235                        p = NULL;
 236                        break;
 237                }
 238                p = hashtable_iterator_value(iter);
 239        }
 240
 241        spin_unlock(&pid_hash_lock);
 242        kfree(iter);
 243        return p;
 244}
 245
 246/* Performs any initialization related to processes, such as create the proc
 247 * cache, prep the scheduler, etc.  When this returns, we should be ready to use
 248 * any process related function. */
 249void proc_init(void)
 250{
 251        /* Catch issues with the vcoremap and TAILQ_ENTRY sizes */
 252        static_assert(sizeof(TAILQ_ENTRY(vcore)) == sizeof(void*) * 2);
 253        proc_cache = kmem_cache_create("proc", sizeof(struct proc),
 254                                       MAX(ARCH_CL_SIZE,
 255                                       __alignof__(struct proc)), 0, NULL, 0,
 256                                       0, NULL);
 257        /* Init PID mask and hash.  pid 0 is reserved. */
 258        SET_BITMASK_BIT(pid_bmask, 0);
 259        spinlock_init(&pid_hash_lock);
 260        spin_lock(&pid_hash_lock);
 261        pid_hash = create_hashtable(100, __generic_hash, __generic_eq);
 262        spin_unlock(&pid_hash_lock);
 263        schedule_init();
 264
 265        atomic_init(&num_envs, 0);
 266}
 267
 268void proc_set_username(struct proc *p, char *name)
 269{
 270        set_username(&p->user, name);
 271}
 272
 273/*
 274 * Copies username from the parent process. This is the only case where a
 275 * reader blocks writing, just to be extra safe during process initialization.
 276 *
 277 * Note that since this is intended to be called during initialization, the
 278 * child's name lock is NOT used for writing. Nothing else should be able to
 279 * read or write yet, so this can be a simple memcpy once the parent is locked.
 280 */
 281void proc_inherit_parent_username(struct proc *child, struct proc *parent)
 282{
 283        spin_lock(&parent->user.name_lock);
 284
 285        // copy entire parent buffer for constant runtime
 286        memcpy(child->user.name, parent->user.name, sizeof(child->user.name));
 287
 288        spin_unlock(&parent->user.name_lock);
 289}
 290
 291void proc_set_progname(struct proc *p, char *name)
 292{
 293        if (name == NULL)
 294                name = DEFAULT_PROGNAME;
 295
 296        /* might have an issue if a dentry name isn't null terminated, and we'd
 297         * get extra junk up to progname_sz. Or crash. */
 298        strlcpy(p->progname, name, PROC_PROGNAME_SZ);
 299}
 300
 301void proc_replace_binary_path(struct proc *p, char *path)
 302{
 303        if (p->binary_path)
 304                free_path(p, p->binary_path);
 305        p->binary_path = path;
 306}
 307
 308/* Be sure you init'd the vcore lists before calling this. */
 309void proc_init_procinfo(struct proc* p)
 310{
 311        p->procinfo->pid = p->pid;
 312        p->procinfo->ppid = p->ppid;
 313        p->procinfo->max_vcores = max_vcores(p);
 314        p->procinfo->tsc_freq = __proc_global_info.tsc_freq;
 315        p->procinfo->timing_overhead = __proc_global_info.tsc_overhead;
 316        p->procinfo->program_end = 0;
 317        /* 0'ing the arguments.  Some higher function will need to set them */
 318        memset(p->procinfo->res_grant, 0, sizeof(p->procinfo->res_grant));
 319        /* 0'ing the vcore/pcore map.  Will link the vcores later. */
 320        memset(&p->procinfo->vcoremap, 0, sizeof(p->procinfo->vcoremap));
 321        memset(&p->procinfo->pcoremap, 0, sizeof(p->procinfo->pcoremap));
 322        p->procinfo->num_vcores = 0;
 323        p->procinfo->is_mcp = FALSE;
 324        p->procinfo->coremap_seqctr = SEQCTR_INITIALIZER;
 325        /* It's a bug in the kernel if we let them ask for more than max */
 326        for (int i = 0; i < p->procinfo->max_vcores; i++) {
 327                TAILQ_INSERT_TAIL(&p->inactive_vcs, &p->procinfo->vcoremap[i],
 328                                  list);
 329        }
 330}
 331
 332void proc_init_procdata(struct proc *p)
 333{
 334        memset(p->procdata, 0, sizeof(struct procdata));
 335        /* processes can't go into vc context on vc 0 til they unset this.  This
 336         * is for processes that block before initing uthread code (like rtld).
 337         */
 338        atomic_set(&p->procdata->vcore_preempt_data[0].flags, VC_SCP_NOVCCTX);
 339}
 340
 341static void proc_open_stdfds(struct proc *p)
 342{
 343        int fd;
 344        struct proc *old_current = current;
 345
 346        /* Due to the way the syscall helpers assume the target process is
 347         * current, we need to set current temporarily.  We don't use switch_to,
 348         * since that actually loads the process's address space, which might be
 349         * empty or incomplete.  These syscalls shouldn't access user memory,
 350         * especially considering how we're probably in the boot pgdir. */
 351        current = p;
 352        fd = sysopenat(AT_FDCWD, "#cons/stdin", O_READ, 0);
 353        assert(fd == 0);
 354        fd = sysopenat(AT_FDCWD, "#cons/stdout", O_WRITE, 0);
 355        assert(fd == 1);
 356        fd = sysopenat(AT_FDCWD, "#cons/stderr", O_WRITE, 0);
 357        assert(fd == 2);
 358        current = old_current;
 359}
 360
 361/* Allocates and initializes a process, with the given parent.  Currently
 362 * writes the *p into **pp, and returns 0 on success, < 0 for an error.
 363 * Errors include:
 364 *  - ENOFREEPID if it can't get a PID
 365 *  - ENOMEM on memory exhaustion */
 366error_t proc_alloc(struct proc **pp, struct proc *parent, int flags)
 367{
 368        error_t r;
 369        struct proc *p;
 370
 371        if (!(p = kmem_cache_alloc(proc_cache, 0)))
 372                return -ENOMEM;
 373        /* zero everything by default, other specific items are set below */
 374        memset(p, 0, sizeof(*p));
 375
 376        /* only one ref, which we pass back.  the old 'existence' ref is managed
 377         * by the ksched */
 378        kref_init(&p->p_kref, __proc_free, 1);
 379        /* Initialize the address space */
 380        if ((r = env_setup_vm(p)) < 0) {
 381                kmem_cache_free(proc_cache, p);
 382                return r;
 383        }
 384        if (!(p->pid = get_free_pid())) {
 385                kmem_cache_free(proc_cache, p);
 386                return -ENOFREEPID;
 387        }
 388        if (parent && parent->binary_path)
 389                kstrdup(&p->binary_path, parent->binary_path);
 390        /* Set the basic status variables. */
 391        spinlock_init(&p->proc_lock);
 392        spinlock_init(&p->user.name_lock);
 393        /* so we can see processes killed by the kernel */
 394        p->exitcode = 1337;
 395        if (parent) {
 396                p->ppid = parent->pid;
 397                proc_inherit_parent_username(p, parent);
 398                proc_incref(p, 1);      /* storing a ref in the parent */
 399                /* using the CV's lock to protect anything related to child
 400                 * waiting */
 401                cv_lock(&parent->child_wait);
 402                TAILQ_INSERT_TAIL(&parent->children, p, sibling_link);
 403                cv_unlock(&parent->child_wait);
 404        } else {
 405                p->ppid = 0;
 406                strlcpy(p->user.name, eve.name, sizeof(p->user.name));
 407                printk("Parentless process assigned username '%s'\n",
 408                       p->user.name);
 409        }
 410        TAILQ_INIT(&p->children);
 411        cv_init(&p->child_wait);
 412        /* shouldn't go through state machine for init */
 413        p->state = PROC_CREATED;
 414        p->env_flags = 0;
 415        spinlock_init(&p->vmr_lock);
 416        spinlock_init(&p->pte_lock);
 417        TAILQ_INIT(&p->vm_regions); /* could init this in the slab */
 418        p->vmr_history = 0;
 419        /* Initialize the vcore lists, we'll build the inactive list so that it
 420         * includes all vcores when we initialize procinfo.  Do this before
 421         * initing procinfo. */
 422        TAILQ_INIT(&p->online_vcs);
 423        TAILQ_INIT(&p->bulk_preempted_vcs);
 424        TAILQ_INIT(&p->inactive_vcs);
 425        /* Init procinfo/procdata.  Procinfo's argp/argb are 0'd */
 426        proc_init_procinfo(p);
 427        proc_init_procdata(p);
 428
 429        /* Initialize the generic sysevent ring buffer */
 430        SHARED_RING_INIT(&p->procdata->syseventring);
 431        /* Initialize the frontend of the sysevent ring buffer */
 432        FRONT_RING_INIT(&p->syseventfrontring,
 433                        &p->procdata->syseventring,
 434                        SYSEVENTRINGSIZE);
 435
 436        /* Init FS structures TODO: cleanup (might pull this out) */
 437        p->umask = parent ? parent->umask : S_IWGRP | S_IWOTH;
 438        memset(&p->open_files, 0, sizeof(p->open_files)); /* slightly ghetto */
 439        spinlock_init(&p->open_files.lock);
 440        p->open_files.max_files = NR_OPEN_FILES_DEFAULT;
 441        p->open_files.max_fdset = NR_FILE_DESC_DEFAULT;
 442        p->open_files.fd = p->open_files.fd_array;
 443        p->open_files.open_fds = (struct fd_set*)&p->open_files.open_fds_init;
 444        if (parent) {
 445                if (flags & PROC_DUP_FGRP)
 446                        clone_fdt(&parent->open_files, &p->open_files);
 447        } else {
 448                /* no parent, we're created from the kernel */
 449                proc_open_stdfds(p);
 450        }
 451        /* Init the ucq hash lock */
 452        p->ucq_hashlock = (struct hashlock*)&p->ucq_hl_noref;
 453        hashlock_init_irqsave(p->ucq_hashlock, HASHLOCK_DEFAULT_SZ);
 454
 455        atomic_inc(&num_envs);
 456        plan9setup(p, parent, flags);
 457        devalarm_init(p);
 458        TAILQ_INIT(&p->abortable_sleepers);
 459        spinlock_init_irqsave(&p->abort_list_lock);
 460        memset(&p->vmm, 0, sizeof(struct vmm));
 461        spinlock_init(&p->vmm.lock);
 462        qlock_init(&p->vmm.qlock);
 463        TAILQ_INIT(&p->pci_devices);
 464        printd("[%08x] new process %08x\n", current ? current->pid : 0, p->pid);
 465        *pp = p;
 466        return 0;
 467}
 468
 469/* We have a bunch of different ways to make processes.  Call this once the
 470 * process is ready to be used by the rest of the system.  For now, this just
 471 * means when it is ready to be named via the pidhash.  In the future, we might
 472 * push setting the state to CREATED into here. */
 473void __proc_ready(struct proc *p)
 474{
 475        /* Tell the ksched about us.  TODO: do we need to worry about the ksched
 476         * doing stuff to us before we're added to the pid_hash? */
 477        __sched_proc_register(p);
 478        spin_lock(&pid_hash_lock);
 479        hashtable_insert(pid_hash, (void*)(long)p->pid, p);
 480        spin_unlock(&pid_hash_lock);
 481}
 482
 483/* Creates a process from the specified file, argvs, and envps. */
 484struct proc *proc_create(struct file_or_chan *prog, char **argv, char **envp)
 485{
 486        struct proc *p;
 487        error_t r;
 488        int ret;
 489
 490        if ((r = proc_alloc(&p, current, 0 /* flags */)) < 0)
 491                panic("proc_create: %d", r);
 492        int argc = 0, envc = 0;
 493        if(argv) while(argv[argc]) argc++;
 494        if(envp) while(envp[envc]) envc++;
 495        proc_set_progname(p, argc ? argv[0] : NULL);
 496        ret = load_elf(p, prog, argc, argv, envc, envp);
 497        assert(ret == 0);
 498        __proc_ready(p);
 499        return p;
 500}
 501
 502static int __cb_assert_no_pg(struct proc *p, pte_t pte, void *va, void *arg)
 503{
 504        assert(pte_is_unmapped(pte));
 505        return 0;
 506}
 507
 508/* This is called by kref_put(), once the last reference to the process is
 509 * gone.  Don't call this otherwise (it will panic).  It will clean up the
 510 * address space and deallocate any other used memory. */
 511static void __proc_free(struct kref *kref)
 512{
 513        struct proc *p = container_of(kref, struct proc, p_kref);
 514        void *hash_ret;
 515        physaddr_t pa;
 516
 517        printd("[PID %d] freeing proc: %d\n", current ? current->pid : 0,
 518               p->pid);
 519        // All parts of the kernel should have decref'd before __proc_free is
 520        // called
 521        assert(kref_refcnt(&p->p_kref) == 0);
 522        assert(TAILQ_EMPTY(&p->alarmset.list));
 523
 524        if (p->strace) {
 525                kref_put(&p->strace->procs);
 526                kref_put(&p->strace->users);
 527        }
 528        __vmm_struct_cleanup(p);
 529        p->progname[0] = 0;
 530        free_path(p, p->binary_path);
 531        cclose(p->dot);
 532        cclose(p->slash);
 533        p->dot = p->slash = 0; /* catch bugs */
 534        /* now we'll finally decref files for the file-backed vmrs */
 535        unmap_and_destroy_vmrs(p);
 536        /* Remove us from the pid_hash and give our PID back (in that order). */
 537        spin_lock(&pid_hash_lock);
 538        hash_ret = hashtable_remove(pid_hash, (void*)(long)p->pid);
 539        spin_unlock(&pid_hash_lock);
 540        /* might not be in the hash/ready, if we failed during proc creation */
 541        if (hash_ret)
 542                put_free_pid(p->pid);
 543        else
 544                printd("[kernel] pid %d not in the PID hash in %s\n", p->pid,
 545                       __FUNCTION__);
 546        /* All memory below UMAPTOP should have been freed via the VMRs.  The
 547         * stuff above is the global info/page and procinfo/procdata.  We free
 548         * procinfo and procdata, but not the global memory - that's system
 549         * wide.  We could clear the PTEs of the upper stuff (UMAPTOP to UVPT),
 550         * but we shouldn't need to. */
 551        env_user_mem_walk(p, 0, UMAPTOP, __cb_assert_no_pg, 0);
 552        kpages_free(p->procinfo, PROCINFO_NUM_PAGES * PGSIZE);
 553        kpages_free(p->procdata, PROCDATA_NUM_PAGES * PGSIZE);
 554
 555        env_pagetable_free(p);
 556        arch_pgdir_clear(&p->env_pgdir);
 557        p->env_cr3 = 0;
 558
 559        atomic_dec(&num_envs);
 560
 561        /* Dealloc the struct proc */
 562        kmem_cache_free(proc_cache, p);
 563}
 564
 565/* Whether or not actor can control target.  TODO: do something reasonable here.
 566 * Just checking for the parent is a bit limiting.  Could walk the parent-child
 567 * tree, check user ids, or some combination.  Make sure actors can always
 568 * control themselves. */
 569bool proc_controls(struct proc *actor, struct proc *target)
 570{
 571        return TRUE;
 572        #if 0 /* Example: */
 573        return ((actor == target) || (target->ppid == actor->pid));
 574        #endif
 575}
 576
 577/* Helper to incref by val.  Using the helper to help debug/interpose on proc
 578 * ref counting.  Note that pid2proc doesn't use this interface. */
 579void proc_incref(struct proc *p, unsigned int val)
 580{
 581        kref_get(&p->p_kref, val);
 582}
 583
 584/* Helper to decref for debugging.  Don't directly kref_put() for now. */
 585void proc_decref(struct proc *p)
 586{
 587        kref_put(&p->p_kref);
 588}
 589
 590/* Helper, makes p the 'current' process, dropping the old current/cr3.  This no
 591 * longer assumes the passed in reference already counted 'current'.  It will
 592 * incref internally when needed. */
 593static void __set_proc_current(struct proc *p)
 594{
 595        /* We use the pcpui to access 'current' to cut down on the core_id()
 596         * calls, though who know how expensive/painful they are. */
 597        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 598        struct proc *old_proc;
 599
 600        /* If the process wasn't here, then we need to load its address space */
 601        if (p != pcpui->cur_proc) {
 602                proc_incref(p, 1);
 603                lcr3(p->env_cr3);
 604                /* This is "leaving the process context" of the previous proc.
 605                 * The previous lcr3 unloaded the previous proc's context.  This
 606                 * should rarely happen, since we usually proactively leave
 607                 * process context, but this is the fallback. */
 608                old_proc = pcpui->cur_proc;
 609                pcpui->cur_proc = p;
 610                if (old_proc)
 611                        proc_decref(old_proc);
 612        }
 613}
 614
 615/* Flag says if vcore context is not ready, which is set in init_procdata.  The
 616 * process must turn off this flag on vcore0 at some point.  It's off by default
 617 * on all other vcores. */
 618static bool scp_is_vcctx_ready(struct preempt_data *vcpd)
 619{
 620        return !(atomic_read(&vcpd->flags) & VC_SCP_NOVCCTX);
 621}
 622
 623/* Dispatches a _S process to run on the current core.  This should never be
 624 * called to "restart" a core.
 625 *
 626 * This will always return, regardless of whether or not the calling core is
 627 * being given to a process. (it used to pop the tf directly, before we had
 628 * cur_ctx).
 629 *
 630 * Since it always returns, it will never "eat" your reference (old
 631 * documentation talks about this a bit). */
 632void proc_run_s(struct proc *p)
 633{
 634        uint32_t coreid = core_id();
 635        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
 636        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
 637
 638        spin_lock(&p->proc_lock);
 639        switch (p->state) {
 640        case (PROC_DYING):
 641        case (PROC_DYING_ABORT):
 642                spin_unlock(&p->proc_lock);
 643                printk("[kernel] _S %d not starting: async death\n",
 644                       p->pid);
 645                return;
 646        case (PROC_RUNNABLE_S):
 647                __proc_set_state(p, PROC_RUNNING_S);
 648                /* SCPs don't have full vcores, but they act like they have
 649                 * vcore 0.  We map the vcore, since we will want to know where
 650                 * this process is running, even if it is only in RUNNING_S.  We
 651                 * can use the vcoremap, which makes death easy.  num_vcores is
 652                 * still 0, and we do account the time online and offline. */
 653                __seq_start_write(&p->procinfo->coremap_seqctr);
 654                p->procinfo->num_vcores = 0;
 655                __map_vcore(p, 0, coreid);
 656                vcore_account_online(p, 0);
 657                __seq_end_write(&p->procinfo->coremap_seqctr);
 658                /* incref, since we're saving a reference in owning proc later*/
 659                proc_incref(p, 1);
 660                /* lock was protecting the state and VC mapping, not pcpui stuff
 661                 */
 662                spin_unlock(&p->proc_lock);
 663                /* redundant with proc_startcore, might be able to remove that
 664                 * one */
 665                __set_proc_current(p);
 666                /* set us up as owning_proc.  ksched bug if there is already
 667                 * one, for now.  can simply clear_owning if we want to. */
 668                assert(!pcpui->owning_proc);
 669                pcpui->owning_proc = p;
 670                pcpui->owning_vcoreid = 0;
 671                restore_vc_fp_state(vcpd);
 672                /* similar to the old __startcore, start them in vcore context
 673                 * if they have notifs and aren't already in vcore context.
 674                 * o/w, start them wherever they were before (could be either vc
 675                 * ctx or not) */
 676                if (!vcpd->notif_disabled && vcpd->notif_pending
 677                                          && scp_is_vcctx_ready(vcpd)) {
 678                        vcpd->notif_disabled = TRUE;
 679                        /* save the _S's ctx in the uthread slot, build and pop
 680                         * a new one in actual/cur_ctx. */
 681                        vcpd->uthread_ctx = p->scp_ctx;
 682                        pcpui->cur_ctx = &pcpui->actual_ctx;
 683                        memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
 684                        proc_init_ctx(pcpui->cur_ctx, 0, vcpd->vcore_entry,
 685                                      vcpd->vcore_stack, vcpd->vcore_tls_desc);
 686                } else {
 687                        /* If they have no transition stack, then they can't
 688                         * receive events.  The most they are getting is a
 689                         * wakeup from the kernel.  They won't even turn off
 690                         * notif_pending, so we'll do that for them. */
 691                        if (!scp_is_vcctx_ready(vcpd))
 692                                vcpd->notif_pending = FALSE;
 693                        /* this is one of the few times cur_ctx != &actual_ctx*/
 694                        pcpui->cur_ctx = &p->scp_ctx;
 695                }
 696                /* When the calling core idles, it'll call restartcore and run
 697                 * the _S process's context. */
 698                return;
 699        default:
 700                spin_unlock(&p->proc_lock);
 701                panic("Invalid process state %p in %s()!!", p->state,
 702                      __FUNCTION__);
 703        }
 704}
 705
 706/* Helper: sends preempt messages to all vcores on the bulk preempt list, and
 707 * moves them to the inactive list. */
 708static void __send_bulkp_events(struct proc *p)
 709{
 710        struct vcore *vc_i, *vc_temp;
 711        struct event_msg preempt_msg = {0};
 712
 713        /* Whenever we send msgs with the proc locked, we need at least 1 online
 714         */
 715        assert(!TAILQ_EMPTY(&p->online_vcs));
 716        /* Send preempt messages for any left on the BP list.  No need to set
 717         * any flags, it all was done on the real preempt.  Now we're just
 718         * telling the process about any that didn't get restarted and are still
 719         * preempted. */
 720        TAILQ_FOREACH_SAFE(vc_i, &p->bulk_preempted_vcs, list, vc_temp) {
 721                /* Note that if there are no active vcores, send_k_e will post
 722                 * to our own vcore, the last of which will be put on the
 723                 * inactive list and be the first to be started.  We could have
 724                 * issues with deadlocking, since send_k_e() could grab the
 725                 * proclock (if there are no active vcores) */
 726                preempt_msg.ev_type = EV_VCORE_PREEMPT;
 727                preempt_msg.ev_arg2 = vcore2vcoreid(p, vc_i); /* arg2 32 bits */
 728                send_kernel_event(p, &preempt_msg, 0);
 729                /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does
 730                 * that.  We need a loop for the messages, but not necessarily
 731                 * for the list changes.  */
 732                TAILQ_REMOVE(&p->bulk_preempted_vcs, vc_i, list);
 733                TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
 734        }
 735}
 736
 737/* Run an _M.  Can be called safely on one that is already running.  Hold the
 738 * lock before calling.  Other than state checks, this just starts up the _M's
 739 * vcores, much like the second part of give_cores_running.  More specifically,
 740 * give_cores_runnable puts cores on the online list, which this then sends
 741 * messages to.  give_cores_running immediately puts them on the list and sends
 742 * the message.  the two-step style may go out of fashion soon.
 743 *
 744 * This expects that the "instructions" for which core(s) to run this on will be
 745 * in the vcoremap, which needs to be set externally (give_cores()). */
 746void __proc_run_m(struct proc *p)
 747{
 748        struct vcore *vc_i;
 749        switch (p->state) {
 750        case (PROC_WAITING):
 751        case (PROC_DYING):
 752        case (PROC_DYING_ABORT):
 753                warn("ksched tried to run proc %d in state %s\n", p->pid,
 754                     procstate2str(p->state));
 755                return;
 756        case (PROC_RUNNABLE_M):
 757                /* vcoremap[i] holds the coreid of the physical core allocated
 758                 * to this process.  It is set outside proc_run. */
 759                if (p->procinfo->num_vcores) {
 760                        __send_bulkp_events(p);
 761                        __proc_set_state(p, PROC_RUNNING_M);
 762                        /* Up the refcnt, to avoid the n refcnt upping on the
 763                         * destination cores.  Keep in sync with __startcore */
 764                        proc_incref(p, p->procinfo->num_vcores * 2);
 765                        /* Send kernel messages to all online vcores (which were
 766                         * added to the list and mapped in __proc_give_cores()),
 767                         * making them turn online */
 768                        TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
 769                                send_kernel_message(vc_i->pcoreid, __startcore,
 770                                        (long)p,
 771                                        (long)vcore2vcoreid(p, vc_i),
 772                                        (long)vc_i->nr_preempts_sent,
 773                                        KMSG_ROUTINE);
 774                        }
 775                } else {
 776                        warn("Tried to proc_run() an _M with no vcores!");
 777                }
 778                /* There a subtle race avoidance here (when we unlock after
 779                 * sending the message).  __proc_startcore can handle a death
 780                 * message, but we can't have the startcore come after the death
 781                 * message.  Otherwise, it would look like a new process.  So we
 782                 * hold the lock til after we send our message, which prevents a
 783                 * possible death message.
 784                 * - Note there is no guarantee this core's interrupts were on,
 785                 *   so it may not get the message for a while... */
 786                return;
 787        case (PROC_RUNNING_M):
 788                return;
 789        default:
 790                /* unlock just so the monitor can call something that might
 791                 * lock*/
 792                spin_unlock(&p->proc_lock);
 793                panic("Invalid process state %p in %s()!!", p->state,
 794                      __FUNCTION__);
 795        }
 796}
 797
 798/* You must disable IRQs and PRKM before calling this.
 799 *
 800 * Actually runs the given context (trapframe) of process p on the core this
 801 * code executes on.  This is called directly by __startcore, which needs to
 802 * bypass the routine_kmsg check.  Interrupts should be off when you call this.
 803 *
 804 * A note on refcnting: this function will not return, and your proc reference
 805 * will be ignored (not decreffed).  It may be incref'd, if cur_proc was not
 806 * set.  Pass in an already-accounted-for ref, such as owning_proc. */
 807void __proc_startcore(struct proc *p, struct user_context *ctx)
 808{
 809        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 810
 811        assert(!irq_is_enabled());
 812        /* Should never have ktask still set.  If we do, future syscalls could
 813         * try to block later and lose track of our address space. */
 814        assert(!is_ktask(pcpui->cur_kthread));
 815        __set_proc_current(p);
 816        __set_cpu_state(pcpui, CPU_STATE_USER);
 817        proc_pop_ctx(ctx);
 818}
 819
 820/* Restarts/runs the current_ctx, which must be for the current process, on the
 821 * core this code executes on.
 822 *
 823 * For now, we just smp_idle.  We used to do something similar, but customized
 824 * for expecting to return to the process.  But it was a source of bugs.  If we
 825 * want to optimize for the case where we know we had a process current, then we
 826 * can do so here.
 827 *
 828 * Note that PRKM currently calls smp_idle() if it ever has a message, so the
 829 * value of optimizing may depend on the semantics of PRKM. */
 830void proc_restartcore(void)
 831{
 832        smp_idle();
 833}
 834
 835/* Helper for proc_destroy.  Disowns any children. */
 836static void proc_disown_children(struct proc *parent)
 837{
 838        struct proc *child_i, *temp;
 839        struct proc_list todo = TAILQ_HEAD_INITIALIZER(todo);
 840        int ret;
 841
 842        cv_lock(&parent->child_wait);
 843        TAILQ_FOREACH_SAFE(child_i, &parent->children, sibling_link, temp) {
 844                ret = __proc_disown_child(parent, child_i);
 845                /* should never fail, lock should cover the race.  invariant:
 846                 * any child on the list should have us as a parent */
 847                assert(!ret);
 848                TAILQ_INSERT_TAIL(&todo, child_i, sibling_link);
 849        }
 850        cv_unlock(&parent->child_wait);
 851
 852        TAILQ_FOREACH_SAFE(child_i, &todo, sibling_link, temp)
 853                proc_decref(child_i);
 854}
 855
 856/* Destroys the process.  It will destroy the process and return any cores
 857 * to the ksched via the __sched_proc_destroy() CB.
 858 *
 859 * Here's the way process death works:
 860 * 0. grab the lock (protects state transition and core map)
 861 * 1. set state to dying.  that keeps the kernel from doing anything for the
 862 * process (like proc_running it).
 863 * 2. figure out where the process is running (cross-core/async or RUNNING_M)
 864 * 3. IPI to clean up those cores (decref, etc).
 865 * 4. Unlock
 866 * 5. Clean up your core, if applicable
 867 * (Last core/kernel thread to decref cleans up and deallocates resources.)
 868 *
 869 * Note that some cores can be processing async calls, but will eventually
 870 * decref.  Should think about this more, like some sort of callback/revocation.
 871 *
 872 * This function will now always return (it used to not return if the calling
 873 * core was dying).  However, when it returns, a kernel message will eventually
 874 * come in, making you abandon_core, as if you weren't running.  It may be that
 875 * the only reference to p is the one you passed in, and when you decref, it'll
 876 * get __proc_free()d. */
 877void proc_destroy(struct proc *p)
 878{
 879        uint32_t nr_cores_revoked = 0;
 880        struct kthread *sleeper;
 881        struct proc *child_i, *temp;
 882
 883        spin_lock(&p->proc_lock);
 884        /* storage for pc_arr is alloced at decl, which is after grabbing the
 885         * lock*/
 886        uint32_t pc_arr[p->procinfo->num_vcores];
 887        switch (p->state) {
 888        case PROC_DYING: /* someone else killed this already. */
 889        case (PROC_DYING_ABORT):
 890                spin_unlock(&p->proc_lock);
 891                return;
 892        case PROC_CREATED:
 893        case PROC_RUNNABLE_S:
 894        case PROC_WAITING:
 895                break;
 896        case PROC_RUNNABLE_M:
 897        case PROC_RUNNING_M:
 898                /* Need to reclaim any cores this proc might have, even if it's
 899                 * not running yet.  Those running will receive a __death */
 900                nr_cores_revoked = __proc_take_allcores(p, pc_arr, FALSE);
 901                break;
 902        case PROC_RUNNING_S:
 903                #if 0
 904                // here's how to do it manually
 905                if (current == p) {
 906                        lcr3(boot_cr3);
 907                        current = NULL;
 908                        proc_decref(p);         /* this decref is for the cr3 */
 909                }
 910                #endif
 911                send_kernel_message(get_pcoreid(p, 0), __death, (long)p, 0, 0,
 912                                    KMSG_ROUTINE);
 913                __seq_start_write(&p->procinfo->coremap_seqctr);
 914                __unmap_vcore(p, 0);
 915                __seq_end_write(&p->procinfo->coremap_seqctr);
 916                /* If we ever have RUNNING_S run on non-mgmt cores, we'll need
 917                 * to tell the ksched about this now-idle core (after unlocking)
 918                 */
 919                break;
 920        default:
 921                warn("Weird state(%s) in %s()", procstate2str(p->state),
 922                     __FUNCTION__);
 923                spin_unlock(&p->proc_lock);
 924                return;
 925        }
 926        /* At this point, a death IPI should be on its way, either from the
 927         * RUNNING_S one, or from proc_take_cores with a __death.  in general,
 928         * interrupts should be on when you call proc_destroy locally, but
 929         * currently aren't for all things (like traphandlers). */
 930        __proc_set_state(p, PROC_DYING);
 931        spin_unlock(&p->proc_lock);
 932        proc_disown_children(p);
 933        /* Wake any of our kthreads waiting on children, so they can abort */
 934        cv_broadcast(&p->child_wait);
 935        /* we need to close files here, and not in free, since we could have a
 936         * refcnt indirectly related to one of our files.  specifically, if we
 937         * have a parent sleeping on our pipe, that parent won't wake up to
 938         * decref until the pipe closes.  And if the parent doesnt decref, we
 939         * don't free.  Even if we send a SIGCHLD to the parent, that would
 940         * require that the parent to never ignores that signal (or we risk
 941         * never reaping).
 942         *
 943         * Also note that any mmap'd files will still be mmapped.  You can close
 944         * the file after mmapping, with no effect. */
 945        close_fdt(&p->open_files, FALSE);
 946        /* Abort any abortable syscalls.  This won't catch every sleeper, but
 947         * future abortable sleepers are already prevented via the DYING_ABORT
 948         * state.  (signalled DYING_ABORT, no new sleepers will block, and now
 949         * we wake all old sleepers). */
 950        __proc_set_state(p, PROC_DYING_ABORT);
 951        abort_all_sysc(p);
 952        /* Tell the ksched about our death, and which cores we freed up */
 953        __sched_proc_destroy(p, pc_arr, nr_cores_revoked);
 954        /* Tell our parent about our state change (to DYING) */
 955        proc_signal_parent(p);
 956}
 957
 958/* Can use this to signal anything that might cause a parent to wait on the
 959 * child, such as termination, or signals.  Change the state or whatever before
 960 * calling. */
 961void proc_signal_parent(struct proc *child)
 962{
 963        struct kthread *sleeper;
 964        struct proc *parent = pid2proc(child->ppid);
 965        if (!parent)
 966                return;
 967        send_posix_signal(parent, SIGCHLD);
 968        /* there could be multiple kthreads sleeping for various reasons.  even
 969         * an SCP could have multiple async syscalls. */
 970        cv_broadcast(&parent->child_wait);
 971        /* if the parent was waiting, there's a __launch kthread KMSG out there
 972         */
 973        proc_decref(parent);
 974}
 975
 976/* Called when a parent is done with its child, and no longer wants to track the
 977 * child, nor to allow the child to track it.  Call with a lock (cv) held.
 978 * Returns 0 if we disowned, -1 on failure.
 979 *
 980 * If we disowned, (ret == 0), the caller must decref the child. */
 981int __proc_disown_child(struct proc *parent, struct proc *child)
 982{
 983        /* Bail out if the child has already been reaped */
 984        if (!child->ppid)
 985                return -1;
 986        assert(child->ppid == parent->pid);
 987        /* lock protects from concurrent inserts / removals from the list */
 988        TAILQ_REMOVE(&parent->children, child, sibling_link);
 989        /* After this, the child won't be able to get more refs to us, but it
 990         * may still have some references in running code. */
 991        child->ppid = 0;
 992        return 0;
 993}
 994
 995/* Turns *p into an MCP.  Needs to be called from a local syscall of a RUNNING_S
 996 * process.  Returns 0 if it succeeded, an error code otherwise. */
 997int proc_change_to_m(struct proc *p)
 998{
 999        int retval = 0;
1000        spin_lock(&p->proc_lock);
1001        /* in case userspace erroneously tries to change more than once */
1002        if (__proc_is_mcp(p))
1003                goto error_out;
1004        switch (p->state) {
1005        case (PROC_RUNNING_S):
1006                /* issue with if we're async or not (need to preempt it)
1007                 * either of these should trip it. TODO: (ACR) async core req */
1008                if ((current != p) || (get_pcoreid(p, 0) != core_id()))
1009                        panic("We don't handle async RUNNING_S core requests");
1010                struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1011
1012                assert(current_ctx);
1013                /* Copy uthread0's context to VC 0's uthread slot */
1014                copy_current_ctx_to(&vcpd->uthread_ctx);
1015                clear_owning_proc(core_id());   /* so we don't restart */
1016                save_vc_fp_state(vcpd);
1017                /* Userspace needs to not fuck with notif_disabled before
1018                 * transitioning to _M. */
1019                if (vcpd->notif_disabled) {
1020                        printk("[kernel] user bug: notifs disabled for vcore 0\n");
1021                        vcpd->notif_disabled = FALSE;
1022                }
1023                /* in the async case, we'll need to remotely stop and bundle
1024                 * vcore0's TF.  this is already done for the sync case (local
1025                 * syscall). */
1026                /* this process no longer runs on its old location (which is
1027                 * this core, for now, since we don't handle async calls) */
1028                __seq_start_write(&p->procinfo->coremap_seqctr);
1029                // TODO: (ACR) will need to unmap remotely (receive-side)
1030                __unmap_vcore(p, 0);
1031                vcore_account_offline(p, 0);
1032                __seq_end_write(&p->procinfo->coremap_seqctr);
1033                /* change to runnable_m (it's TF is already saved) */
1034                __proc_set_state(p, PROC_RUNNABLE_M);
1035                p->procinfo->is_mcp = TRUE;
1036                spin_unlock(&p->proc_lock);
1037                /* Tell the ksched that we're a real MCP now! */
1038                __sched_proc_change_to_m(p);
1039                return 0;
1040        case (PROC_RUNNABLE_S):
1041                /* Issues: being on the runnable_list, proc_set_state not liking
1042                 * it, and not clearly thinking through how this would happen.
1043                 * Perhaps an async call that gets serviced after you're
1044                 * descheduled? */
1045                warn("Not supporting RUNNABLE_S -> RUNNABLE_M yet.\n");
1046                goto error_out;
1047        case (PROC_DYING):
1048        case (PROC_DYING_ABORT):
1049                warn("Dying, core request coming from %d\n", core_id());
1050                goto error_out;
1051        default:
1052                goto error_out;
1053        }
1054error_out:
1055        spin_unlock(&p->proc_lock);
1056        return -EINVAL;
1057}
1058
1059/* Old code to turn a RUNNING_M to a RUNNING_S, with the calling context
1060 * becoming the new 'thread0'.  Don't use this.  Caller needs to send in a
1061 * pc_arr big enough for all vcores.  Will return the number of cores given up
1062 * by the proc. */
1063uint32_t __proc_change_to_s(struct proc *p, uint32_t *pc_arr)
1064{
1065        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1066        uint32_t num_revoked;
1067
1068        /* Not handling vcore accounting.  Do so if we ever use this */
1069        printk("[kernel] trying to transition _M -> _S (deprecated)!\n");
1070        assert(p->state == PROC_RUNNING_M); // TODO: (ACR) async core req
1071        /* save the context, to be restarted in _S mode */
1072        assert(current_ctx);
1073        copy_current_ctx_to(&p->scp_ctx);
1074        clear_owning_proc(core_id());   /* so we don't restart */
1075        save_vc_fp_state(vcpd);
1076        /* sending death, since it's not our job to save contexts or anything in
1077         * this case. */
1078        num_revoked = __proc_take_allcores(p, pc_arr, FALSE);
1079        __proc_set_state(p, PROC_RUNNABLE_S);
1080        return num_revoked;
1081}
1082
1083/* Helper function.  Is the given pcore a mapped vcore?  No locking involved, be
1084 * careful. */
1085static bool is_mapped_vcore(struct proc *p, uint32_t pcoreid)
1086{
1087        return p->procinfo->pcoremap[pcoreid].valid;
1088}
1089
1090/* Helper function.  Find the vcoreid for a given physical core id for proc p.
1091 * No locking involved, be careful.  Panics on failure. */
1092static uint32_t get_vcoreid(struct proc *p, uint32_t pcoreid)
1093{
1094        assert(is_mapped_vcore(p, pcoreid));
1095        return p->procinfo->pcoremap[pcoreid].vcoreid;
1096}
1097
1098/* Helper function.  Try to find the pcoreid for a given virtual core id for
1099 * proc p.  No locking involved, be careful.  Use this when you can tolerate a
1100 * stale or otherwise 'wrong' answer. */
1101static uint32_t try_get_pcoreid(struct proc *p, uint32_t vcoreid)
1102{
1103        return p->procinfo->vcoremap[vcoreid].pcoreid;
1104}
1105
1106/* Helper function.  Find the pcoreid for a given virtual core id for proc p.
1107 * No locking involved, be careful.  Panics on failure. */
1108static uint32_t get_pcoreid(struct proc *p, uint32_t vcoreid)
1109{
1110        assert(vcore_is_mapped(p, vcoreid));
1111        return try_get_pcoreid(p, vcoreid);
1112}
1113
1114/* Saves the FP state of the calling core into VCPD.  Pairs with
1115 * restore_vc_fp_state().  On x86, the best case overhead of the flags:
1116 *              FNINIT: 36 ns
1117 *              FXSAVE: 46 ns
1118 *              FXRSTR: 42 ns
1119 *              Flagged FXSAVE: 50 ns
1120 *              Flagged FXRSTR: 66 ns
1121 *              Excess flagged FXRSTR: 42 ns
1122 * If we don't do it, we'll need to initialize every VCPD at process creation
1123 * time with a good FPU state (x86 control words are initialized as 0s, like the
1124 * rest of VCPD). */
1125static void save_vc_fp_state(struct preempt_data *vcpd)
1126{
1127        save_fp_state(&vcpd->preempt_anc);
1128        vcpd->rflags |= VC_FPU_SAVED;
1129}
1130
1131/* Conditionally restores the FP state from VCPD.  If the state was not valid,
1132 * we don't bother restoring and just initialize the FPU. */
1133static void restore_vc_fp_state(struct preempt_data *vcpd)
1134{
1135        if (vcpd->rflags & VC_FPU_SAVED) {
1136                restore_fp_state(&vcpd->preempt_anc);
1137                vcpd->rflags &= ~VC_FPU_SAVED;
1138        } else {
1139                init_fp_state();
1140        }
1141}
1142
1143/* Helper for SCPs, saves the core's FPU state into the VCPD vc0 slot */
1144void __proc_save_fpu_s(struct proc *p)
1145{
1146        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1147
1148        save_vc_fp_state(vcpd);
1149}
1150
1151/* Helper: saves the SCP's GP tf state and unmaps vcore 0.  This does *not* save
1152 * the FPU state.
1153 *
1154 * In the future, we'll probably use vc0's space for scp_ctx and the silly
1155 * state.  If we ever do that, we'll need to stop using scp_ctx (soon to be in
1156 * VCPD) as a location for pcpui->cur_ctx to point (dangerous) */
1157void __proc_save_context_s(struct proc *p)
1158{
1159        copy_current_ctx_to(&p->scp_ctx);
1160        __seq_start_write(&p->procinfo->coremap_seqctr);
1161        __unmap_vcore(p, 0);
1162        __seq_end_write(&p->procinfo->coremap_seqctr);
1163        vcore_account_offline(p, 0);
1164}
1165
1166/* Yields the calling core.  Must be called locally (not async) for now.
1167 * - If RUNNING_S, you just give up your time slice and will eventually return,
1168 *   possibly after WAITING on an event.
1169 * - If RUNNING_M, you give up the current vcore (which never returns), and
1170 *   adjust the amount of cores wanted/granted.
1171 * - If you have only one vcore, you switch to WAITING.  There's no 'classic
1172 *   yield' for MCPs (at least not now).  When you run again, you'll have one
1173 *   guaranteed core, starting from the entry point.
1174 *
1175 * If the call is being nice, it means different things for SCPs and MCPs.  For
1176 * MCPs, it means that it is in response to a preemption (which needs to be
1177 * checked).  If there is no preemption pending, just return.  For SCPs, it
1178 * means the proc wants to give up the core, but still has work to do.  If not,
1179 * the proc is trying to wait on an event.  It's not being nice to others, it
1180 * just has no work to do.
1181 *
1182 * This usually does not return (smp_idle()), so it will eat your reference.
1183 * Also note that it needs a non-current/edible reference, since it will abandon
1184 * and continue to use the *p (current == 0, no cr3, etc).
1185 *
1186 * We disable interrupts for most of it too, since we need to protect
1187 * current_ctx and not race with __notify (which doesn't play well with
1188 * concurrent yielders). */
1189void proc_yield(struct proc *p, bool being_nice)
1190{
1191        uint32_t vcoreid, pcoreid = core_id();
1192        struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1193        struct vcore *vc;
1194        struct preempt_data *vcpd;
1195
1196        /* Need to lock to prevent concurrent vcore changes (online, inactive,
1197         * the mapping, etc).  This plus checking the nr_preempts is enough to
1198         * tell if our vcoreid and cur_ctx ought to be here still or if we
1199         * should abort */
1200        spin_lock(&p->proc_lock); /* horrible scalability.  =( */
1201        switch (p->state) {
1202        case (PROC_RUNNING_S):
1203                if (!being_nice) {
1204                        /* waiting for an event to unblock us */
1205                        vcpd = &p->procdata->vcore_preempt_data[0];
1206                        /* syncing with event's SCP code.  we set waiting, then
1207                         * check pending.  they set pending, then check waiting.
1208                         * it's not possible for us to miss the notif *and* for
1209                         * them to miss WAITING.  one (or both) of us will see
1210                         * and make sure the proc wakes up.  */
1211                        __proc_set_state(p, PROC_WAITING);
1212                        /* don't let the state write pass the notif read */
1213                        wrmb();
1214                        if (vcpd->notif_pending) {
1215                                __proc_set_state(p, PROC_RUNNING_S);
1216                                /* they can't handle events, just need to
1217                                 * prevent a yield.  (note the notif_pendings
1218                                 * are collapsed). */
1219                                if (!scp_is_vcctx_ready(vcpd))
1220                                        vcpd->notif_pending = FALSE;
1221                                goto out_failed;
1222                        }
1223                        /* if we're here, we want to sleep.  a concurrent event
1224                         * that hasn't already written notif_pending will have
1225                         * seen WAITING, and will be spinning while we do this.
1226                         * */
1227                        __proc_save_context_s(p);
1228                        spin_unlock(&p->proc_lock);
1229                } else {
1230                        /* yielding to allow other processes to run.  we're
1231                         * briefly WAITING, til we are woken up */
1232                        __proc_set_state(p, PROC_WAITING);
1233                        __proc_save_context_s(p);
1234                        spin_unlock(&p->proc_lock);
1235                        /* immediately wake up the proc (makes it runnable) */
1236                        proc_wakeup(p);
1237                }
1238                goto out_yield_core;
1239        case (PROC_RUNNING_M):
1240                break;                  /* will handle this stuff below */
1241        case (PROC_DYING):              /* incoming __death */
1242        case (PROC_DYING_ABORT):
1243        case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
1244                goto out_failed;
1245        default:
1246                panic("Weird state(%s) in %s()", procstate2str(p->state),
1247                      __FUNCTION__);
1248        }
1249        /* This is which vcore this pcore thinks it is, regardless of any
1250         * unmappings that may have happened remotely (with __PRs waiting to
1251         * run) */
1252        vcoreid = pcpui->owning_vcoreid;
1253        vc = vcoreid2vcore(p, vcoreid);
1254        vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1255        /* This is how we detect whether or not a __PR happened. */
1256        if (vc->nr_preempts_sent != vc->nr_preempts_done)
1257                goto out_failed;
1258        /* Sanity checks.  If we were preempted or are dying, we should have
1259         * noticed by now. */
1260        assert(is_mapped_vcore(p, pcoreid));
1261        assert(vcoreid == get_vcoreid(p, pcoreid));
1262        /* no reason to be nice, return */
1263        if (being_nice && !vc->preempt_pending)
1264                goto out_failed;
1265        /* At this point, AFAIK there should be no preempt/death messages on the
1266         * way, and we're on the online list.  So we'll go ahead and do the
1267         * yielding business. */
1268        /* If there's a preempt pending, we don't need to preempt later since we
1269         * are yielding (nice or otherwise).  If not, this is just a regular
1270         * yield. */
1271        if (vc->preempt_pending) {
1272                vc->preempt_pending = 0;
1273        } else {
1274                /* Optional: on a normal yield, check to see if we are putting
1275                 * them below amt_wanted (help with user races) and bail. */
1276                if (p->procdata->res_req[RES_CORES].amt_wanted >=
1277                                       p->procinfo->num_vcores)
1278                        goto out_failed;
1279        }
1280        /* Don't let them yield if they are missing a notification.  Userspace
1281         * must not leave vcore context without dealing with notif_pending.
1282         * pop_user_ctx() handles leaving via uthread context.  This handles
1283         * leaving via a yield.
1284         *
1285         * This early check is an optimization.  The real check is below when it
1286         * works with the online_vcs list (syncing with event.c and INDIR/IPI
1287         * posting). */
1288        if (vcpd->notif_pending)
1289                goto out_failed;
1290        /* Now we'll actually try to yield */
1291        printd("[K] Process %d (%p) is yielding on vcore %d\n", p->pid, p,
1292               get_vcoreid(p, pcoreid));
1293        /* Remove from the online list, add to the yielded list, and unmap
1294         * the vcore, which gives up the core. */
1295        TAILQ_REMOVE(&p->online_vcs, vc, list);
1296        /* Now that we're off the online list, check to see if an alert made
1297         * it through (event.c sets this) */
1298        wrmb(); /* prev write must hit before reading notif_pending */
1299        /* Note we need interrupts disabled, since a __notify can come in
1300         * and set pending to FALSE */
1301        if (vcpd->notif_pending) {
1302                /* We lost, put it back on the list and abort the yield.  If we
1303                 * ever build an myield, we'll need a way to deal with this for
1304                 * all vcores */
1305                TAILQ_INSERT_TAIL(&p->online_vcs, vc, list); /* could go HEAD */
1306                goto out_failed;
1307        }
1308        /* Not really a kmsg, but it acts like one w.r.t. proc mgmt */
1309        pcpui_trace_kmsg(pcpui, (uintptr_t)proc_yield);
1310        /* We won the race with event sending, we can safely yield */
1311        TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1312        /* Note this protects stuff userspace should look at, which doesn't
1313         * include the TAILQs. */
1314        __seq_start_write(&p->procinfo->coremap_seqctr);
1315        /* Next time the vcore starts, it starts fresh */
1316        vcpd->notif_disabled = FALSE;
1317        __unmap_vcore(p, vcoreid);
1318        p->procinfo->num_vcores--;
1319        p->procinfo->res_grant[RES_CORES] = p->procinfo->num_vcores;
1320        __seq_end_write(&p->procinfo->coremap_seqctr);
1321        vcore_account_offline(p, vcoreid);
1322        /* No more vcores?  Then we wait on an event */
1323        if (p->procinfo->num_vcores == 0) {
1324                /* consider a ksched op to tell it about us WAITING */
1325                __proc_set_state(p, PROC_WAITING);
1326        }
1327        spin_unlock(&p->proc_lock);
1328        /* We discard the current context, but we still need to restore the core
1329         */
1330        arch_finalize_ctx(pcpui->cur_ctx);
1331        /* Hand the now-idle core to the ksched */
1332        __sched_put_idle_core(p, pcoreid);
1333        goto out_yield_core;
1334out_failed:
1335        /* for some reason we just want to return, either to take a KMSG that
1336         * cleans us up, or because we shouldn't yield (ex: notif_pending). */
1337        spin_unlock(&p->proc_lock);
1338        return;
1339out_yield_core:                         /* successfully yielded the core */
1340        proc_decref(p);                 /* need to eat the ref passed in */
1341        /* Clean up the core and idle. */
1342        clear_owning_proc(pcoreid);     /* so we don't restart */
1343        abandon_core();
1344        smp_idle();
1345}
1346
1347/* Sends a notification (aka active notification, aka IPI) to p's vcore.  We
1348 * only send a notification if one they are enabled.  There's a bunch of weird
1349 * cases with this, and how pending / enabled are signals between the user and
1350 * kernel - check the documentation.  Note that pending is more about messages.
1351 * The process needs to be in vcore_context, and the reason is usually a
1352 * message.  We set pending here in case we were called to prod them into vcore
1353 * context (like via a sys_self_notify).  Also note that this works for _S
1354 * procs, if you send to vcore 0 (and the proc is running). */
1355void proc_notify(struct proc *p, uint32_t vcoreid)
1356{
1357        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1358
1359        assert(proc_vcoreid_is_safe(p, vcoreid));
1360        /* If you're thinking about checking notif_pending and then returning if
1361         * it is already set, note that some callers (e.g. the event system) set
1362         * notif_pending when they deliver a message, regardless of whether
1363         * there is an IPI or not.  Those callers assume that we don't care
1364         * about notif_pending, only notif_disabled.  So don't change this
1365         * without changing them (probably can't without a lot of thought - that
1366         * notif_pending is about missing messages.  It might be possible to say
1367         * "no IPI, but don't let me miss messages that were delivered." */
1368        vcpd->notif_pending = TRUE;
1369        wrmb(); /* must write notif_pending before reading notif_disabled */
1370        if (!vcpd->notif_disabled) {
1371                /* GIANT WARNING: we aren't using the proc-lock to protect the
1372                 * vcoremap.  We want to be able to use this from interrupt
1373                 * context, and don't want the proc_lock to be an irqsave.
1374                 * Spurious __notify() kmsgs are okay (it checks to see if the
1375                 * right receiver is current). */
1376                if (vcore_is_mapped(p, vcoreid)) {
1377                        printd("[kernel] sending notif to vcore %d\n", vcoreid);
1378                        /* This use of try_get_pcoreid is racy, might be
1379                         * unmapped */
1380                        send_kernel_message(try_get_pcoreid(p, vcoreid),
1381                                            __notify, (long)p, 0, 0,
1382                                            KMSG_ROUTINE);
1383                }
1384        }
1385}
1386
1387/* Makes sure p is runnable.  Callers may spam this, so it needs to handle
1388 * repeated calls for the same event.  Callers include event delivery, SCP
1389 * yield, and new SCPs.  Will trigger __sched_.cp_wakeup() CBs.  Will only
1390 * trigger the CB once, regardless of how many times we are called, *until* the
1391 * proc becomes WAITING again, presumably because of something the ksched did.*/
1392void proc_wakeup(struct proc *p)
1393{
1394        spin_lock(&p->proc_lock);
1395        if (__proc_is_mcp(p)) {
1396                /* we only wake up WAITING mcps */
1397                if (p->state != PROC_WAITING) {
1398                        spin_unlock(&p->proc_lock);
1399                        return;
1400                }
1401                __proc_set_state(p, PROC_RUNNABLE_M);
1402                spin_unlock(&p->proc_lock);
1403                __sched_mcp_wakeup(p);
1404                return;
1405        } else {
1406                /* SCPs can wake up for a variety of reasons.  the only times we
1407                 * need to do something is if it was waiting or just created.
1408                 * other cases are either benign (just go out), or potential
1409                 * bugs (_Ms) */
1410                switch (p->state) {
1411                case (PROC_CREATED):
1412                case (PROC_WAITING):
1413                        __proc_set_state(p, PROC_RUNNABLE_S);
1414                        break;
1415                case (PROC_RUNNABLE_S):
1416                case (PROC_RUNNING_S):
1417                case (PROC_DYING):
1418                case (PROC_DYING_ABORT):
1419                        spin_unlock(&p->proc_lock);
1420                        return;
1421                case (PROC_RUNNABLE_M):
1422                case (PROC_RUNNING_M):
1423                        warn("Weird state(%s) in %s()", procstate2str(p->state),
1424                             __FUNCTION__);
1425                        spin_unlock(&p->proc_lock);
1426                        return;
1427                }
1428                /* thanks, past brho! */
1429                printd("[kernel] FYI, waking up an _S proc\n");
1430                spin_unlock(&p->proc_lock);
1431                __sched_scp_wakeup(p);
1432        }
1433}
1434
1435/* Is the process in multi_mode / is an MCP or not?  */
1436bool __proc_is_mcp(struct proc *p)
1437{
1438        /* in lieu of using the amount of cores requested, or having a bunch of
1439         * states (like PROC_WAITING_M and _S), I'll just track it with a bool.
1440         */
1441        return p->procinfo->is_mcp;
1442}
1443
1444bool proc_is_vcctx_ready(struct proc *p)
1445{
1446        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[0];
1447
1448        return scp_is_vcctx_ready(vcpd);
1449}
1450
1451/************************  Preemption Functions  ******************************
1452 * Don't rely on these much - I'll be sure to change them up a bit.
1453 *
1454 * Careful about what takes a vcoreid and what takes a pcoreid.  Also, there may
1455 * be weird glitches with setting the state to RUNNABLE_M.  It is somewhat in
1456 * flux.  The num_vcores is changed after take_cores, but some of the messages
1457 * (or local traps) may not yet be ready to handle seeing their future state.
1458 * But they should be, so fix those when they pop up.
1459 *
1460 * Another thing to do would be to make the _core functions take a pcorelist,
1461 * and not just one pcoreid. */
1462
1463/* Sets a preempt_pending warning for p's vcore, to go off 'when'.  If you care
1464 * about locking, do it before calling.  Takes a vcoreid! */
1465void __proc_preempt_warn(struct proc *p, uint32_t vcoreid, uint64_t when)
1466{
1467        struct event_msg local_msg = {0};
1468
1469        /* danger with doing this unlocked: preempt_pending is set, but never
1470         * 0'd, since it is unmapped and not dealt with (TODO)*/
1471        p->procinfo->vcoremap[vcoreid].preempt_pending = when;
1472
1473        /* Send the event (which internally checks to see how they want it) */
1474        local_msg.ev_type = EV_PREEMPT_PENDING;
1475        local_msg.ev_arg1 = vcoreid;
1476        /* Whenever we send msgs with the proc locked, we need at least 1
1477         * online.  Caller needs to make sure the core was online/mapped. */
1478        assert(!TAILQ_EMPTY(&p->online_vcs));
1479        send_kernel_event(p, &local_msg, vcoreid);
1480
1481        /* TODO: consider putting in some lookup place for the alarm to find it.
1482         * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1483}
1484
1485/* Warns all active vcores of an impending preemption.  Hold the lock if you
1486 * care about the mapping (and you should). */
1487void __proc_preempt_warnall(struct proc *p, uint64_t when)
1488{
1489        struct vcore *vc_i;
1490        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1491                __proc_preempt_warn(p, vcore2vcoreid(p, vc_i), when);
1492        /* TODO: consider putting in some lookup place for the alarm to find it.
1493         * til then, it'll have to scan the vcoremap (O(n) instead of O(m)) */
1494}
1495
1496// TODO: function to set an alarm, if none is outstanding
1497
1498/* Raw function to preempt a single core.  If you care about locking, do it
1499 * before calling. */
1500void __proc_preempt_core(struct proc *p, uint32_t pcoreid)
1501{
1502        uint32_t vcoreid = get_vcoreid(p, pcoreid);
1503        struct event_msg preempt_msg = {0};
1504        /* works with nr_preempts_done to signal completion of a preemption */
1505        p->procinfo->vcoremap[vcoreid].nr_preempts_sent++;
1506        // expects a pcorelist.  assumes pcore is mapped and running_m
1507        __proc_take_corelist(p, &pcoreid, 1, TRUE);
1508        /* Only send the message if we have an online core.  o/w, it would fuck
1509         * us up (deadlock), and hey don't need a message.  the core we just
1510         * took will be the first one to be restarted.  It will look like a
1511         * notif.  in the future, we could send the event if we want, but the
1512         * caller needs to do that (after unlocking). */
1513        if (!TAILQ_EMPTY(&p->online_vcs)) {
1514                preempt_msg.ev_type = EV_VCORE_PREEMPT;
1515                preempt_msg.ev_arg2 = vcoreid;
1516                send_kernel_event(p, &preempt_msg, 0);
1517        }
1518}
1519
1520/* Raw function to preempt every vcore.  If you care about locking, do it before
1521 * calling. */
1522uint32_t __proc_preempt_all(struct proc *p, uint32_t *pc_arr)
1523{
1524        struct vcore *vc_i;
1525
1526        /* TODO:(BULK) PREEMPT - don't bother with this, set a proc wide flag,
1527         * or just make us RUNNABLE_M.  Note this is also used by __map_vcore.
1528         */
1529        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1530                vc_i->nr_preempts_sent++;
1531        return __proc_take_allcores(p, pc_arr, TRUE);
1532}
1533
1534/* Warns and preempts a vcore from p.  No delaying / alarming, or anything.  The
1535 * warning will be for u usec from now.  Returns TRUE if the core belonged to
1536 * the proc (and thus preempted), False if the proc no longer has the core. */
1537bool proc_preempt_core(struct proc *p, uint32_t pcoreid, uint64_t usec)
1538{
1539        uint64_t warn_time = read_tsc() + usec2tsc(usec);
1540        bool retval = FALSE;
1541        if (p->state != PROC_RUNNING_M) {
1542                /* more of an FYI for brho.  should be harmless to return. */
1543                warn("Tried to preempt from a non RUNNING_M proc!");
1544                return FALSE;
1545        }
1546        spin_lock(&p->proc_lock);
1547        if (is_mapped_vcore(p, pcoreid)) {
1548                __proc_preempt_warn(p, get_vcoreid(p, pcoreid), warn_time);
1549                __proc_preempt_core(p, pcoreid);
1550                /* we might have taken the last core */
1551                if (!p->procinfo->num_vcores)
1552                        __proc_set_state(p, PROC_RUNNABLE_M);
1553                retval = TRUE;
1554        }
1555        spin_unlock(&p->proc_lock);
1556        return retval;
1557}
1558
1559/* Warns and preempts all from p.  No delaying / alarming, or anything.  The
1560 * warning will be for u usec from now. */
1561void proc_preempt_all(struct proc *p, uint64_t usec)
1562{
1563        uint64_t warn_time = read_tsc() + usec2tsc(usec);
1564        uint32_t num_revoked = 0;
1565
1566        spin_lock(&p->proc_lock);
1567        /* storage for pc_arr is alloced at decl, which is after grabbing the
1568         * lock*/
1569        uint32_t pc_arr[p->procinfo->num_vcores];
1570
1571        /* DYING could be okay */
1572        if (p->state != PROC_RUNNING_M) {
1573                warn("Tried to preempt from a non RUNNING_M proc!");
1574                spin_unlock(&p->proc_lock);
1575                return;
1576        }
1577        __proc_preempt_warnall(p, warn_time);
1578        num_revoked = __proc_preempt_all(p, pc_arr);
1579        assert(!p->procinfo->num_vcores);
1580        __proc_set_state(p, PROC_RUNNABLE_M);
1581        spin_unlock(&p->proc_lock);
1582        /* TODO: when we revise this func, look at __put_idle */
1583        /* Return the cores to the ksched */
1584        if (num_revoked)
1585                __sched_put_idle_cores(p, pc_arr, num_revoked);
1586}
1587
1588/* Give the specific pcore to proc p.  Lots of assumptions, so don't really use
1589 * this.  The proc needs to be _M and prepared for it.  the pcore needs to be
1590 * free, etc. */
1591void proc_give(struct proc *p, uint32_t pcoreid)
1592{
1593        warn("Your idlecoremap is now screwed up");     /* TODO (IDLE) */
1594        spin_lock(&p->proc_lock);
1595        // expects a pcorelist, we give it a list of one
1596        __proc_give_cores(p, &pcoreid, 1);
1597        spin_unlock(&p->proc_lock);
1598}
1599
1600/* Global version of the helper, for sys_get_vcoreid (might phase that syscall
1601 * out). */
1602uint32_t proc_get_vcoreid(struct proc *p)
1603{
1604        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1605
1606        if (pcpui->owning_proc == p) {
1607                return pcpui->owning_vcoreid;
1608        } else {
1609                warn("Asked for vcoreid for %p, but %p is pwns", p,
1610                     pcpui->owning_proc);
1611                return (uint32_t)-1;
1612        }
1613}
1614
1615/* TODO: make all of these static inlines when we gut the env crap */
1616bool vcore_is_mapped(struct proc *p, uint32_t vcoreid)
1617{
1618        return p->procinfo->vcoremap[vcoreid].valid;
1619}
1620
1621/* Can do this, or just create a new field and save it in the vcoremap */
1622uint32_t vcore2vcoreid(struct proc *p, struct vcore *vc)
1623{
1624        return (vc - p->procinfo->vcoremap);
1625}
1626
1627struct vcore *vcoreid2vcore(struct proc *p, uint32_t vcoreid)
1628{
1629        return &p->procinfo->vcoremap[vcoreid];
1630}
1631
1632/********** Core granting (bulk and single) ***********/
1633
1634/* Helper: gives pcore to the process, mapping it to the next available vcore
1635 * from list vc_list.  Returns TRUE if we succeeded (non-empty).  If you pass in
1636 * **vc, we'll tell you which vcore it was. */
1637static bool __proc_give_a_pcore(struct proc *p, uint32_t pcore,
1638                                struct vcore_tailq *vc_list, struct vcore **vc)
1639{
1640        struct vcore *new_vc;
1641
1642        new_vc = TAILQ_FIRST(vc_list);
1643        if (!new_vc)
1644                return FALSE;
1645        printd("setting vcore %d to pcore %d\n", vcore2vcoreid(p, new_vc),
1646               pcore);
1647        TAILQ_REMOVE(vc_list, new_vc, list);
1648        TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
1649        __map_vcore(p, vcore2vcoreid(p, new_vc), pcore);
1650        if (vc)
1651                *vc = new_vc;
1652        return TRUE;
1653}
1654
1655static void __proc_give_cores_runnable(struct proc *p, uint32_t *pc_arr,
1656                                       uint32_t num)
1657{
1658        assert(p->state == PROC_RUNNABLE_M);
1659        assert(num);    /* catch bugs */
1660        /* add new items to the vcoremap */
1661        /* unncessary if offline */
1662        __seq_start_write(&p->procinfo->coremap_seqctr);
1663        p->procinfo->num_vcores += num;
1664        for (int i = 0; i < num; i++) {
1665                /* Try from the bulk list first */
1666                if (__proc_give_a_pcore(p, pc_arr[i], &p->bulk_preempted_vcs,
1667                                        0))
1668                        continue;
1669                /* o/w, try from the inactive list.  at one point, i thought
1670                 * there might be a legit way in which the inactive list could
1671                 * be empty, but that i wanted to catch it via an assert. */
1672                assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs, 0));
1673        }
1674        __seq_end_write(&p->procinfo->coremap_seqctr);
1675}
1676
1677static void __proc_give_cores_running(struct proc *p, uint32_t *pc_arr,
1678                                      uint32_t num)
1679{
1680        struct vcore *vc_i;
1681        /* Up the refcnt, since num cores are going to start using this
1682         * process and have it loaded in their owning_proc and 'current'. */
1683        proc_incref(p, num * 2);        /* keep in sync with __startcore */
1684        __seq_start_write(&p->procinfo->coremap_seqctr);
1685        p->procinfo->num_vcores += num;
1686        assert(TAILQ_EMPTY(&p->bulk_preempted_vcs));
1687        for (int i = 0; i < num; i++) {
1688                assert(__proc_give_a_pcore(p, pc_arr[i], &p->inactive_vcs,
1689                                           &vc_i));
1690                send_kernel_message(pc_arr[i], __startcore, (long)p,
1691                                    (long)vcore2vcoreid(p, vc_i),
1692                                    (long)vc_i->nr_preempts_sent, KMSG_ROUTINE);
1693        }
1694        __seq_end_write(&p->procinfo->coremap_seqctr);
1695}
1696
1697/* Gives process p the additional num cores listed in pcorelist.  If the proc is
1698 * not RUNNABLE_M or RUNNING_M, this will fail and allocate none of the core
1699 * (and return -1).  If you're RUNNING_M, this will startup your new cores at
1700 * the entry point with their virtual IDs (or restore a preemption).  If you're
1701 * RUNNABLE_M, you should call __proc_run_m after this so that the process can
1702 * start to use its cores.  In either case, this returns 0.
1703 *
1704 * If you're *_S, make sure your core0's TF is set (which is done when coming in
1705 * via arch/trap.c and we are RUNNING_S), change your state, then call this.
1706 * Then call __proc_run_m().
1707 *
1708 * The reason I didn't bring the _S cases from core_request over here is so we
1709 * can keep this family of calls dealing with only *_Ms, to avoiding caring if
1710 * this is called from another core, and to avoid the _S -> _M transition.
1711 *
1712 * WARNING: You must hold the proc_lock before calling this! */
1713int __proc_give_cores(struct proc *p, uint32_t *pc_arr, uint32_t num)
1714{
1715        /* should never happen: */
1716        assert(num + p->procinfo->num_vcores <= MAX_NUM_CORES);
1717        switch (p->state) {
1718        case (PROC_RUNNABLE_S):
1719        case (PROC_RUNNING_S):
1720                warn("Don't give cores to a process in a *_S state!\n");
1721                return -1;
1722        case (PROC_DYING):
1723        case (PROC_DYING_ABORT):
1724        case (PROC_WAITING):
1725                /* can't accept, just fail */
1726                return -1;
1727        case (PROC_RUNNABLE_M):
1728                __proc_give_cores_runnable(p, pc_arr, num);
1729                break;
1730        case (PROC_RUNNING_M):
1731                __proc_give_cores_running(p, pc_arr, num);
1732                break;
1733        default:
1734                panic("Weird state(%s) in %s()", procstate2str(p->state),
1735                      __FUNCTION__);
1736        }
1737        /* TODO: considering moving to the ksched (hard, due to yield) */
1738        p->procinfo->res_grant[RES_CORES] += num;
1739        return 0;
1740}
1741
1742/********** Core revocation (bulk and single) ***********/
1743
1744/* Revokes a single vcore from a process (unmaps or sends a KMSG to unmap). */
1745static void __proc_revoke_core(struct proc *p, uint32_t vcoreid, bool preempt)
1746{
1747        uint32_t pcoreid = get_pcoreid(p, vcoreid);
1748        struct preempt_data *vcpd;
1749        if (preempt) {
1750                /* Lock the vcore's state (necessary for preemption recovery) */
1751                vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1752                atomic_or(&vcpd->flags, VC_K_LOCK);
1753                send_kernel_message(pcoreid, __preempt, (long)p, 0, 0,
1754                                    KMSG_ROUTINE);
1755        } else {
1756                send_kernel_message(pcoreid, __death, (long)p, 0, 0,
1757                                    KMSG_ROUTINE);
1758        }
1759}
1760
1761/* Revokes all cores from the process (unmaps or sends a KMSGS). */
1762static void __proc_revoke_allcores(struct proc *p, bool preempt)
1763{
1764        struct vcore *vc_i;
1765
1766        /* TODO: if we ever get broadcast messaging, use it here (still need to
1767         * lock the vcores' states for preemption) */
1768        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1769                __proc_revoke_core(p, vcore2vcoreid(p, vc_i), preempt);
1770}
1771
1772/* Might be faster to scan the vcoremap than to walk the list... */
1773static void __proc_unmap_allcores(struct proc *p)
1774{
1775        struct vcore *vc_i;
1776        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1777                __unmap_vcore(p, vcore2vcoreid(p, vc_i));
1778}
1779
1780/* Takes (revoke via kmsg or unmap) from process p the num cores listed in
1781 * pc_arr.  Will preempt if 'preempt' is set.  o/w, no state will be saved, etc.
1782 * Don't use this for taking all of a process's cores.
1783 *
1784 * Make sure you hold the lock when you call this, and make sure that the pcore
1785 * actually belongs to the proc, non-trivial due to other __preempt messages. */
1786void __proc_take_corelist(struct proc *p, uint32_t *pc_arr, uint32_t num,
1787                          bool preempt)
1788{
1789        struct vcore *vc;
1790        uint32_t vcoreid;
1791        assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1792        __seq_start_write(&p->procinfo->coremap_seqctr);
1793        for (int i = 0; i < num; i++) {
1794                vcoreid = get_vcoreid(p, pc_arr[i]);
1795                /* Sanity check */
1796                assert(pc_arr[i] == get_pcoreid(p, vcoreid));
1797                /* Revoke / unmap core */
1798                if (p->state == PROC_RUNNING_M)
1799                        __proc_revoke_core(p, vcoreid, preempt);
1800                __unmap_vcore(p, vcoreid);
1801                /* Change lists for the vcore.  Note, the vcore is already
1802                 * unmapped and/or the messages are already in flight.  The only
1803                 * code that looks at the lists without holding the lock is
1804                 * event code. */
1805                vc = vcoreid2vcore(p, vcoreid);
1806                TAILQ_REMOVE(&p->online_vcs, vc, list);
1807                /* even for single preempts, we use the inactive list.  bulk
1808                 * preempt is only used for when we take everything. */
1809                TAILQ_INSERT_HEAD(&p->inactive_vcs, vc, list);
1810        }
1811        p->procinfo->num_vcores -= num;
1812        __seq_end_write(&p->procinfo->coremap_seqctr);
1813        p->procinfo->res_grant[RES_CORES] -= num;
1814}
1815
1816/* Takes all cores from a process (revoke via kmsg or unmap), putting them on
1817 * the appropriate vcore list, and fills pc_arr with the pcores revoked, and
1818 * returns the number of entries in pc_arr.
1819 *
1820 * Make sure pc_arr is big enough to handle num_vcores().
1821 * Make sure you hold the lock when you call this. */
1822uint32_t __proc_take_allcores(struct proc *p, uint32_t *pc_arr, bool preempt)
1823{
1824        struct vcore *vc_i, *vc_temp;
1825        uint32_t num = 0;
1826        assert(p->state & (PROC_RUNNING_M | PROC_RUNNABLE_M));
1827        __seq_start_write(&p->procinfo->coremap_seqctr);
1828        /* Write out which pcores we're going to take */
1829        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
1830                pc_arr[num++] = vc_i->pcoreid;
1831        /* Revoke if they are running, and unmap.  Both of these need the online
1832         * list to not be changed yet. */
1833        if (p->state == PROC_RUNNING_M)
1834                __proc_revoke_allcores(p, preempt);
1835        __proc_unmap_allcores(p);
1836        /* Move the vcores from online to the head of the appropriate list */
1837        TAILQ_FOREACH_SAFE(vc_i, &p->online_vcs, list, vc_temp) {
1838                /* TODO: we may want a TAILQ_CONCAT_HEAD, or something that does
1839                 * that */
1840                TAILQ_REMOVE(&p->online_vcs, vc_i, list);
1841                /* Put the cores on the appropriate list */
1842                if (preempt)
1843                        TAILQ_INSERT_HEAD(&p->bulk_preempted_vcs, vc_i, list);
1844                else
1845                        TAILQ_INSERT_HEAD(&p->inactive_vcs, vc_i, list);
1846        }
1847        assert(TAILQ_EMPTY(&p->online_vcs));
1848        assert(num == p->procinfo->num_vcores);
1849        p->procinfo->num_vcores = 0;
1850        __seq_end_write(&p->procinfo->coremap_seqctr);
1851        p->procinfo->res_grant[RES_CORES] = 0;
1852        return num;
1853}
1854
1855/* Helper to do the vcore->pcore and inverse mapping.  Hold the lock when
1856 * calling. */
1857void __map_vcore(struct proc *p, uint32_t vcoreid, uint32_t pcoreid)
1858{
1859        p->procinfo->vcoremap[vcoreid].pcoreid = pcoreid;
1860        p->procinfo->vcoremap[vcoreid].valid = TRUE;
1861        p->procinfo->pcoremap[pcoreid].vcoreid = vcoreid;
1862        p->procinfo->pcoremap[pcoreid].valid = TRUE;
1863}
1864
1865/* Helper to unmap the vcore->pcore and inverse mapping.  Hold the lock when
1866 * calling. */
1867void __unmap_vcore(struct proc *p, uint32_t vcoreid)
1868{
1869        p->procinfo->pcoremap[p->procinfo->vcoremap[vcoreid].pcoreid].valid =
1870                FALSE;
1871        p->procinfo->vcoremap[vcoreid].valid = FALSE;
1872}
1873
1874/* Stop running whatever context is on this core and load a known-good cr3.
1875 * Note this leaves no trace of what was running. This "leaves the process's
1876 * context.
1877 *
1878 * This does not clear the owning proc.  Use the other helper for that.
1879 *
1880 * Returns whether or not there was a process present. */
1881bool abandon_core(void)
1882{
1883        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1884
1885        /* Syscalls that don't return will ultimately call abadon_core(), so we
1886         * need to make sure we don't think we are still working on a syscall.
1887         * */
1888        pcpui->cur_kthread->sysc = 0;
1889        pcpui->cur_kthread->errbuf = 0; /* just in case */
1890        if (pcpui->cur_proc) {
1891                __abandon_core();
1892                return true;
1893        }
1894        return false;
1895}
1896
1897/* Helper to clear the core's owning processor and manage refcnting.  Pass in
1898 * core_id() to save a couple core_id() calls. */
1899void clear_owning_proc(uint32_t coreid)
1900{
1901        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
1902        struct proc *p = pcpui->owning_proc;
1903
1904        __clear_owning_proc(coreid);
1905        pcpui->owning_proc = 0;
1906        pcpui->owning_vcoreid = 0xdeadbeef;
1907        pcpui->cur_ctx = 0;     /* catch bugs for now (may go away) */
1908        if (p)
1909                proc_decref(p);
1910}
1911
1912/* Switches to the address space/context of new_p, doing nothing if we are
1913 * already in new_p.  This won't add extra refcnts or anything, and needs to be
1914 * paired with switch_back() at the end of whatever function you are in.
1915 * Specifically, the uncounted refs are one for the old_proc, which is passed
1916 * back to the caller, and new_p is getting placed in cur_proc. */
1917uintptr_t switch_to(struct proc *new_p)
1918{
1919        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1920        struct kthread *kth = pcpui->cur_kthread;
1921        struct proc *old_proc;
1922        uintptr_t ret;
1923
1924        old_proc = pcpui->cur_proc;             /* uncounted ref */
1925        /* If we aren't the proc already, then switch to it */
1926        if (old_proc != new_p) {
1927                pcpui->cur_proc = new_p;        /* uncounted ref */
1928                if (new_p)
1929                        lcr3(new_p->env_cr3);
1930                else
1931                        lcr3(boot_cr3);
1932        }
1933        ret = (uintptr_t)old_proc;
1934        if (is_ktask(kth)) {
1935                if (!(kth->flags & KTH_SAVE_ADDR_SPACE)) {
1936                        kth->flags |= KTH_SAVE_ADDR_SPACE;
1937                        /* proc pointers are aligned; we can use the lower bit
1938                         * as a signal to turn off SAVE_ADDR_SPACE. */
1939                        ret |= 0x1;
1940                }
1941        }
1942        return ret;
1943}
1944
1945/* This switches back from new_p to the original process.  Pair it with
1946 * switch_to(), and pass in its return value for old_ret. */
1947void switch_back(struct proc *new_p, uintptr_t old_ret)
1948{
1949        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1950        struct kthread *kth = pcpui->cur_kthread;
1951        struct proc *old_proc;
1952
1953        if (is_ktask(kth)) {
1954                if (old_ret & 0x1) {
1955                        kth->flags &= ~KTH_SAVE_ADDR_SPACE;
1956                        old_ret &= ~0x1;
1957                }
1958        }
1959        old_proc = (struct proc*)old_ret;
1960        if (old_proc != new_p) {
1961                pcpui->cur_proc = old_proc;
1962                if (old_proc)
1963                        lcr3(old_proc->env_cr3);
1964                else
1965                        lcr3(boot_cr3);
1966        }
1967}
1968
1969/* Will send a TLB shootdown message to every vcore in the main address space
1970 * (aka, all vcores for now).  The message will take the start and end virtual
1971 * addresses as well, in case we want to be more clever about how much we
1972 * shootdown and batching our messages.  Should do the sanity about rounding up
1973 * and down in this function too.
1974 *
1975 * Would be nice to have a broadcast kmsg at this point.  Note this may send a
1976 * message to the calling core (interrupting it, possibly while holding the
1977 * proc_lock).  We don't need to process routine messages since it's an
1978 * immediate message. */
1979void proc_tlbshootdown(struct proc *p, uintptr_t start, uintptr_t end)
1980{
1981        /* TODO: need a better way to find cores running our address space.  we
1982         * can have kthreads running syscalls, async calls, processes being
1983         * created. */
1984        struct vcore *vc_i;
1985
1986        /* TODO: we might be able to avoid locking here in the future (we must
1987         * hit all online, and we can check __mapped).  it'll be complicated. */
1988        spin_lock(&p->proc_lock);
1989        switch (p->state) {
1990        case (PROC_RUNNING_S):
1991                tlbflush();
1992                break;
1993        case (PROC_RUNNING_M):
1994                /* TODO: (TLB) sanity checks and rounding on the ranges.
1995                 *
1996                 * We need to make sure that once a core that was online has
1997                 * been removed from the online list, then it must receive a TLB
1998                 * flush (abandon_core()) before running the process again.
1999                 * Either that, or make other decisions about who to
2000                 * TLB-shootdown. */
2001                TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2002                        send_kernel_message(vc_i->pcoreid, __tlbshootdown,
2003                                            start, end, 0, KMSG_IMMEDIATE);
2004                }
2005                break;
2006        default:
2007                /* TODO: til we fix shootdowns, there are some odd cases where
2008                 * we have the address space loaded, but the state is in
2009                 * transition. */
2010                if (p == current)
2011                        tlbflush();
2012        }
2013        spin_unlock(&p->proc_lock);
2014}
2015
2016/* Helper, used by __startcore and __set_curctx, which sets up cur_ctx to run a
2017 * given process's vcore.  Caller needs to set up things like owning_proc and
2018 * whatnot.  Note that we might not have p loaded as current. */
2019static void __set_curctx_to_vcoreid(struct proc *p, uint32_t vcoreid,
2020                                    uint32_t old_nr_preempts_sent)
2021{
2022        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2023        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2024        struct vcore *vc = vcoreid2vcore(p, vcoreid);
2025
2026        /* Spin until our vcore's old preemption is done.  When __SC was sent,
2027         * we were told what the nr_preempts_sent was at that time.  Once that
2028         * many are done, it is time for us to run.  This forces a
2029         * 'happens-before' ordering on a __PR of our VC before this __SC of the
2030         * VC.  Note the nr_done should not exceed old_nr_sent, since further
2031         * __PR are behind this __SC in the KMSG queue. */
2032        while (old_nr_preempts_sent != vc->nr_preempts_done)
2033                cpu_relax();
2034        /* read nr_done before any other rd or wr.  CPU mb in the atomic. */
2035        cmb();
2036        /* Mark that this vcore as no longer preempted.  No danger of clobbering
2037         * other writes, since this would get turned on in __preempt (which
2038         * can't be concurrent with this function on this core), and the atomic
2039         * is just toggling the one bit (a concurrent VC_K_LOCK will work) */
2040        atomic_and(&vcpd->flags, ~VC_PREEMPTED);
2041        /* Once the VC is no longer preempted, we allow it to receive msgs.  We
2042         * could let userspace do it, but handling it here makes it easier for
2043         * them to handle_indirs (when they turn this flag off).  Note the
2044         * atomics provide the needed barriers (cmb and mb on flags). */
2045        atomic_or(&vcpd->flags, VC_CAN_RCV_MSG);
2046        printd("[kernel] startcore on physical core %d for process %d's vcore %d\n",
2047               core_id(), p->pid, vcoreid);
2048        /* If notifs are disabled, the vcore was in vcore context and we need to
2049         * restart the vcore_ctx.  o/w, we give them a fresh vcore (which is
2050         * also what happens the first time a vcore comes online).  No matter
2051         * what, they'll restart in vcore context.  It's just a matter of
2052         * whether or not it is the old, interrupted vcore context. */
2053        if (vcpd->notif_disabled) {
2054                /* copy-in the tf we'll pop, then set all security-related
2055                 * fields */
2056                pcpui->actual_ctx = vcpd->vcore_ctx;
2057                proc_secure_ctx(&pcpui->actual_ctx);
2058        } else { /* not restarting from a preemption, use a fresh vcore */
2059                assert(vcpd->vcore_stack);
2060                proc_init_ctx(&pcpui->actual_ctx, vcoreid, vcpd->vcore_entry,
2061                              vcpd->vcore_stack, vcpd->vcore_tls_desc);
2062                /* Disable/mask active notifications for fresh vcores */
2063                vcpd->notif_disabled = TRUE;
2064        }
2065        /* Regardless of whether or not we have a 'fresh' VC, we need to restore
2066         * the FPU state for the VC according to VCPD (which means either a
2067         * saved FPU state or a brand new init).  Starting a fresh VC is just
2068         * referring to the GP context we run.  The vcore itself needs to have
2069         * the FPU state loaded from when it previously ran and was saved (or a
2070         * fresh FPU if it wasn't saved).  For fresh FPUs, the main purpose is
2071         * for limiting info leakage.  I think VCs that don't need FPU state for
2072         * some reason (like having a current_uthread) can handle any sort of
2073         * FPU state, since it gets sorted when they pop their next uthread.
2074         *
2075         * Note this can cause a GP fault on x86 if the state is corrupt.  In
2076         * lieu of reading in the huge FP state and mucking with mxcsr_mask, we
2077         * should handle this like a KPF on user code. */
2078        restore_vc_fp_state(vcpd);
2079        /* cur_ctx was built above (in actual_ctx), now use it */
2080        pcpui->cur_ctx = &pcpui->actual_ctx;
2081        /* this cur_ctx will get run when the kernel returns / idles */
2082        vcore_account_online(p, vcoreid);
2083}
2084
2085/* Changes calling vcore to be vcoreid.  enable_my_notif tells us about how the
2086 * state calling vcore wants to be left in.  It will look like caller_vcoreid
2087 * was preempted.  Note we don't care about notif_pending.
2088 *
2089 * Will return:
2090 *      0 if we successfully changed to the target vcore.
2091 *      -EBUSY if the target vcore is already mapped (a good kind of failure)
2092 *      -EAGAIN if we failed for some other reason and need to try again.  For
2093 *      example, the caller could be preempted, and we never even attempted to
2094 *      change.
2095 *      -EINVAL some userspace bug */
2096int proc_change_to_vcore(struct proc *p, uint32_t new_vcoreid,
2097                         bool enable_my_notif)
2098{
2099        uint32_t caller_vcoreid, pcoreid = core_id();
2100        struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
2101        struct preempt_data *caller_vcpd;
2102        struct vcore *caller_vc, *new_vc;
2103        struct event_msg preempt_msg = {0};
2104        int retval = -EAGAIN;   /* by default, try again */
2105
2106        /* Need to not reach outside the vcoremap, which might be smaller in the
2107         * future, but should always be as big as max_vcores */
2108        assert(proc_vcoreid_is_safe(p, new_vcoreid));
2109        /* Need to lock to prevent concurrent vcore changes, like in yield. */
2110        spin_lock(&p->proc_lock);
2111        /* new_vcoreid is already runing, abort */
2112        if (vcore_is_mapped(p, new_vcoreid)) {
2113                retval = -EBUSY;
2114                goto out_locked;
2115        }
2116        /* Need to make sure our vcore is allowed to switch.  We might have a
2117         * __preempt, __death, etc, coming in.  Similar to yield. */
2118        switch (p->state) {
2119        case (PROC_RUNNING_M):
2120                break;          /* the only case we can proceed */
2121        case (PROC_RUNNING_S):  /* user bug, just return */
2122        case (PROC_DYING):      /* incoming __death */
2123        case (PROC_DYING_ABORT):
2124        case (PROC_RUNNABLE_M): /* incoming (bulk) preempt/myield TODO:(BULK) */
2125                goto out_locked;
2126        default:
2127                panic("Weird state(%s) in %s()", procstate2str(p->state),
2128                      __FUNCTION__);
2129        }
2130        /* This is which vcore this pcore thinks it is, regardless of any
2131         * unmappings that may have happened remotely (with __PRs waiting to
2132         * run) */
2133        caller_vcoreid = pcpui->owning_vcoreid;
2134        caller_vc = vcoreid2vcore(p, caller_vcoreid);
2135        caller_vcpd = &p->procdata->vcore_preempt_data[caller_vcoreid];
2136        /* This is how we detect whether or not a __PR happened.  If it did,
2137         * just abort and handle the kmsg.  No new __PRs are coming since we
2138         * hold the lock.  This also detects a __PR followed by a __SC for the
2139         * same VC. */
2140        if (caller_vc->nr_preempts_sent != caller_vc->nr_preempts_done)
2141                goto out_locked;
2142        /* Sanity checks.  If we were preempted or are dying, we should have
2143         * noticed by now. */
2144        assert(is_mapped_vcore(p, pcoreid));
2145        assert(caller_vcoreid == get_vcoreid(p, pcoreid));
2146        /* Should only call from vcore context */
2147        if (!caller_vcpd->notif_disabled) {
2148                retval = -EINVAL;
2149                printk("[kernel] You tried to change vcores from uth ctx\n");
2150                goto out_locked;
2151        }
2152        /* Ok, we're clear to do the switch.  Lets figure out who the new one is
2153         */
2154        new_vc = vcoreid2vcore(p, new_vcoreid);
2155        printd("[kernel] changing vcore %d to vcore %d\n", caller_vcoreid,
2156               new_vcoreid);
2157        /* enable_my_notif signals how we'll be restarted */
2158        if (enable_my_notif) {
2159                /* if they set this flag, then the vcore can just restart from
2160                 * scratch, and we don't care about either the uthread_ctx or
2161                 * the vcore_ctx. */
2162                caller_vcpd->notif_disabled = FALSE;
2163                /* Don't need to save the FPU.  There should be no uthread or
2164                 * other reason to return to the FPU state.  But we do need to
2165                 * finalize the context, even though we are throwing it away.
2166                 * We need to return the pcore to a state where it can run any
2167                 * context and not be bound to the old context. */
2168                arch_finalize_ctx(pcpui->cur_ctx);
2169        } else {
2170                /* need to set up the calling vcore's ctx so that it'll get
2171                 * restarted by __startcore, to make the caller look like it was
2172                 * preempted. */
2173                copy_current_ctx_to(&caller_vcpd->vcore_ctx);
2174                save_vc_fp_state(caller_vcpd);
2175        }
2176        /* Mark our core as preempted (for userspace recovery).  Userspace
2177         * checks this in handle_indirs, and it needs to check the mbox
2178         * regardless of enable_my_notif.  This does mean cores that change-to
2179         * with no intent to return will be tracked as PREEMPTED until they
2180         * start back up (maybe forever). */
2181        atomic_or(&caller_vcpd->flags, VC_PREEMPTED);
2182        /* Either way, unmap and offline our current vcore */
2183        /* Move the caller from online to inactive */
2184        TAILQ_REMOVE(&p->online_vcs, caller_vc, list);
2185        /* We don't bother with the notif_pending race.  note that notif_pending
2186         * could still be set.  this was a preempted vcore, and userspace will
2187         * need to deal with missed messages (preempt_recover() will handle
2188         * that) */
2189        TAILQ_INSERT_HEAD(&p->inactive_vcs, caller_vc, list);
2190        /* Move the new one from inactive to online */
2191        TAILQ_REMOVE(&p->inactive_vcs, new_vc, list);
2192        TAILQ_INSERT_TAIL(&p->online_vcs, new_vc, list);
2193        /* Change the vcore map */
2194        __seq_start_write(&p->procinfo->coremap_seqctr);
2195        __unmap_vcore(p, caller_vcoreid);
2196        __map_vcore(p, new_vcoreid, pcoreid);
2197        __seq_end_write(&p->procinfo->coremap_seqctr);
2198        vcore_account_offline(p, caller_vcoreid);
2199        /* Send either a PREEMPT msg or a CHECK_MSGS msg.  If they said to
2200         * enable_my_notif, then all userspace needs is to check messages, not a
2201         * full preemption recovery. */
2202        preempt_msg.ev_type = (enable_my_notif ? EV_CHECK_MSGS :
2203                               EV_VCORE_PREEMPT);
2204        preempt_msg.ev_arg2 = caller_vcoreid;   /* arg2 is 32 bits */
2205        /* Whenever we send msgs with the proc locked, we need at least 1
2206         * online.  In this case, it's the one we just changed to. */
2207        assert(!TAILQ_EMPTY(&p->online_vcs));
2208        send_kernel_event(p, &preempt_msg, new_vcoreid);
2209        /* So this core knows which vcore is here. (cur_proc and owning_proc are
2210         * already correct): */
2211        pcpui->owning_vcoreid = new_vcoreid;
2212        /* Until we set_curctx, we don't really have a valid current tf.  The
2213         * stuff in that old one is from our previous vcore, not the current
2214         * owning_vcoreid.  This matters for other KMSGS that will run before
2215         * __set_curctx (like __notify). */
2216        pcpui->cur_ctx = 0;
2217        /* Need to send a kmsg to finish.  We can't set_curctx til the __PR is
2218         * done, but we can't spin right here while holding the lock (can't spin
2219         * while waiting on a message, roughly) */
2220        send_kernel_message(pcoreid, __set_curctx, (long)p, (long)new_vcoreid,
2221                            (long)new_vc->nr_preempts_sent, KMSG_ROUTINE);
2222        retval = 0;
2223        /* Fall through to exit */
2224out_locked:
2225        spin_unlock(&p->proc_lock);
2226        return retval;
2227}
2228
2229/* Kernel message handler to start a process's context on this core, when the
2230 * core next considers running a process.  Tightly coupled with __proc_run_m().
2231 * Interrupts are disabled. */
2232void __startcore(uint32_t srcid, long a0, long a1, long a2)
2233{
2234        uint32_t vcoreid = (uint32_t)a1;
2235        uint32_t coreid = core_id();
2236        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2237        struct proc *p_to_run = (struct proc *)a0;
2238        uint32_t old_nr_preempts_sent = (uint32_t)a2;
2239
2240        assert(p_to_run);
2241        /* Can not be any TF from a process here already */
2242        assert(!pcpui->owning_proc);
2243        /* the sender of the kmsg increfed already for this saved ref to
2244         * p_to_run */
2245        pcpui->owning_proc = p_to_run;
2246        pcpui->owning_vcoreid = vcoreid;
2247        /* sender increfed again, assuming we'd install to cur_proc.  only do
2248         * this if no one else is there.  this is an optimization, since we
2249         * expect to send these __startcores to idles cores, and this saves a
2250         * scramble to incref when all of the cores restartcore/startcore later.
2251         * Keep in sync with __proc_give_cores() and __proc_run_m(). */
2252        if (!pcpui->cur_proc) {
2253                pcpui->cur_proc = p_to_run; /* install the ref to cur_proc */
2254                lcr3(p_to_run->env_cr3);
2255        } else {
2256                proc_decref(p_to_run);
2257        }
2258        /* Note we are not necessarily in the cr3 of p_to_run */
2259        /* Now that we sorted refcnts and know p / which vcore it should be, set
2260         * up pcpui->cur_ctx so that it will run that particular vcore */
2261        __set_curctx_to_vcoreid(p_to_run, vcoreid, old_nr_preempts_sent);
2262}
2263
2264/* Kernel message handler to load a proc's vcore context on this core.  Similar
2265 * to __startcore, except it is used when p already controls the core (e.g.
2266 * change_to).  Since the core is already controlled, pcpui such as owning proc,
2267 * vcoreid, and cur_proc are all already set. */
2268void __set_curctx(uint32_t srcid, long a0, long a1, long a2)
2269{
2270        struct proc *p = (struct proc*)a0;
2271        uint32_t vcoreid = (uint32_t)a1;
2272        uint32_t old_nr_preempts_sent = (uint32_t)a2;
2273        __set_curctx_to_vcoreid(p, vcoreid, old_nr_preempts_sent);
2274}
2275
2276/* Bail out if it's the wrong process, or if they no longer want a notif.  Try
2277 * not to grab locks or write access to anything that isn't per-core in here. */
2278void __notify(uint32_t srcid, long a0, long a1, long a2)
2279{
2280        uint32_t vcoreid, coreid = core_id();
2281        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2282        struct preempt_data *vcpd;
2283        struct proc *p = (struct proc*)a0;
2284
2285        /* Not the right proc */
2286        if (p != pcpui->owning_proc)
2287                return;
2288        /* the core might be owned, but not have a valid cur_ctx (if we're in
2289         * the process of changing */
2290        if (!pcpui->cur_ctx)
2291                return;
2292        /* Common cur_ctx sanity checks.  Note cur_ctx could be an _S's scp_ctx
2293         */
2294        vcoreid = pcpui->owning_vcoreid;
2295        vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2296        /* for SCPs that haven't (and might never) call vc_event_init, like
2297         * rtld.  this is harmless for MCPS to check this */
2298        if (!scp_is_vcctx_ready(vcpd))
2299                return;
2300        printd("received active notification for proc %d's vcore %d on pcore %d\n",
2301               p->procinfo->pid, vcoreid, coreid);
2302        /* sort signals.  notifs are now masked, like an interrupt gate */
2303        if (vcpd->notif_disabled)
2304                return;
2305        vcpd->notif_disabled = TRUE;
2306        /* save the old ctx in the uthread slot, build and pop a new one.  Note
2307         * that silly state isn't our business for a notification. */
2308        copy_current_ctx_to(&vcpd->uthread_ctx);
2309        memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
2310        proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
2311                      vcpd->vcore_stack, vcpd->vcore_tls_desc);
2312        /* this cur_ctx will get run when the kernel returns / idles */
2313}
2314
2315void __preempt(uint32_t srcid, long a0, long a1, long a2)
2316{
2317        uint32_t vcoreid, coreid = core_id();
2318        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2319        struct preempt_data *vcpd;
2320        struct proc *p = (struct proc*)a0;
2321
2322        assert(p);
2323        if (p != pcpui->owning_proc) {
2324                panic("__preempt arrived for proc (%p) that was not owning (%p)!",
2325                      p, pcpui->owning_proc);
2326        }
2327        /* Common cur_ctx sanity checks */
2328        assert(pcpui->cur_ctx);
2329        assert(pcpui->cur_ctx == &pcpui->actual_ctx);
2330        vcoreid = pcpui->owning_vcoreid;
2331        vcpd = &p->procdata->vcore_preempt_data[vcoreid];
2332        printd("[kernel] received __preempt for proc %d's vcore %d on pcore %d\n",
2333               p->procinfo->pid, vcoreid, coreid);
2334        /* if notifs are disabled, the vcore is in vcore context (as far as
2335         * we're concerned), and we save it in the vcore slot. o/w, we save the
2336         * process's cur_ctx in the uthread slot, and it'll appear to the vcore
2337         * when it comes back up the uthread just took a notification. */
2338        if (vcpd->notif_disabled)
2339                copy_current_ctx_to(&vcpd->vcore_ctx);
2340        else
2341                copy_current_ctx_to(&vcpd->uthread_ctx);
2342        /* Userspace in a preemption handler on another core might be copying FP
2343         * state from memory (VCPD) at the moment, and if so we don't want to
2344         * clobber it.  In this rare case, our current core's FPU state should
2345         * be the same as whatever is in VCPD, so this shouldn't be necessary,
2346         * but the arch-specific save function might do something other than
2347         * write out bit-for-bit the exact same data.  Checking STEALING
2348         * suffices, since we hold the K_LOCK (preventing userspace from
2349         * starting a fresh STEALING phase concurrently). */
2350        if (!(atomic_read(&vcpd->flags) & VC_UTHREAD_STEALING))
2351                save_vc_fp_state(vcpd);
2352        /* Mark the vcore as preempted and unlock (was locked by the sender). */
2353        atomic_or(&vcpd->flags, VC_PREEMPTED);
2354        atomic_and(&vcpd->flags, ~VC_K_LOCK);
2355        /* either __preempt or proc_yield() ends the preempt phase. */
2356        p->procinfo->vcoremap[vcoreid].preempt_pending = 0;
2357        vcore_account_offline(p, vcoreid);
2358        /* make sure everything else hits before we finish the preempt */
2359        wmb();
2360        /* up the nr_done, which signals the next __startcore for this vc */
2361        p->procinfo->vcoremap[vcoreid].nr_preempts_done++;
2362        /* We won't restart the process later.  current gets cleared later when
2363         * we notice there is no owning_proc and we have nothing to do
2364         * (smp_idle, restartcore, etc) */
2365        clear_owning_proc(coreid);
2366}
2367
2368/* Kernel message handler to clean up the core when a process is dying.
2369 * Note this leaves no trace of what was running.
2370 * It's okay if death comes to a core that's already idling and has no current.
2371 * It could happen if a process decref'd before __proc_startcore could incref. */
2372void __death(uint32_t srcid, long a0, long a1, long a2)
2373{
2374        uint32_t vcoreid, coreid = core_id();
2375        struct per_cpu_info *pcpui = &per_cpu_info[coreid];
2376        struct proc *p = (struct proc*)a0;
2377
2378        assert(p);
2379        if (p != pcpui->owning_proc) {
2380                /* Older versions of Akaros thought it was OK to have a __death
2381                 * hit a core that no longer had a process.  I think it's a bug
2382                 * now. */
2383                panic("__death arrived for proc (%p) that was not owning (%p)!",
2384                      p, pcpui->owning_proc);
2385        }
2386        vcoreid = pcpui->owning_vcoreid;
2387        printd("[kernel] death on physical core %d for process %d's vcore %d\n",
2388               coreid, p->pid, vcoreid);
2389        vcore_account_offline(p, vcoreid);      /* in case anyone is counting */
2390        /* We won't restart the process later.  current gets cleared later when
2391         * we notice there is no owning_proc and we have nothing to do
2392         * (smp_idle, restartcore, etc). */
2393        arch_finalize_ctx(pcpui->cur_ctx);
2394        clear_owning_proc(coreid);
2395}
2396
2397/* Kernel message handler, usually sent IMMEDIATE, to shoot down virtual
2398 * addresses from a0 to a1. */
2399void __tlbshootdown(uint32_t srcid, long a0, long a1, long a2)
2400{
2401        /* TODO: (TLB) something more intelligent with the range */
2402        tlbflush();
2403}
2404
2405void print_allpids(void)
2406{
2407        void print_proc_state(void *item, void *opaque)
2408        {
2409                struct proc *p = (struct proc*)item;
2410                assert(p);
2411                /* this actually adds an extra space, since no progname is ever
2412                 * PROGNAME_SZ bytes, due to the \0 counted in PROGNAME. */
2413                printk("%8d %-*s %-10s %6d\n", p->pid, PROC_PROGNAME_SZ,
2414                       p->progname, procstate2str(p->state), p->ppid);
2415        }
2416        char dashes[PROC_PROGNAME_SZ];
2417        memset(dashes, '-', PROC_PROGNAME_SZ);
2418        dashes[PROC_PROGNAME_SZ - 1] = '\0';
2419        /* -5, for 'Name ' */
2420        printk("     PID Name %-*s State      Parent    \n",
2421               PROC_PROGNAME_SZ - 5, "");
2422        printk("------------------------------%s\n", dashes);
2423        spin_lock(&pid_hash_lock);
2424        hash_for_each(pid_hash, print_proc_state, NULL);
2425        spin_unlock(&pid_hash_lock);
2426}
2427
2428void proc_get_set(struct process_set *pset)
2429{
2430        void enum_proc(void *item, void *opaque)
2431        {
2432                struct proc *p = (struct proc*) item;
2433                struct process_set *pset = (struct process_set *) opaque;
2434
2435                if (pset->num_processes < pset->size) {
2436                        if (!kref_get_not_zero(&p->p_kref, 1))
2437                                return;
2438
2439                        pset->procs[pset->num_processes] = p;
2440                        pset->num_processes++;
2441                }
2442        }
2443
2444        static const size_t num_extra_alloc = 16;
2445
2446        pset->procs = NULL;
2447        do {
2448                if (pset->procs)
2449                        proc_free_set(pset);
2450                pset->size = atomic_read(&num_envs) + num_extra_alloc;
2451                pset->num_processes = 0;
2452                pset->procs = (struct proc **)
2453                        kzmalloc(pset->size * sizeof(struct proc *), MEM_WAIT);
2454
2455                spin_lock(&pid_hash_lock);
2456                hash_for_each(pid_hash, enum_proc, pset);
2457                spin_unlock(&pid_hash_lock);
2458
2459        } while (pset->num_processes == pset->size);
2460}
2461
2462void proc_free_set(struct process_set *pset)
2463{
2464        for (size_t i = 0; i < pset->num_processes; i++)
2465                proc_decref(pset->procs[i]);
2466        kfree(pset->procs);
2467}
2468
2469void print_proc_info(pid_t pid, int verbosity)
2470{
2471        int j = 0;
2472        uint64_t total_time = 0;
2473        struct proc *child, *p = pid2proc(pid);
2474        struct vcore *vc_i;
2475        struct preempt_data *vcpd;
2476
2477        if (!p) {
2478                printk("Bad PID.\n");
2479                return;
2480        }
2481        vcpd = &p->procdata->vcore_preempt_data[0];
2482        print_lock();
2483        spinlock_debug(&p->proc_lock);
2484        //spin_lock(&p->proc_lock); // No locking!!
2485        printk("struct proc: %p\n", p);
2486        printk("Program name: %s\n", p->progname);
2487        printk("PID: %d\n", p->pid);
2488        printk("PPID: %d\n", p->ppid);
2489        printk("State: %s (%p)\n", procstate2str(p->state), p->state);
2490        printk("\tIs %san MCP\n", p->procinfo->is_mcp ? "" : "not ");
2491        if (!scp_is_vcctx_ready(vcpd))
2492                printk("\tIs NOT vcctx ready\n");
2493        if (verbosity > 0 && !p->procinfo->is_mcp) {
2494                printk("Last saved SCP context:");
2495                backtrace_user_ctx(p, &p->scp_ctx);
2496        }
2497        printk("Refcnt: %d\n", atomic_read(&p->p_kref.refcount) - 1);
2498        printk("Flags: 0x%08x\n", p->env_flags);
2499        printk("CR3(phys): %p\n", p->env_cr3);
2500        printk("Num Vcores: %d\n", p->procinfo->num_vcores);
2501        printk("Vcore Lists (may be in flux w/o locking):\n----------------\n");
2502        printk("Online:\n");
2503        TAILQ_FOREACH(vc_i, &p->online_vcs, list)
2504                printk("\tVcore %d -> Pcore %d\n", vcore2vcoreid(p, vc_i),
2505                       vc_i->pcoreid);
2506        printk("Bulk Preempted:\n");
2507        TAILQ_FOREACH(vc_i, &p->bulk_preempted_vcs, list)
2508                printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2509        printk("Inactive / Yielded:\n");
2510        TAILQ_FOREACH(vc_i, &p->inactive_vcs, list)
2511                printk("\tVcore %d\n", vcore2vcoreid(p, vc_i));
2512        if (verbosity > 0) {
2513                printk("Nsec Online, up to the last offlining:\n");
2514                printk("------------------------");
2515                for (int i = 0; i < p->procinfo->max_vcores; i++) {
2516                        uint64_t vc_time = tsc2nsec(vcore_account_gettotal(p,
2517                                                                           i));
2518
2519                        if (i % 4 == 0)
2520                                printk("\n");
2521                        printk("  VC %3d: %14llu", i, vc_time);
2522                        total_time += vc_time;
2523                }
2524                printk("\n");
2525                printk("Total CPU-NSEC: %llu\n", total_time);
2526        }
2527        printk("Resources:\n------------------------\n");
2528        for (int i = 0; i < MAX_NUM_RESOURCES; i++)
2529                printk("\tRes type: %02d, amt wanted: %08d amt granted: %08d\n",
2530                       i, p->procdata->res_req[i].amt_wanted,
2531                       p->procinfo->res_grant[i]);
2532        printk("Open Files:\n");
2533        struct fd_table *files = &p->open_files;
2534
2535        if (spin_locked(&files->lock)) {
2536                spinlock_debug(&files->lock);
2537                printk("FILE LOCK HELD, ABORTING\n");
2538                print_unlock();
2539                proc_decref(p);
2540                return;
2541        }
2542        spin_lock(&files->lock);
2543        for (int i = 0; i < files->max_files; i++) {
2544                if (GET_BITMASK_BIT(files->open_fds->fds_bits, i)) {
2545                        printk("\tFD: %02d, ", i);
2546                        assert(files->fd[i].fd_chan);
2547                        print_chaninfo(files->fd[i].fd_chan);
2548                }
2549        }
2550        spin_unlock(&files->lock);
2551        printk("Children: (PID (struct proc *))\n");
2552        TAILQ_FOREACH(child, &p->children, sibling_link)
2553                printk("\t%d (%p)\n", child->pid, child);
2554        print_unlock();
2555        /* no locking / unlocking or refcnting */
2556        // spin_unlock(&p->proc_lock);
2557        proc_decref(p);
2558}
2559
2560/* Debugging function, checks what (process, vcore) is supposed to run on this
2561 * pcore.  Meant to be called from smp_idle() before halting. */
2562void check_my_owner(void)
2563{
2564        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2565        void shazbot(void *item, void *opaque)
2566        {
2567                struct proc *p = (struct proc*)item;
2568                struct vcore *vc_i;
2569                assert(p);
2570                spin_lock(&p->proc_lock);
2571                TAILQ_FOREACH(vc_i, &p->online_vcs, list) {
2572                        /* this isn't true, a __startcore could be on the way
2573                         * and we're already "online" */
2574                        if (vc_i->pcoreid == core_id()) {
2575                                /* Immediate message was sent, we should get it
2576                                 * when we enable interrupts, which should cause
2577                                 * us to skip cpu_halt() */
2578                                if (!STAILQ_EMPTY(&pcpui->immed_amsgs))
2579                                        continue;
2580                                printk("Owned pcore (%d) has no owner, by %p, vc %d!\n",
2581                                       core_id(), p, vcore2vcoreid(p, vc_i));
2582                                spin_unlock(&p->proc_lock);
2583                                spin_unlock(&pid_hash_lock);
2584                                monitor(0);
2585                        }
2586                }
2587                spin_unlock(&p->proc_lock);
2588        }
2589        assert(!irq_is_enabled());
2590        if (!booting && !pcpui->owning_proc) {
2591                spin_lock(&pid_hash_lock);
2592                hash_for_each(pid_hash, shazbot, NULL);
2593                spin_unlock(&pid_hash_lock);
2594        }
2595}
2596