akaros/kern/src/kthread.c
<<
>>
Prefs
   1/* Copyright (c) 2010-13 The Regents of the University of California
   2 * Barret Rhoden <brho@cs.berkeley.edu>
   3 * See LICENSE for details.
   4 *
   5 * Kernel threading.  These are for blocking within the kernel for whatever
   6 * reason, usually during blocking IO operations. */
   7
   8#include <kthread.h>
   9#include <slab.h>
  10#include <page_alloc.h>
  11#include <pmap.h>
  12#include <smp.h>
  13#include <schedule.h>
  14#include <kstack.h>
  15#include <kmalloc.h>
  16#include <arch/uaccess.h>
  17
  18#define KSTACK_NR_GUARD_PGS             1
  19#define KSTACK_GUARD_SZ                 (KSTACK_NR_GUARD_PGS * PGSIZE)
  20static struct kmem_cache *kstack_cache;
  21
  22/* We allocate KSTKSIZE + PGSIZE vaddrs.  So for one-page stacks, we get two
  23 * pages.  blob points to the bottom of this space.  Our job is to allocate the
  24 * physical pages for the stack and set up the virtual-to-physical mappings. */
  25int kstack_ctor(void *blob, void *priv, int flags)
  26{
  27        void *stackbot;
  28
  29        stackbot = kpages_alloc(KSTKSIZE, flags);
  30        if (!stackbot)
  31                return -1;
  32        if (map_vmap_segment((uintptr_t)blob, 0x123456000, KSTACK_NR_GUARD_PGS,
  33                             PTE_NONE))
  34                goto error;
  35        if (map_vmap_segment((uintptr_t)blob + KSTACK_GUARD_SZ, PADDR(stackbot),
  36                             KSTKSIZE / PGSIZE, PTE_KERN_RW))
  37                goto error;
  38        return 0;
  39error:
  40        /* On failure, we only need to undo what our dtor would do.  The unmaps
  41         * happen in the vmap_arena ffunc. */
  42        kpages_free(stackbot, KSTKSIZE);
  43        return -1;
  44}
  45
  46/* The vmap_arena free will unmap the vaddrs on its own.  We just need to free
  47 * the physical memory we allocated in ctor.  Although we still have mappings
  48 * and TLB entries pointing to the memory after we free it (and thus it can be
  49 * reused), this is no more dangerous than just freeing the stack.  Errant
  50 * pointers into an old kstack are still dangerous. */
  51void kstack_dtor(void *blob, void *priv)
  52{
  53        void *stackbot;
  54        pte_t pte;
  55
  56        pte = pgdir_walk(boot_pgdir, blob + KSTACK_GUARD_SZ, 0);
  57        assert(pte_walk_okay(pte));
  58        stackbot = KADDR(pte_get_paddr(pte));
  59        kpages_free(stackbot, KSTKSIZE);
  60}
  61
  62uintptr_t get_kstack(void)
  63{
  64        void *blob;
  65
  66        blob = kmem_cache_alloc(kstack_cache, MEM_ATOMIC);
  67        /* TODO: think about MEM_WAIT within kthread/blocking code. */
  68        assert(blob);
  69        return (uintptr_t)blob + KSTKSIZE + KSTACK_GUARD_SZ;
  70}
  71
  72void put_kstack(uintptr_t stacktop)
  73{
  74        kmem_cache_free(kstack_cache, (void*)(stacktop - KSTKSIZE
  75                                              - KSTACK_GUARD_SZ));
  76}
  77
  78uintptr_t *kstack_bottom_addr(uintptr_t stacktop)
  79{
  80        /* canary at the bottom of the stack */
  81        assert(!PGOFF(stacktop));
  82        return (uintptr_t*)(stacktop - KSTKSIZE);
  83}
  84
  85struct kmem_cache *kthread_kcache;
  86
  87void kthread_init(void)
  88{
  89        kthread_kcache = kmem_cache_create("kthread", sizeof(struct kthread),
  90                                           __alignof__(struct kthread), 0,
  91                                           NULL, 0, 0, NULL);
  92        kstack_cache = kmem_cache_create("kstack", KSTKSIZE + KSTACK_GUARD_SZ,
  93                                         PGSIZE, 0, vmap_arena, kstack_ctor,
  94                                         kstack_dtor, NULL);
  95}
  96
  97/* Used by early init routines (smp_boot, etc) */
  98struct kthread *__kthread_zalloc(void)
  99{
 100        struct kthread *kthread;
 101
 102        kthread = kmem_cache_alloc(kthread_kcache, 0);
 103        assert(kthread);
 104        memset(kthread, 0, sizeof(struct kthread));
 105        return kthread;
 106}
 107
 108/* Helper during early boot, where we jump from the bootstack to a real kthread
 109 * stack, then run f().  Note that we don't have a kthread yet (done in smp.c).
 110 *
 111 * After this, our callee (f) can free the bootstack, if we care, by adding it
 112 * to the base arena (use the KERNBASE addr, not the KERN_LOAD_ADDR). */
 113void __use_real_kstack(void (*f)(void *arg))
 114{
 115        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 116        uintptr_t new_stacktop;
 117
 118        new_stacktop = get_kstack();
 119        set_stack_top(new_stacktop);
 120        __reset_stack_pointer(0, new_stacktop, f);
 121}
 122
 123/* Starts kthread on the calling core.  This does not return, and will handle
 124 * the details of cleaning up whatever is currently running (freeing its stack,
 125 * etc).  Pairs with sem_down(). */
 126void restart_kthread(struct kthread *kthread)
 127{
 128        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 129        uintptr_t current_stacktop;
 130        struct kthread *cur_kth;
 131        struct proc *old_proc;
 132
 133        /* Avoid messy complications.  The kthread will enable_irqsave() when it
 134         * comes back up. */
 135        disable_irq();
 136        /* Free any spare, since we need the current to become the spare.
 137         * Without the spare, we can't free our current kthread/stack (we could
 138         * free the kthread, but not the stack, since we're still on it).  And
 139         * we can't free anything after popping kthread, since we never return.
 140         * */
 141        if (pcpui->spare) {
 142                put_kstack(pcpui->spare->stacktop);
 143                kmem_cache_free(kthread_kcache, pcpui->spare);
 144        }
 145        cur_kth = pcpui->cur_kthread;
 146        current_stacktop = cur_kth->stacktop;
 147        assert(!cur_kth->sysc); /* catch bugs, prev user should clear */
 148        /* Set the spare stuff (current kthread, which includes its stacktop) */
 149        pcpui->spare = cur_kth;
 150        /* When a kthread runs, its stack is the default kernel stack */
 151        set_stack_top(kthread->stacktop);
 152        pcpui->cur_kthread = kthread;
 153        /* Only change current if we need to (the kthread was in process
 154         * context) */
 155        if (kthread->proc) {
 156                if (kthread->proc == pcpui->cur_proc) {
 157                        /* We're already loaded, but we do need to drop the
 158                         * extra ref stored in kthread->proc. */
 159                        proc_decref(kthread->proc);
 160                        kthread->proc = 0;
 161                } else {
 162                        /* Load our page tables before potentially decreffing
 163                         * cur_proc.
 164                         *
 165                         * We don't need to do an EPT flush here.  The EPT is
 166                         * flushed and managed in sync with the VMCS.  We won't
 167                         * run a different VM (and thus *need* a different EPT)
 168                         * without first removing the old GPC, which ultimately
 169                         * will result in a flushed EPT (on x86, this actually
 170                         * happens when we clear_owning_proc()). */
 171                        lcr3(kthread->proc->env_cr3);
 172                        /* Might have to clear out an existing current.  If they
 173                         * need to be set later (like in restartcore), it'll be
 174                         * done on demand. */
 175                        old_proc = pcpui->cur_proc;
 176                        /* Transfer our counted ref from kthread->proc to
 177                         * cur_proc. */
 178                        pcpui->cur_proc = kthread->proc;
 179                        kthread->proc = 0;
 180                        if (old_proc)
 181                                proc_decref(old_proc);
 182                }
 183        }
 184        /* Finally, restart our thread */
 185        longjmp(&kthread->context, 1);
 186}
 187
 188/* Kmsg handler to launch/run a kthread.  This must be a routine message, since
 189 * it does not return.  */
 190static void __launch_kthread(uint32_t srcid, long a0, long a1, long a2)
 191{
 192        struct kthread *kthread = (struct kthread*)a0;
 193        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 194        struct proc *cur_proc = pcpui->cur_proc;
 195
 196        if (pcpui->owning_proc && pcpui->owning_proc != kthread->proc) {
 197                /* Some process should be running here that is not the same as
 198                 * the kthread.  This means the _M is getting interrupted or
 199                 * otherwise delayed.  If we want to do something other than run
 200                 * it (like send the kmsg to another pcore, or ship the context
 201                 * from here to somewhere else/deschedule it (like for an _S)),
 202                 * do it here.
 203                 *
 204                 * If you want to do something here, call out to the ksched,
 205                 * then abandon_core(). */
 206                cmb();  /* do nothing/placeholder */
 207        }
 208        /* o/w, just run the kthread.  any trapframes that are supposed to run
 209         * or were interrupted will run whenever the kthread smp_idles() or
 210         * otherwise finishes. */
 211        restart_kthread(kthread);
 212        assert(0);
 213}
 214
 215/* Call this when a kthread becomes runnable/unblocked.  We don't do anything
 216 * particularly smart yet, but when we do, we can put it here. */
 217void kthread_runnable(struct kthread *kthread)
 218{
 219        int dst;
 220
 221        /* TODO: KSCHED - this is a scheduling decision.  The kthread can be
 222         * woken up by threads from somewhat unrelated processes.  Consider
 223         * unlocking a sem or kicking an RV from an MCP's syscall.  Where was
 224         * this kthread running before?  Did it belong to the MCP?  Is the
 225         * kthread from an old MCP that was on this core, but there is now a new
 226         * MCP?  (This can happen with alarms, currently).
 227         *
 228         * For ktasks, they tend to sleep on an RV forever.  Once they migrate
 229         * to a core other than core 0 due to blocking on a qlock/sem, they will
 230         * tend to stay on that core forever, interfering with an unrelated MCP.
 231         *
 232         * We could consider some sort of core affinity, but for now, we can
 233         * just route all ktasks to core 0.  Note this may hide some bugs that
 234         * would otherwise be exposed by running in parallel. */
 235        if (is_ktask(kthread))
 236                dst = 0;
 237        else
 238                dst = core_id();
 239        send_kernel_message(dst, __launch_kthread, (long)kthread, 0, 0,
 240                            KMSG_ROUTINE);
 241}
 242
 243/* Stop the current kthread.  It'll get woken up next time we run routine kmsgs,
 244 * after all existing kmsgs are processed. */
 245void kthread_yield(void)
 246{
 247        struct semaphore local_sem, *sem = &local_sem;
 248
 249        sem_init(sem, 0);
 250        run_as_rkm(sem_up, sem);
 251        sem_down(sem);
 252}
 253
 254void kthread_usleep(uint64_t usec)
 255{
 256        ERRSTACK(1);
 257        /* TODO: classic ksched issue: where do we want the wake up to happen?
 258         */
 259        struct timer_chain *tchain = &per_cpu_info[core_id()].tchain;
 260        struct rendez rv;
 261
 262        int ret_zero(void *ignored)
 263        {
 264                return 0;
 265        }
 266
 267        /* "discard the error" style (we run the conditional code) */
 268        if (!waserror()) {
 269                rendez_init(&rv);
 270                rendez_sleep_timeout(&rv, ret_zero, 0, usec);
 271        }
 272        poperror();
 273}
 274
 275static void __ktask_wrapper(uint32_t srcid, long a0, long a1, long a2)
 276{
 277        ERRSTACK(1);
 278        void (*fn)(void*) = (void (*)(void*))a0;
 279        void *arg = (void*)a1;
 280        char *name = (char*)a2;
 281        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
 282
 283        assert(is_ktask(pcpui->cur_kthread));
 284        pcpui->cur_kthread->name = name;
 285        /* There are some rendezs out there that aren't wrapped.  Though no one
 286         * can abort them.  Yet. */
 287        if (waserror()) {
 288                printk("Ktask %s threw error %s\n", name, current_errstr());
 289                goto out;
 290        }
 291        enable_irq();
 292        fn(arg);
 293out:
 294        disable_irq();
 295        pcpui->cur_kthread->name = 0;
 296        poperror();
 297        /* if we blocked, when we return, PRKM will smp_idle() */
 298}
 299
 300/* Creates a kernel task, running fn(arg), named "name".  This is just a routine
 301 * kernel message that happens to have a name, and is allowed to block.  It
 302 * won't be associated with any process.  For lack of a better place, we'll just
 303 * start it on the calling core.  Caller (and/or fn) need to deal with the
 304 * storage for *name. */
 305void ktask(char *name, void (*fn)(void*), void *arg)
 306{
 307        send_kernel_message(core_id(), __ktask_wrapper, (long)fn, (long)arg,
 308                            (long)name, KMSG_ROUTINE);
 309}
 310
 311/* Semaphores, using kthreads directly */
 312static void db_blocked_kth(struct kth_db_info *db);
 313static void db_unblocked_kth(struct kth_db_info *db);
 314static void db_init(struct kth_db_info *db, int type);
 315
 316static void sem_init_common(struct semaphore *sem, int signals)
 317{
 318        TAILQ_INIT(&sem->waiters);
 319        sem->nr_signals = signals;
 320        db_init(&sem->db, KTH_DB_SEM);
 321}
 322
 323void sem_init(struct semaphore *sem, int signals)
 324{
 325        sem_init_common(sem, signals);
 326        spinlock_init(&sem->lock);
 327}
 328
 329void sem_init_irqsave(struct semaphore *sem, int signals)
 330{
 331        sem_init_common(sem, signals);
 332        spinlock_init_irqsave(&sem->lock);
 333}
 334
 335bool sem_trydown_bulk(struct semaphore *sem, int nr_signals)
 336{
 337        bool ret = FALSE;
 338
 339        /* lockless peek */
 340        if (sem->nr_signals - nr_signals < 0)
 341                return ret;
 342        spin_lock(&sem->lock);
 343        if (sem->nr_signals - nr_signals >= 0) {
 344                sem->nr_signals--;
 345                ret = TRUE;
 346        }
 347        spin_unlock(&sem->lock);
 348        return ret;
 349}
 350
 351bool sem_trydown(struct semaphore *sem)
 352{
 353        return sem_trydown_bulk(sem, 1);
 354}
 355
 356/* Bottom-half of sem_down.  This is called after we jumped to the new stack. */
 357static void __attribute__((noreturn)) __sem_unlock_and_idle(void *arg)
 358{
 359        struct semaphore *sem = (struct semaphore*)arg;
 360
 361        spin_unlock(&sem->lock);
 362        smp_idle();
 363}
 364
 365static void pre_block_check(int nr_locks)
 366{
 367        struct per_cpu_info *pcpui = this_pcpui_ptr();
 368
 369        assert(can_block(pcpui));
 370        /* Make sure we aren't holding any locks (only works if SPINLOCK_DEBUG)
 371         */
 372        if (pcpui->lock_depth > nr_locks)
 373                panic("Kthread tried to sleep, with lockdepth %d\n", pcpui->lock_depth);
 374
 375}
 376
 377static struct kthread *save_kthread_ctx(void)
 378{
 379        struct kthread *kthread, *new_kthread;
 380        register uintptr_t new_stacktop;
 381        struct per_cpu_info *pcpui = this_pcpui_ptr();
 382
 383        assert(pcpui->cur_kthread);
 384        /* We're probably going to sleep, so get ready.  We'll check again
 385         * later. */
 386        kthread = pcpui->cur_kthread;
 387        /* We need to have a spare slot for restart, so we also use it when
 388         * sleeping.  Right now, we need a new kthread to take over if/when our
 389         * current kthread sleeps.  Use the spare, and if not, get a new one.
 390         *
 391         * Note we do this with interrupts disabled (which protects us from
 392         * concurrent modifications). */
 393        if (pcpui->spare) {
 394                new_kthread = pcpui->spare;
 395                new_stacktop = new_kthread->stacktop;
 396                pcpui->spare = 0;
 397                /* The old flags could have KTH_IS_KTASK set.  The reason is
 398                 * that the launching of blocked kthreads also uses PRKM, and
 399                 * that KMSG (__launch_kthread) doesn't return.  Thus the
 400                 * soon-to-be spare kthread, that is launching another, has
 401                 * flags & KTH_IS_KTASK set. */
 402                new_kthread->flags = KTH_DEFAULT_FLAGS;
 403                new_kthread->proc = 0;
 404                new_kthread->name = 0;
 405        } else {
 406                new_kthread = __kthread_zalloc();
 407                new_kthread->flags = KTH_DEFAULT_FLAGS;
 408                new_stacktop = get_kstack();
 409                new_kthread->stacktop = new_stacktop;
 410        }
 411        /* Set the core's new default stack and kthread */
 412        set_stack_top(new_stacktop);
 413        pcpui->cur_kthread = new_kthread;
 414        /* Kthreads that are ktasks are not related to any process, and do not
 415         * need to work in a process's address space.  They can operate in any
 416         * address space that has the kernel mapped (like boot_pgdir, or any
 417         * pgdir).  Some ktasks may switch_to, at which point they do care about
 418         * the address space and must maintain a reference.
 419         *
 420         * Normal kthreads need to stay in the process context, but we want the
 421         * core (which could be a vcore) to stay in the context too. */
 422        if ((kthread->flags & KTH_SAVE_ADDR_SPACE) && current) {
 423                kthread->proc = current;
 424                /* In the future, we could check owning_proc. If it isn't set,
 425                 * we could clear current and transfer the refcnt to
 426                 * kthread->proc.  If so, we'll need to reset the cr3 to
 427                 * something (boot_cr3 or owning_proc's cr3), which might not be
 428                 * worth the potentially excessive TLB flush. */
 429                proc_incref(kthread->proc, 1);
 430        } else {
 431                assert(kthread->proc == 0);
 432        }
 433        return kthread;
 434}
 435
 436static void unsave_kthread_ctx(struct kthread *kthread)
 437{
 438        struct per_cpu_info *pcpui = this_pcpui_ptr();
 439        struct kthread *new_kthread = pcpui->cur_kthread;
 440
 441        printd("[kernel] Didn't sleep, unwinding...\n");
 442        /* Restore the core's current and default stacktop */
 443        if (kthread->flags & KTH_SAVE_ADDR_SPACE) {
 444                proc_decref(kthread->proc);
 445                kthread->proc = 0;
 446        }
 447        set_stack_top(kthread->stacktop);
 448        pcpui->cur_kthread = kthread;
 449        /* Save the allocs as the spare */
 450        assert(!pcpui->spare);
 451        pcpui->spare = new_kthread;
 452}
 453
 454/* This downs the semaphore and suspends the current kernel context on its
 455 * waitqueue if there are no pending signals. */
 456void sem_down(struct semaphore *sem)
 457{
 458        bool irqs_were_on = irq_is_enabled();
 459        struct kthread *kthread;
 460
 461        pre_block_check(0);
 462
 463        /* Try to down the semaphore.  If there is a signal there, we can skip
 464         * all of the sleep prep and just return. */
 465#ifdef CONFIG_SEM_SPINWAIT
 466        for (int i = 0; i < CONFIG_SEM_SPINWAIT_NR_LOOPS; i++) {
 467                if (sem_trydown(sem))
 468                        goto block_return_path;
 469                cpu_relax();
 470        }
 471#else
 472        if (sem_trydown(sem))
 473                goto block_return_path;
 474#endif
 475
 476        kthread = save_kthread_ctx();
 477        if (setjmp(&kthread->context))
 478                goto block_return_path;
 479
 480        spin_lock(&sem->lock);
 481        sem->nr_signals -= 1;
 482        if (sem->nr_signals < 0) {
 483                TAILQ_INSERT_TAIL(&sem->waiters, kthread, link);
 484                db_blocked_kth(&sem->db);
 485                /* At this point, we know we'll sleep and change stacks.  Once
 486                 * we unlock the sem, we could have the kthread restarted
 487                 * (possibly on another core), so we need to leave the old stack
 488                 * before unlocking.  If we don't and we stay on the stack, then
 489                 * if we take an IRQ or NMI (NMI that doesn't change stacks,
 490                 * unlike x86_64), we'll be using the stack at the same time as
 491                 * the kthread.  We could just disable IRQs, but that wouldn't
 492                 * protect us from NMIs that don't change stacks. */
 493                __reset_stack_pointer(sem, current_kthread->stacktop,
 494                                      __sem_unlock_and_idle);
 495                assert(0);
 496        }
 497        spin_unlock(&sem->lock);
 498
 499        unsave_kthread_ctx(kthread);
 500
 501block_return_path:
 502        printd("[kernel] Returning from being 'blocked'! at %llu\n", read_tsc());
 503        /* restart_kthread and longjmp did not reenable IRQs.  We need to make
 504         * sure irqs are on if they were on when we started to block.  If they
 505         * were already on and we short-circuited the block, it's harmless to
 506         * reenable them. */
 507        if (irqs_were_on)
 508                enable_irq();
 509}
 510
 511void sem_down_bulk(struct semaphore *sem, int nr_signals)
 512{
 513        /* This is far from ideal.  Our current sem code expects a 1:1 pairing
 514         * of signals to waiters.  For instance, if we have 10 waiters of -1
 515         * each or 1 waiter of -10, we can't tell from looking at the overall
 516         * structure.  We'd need to track the desired number of signals per
 517         * waiter.
 518         *
 519         * Note that if there are a bunch of signals available, sem_down will
 520         * quickly do a try_down and return, so we won't block repeatedly.  But
 521         * if we do block, we could wake up N times. */
 522        for (int i = 0; i < nr_signals; i++)
 523                sem_down(sem);
 524}
 525
 526/* Ups the semaphore.  If it was < 0, we need to wake up someone, which we do.
 527 * Returns TRUE if we woke someone, FALSE o/w (used for debugging in some
 528 * places).  If we need more control, we can implement a version of the old
 529 * __up_sem() again.  */
 530bool sem_up(struct semaphore *sem)
 531{
 532        struct kthread *kthread = 0;
 533
 534        spin_lock(&sem->lock);
 535        if (sem->nr_signals++ < 0) {
 536                assert(!TAILQ_EMPTY(&sem->waiters));
 537                /* could do something with 'priority' here */
 538                kthread = TAILQ_FIRST(&sem->waiters);
 539                TAILQ_REMOVE(&sem->waiters, kthread, link);
 540                db_unblocked_kth(&sem->db);
 541        } else {
 542                assert(TAILQ_EMPTY(&sem->waiters));
 543        }
 544        spin_unlock(&sem->lock);
 545        /* Note that once we call kthread_runnable(), we cannot touch the sem
 546         * again.  Some sems are on stacks.  The caller can touch sem, if it
 547         * knows about the memory/usage of the sem.  Likewise, we can't touch
 548         * the kthread either. */
 549        if (kthread) {
 550                kthread_runnable(kthread);
 551                return TRUE;
 552        }
 553        return FALSE;
 554}
 555
 556bool sem_trydown_bulk_irqsave(struct semaphore *sem, int nr_signals)
 557{
 558        bool ret;
 559        int8_t irq_state = 0;
 560
 561        disable_irqsave(&irq_state);
 562        ret = sem_trydown_bulk(sem, nr_signals);
 563        enable_irqsave(&irq_state);
 564        return ret;
 565}
 566
 567bool sem_trydown_irqsave(struct semaphore *sem)
 568{
 569        return sem_trydown_bulk_irqsave(sem, 1);
 570}
 571
 572void sem_down_bulk_irqsave(struct semaphore *sem, int nr_signals)
 573{
 574        int8_t irq_state = 0;
 575
 576        disable_irqsave(&irq_state);
 577        sem_down_bulk(sem, nr_signals);
 578        enable_irqsave(&irq_state);
 579}
 580
 581void sem_down_irqsave(struct semaphore *sem)
 582{
 583        sem_down_bulk_irqsave(sem, 1);
 584}
 585
 586bool sem_up_irqsave(struct semaphore *sem)
 587{
 588        bool retval;
 589        int8_t irq_state = 0;
 590
 591        disable_irqsave(&irq_state);
 592        retval = sem_up(sem);
 593        enable_irqsave(&irq_state);
 594        return retval;
 595}
 596
 597/* Sem debugging */
 598
 599#ifdef CONFIG_SEMAPHORE_DEBUG
 600
 601static struct kth_db_tailq objs_with_waiters =
 602                       TAILQ_HEAD_INITIALIZER(objs_with_waiters);
 603static spinlock_t objs_with_waiters_lock = SPINLOCK_INITIALIZER_IRQSAVE;
 604
 605static struct kthread_tailq *db_get_waiters(struct kth_db_info *db)
 606{
 607        struct semaphore *sem;
 608        struct cond_var *cv;
 609
 610        switch (db->type) {
 611        case KTH_DB_SEM:
 612                return &container_of(db, struct semaphore, db)->waiters;
 613        case KTH_DB_CV:
 614                return &container_of(db, struct cond_var, db)->waiters;
 615        }
 616        panic("Bad type %d in db %p\n", db->type, db);
 617}
 618
 619static spinlock_t *db_get_spinlock(struct kth_db_info *db)
 620{
 621        struct semaphore *sem;
 622        struct cond_var *cv;
 623
 624        switch (db->type) {
 625        case KTH_DB_SEM:
 626                return &container_of(db, struct semaphore, db)->lock;
 627        case KTH_DB_CV:
 628                return container_of(db, struct cond_var, db)->lock;
 629        }
 630        panic("Bad type %d in db %p\n", db->type, db);
 631}
 632
 633static void db_blocked_kth(struct kth_db_info *db)
 634{
 635        spin_lock_irqsave(&objs_with_waiters_lock);
 636        if (!db->on_list) {
 637                TAILQ_INSERT_HEAD(&objs_with_waiters, db, link);
 638                db->on_list = true;
 639        }
 640        spin_unlock_irqsave(&objs_with_waiters_lock);
 641}
 642
 643static void db_unblocked_kth(struct kth_db_info *db)
 644{
 645        spin_lock_irqsave(&objs_with_waiters_lock);
 646        if (TAILQ_EMPTY(db_get_waiters(db))) {
 647                TAILQ_REMOVE(&objs_with_waiters, db, link);
 648                db->on_list = false;
 649        }
 650        spin_unlock_irqsave(&objs_with_waiters_lock);
 651}
 652
 653static void db_init(struct kth_db_info *db, int type)
 654{
 655        db->type = type;
 656        db->on_list = false;
 657}
 658
 659static bool __obj_has_pid(struct kth_db_info *db, pid_t pid)
 660{
 661        struct kthread *kth_i;
 662
 663        if (pid == -1)
 664                return true;
 665        TAILQ_FOREACH(kth_i, db_get_waiters(db), link) {
 666                if (kth_i->proc) {
 667                        if (kth_i->proc->pid == pid)
 668                                return true;
 669                } else {
 670                        if (pid == 0)
 671                                return true;
 672                }
 673        }
 674        return false;
 675}
 676
 677static void db_print_obj(struct kth_db_info *db, pid_t pid)
 678{
 679        struct kthread *kth_i;
 680
 681        /* Always safe to irqsave.  We trylock, since the lock ordering is
 682         * obj_lock
 683         * -> list_lock. */
 684        if (!spin_trylock_irqsave(db_get_spinlock(db)))
 685                return;
 686        if (!__obj_has_pid(db, pid)) {
 687                spin_unlock_irqsave(db_get_spinlock(db));
 688                return;
 689        }
 690        printk("Object %p (%3s):\n", db, db->type == KTH_DB_SEM ? "sem" :
 691                                         db->type == KTH_DB_CV ? "cv" : "unk");
 692        TAILQ_FOREACH(kth_i, db_get_waiters(db), link)
 693                printk("\tKthread %p (%s), proc %d, sysc %p, pc/frame %p %p\n",
 694                       kth_i, kth_i->name, kth_i->proc ? kth_i->proc->pid : 0,
 695                       kth_i->sysc, jmpbuf_get_pc(&kth_i->context),
 696                       jmpbuf_get_fp(&kth_i->context));
 697        printk("\n");
 698        spin_unlock_irqsave(db_get_spinlock(db));
 699}
 700
 701void print_db_blk_info(pid_t pid)
 702{
 703        struct kth_db_info *db_i;
 704
 705        print_lock();
 706        printk("All objects with waiters:\n");
 707        spin_lock_irqsave(&objs_with_waiters_lock);
 708        TAILQ_FOREACH(db_i, &objs_with_waiters, link)
 709                db_print_obj(db_i, pid);
 710        spin_unlock_irqsave(&objs_with_waiters_lock);
 711        print_unlock();
 712}
 713
 714#else
 715
 716static void db_blocked_kth(struct kth_db_info *db)
 717{
 718}
 719
 720static void db_unblocked_kth(struct kth_db_info *db)
 721{
 722}
 723
 724static void db_init(struct kth_db_info *db, int type)
 725{
 726}
 727
 728void print_db_blk_info(pid_t pid)
 729{
 730        printk("Failed to print all sems: build with CONFIG_SEMAPHORE_DEBUG\n");
 731}
 732
 733#endif /* CONFIG_SEMAPHORE_DEBUG */
 734
 735static void __cv_raw_init(struct cond_var *cv)
 736{
 737        TAILQ_INIT(&cv->waiters);
 738        cv->nr_waiters = 0;
 739        db_init(&cv->db, KTH_DB_CV);
 740}
 741
 742/* Condition variables, using semaphores and kthreads */
 743void cv_init(struct cond_var *cv)
 744{
 745        __cv_raw_init(cv);
 746
 747        cv->lock = &cv->internal_lock;
 748        spinlock_init(cv->lock);
 749}
 750
 751void cv_init_irqsave(struct cond_var *cv)
 752{
 753        __cv_raw_init(cv);
 754
 755        cv->lock = &cv->internal_lock;
 756        spinlock_init_irqsave(cv->lock);
 757}
 758
 759void cv_init_with_lock(struct cond_var *cv, spinlock_t *lock)
 760{
 761        __cv_raw_init(cv);
 762
 763        cv->lock = lock;
 764}
 765
 766void cv_init_irqsave_with_lock(struct cond_var *cv, spinlock_t *lock)
 767{
 768        cv_init_with_lock(cv, lock);
 769}
 770
 771void cv_lock(struct cond_var *cv)
 772{
 773        spin_lock(cv->lock);
 774}
 775
 776void cv_unlock(struct cond_var *cv)
 777{
 778        spin_unlock(cv->lock);
 779}
 780
 781void cv_lock_irqsave(struct cond_var *cv, int8_t *irq_state)
 782{
 783        disable_irqsave(irq_state);
 784        cv_lock(cv);
 785}
 786
 787void cv_unlock_irqsave(struct cond_var *cv, int8_t *irq_state)
 788{
 789        cv_unlock(cv);
 790        enable_irqsave(irq_state);
 791}
 792
 793static void __attribute__((noreturn)) __cv_unlock_and_idle(void *arg)
 794{
 795        struct cond_var *cv = arg;
 796
 797        cv_unlock(cv);
 798        smp_idle();
 799}
 800
 801/* Comes in locked.  Regarding IRQs, the initial cv_lock_irqsave would have
 802 * disabled irqs.  When this returns, IRQs would still be disabled.  If it was a
 803 * regular cv_lock(), IRQs will be enabled when we return. */
 804void cv_wait_and_unlock(struct cond_var *cv)
 805{
 806        bool irqs_were_on = irq_is_enabled();
 807        struct kthread *kthread;
 808
 809        pre_block_check(1);
 810
 811        kthread = save_kthread_ctx();
 812        if (setjmp(&kthread->context)) {
 813                /* When the kthread restarts, IRQs are off. */
 814                if (irqs_were_on)
 815                        enable_irq();
 816                return;
 817        }
 818
 819        TAILQ_INSERT_TAIL(&cv->waiters, kthread, link);
 820        cv->nr_waiters++;
 821        db_blocked_kth(&cv->db);
 822
 823        __reset_stack_pointer(cv, current_kthread->stacktop,
 824                              __cv_unlock_and_idle);
 825        assert(0);
 826}
 827
 828/* Comes in locked.  Note cv_lock does not disable irqs.   They should still be
 829 * disabled from the initial cv_lock_irqsave(), which cv_wait_and_unlock()
 830 * maintained. */
 831void cv_wait(struct cond_var *cv)
 832{
 833        cv_wait_and_unlock(cv);
 834        cv_lock(cv);
 835}
 836
 837/* Helper, wakes exactly one, and there should have been at least one waiter. */
 838static void __cv_wake_one(struct cond_var *cv)
 839{
 840        struct kthread *kthread;
 841
 842        kthread = TAILQ_FIRST(&cv->waiters);
 843        TAILQ_REMOVE(&cv->waiters, kthread, link);
 844        db_unblocked_kth(&cv->db);
 845        kthread_runnable(kthread);
 846}
 847
 848void __cv_signal(struct cond_var *cv)
 849{
 850        if (cv->nr_waiters) {
 851                cv->nr_waiters--;
 852                __cv_wake_one(cv);
 853        }
 854}
 855
 856void __cv_broadcast(struct cond_var *cv)
 857{
 858        while (cv->nr_waiters) {
 859                cv->nr_waiters--;
 860                __cv_wake_one(cv);
 861        }
 862}
 863
 864void cv_signal(struct cond_var *cv)
 865{
 866        spin_lock(cv->lock);
 867        __cv_signal(cv);
 868        spin_unlock(cv->lock);
 869}
 870
 871void cv_broadcast(struct cond_var *cv)
 872{
 873        spin_lock(cv->lock);
 874        __cv_broadcast(cv);
 875        spin_unlock(cv->lock);
 876}
 877
 878void cv_signal_irqsave(struct cond_var *cv, int8_t *irq_state)
 879{
 880        disable_irqsave(irq_state);
 881        cv_signal(cv);
 882        enable_irqsave(irq_state);
 883}
 884
 885void cv_broadcast_irqsave(struct cond_var *cv, int8_t *irq_state)
 886{
 887        disable_irqsave(irq_state);
 888        cv_broadcast(cv);
 889        enable_irqsave(irq_state);
 890}
 891
 892/* Helper, aborts and releases a CLE.  dereg_ spinwaits on abort_in_progress.
 893 * This can throw a PF */
 894static void __abort_and_release_cle(struct cv_lookup_elm *cle)
 895{
 896        int8_t irq_state = 0;
 897
 898        /* At this point, we have a handle on the syscall that we want to abort
 899         * (via the cle), and we know none of the memory will disappear on us
 900         * (deregers wait on the flag).  So we'll signal ABORT, which rendez
 901         * will pick up next time it is awake.  Then we make sure it is awake
 902         * with a broadcast. */
 903        atomic_or(&cle->sysc->flags, SC_ABORT);
 904        /* flags write before signal; atomic op provided CPU mb */
 905        cmb();
 906        cv_broadcast_irqsave(cle->cv, &irq_state);
 907        /* broadcast writes before abort flag; atomic op provided CPU mb */
 908        cmb();
 909        atomic_dec(&cle->abort_in_progress);
 910}
 911
 912/* Attempts to abort p's sysc.  It will only do so if the sysc lookup succeeds,
 913 * so we can handle "guesses" for syscalls that might not be sleeping.  This
 914 * style of "do it if you know you can" is the best way here - anything else
 915 * runs into situations where you don't know if the memory is safe to touch or
 916 * not (we're doing a lookup via pointer address, and only dereferencing if that
 917 * succeeds).  Even something simple like letting userspace write SC_ABORT is
 918 * very hard for them, since they don't know a sysc's state for sure (under the
 919 * current system).
 920 *
 921 * Here are the rules:
 922 * - if you're flagged SC_ABORT, you don't sleep
 923 * - if you sleep, you're on the list
 924 * - if you are on the list or abort_in_progress is set, CV is signallable, and
 925 *   all the memory for CLE is safe */
 926bool abort_sysc(struct proc *p, uintptr_t sysc)
 927{
 928        ERRSTACK(1);
 929        struct cv_lookup_elm *cle;
 930        int8_t irq_state = 0;
 931
 932        spin_lock_irqsave(&p->abort_list_lock);
 933        TAILQ_FOREACH(cle, &p->abortable_sleepers, link) {
 934                if ((uintptr_t)cle->sysc == sysc) {
 935                        /* Note: we could have multiple aborters, so we need to
 936                         * use a numeric refcnt instead of a flag. */
 937                        atomic_inc(&cle->abort_in_progress);
 938                        break;
 939                }
 940        }
 941        spin_unlock_irqsave(&p->abort_list_lock);
 942        if (!cle)
 943                return FALSE;
 944        if (!waserror())        /* discard error */
 945                __abort_and_release_cle(cle);
 946        poperror();
 947        return TRUE;
 948}
 949
 950/* This will abort any abortables at the time the call was started for which
 951 * should_abort(cle, arg) returns true.  New abortables could be registered
 952 * concurrently.
 953 *
 954 * One caller for this is proc_destroy(), in which case DYING_ABORT will be set,
 955 * and new abortables will quickly abort and dereg when they see their proc is
 956 * DYING_ABORT. */
 957static int __abort_all_sysc(struct proc *p,
 958                            bool (*should_abort)(struct cv_lookup_elm*, void*),
 959                            void *arg)
 960{
 961        ERRSTACK(1);
 962        struct cv_lookup_elm *cle;
 963        int8_t irq_state = 0;
 964        struct cv_lookup_tailq abortall_list;
 965        uintptr_t old_proc = switch_to(p);
 966        int ret = 0;
 967
 968        /* Concerns: we need to not remove them from their original list, since
 969         * concurrent wake ups will cause a dereg, which will remove from the
 970         * list.  We also can't touch freed memory, so we need a refcnt to keep
 971         * cles around. */
 972        TAILQ_INIT(&abortall_list);
 973        spin_lock_irqsave(&p->abort_list_lock);
 974        TAILQ_FOREACH(cle, &p->abortable_sleepers, link) {
 975                if (!should_abort(cle, arg))
 976                        continue;
 977                atomic_inc(&cle->abort_in_progress);
 978                TAILQ_INSERT_HEAD(&abortall_list, cle, abortall_link);
 979                ret++;
 980        }
 981        spin_unlock_irqsave(&p->abort_list_lock);
 982        if (!waserror()) { /* discard error */
 983                TAILQ_FOREACH(cle, &abortall_list, abortall_link)
 984                        __abort_and_release_cle(cle);
 985        }
 986        poperror();
 987        switch_back(p, old_proc);
 988        return ret;
 989}
 990
 991static bool always_abort(struct cv_lookup_elm *cle, void *arg)
 992{
 993        return TRUE;
 994}
 995
 996void abort_all_sysc(struct proc *p)
 997{
 998        __abort_all_sysc(p, always_abort, 0);
 999}
1000
1001/* cle->sysc could be a bad pointer.  we can either use copy_from_user (btw,
1002 * we're already in their addr space) or we can use a waserror in
1003 * __abort_all_sysc().  Both options are fine.  I went with it here for a couple
1004 * reasons.  It is only this abort function pointer that accesses sysc, though
1005 * that could change.  Our syscall aborting isn't plugged into a broader error()
1006 * handler yet, which means we'd want to poperror instead of nexterror in
1007 * __abort_all_sysc, and that would required int ret getting a volatile flag. */
1008static bool sysc_uses_fd(struct cv_lookup_elm *cle, void *fd)
1009{
1010        struct syscall local_sysc;
1011        int err;
1012
1013        err = copy_from_user(&local_sysc, cle->sysc, sizeof(struct syscall));
1014        /* Trigger an abort on error */
1015        if (err)
1016                return TRUE;
1017        return syscall_uses_fd(&local_sysc, (int)(long)fd);
1018}
1019
1020int abort_all_sysc_fd(struct proc *p, int fd)
1021{
1022        return __abort_all_sysc(p, sysc_uses_fd, (void*)(long)fd);
1023}
1024
1025/* Being on the abortable list means that the CLE, KTH, SYSC, and CV are valid
1026 * memory.  The lock ordering is {CV lock, list_lock}.  Callers to this *will*
1027 * have CV held.  This is done to avoid excessive locking in places like
1028 * rendez_sleep, which want to check the condition before registering. */
1029void __reg_abortable_cv(struct cv_lookup_elm *cle, struct cond_var *cv)
1030{
1031        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1032
1033        cle->cv = cv;
1034        cle->kthread = pcpui->cur_kthread;
1035        /* Could be a ktask.  Can build in support for aborting these later */
1036        if (is_ktask(cle->kthread)) {
1037                cle->sysc = 0;
1038                return;
1039        }
1040        cle->sysc = cle->kthread->sysc;
1041        cle->proc = pcpui->cur_proc;
1042        atomic_init(&cle->abort_in_progress, 0);
1043        spin_lock_irqsave(&cle->proc->abort_list_lock);
1044        TAILQ_INSERT_HEAD(&cle->proc->abortable_sleepers, cle, link);
1045        spin_unlock_irqsave(&cle->proc->abort_list_lock);
1046}
1047
1048/* We're racing with the aborter too, who will hold the flag in cle to protect
1049 * its ref on our cle.  While the lock ordering is CV, list, callers to this
1050 * must *not* have the cv lock held.  The reason is this waits on a successful
1051 * abort_sysc, which is trying to cv_{signal,broadcast}, which could wait on the
1052 * CV lock.  So if we hold the CV lock, we can deadlock (circular dependency).*/
1053void dereg_abortable_cv(struct cv_lookup_elm *cle)
1054{
1055        if (is_ktask(cle->kthread))
1056                return;
1057        assert(cle->proc);
1058        spin_lock_irqsave(&cle->proc->abort_list_lock);
1059        TAILQ_REMOVE(&cle->proc->abortable_sleepers, cle, link);
1060        spin_unlock_irqsave(&cle->proc->abort_list_lock);
1061        /* If we won the race and yanked it out of the list before abort claimed
1062         * it, this will already be FALSE. */
1063        while (atomic_read(&cle->abort_in_progress))
1064                cpu_relax();
1065}
1066
1067/* Helper to sleepers to know if they should abort or not.  I'll probably extend
1068 * this with things for ktasks in the future. */
1069bool should_abort(struct cv_lookup_elm *cle)
1070{
1071        struct syscall local_sysc;
1072        int err;
1073
1074        if (is_ktask(cle->kthread))
1075                return FALSE;
1076        if (cle->proc && (cle->proc->state == PROC_DYING_ABORT))
1077                return TRUE;
1078        if (cle->sysc) {
1079                assert(cle->proc && (cle->proc == current));
1080                err = copy_from_user(&local_sysc, cle->sysc,
1081                                     offsetof(struct syscall, flags) +
1082                                     sizeof(cle->sysc->flags));
1083                /* just go ahead and abort if there was an error */
1084                if (err || (atomic_read(&local_sysc.flags) & SC_ABORT))
1085                        return TRUE;
1086        }
1087        return FALSE;
1088}
1089
1090/* Sometimes the kernel needs to switch out of process context and into a
1091 * 'process-less' kernel thread.  This is basically a ktask.  We use this mostly
1092 * when performing file ops as the kernel.  It's nasty, and all uses of this
1093 * probably should be removed.  (TODO: KFOP). */
1094uintptr_t switch_to_ktask(void)
1095{
1096        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1097        struct kthread *kth = pcpui->cur_kthread;
1098
1099        if (is_ktask(kth))
1100                return 0;
1101        /* We leave the SAVE_ADDR_SPACE flag on.  Now we're basically a ktask
1102         * that cares about its addr space, since we need to return to it (not
1103         * that we're leaving). */
1104        kth->flags |= KTH_IS_KTASK;
1105        return 1;
1106}
1107
1108void switch_back_from_ktask(uintptr_t old_ret)
1109{
1110        struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1111        struct kthread *kth = pcpui->cur_kthread;
1112
1113        if (old_ret)
1114                kth->flags &= ~KTH_IS_KTASK;
1115}
1116