akaros/kern/src/syscall.c
<<
>>
Prefs
   1/* See COPYRIGHT for copyright information. */
   2
   3//#define DEBUG
   4#include <ros/common.h>
   5#include <ros/limits.h>
   6#include <arch/types.h>
   7#include <arch/arch.h>
   8#include <arch/mmu.h>
   9#include <arch/console.h>
  10#include <time.h>
  11#include <error.h>
  12
  13#include <elf.h>
  14#include <string.h>
  15#include <assert.h>
  16#include <process.h>
  17#include <schedule.h>
  18#include <pmap.h>
  19#include <umem.h>
  20#include <mm.h>
  21#include <trap.h>
  22#include <syscall.h>
  23#include <kmalloc.h>
  24#include <profiler.h>
  25#include <stdio.h>
  26#include <hashtable.h>
  27#include <bitmask.h>
  28#include <smp.h>
  29#include <arsc_server.h>
  30#include <event.h>
  31#include <kprof.h>
  32#include <termios.h>
  33#include <manager.h>
  34#include <ros/procinfo.h>
  35#include <rcu.h>
  36
  37static int execargs_stringer(struct proc *p, char *d, size_t slen,
  38                             char *path, size_t path_l,
  39                             char *argenv, size_t argenv_l);
  40
  41/* Global, used by the kernel monitor for syscall debugging. */
  42bool systrace_loud = FALSE;
  43
  44/* Helper, given the trace record, pretty-print the trace's contents into the
  45 * trace's pretty buf.  'entry' says whether we're an entry record or not
  46 * (exit).  Returns the number of bytes put into the pretty_buf. */
  47static size_t systrace_fill_pretty_buf(struct systrace_record *trace,
  48                                       bool entry)
  49{
  50        size_t len = 0;
  51        struct timespec ts_start = tsc2timespec(trace->start_timestamp);
  52        struct timespec ts_end = tsc2timespec(trace->end_timestamp);
  53
  54        /* Slightly different formats between entry and exit.  Entry has retval
  55         * set to ---, and begins with E.  Exit begins with X. */
  56        if (entry) {
  57                len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
  58                      "E [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, "
  59                      "0x%llx, 0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: --- "
  60                      "proc: %d core: %2d vcore: %2d errno: --- data: ",
  61                               ts_start.tv_sec,
  62                               ts_start.tv_nsec,
  63                               ts_end.tv_sec,
  64                               ts_end.tv_nsec,
  65                               trace->syscallno,
  66                               syscall_table[trace->syscallno].name,
  67                               trace->arg0,
  68                               trace->arg1,
  69                               trace->arg2,
  70                               trace->arg3,
  71                               trace->arg4,
  72                               trace->arg5,
  73                               trace->pid,
  74                               trace->coreid,
  75                               trace->vcoreid);
  76        } else {
  77                len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
  78                      "X [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, "
  79                      "0x%llx, 0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: 0x%llx "
  80                      "proc: %d core: %2d vcore: -- errno: %3d data: ",
  81                               ts_start.tv_sec,
  82                               ts_start.tv_nsec,
  83                               ts_end.tv_sec,
  84                               ts_end.tv_nsec,
  85                               trace->syscallno,
  86                               syscall_table[trace->syscallno].name,
  87                               trace->arg0,
  88                               trace->arg1,
  89                               trace->arg2,
  90                               trace->arg3,
  91                               trace->arg4,
  92                               trace->arg5,
  93                               trace->retval,
  94                               trace->pid,
  95                               trace->coreid,
  96                               trace->errno);
  97        }
  98        len += printdump(trace->pretty_buf + len, trace->datalen,
  99                         SYSTR_PRETTY_BUF_SZ - len - 1,
 100                         trace->data);
 101        len += snprintf(trace->pretty_buf + len, SYSTR_PRETTY_BUF_SZ - len,
 102                        "\n");
 103        return len;
 104}
 105
 106/* If some syscalls block, then they can really hurt the user and the
 107 * kernel.  For instance, if you blocked another call because the trace queue is
 108 * full, the 2LS will want to yield the vcore, but then *that* call would block
 109 * too.  Since that caller was in vcore context, the core will just spin
 110 * forever.
 111 *
 112 * Even worse, some syscalls operate on the calling core or current context,
 113 * thus accessing pcpui.  If we block, then that old context is gone.  Worse, we
 114 * could migrate and then be operating on a different core.  Imagine
 115 * SYS_halt_core.  Doh! */
 116static bool sysc_can_block(unsigned int sysc_num)
 117{
 118        switch (sysc_num) {
 119        case SYS_proc_yield:
 120        case SYS_fork:
 121        case SYS_exec:
 122        case SYS_pop_ctx:
 123        case SYS_getvcoreid:
 124        case SYS_halt_core:
 125        case SYS_vc_entry:
 126        case SYS_change_vcore:
 127        case SYS_change_to_m:
 128                return FALSE;
 129        }
 130        return TRUE;
 131}
 132
 133/* Helper: spits out our trace to the various sinks. */
 134static void systrace_output(struct systrace_record *trace,
 135                            struct strace *strace, bool entry)
 136{
 137        ERRSTACK(1);
 138        size_t pretty_len;
 139
 140        /* qio ops can throw, especially the blocking qwrite.  I had it block on
 141         * the outbound path of sys_proc_destroy().  The rendez immediately
 142         * throws. */
 143        if (waserror()) {
 144                poperror();
 145                return;
 146        }
 147        pretty_len = systrace_fill_pretty_buf(trace, entry);
 148        if (strace) {
 149                /* At this point, we're going to emit the exit trace.  It's just
 150                 * a question of whether or not we block while doing it. */
 151                if (strace->drop_overflow || !sysc_can_block(trace->syscallno))
 152                        qiwrite(strace->q, trace->pretty_buf, pretty_len);
 153                else
 154                        qwrite(strace->q, trace->pretty_buf, pretty_len);
 155        }
 156        if (systrace_loud)
 157                printk("%s", trace->pretty_buf);
 158        poperror();
 159}
 160
 161static bool should_strace(struct proc *p, struct syscall *sysc)
 162{
 163        unsigned int sysc_num;
 164
 165        if (systrace_loud)
 166                return TRUE;
 167        if (!p->strace || !p->strace->tracing)
 168                return FALSE;
 169        /* TOCTTOU concerns - sysc is __user. */
 170        sysc_num = ACCESS_ONCE(sysc->num);
 171        if (qfull(p->strace->q)) {
 172                if (p->strace->drop_overflow || !sysc_can_block(sysc_num)) {
 173                        atomic_inc(&p->strace->nr_drops);
 174                        return FALSE;
 175                }
 176        }
 177        if (sysc_num > MAX_SYSCALL_NR)
 178                return FALSE;
 179        return test_bit(sysc_num, p->strace->trace_set);
 180}
 181
 182/* Helper, copies len bytes from u_data to the trace->data, if there's room. */
 183static void copy_tracedata_from_user(struct systrace_record *trace,
 184                                     long u_data, size_t len)
 185{
 186        size_t copy_amt;
 187
 188        copy_amt = MIN(sizeof(trace->data) - trace->datalen, len);
 189        copy_from_user(trace->data + trace->datalen, (void*)u_data, copy_amt);
 190        trace->datalen += copy_amt;
 191}
 192
 193/* Helper, snprintfs to the trace, if there's room. */
 194static void snprintf_to_trace(struct systrace_record *trace, const char *fmt,
 195                              ...)
 196{
 197        va_list ap;
 198        int rc;
 199
 200        va_start(ap, fmt);
 201        rc = vsnprintf((char*)trace->data + trace->datalen,
 202                       sizeof(trace->data) - trace->datalen, fmt, ap);
 203        va_end(ap);
 204        if (!snprintf_error(rc, sizeof(trace->data) - trace->datalen))
 205                trace->datalen += rc;
 206}
 207
 208static bool trace_data_full(struct systrace_record *trace)
 209{
 210        return trace->datalen == sizeof(trace->data);
 211}
 212
 213static bool systrace_has_error(struct systrace_record *trace)
 214{
 215        return syscall_retval_is_error(trace->syscallno, trace->retval);
 216}
 217
 218/* Starts a trace for p running sysc, attaching it to kthread.  Pairs with
 219 * systrace_finish_trace(). */
 220static void systrace_start_trace(struct kthread *kthread, struct syscall *sysc)
 221{
 222        struct proc *p = current;
 223        struct systrace_record *trace;
 224
 225        kthread->strace = 0;
 226        if (!should_strace(p, sysc))
 227                return;
 228        /* TODO: consider a block_alloc and qpass, though note that we actually
 229         * write the same trace in twice (entry and exit). */
 230        trace = kpages_alloc(SYSTR_BUF_SZ, MEM_ATOMIC);
 231        if (p->strace) {
 232                if (!trace) {
 233                        atomic_inc(&p->strace->nr_drops);
 234                        return;
 235                }
 236                /* Avoiding the atomic op.  We sacrifice accuracy for less
 237                 * overhead. */
 238                p->strace->appx_nr_sysc++;
 239        } else {
 240                if (!trace)
 241                        return;
 242        }
 243        /* if you ever need to debug just one strace function, this is
 244         * handy way to do it: just bail out if it's not the one you
 245         * want.
 246         * if (sysc->num != SYS_exec)
 247         * return; */
 248        trace->start_timestamp = read_tsc();
 249        trace->end_timestamp = 0;
 250        trace->syscallno = sysc->num;
 251        trace->arg0 = sysc->arg0;
 252        trace->arg1 = sysc->arg1;
 253        trace->arg2 = sysc->arg2;
 254        trace->arg3 = sysc->arg3;
 255        trace->arg4 = sysc->arg4;
 256        trace->arg5 = sysc->arg5;
 257        trace->retval = 0;
 258        trace->pid = p->pid;
 259        trace->coreid = core_id();
 260        trace->vcoreid = proc_get_vcoreid(p);
 261        trace->pretty_buf = (char*)trace + sizeof(struct systrace_record);
 262        trace->datalen = 0;
 263        trace->data[0] = 0;
 264
 265        switch (sysc->num) {
 266        case SYS_write:
 267        case SYS_openat:
 268        case SYS_chdir:
 269        case SYS_nmount:
 270                copy_tracedata_from_user(trace, sysc->arg1, sysc->arg2);
 271                break;
 272        case SYS_stat:
 273        case SYS_lstat:
 274        case SYS_access:
 275        case SYS_unlink:
 276        case SYS_mkdir:
 277        case SYS_rmdir:
 278        case SYS_wstat:
 279                copy_tracedata_from_user(trace, sysc->arg0, sysc->arg1);
 280                break;
 281        case SYS_link:
 282        case SYS_symlink:
 283        case SYS_rename:
 284        case SYS_nbind:
 285                copy_tracedata_from_user(trace, sysc->arg0, sysc->arg1);
 286                snprintf_to_trace(trace, " -> ");
 287                copy_tracedata_from_user(trace, sysc->arg2, sysc->arg3);
 288                break;
 289        case SYS_nunmount:
 290                copy_tracedata_from_user(trace, sysc->arg2, sysc->arg3);
 291                break;
 292        case SYS_exec:
 293                trace->datalen = execargs_stringer(current,
 294                                                   (char *)trace->data,
 295                                                   sizeof(trace->data),
 296                                                   (char *)sysc->arg0,
 297                                                   sysc->arg1,
 298                                                   (char *)sysc->arg2,
 299                                                   sysc->arg3);
 300                break;
 301        case SYS_proc_create:
 302                trace->datalen = execargs_stringer(current,
 303                                                   (char *)trace->data,
 304                                                   sizeof(trace->data),
 305                                                   (char *)sysc->arg0,
 306                                                   sysc->arg1,
 307                                                   (char *)sysc->arg2,
 308                                                   sysc->arg3);
 309                break;
 310        case SYS_tap_fds:
 311                for (size_t i = 0; i < (size_t)sysc->arg1; i++) {
 312                        struct fd_tap_req *tap_reqs = (struct
 313                                                       fd_tap_req*)sysc->arg0;
 314                        int fd, cmd, filter;
 315
 316                        tap_reqs += i;
 317                        copy_from_user(&fd, &tap_reqs->fd, sizeof(fd));
 318                        copy_from_user(&cmd, &tap_reqs->cmd, sizeof(cmd));
 319                        copy_from_user(&filter, &tap_reqs->filter,
 320                                       sizeof(filter));
 321                        snprintf_to_trace(trace, "%d (%d 0x%x), ", fd, cmd,
 322                                          filter);
 323                        if (trace_data_full(trace))
 324                                break;
 325                }
 326                break;
 327        }
 328        systrace_output(trace, p->strace, TRUE);
 329
 330        kthread->strace = trace;
 331}
 332
 333/* Finishes the trace on kthread for p, with retval being the return from the
 334 * syscall we're tracing.  Pairs with systrace_start_trace(). */
 335static void systrace_finish_trace(struct kthread *kthread, long retval)
 336{
 337        struct proc *p = current;
 338        struct systrace_record *trace;
 339
 340        if (!kthread->strace)
 341                return;
 342        trace = kthread->strace;
 343        trace->end_timestamp = read_tsc();
 344        trace->retval = retval;
 345        trace->coreid = core_id();
 346        /* Can't trust the vcoreid of an exit record.  This'll be ignored later.
 347         */
 348        trace->vcoreid = -1;
 349        trace->errno = get_errno();
 350        trace->datalen = 0;
 351
 352        /* Only try to do the trace data if we didn't do it on entry */
 353        if (systrace_has_error(trace)) {
 354                snprintf_to_trace(trace, "errstr: %s", current_errstr());
 355        } else {
 356                switch (trace->syscallno) {
 357                case SYS_read:
 358                        if (retval <= 0)
 359                                break;
 360                        copy_tracedata_from_user(trace, trace->arg1, retval);
 361                        break;
 362                case SYS_getcwd:
 363                        if (retval < 0)
 364                                break;
 365                        copy_tracedata_from_user(trace, trace->arg0, retval);
 366                        break;
 367                case SYS_readlink:
 368                        if (retval <= 0)
 369                                break;
 370                        copy_tracedata_from_user(trace, trace->arg0,
 371                                                 trace->arg1);
 372                        snprintf_to_trace(trace, " -> ");
 373                        copy_tracedata_from_user(trace, trace->arg2, retval);
 374                        break;
 375                }
 376        }
 377
 378        systrace_output(trace, p->strace, FALSE);
 379        kpages_free(kthread->strace, SYSTR_BUF_SZ);
 380        kthread->strace = 0;
 381}
 382
 383#ifdef CONFIG_SYSCALL_STRING_SAVING
 384
 385static void alloc_sysc_str(struct kthread *kth)
 386{
 387        kth->name = kmalloc(SYSCALL_STRLEN, MEM_ATOMIC);
 388        if (!kth->name)
 389                return;
 390        kth->name[0] = 0;
 391}
 392
 393static void free_sysc_str(struct kthread *kth)
 394{
 395        char *str = kth->name;
 396
 397        kth->name = 0;
 398        kfree(str);
 399}
 400
 401#define sysc_save_str(...)                                                     \
 402{                                                                              \
 403        struct per_cpu_info *pcpui = this_pcpui_ptr();                         \
 404                                                                               \
 405        if (pcpui->cur_kthread->name)                                          \
 406                snprintf(pcpui->cur_kthread->name, SYSCALL_STRLEN,             \
 407                         __VA_ARGS__);                                         \
 408}
 409
 410#else
 411
 412static void alloc_sysc_str(struct kthread *kth)
 413{
 414}
 415
 416static void free_sysc_str(struct kthread *kth)
 417{
 418}
 419
 420#define sysc_save_str(...)
 421
 422#endif /* CONFIG_SYSCALL_STRING_SAVING */
 423
 424/* Helper to finish a syscall, signalling if appropriate */
 425static void finish_sysc(struct syscall *sysc, struct proc *p, long retval)
 426{
 427        sysc->retval = retval;
 428        /* Atomically turn on the LOCK and SC_DONE flag.  The lock tells
 429         * userspace we're messing with the flags and to not proceed.  We use it
 430         * instead of CASing with userspace.  We need the atomics since we're
 431         * racing with userspace for the event_queue registration.  The 'lock'
 432         * tells userspace to not muck with the flags while we're signalling. */
 433        atomic_or(&sysc->flags, SC_K_LOCK | SC_DONE);
 434        __signal_syscall(sysc, p);
 435        atomic_and(&sysc->flags, ~SC_K_LOCK);
 436}
 437
 438/* Helper that "finishes" the current async syscall.  This should be used with
 439 * care when we are not using the normal syscall completion path.
 440 *
 441 * Do *NOT* complete the same syscall twice.  This is catastrophic for _Ms, and
 442 * a bad idea for _S.
 443 *
 444 * It is possible for another user thread to see the syscall being done early -
 445 * they just need to be careful with the weird proc management calls (as in,
 446 * don't trust an async fork).
 447 *
 448 * *sysc is in user memory, and should be pinned (TODO: UMEM).  There may be
 449 * issues with unpinning this if we never return. */
 450static void finish_current_sysc(long retval)
 451{
 452        /* Need to re-load pcpui, in case we migrated */
 453        struct per_cpu_info *pcpui = this_pcpui_ptr();
 454        struct syscall *sysc = pcpui->cur_kthread->sysc;
 455
 456        assert(sysc);
 457        /* Some 9ns paths set errstr, but not errno.  glibc will ignore errstr.
 458         * this is somewhat hacky, since errno might get set unnecessarily */
 459        if ((current_errstr()[0] != 0) && !get_errno())
 460                set_errno(EUNSPECIFIED);
 461        sysc->err = pcpui->cur_kthread->errno;
 462        strncpy(sysc->errstr, pcpui->cur_kthread->errstr, MAX_ERRSTR_LEN);
 463        free_sysc_str(pcpui->cur_kthread);
 464        systrace_finish_trace(pcpui->cur_kthread, retval);
 465        pcpui = this_pcpui_ptr();       /* reload again */
 466        finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc, retval);
 467        pcpui->cur_kthread->sysc = NULL;
 468}
 469
 470/* Callable by any function while executing a syscall (or otherwise, actually).
 471 */
 472void set_errno(int errno)
 473{
 474        struct per_cpu_info *pcpui = this_pcpui_ptr();
 475
 476        if (pcpui->cur_kthread)
 477                pcpui->cur_kthread->errno = errno;
 478}
 479
 480/* Callable by any function while executing a syscall (or otherwise, actually).
 481 */
 482int get_errno(void)
 483{
 484        struct per_cpu_info *pcpui = this_pcpui_ptr();
 485
 486        if (pcpui->cur_kthread)
 487                return pcpui->cur_kthread->errno;
 488        /* if there's no errno to get, that's not an error I guess. */
 489        return 0;
 490}
 491
 492void unset_errno(void)
 493{
 494        struct per_cpu_info *pcpui = this_pcpui_ptr();
 495
 496        if (!pcpui->cur_kthread)
 497                return;
 498        pcpui->cur_kthread->errno = 0;
 499        pcpui->cur_kthread->errstr[0] = '\0';
 500}
 501
 502void vset_errstr(const char *fmt, va_list ap)
 503{
 504        struct per_cpu_info *pcpui = this_pcpui_ptr();
 505
 506        if (!pcpui->cur_kthread)
 507                return;
 508
 509        vsnprintf(pcpui->cur_kthread->errstr, MAX_ERRSTR_LEN, fmt, ap);
 510
 511        /* TODO: likely not needed */
 512        pcpui->cur_kthread->errstr[MAX_ERRSTR_LEN - 1] = '\0';
 513}
 514
 515void set_errstr(const char *fmt, ...)
 516{
 517        va_list ap;
 518
 519        assert(fmt);
 520        va_start(ap, fmt);
 521        vset_errstr(fmt, ap);
 522        va_end(ap);
 523}
 524
 525char *current_errstr(void)
 526{
 527        struct per_cpu_info *pcpui = this_pcpui_ptr();
 528
 529        if (!pcpui->cur_kthread)
 530                return "no errstr";
 531        return pcpui->cur_kthread->errstr;
 532}
 533
 534void set_error(int error, const char *fmt, ...)
 535{
 536        va_list ap;
 537
 538        set_errno(error);
 539
 540        assert(fmt);
 541        va_start(ap, fmt);
 542        vset_errstr(fmt, ap);
 543        va_end(ap);
 544}
 545
 546struct errbuf *get_cur_errbuf(void)
 547{
 548        return this_pcpui_var(cur_kthread)->errbuf;
 549}
 550
 551void set_cur_errbuf(struct errbuf *ebuf)
 552{
 553        this_pcpui_var(cur_kthread)->errbuf = ebuf;
 554}
 555
 556char *get_cur_genbuf(void)
 557{
 558        struct per_cpu_info *pcpui = this_pcpui_ptr();
 559
 560        assert(pcpui->cur_kthread);
 561        return pcpui->cur_kthread->generic_buf;
 562}
 563
 564/* Helper, looks up proc* for pid and ensures p controls that proc. 0 o/w */
 565static struct proc *get_controllable_proc(struct proc *p, pid_t pid)
 566{
 567        struct proc *target = pid2proc(pid);
 568
 569        if (!target) {
 570                set_error(ESRCH, "no proc for pid %d", pid);
 571                return 0;
 572        }
 573        if (!proc_controls(p, target)) {
 574                set_error(EPERM, "can't control pid %d", pid);
 575                proc_decref(target);
 576                return 0;
 577        }
 578        return target;
 579}
 580
 581static int unpack_argenv(struct argenv *argenv, size_t argenv_l,
 582                         int *argc_p, char ***argv_p,
 583                         int *envc_p, char ***envp_p)
 584{
 585        int argc = argenv->argc;
 586        int envc = argenv->envc;
 587        char **argv = (char**)argenv->buf;
 588        char **envp = argv + argc;
 589        char *argbuf = (char*)(envp + envc);
 590        uintptr_t argbuf_offset = (uintptr_t)(argbuf - (char*)(argenv));
 591
 592        /* ARG_MAX is the max number of bytes, which is an upper bound on the
 593         * number of args or envs. */
 594        if (argc > ARG_MAX || envc > ARG_MAX)
 595                return -1;
 596        if (((char*)argv - (char*)argenv) > argenv_l)
 597                return -1;
 598        if (((char*)argv + (argc * sizeof(char**)) - (char*)argenv) > argenv_l)
 599                return -1;
 600        if (((char*)envp - (char*)argenv) > argenv_l)
 601                return -1;
 602        if (((char*)envp + (envc * sizeof(char**)) - (char*)argenv) > argenv_l)
 603                return -1;
 604        if (((char*)argbuf - (char*)argenv) > argenv_l)
 605                return -1;
 606        for (int i = 0; i < argc; i++) {
 607                if ((uintptr_t)(argv[i] + argbuf_offset) > argenv_l)
 608                        return -1;
 609                argv[i] += (uintptr_t)argbuf;
 610        }
 611        for (int i = 0; i < envc; i++) {
 612                if ((uintptr_t)(envp[i] + argbuf_offset) > argenv_l)
 613                        return -1;
 614                envp[i] += (uintptr_t)argbuf;
 615        }
 616        *argc_p = argc;
 617        *argv_p = argv;
 618        *envc_p = envc;
 619        *envp_p = envp;
 620        return 0;
 621}
 622
 623/************** Utility Syscalls **************/
 624
 625static int sys_null(void)
 626{
 627        return 0;
 628}
 629
 630/* Diagnostic function: blocks the kthread/syscall, to help userspace test its
 631 * async I/O handling. */
 632static int sys_block(struct proc *p, unsigned long usec)
 633{
 634        sysc_save_str("block for %lu usec", usec);
 635        kthread_usleep(usec);
 636        return 0;
 637}
 638
 639/* Pause execution for a number of nanoseconds.
 640 * The current implementation rounds up to the nearest microsecond. If the
 641 * syscall is aborted, we return the remaining time the call would have ran
 642 * in the 'rem' parameter.  */
 643static int sys_nanosleep(struct proc *p,
 644                         const struct timespec *req,
 645                         struct timespec *rem)
 646{
 647        ERRSTACK(1);
 648        uint64_t usec;
 649        struct timespec kreq, krem = {0, 0};
 650        uint64_t tsc = read_tsc();
 651
 652        /* Check the input arguments. */
 653        if (memcpy_from_user(p, &kreq, req, sizeof(struct timespec))) {
 654                set_errno(EFAULT);
 655                return -1;
 656        }
 657        if (rem && memcpy_to_user(p, rem, &krem, sizeof(struct timespec))) {
 658                set_errno(EFAULT);
 659                return -1;
 660        }
 661        if (kreq.tv_sec < 0) {
 662                set_errno(EINVAL);
 663                return -1;
 664        }
 665        if ((kreq.tv_nsec < 0) || (kreq.tv_nsec > 999999999)) {
 666                set_errno(EINVAL);
 667                return -1;
 668        }
 669
 670        /* Convert timespec to usec. Ignore overflow on the tv_sec field. */
 671        usec = kreq.tv_sec * 1000000;
 672        usec += DIV_ROUND_UP(kreq.tv_nsec, 1000);
 673
 674        /* Attempt to sleep. If we get aborted, copy the remaining time into
 675         * 'rem' and return. We assume the tsc is sufficient to tell how much
 676         * time is remaining (i.e. it only overflows on the order of hundreds of
 677         * years, which should be sufficiently long enough to ensure we don't
 678         * overflow). */
 679        if (waserror()) {
 680                krem = tsc2timespec(read_tsc() - tsc);
 681                if (rem &&
 682                    memcpy_to_user(p, rem, &krem, sizeof(struct timespec)))
 683                        set_errno(EFAULT);
 684                poperror();
 685                return -1;
 686        }
 687        sysc_save_str("nanosleep for %lu usec", usec);
 688        kthread_usleep(usec);
 689        poperror();
 690        return 0;
 691}
 692
 693static int sys_cache_invalidate(void)
 694{
 695        #ifdef CONFIG_X86
 696                wbinvd();
 697        #endif
 698        return 0;
 699}
 700
 701/* sys_reboot(): called directly from dispatch table. */
 702
 703/* Returns the id of the physical core this syscall is executed on. */
 704static uint32_t sys_getpcoreid(void)
 705{
 706        return core_id();
 707}
 708
 709// TODO: Temporary hack until thread-local storage is implemented on i386 and
 710// this is removed from the user interface
 711static size_t sys_getvcoreid(struct proc *p)
 712{
 713        return proc_get_vcoreid(p);
 714}
 715
 716/************** Process management syscalls **************/
 717
 718/* Helper for proc_create and fork */
 719static void inherit_strace(struct proc *parent, struct proc *child)
 720{
 721        if (parent->strace && parent->strace->inherit) {
 722                /* Refcnt on both, put in the child's ->strace. */
 723                kref_get(&parent->strace->users, 1);
 724                kref_get(&parent->strace->procs, 1);
 725                child->strace = parent->strace;
 726        }
 727}
 728
 729/* Creates a process from the file 'path'.  The process is not runnable by
 730 * default, so it needs it's status to be changed so that the next call to
 731 * schedule() will try to run it. */
 732static int sys_proc_create(struct proc *p, char *path, size_t path_l,
 733                           char *argenv, size_t argenv_l, int flags)
 734{
 735        int pid = 0;
 736        char *t_path;
 737        struct file_or_chan *program;
 738        struct proc *new_p;
 739        int argc, envc;
 740        char **argv, **envp;
 741        struct argenv *kargenv;
 742
 743        t_path = copy_in_path(p, path, path_l);
 744        if (!t_path)
 745                return -1;
 746        program = foc_open(t_path, O_EXEC | O_READ, 0);
 747        if (!program)
 748                goto error_with_path;
 749        if (!is_valid_elf(program)) {
 750                set_errno(ENOEXEC);
 751                goto error_with_file;
 752        }
 753        /* Check the size of the argenv array, error out if too large. */
 754        if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
 755                set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
 756                                  argenv_l);
 757                goto error_with_file;
 758        }
 759        /* Copy the argenv array into a kernel buffer. Delay processing of the
 760         * array to load_elf(). */
 761        kargenv = user_memdup_errno(p, argenv, argenv_l);
 762        if (!kargenv) {
 763                set_error(EINVAL, "Failed to copy in the args");
 764                goto error_with_file;
 765        }
 766        /* Unpack the argenv array into more usable variables. Integrity
 767         * checking done along side this as well. */
 768        if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
 769                set_error(EINVAL, "Failed to unpack the args");
 770                goto error_with_kargenv;
 771        }
 772        /* TODO: need to split the proc creation, since you must load after
 773         * setting args/env, since auxp gets set up there. */
 774        //new_p = proc_create(program, 0, 0);
 775        if (proc_alloc(&new_p, current, flags)) {
 776                set_error(ENOMEM, "Failed to alloc new proc");
 777                goto error_with_kargenv;
 778        }
 779        inherit_strace(p, new_p);
 780        /* close the CLOEXEC ones, even though this isn't really an exec */
 781        close_fdt(&new_p->open_files, TRUE);
 782        /* Load the elf. */
 783        if (load_elf(new_p, program, argc, argv, envc, envp)) {
 784                set_error(EINVAL, "Failed to load elf");
 785                goto error_with_proc;
 786        }
 787        /* progname is argv0, which accounts for symlinks */
 788        proc_set_progname(new_p, argc ? argv[0] : NULL);
 789        proc_replace_binary_path(new_p, t_path);
 790        foc_decref(program);
 791        user_memdup_free(p, kargenv);
 792        __proc_ready(new_p);
 793        pid = new_p->pid;
 794        profiler_notify_new_process(new_p);
 795        /* give up the reference created in proc_create() */
 796        proc_decref(new_p);
 797        return pid;
 798error_with_proc:
 799        /* proc_destroy will decref once, which is for the ref created in
 800         * proc_create().  We don't decref again (the usual "+1 for existing"),
 801         * since the scheduler, which usually handles that, hasn't heard about
 802         * the process (via __proc_ready()). */
 803        proc_destroy(new_p);
 804error_with_kargenv:
 805        user_memdup_free(p, kargenv);
 806error_with_file:
 807        foc_decref(program);
 808error_with_path:
 809        free_path(p, t_path);
 810        return -1;
 811}
 812
 813/* Makes process PID runnable.  Consider moving the functionality to process.c
 814 */
 815static error_t sys_proc_run(struct proc *p, unsigned pid)
 816{
 817        error_t retval = 0;
 818        struct proc *target = get_controllable_proc(p, pid);
 819
 820        if (!target)
 821                return -1;
 822        if (target->state != PROC_CREATED) {
 823                set_errno(EINVAL);
 824                proc_decref(target);
 825                return -1;
 826        }
 827        /* Note a proc can spam this for someone it controls.  Seems safe - if
 828         * it isn't we can change it. */
 829        proc_wakeup(target);
 830        proc_decref(target);
 831        return 0;
 832}
 833
 834/* Destroy proc pid.  If this is called by the dying process, it will never
 835 * return.  o/w it will return 0 on success, or an error.  Errors include:
 836 * - ESRCH: if there is no such process with pid
 837 * - EPERM: if caller does not control pid */
 838static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
 839{
 840        error_t r;
 841        struct proc *p_to_die = get_controllable_proc(p, pid);
 842        if (!p_to_die)
 843                return -1;
 844        if (p_to_die == p) {
 845                p->exitcode = exitcode;
 846                printd("[PID %d] proc exiting gracefully (code %d)\n",
 847                       p->pid,exitcode);
 848        } else {
 849                p_to_die->exitcode = exitcode;
 850                printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
 851        }
 852        proc_destroy(p_to_die);
 853        proc_decref(p_to_die);
 854        return 0;
 855}
 856
 857static int sys_proc_yield(struct proc *p, bool being_nice)
 858{
 859        /* proc_yield() often doesn't return - we need to finish the syscall
 860         * early.  If it doesn't return, it expects to eat our reference (for
 861         * now). */
 862        finish_current_sysc(0);
 863        proc_incref(p, 1);
 864        proc_yield(p, being_nice);
 865        proc_decref(p);
 866        /* Shouldn't return, to prevent the chance of mucking with cur_sysc. */
 867        smp_idle();
 868        assert(0);
 869}
 870
 871static int sys_change_vcore(struct proc *p, uint32_t vcoreid,
 872                            bool enable_my_notif)
 873{
 874        if (!proc_vcoreid_is_safe(p, vcoreid)) {
 875                set_error(EINVAL, "vcoreid %d out of range %d", vcoreid,
 876                          p->procinfo->max_vcores);
 877                return -1;
 878        }
 879        /* Note retvals can be negative, but we don't mess with errno in case
 880         * callers use this in low-level code and want to extract the 'errno'.
 881         */
 882        return proc_change_to_vcore(p, vcoreid, enable_my_notif);
 883}
 884
 885static ssize_t sys_fork(env_t* e)
 886{
 887        uintptr_t temp;
 888        int ret;
 889
 890        // TODO: right now we only support fork for single-core processes
 891        if (e->state != PROC_RUNNING_S) {
 892                set_errno(EINVAL);
 893                return -1;
 894        }
 895        env_t* env;
 896
 897        ret = proc_alloc(&env, current, PROC_DUP_FGRP);
 898        if (ret < 0) {
 899                set_errno(-ret);
 900                return -1;
 901        }
 902        proc_set_progname(env, e->progname);
 903
 904        /* Can't really fork if we don't have a current_ctx to fork */
 905        if (!current_ctx) {
 906                proc_destroy(env);
 907                proc_decref(env);
 908                set_errno(EINVAL);
 909                return -1;
 910        }
 911        assert(current == this_pcpui_var(owning_proc));
 912        copy_current_ctx_to(&env->scp_ctx);
 913
 914        /* Make the new process have the same VMRs as the older.  This will copy
 915         * the contents of non MAP_SHARED pages to the new VMRs. */
 916        if (duplicate_vmrs(e, env)) {
 917                proc_destroy(env);
 918                proc_decref(env);
 919                set_errno(ENOMEM);
 920                return -1;
 921        }
 922        /* Switch to the new proc's address space and finish the syscall.  We'll
 923         * never naturally finish this syscall for the new proc, since its
 924         * memory is cloned before we return for the original process.  If we
 925         * ever do CoW for forked memory, this will be the first place that gets
 926         * CoW'd. */
 927        temp = switch_to(env);
 928        finish_sysc(current_kthread->sysc, env, 0);
 929        switch_back(env, temp);
 930
 931        /* Copy some state from the original proc into the new proc. */
 932        env->env_flags = e->env_flags;
 933
 934        inherit_strace(e, env);
 935
 936        /* In general, a forked process should be a fresh process, and we copy
 937         * over whatever stuff is needed between procinfo/procdata. */
 938        *env->procdata = *e->procdata;
 939        env->procinfo->program_end = e->procinfo->program_end;
 940
 941        /* FYI: once we call ready, the proc is open for concurrent usage */
 942        __proc_ready(env);
 943        proc_wakeup(env);
 944
 945        // don't decref the new process.
 946        // that will happen when the parent waits for it.
 947        // TODO: if the parent doesn't wait, we need to change the child's
 948        // parent when the parent dies, or at least decref it
 949
 950        printd("[PID %d] fork PID %d\n", e->pid, env->pid);
 951        ret = env->pid;
 952        profiler_notify_new_process(env);
 953        proc_decref(env); /* give up the reference created in proc_alloc() */
 954        return ret;
 955}
 956
 957/* string for sys_exec arguments. Assumes that d is pointing to zero'd
 958 * storage or storage that does not require null termination or
 959 * provides the null. */
 960static int execargs_stringer(struct proc *p, char *d, size_t slen,
 961                             char *path, size_t path_l,
 962                             char *argenv, size_t argenv_l)
 963{
 964        int argc, envc, i;
 965        char **argv, **envp;
 966        struct argenv *kargenv;
 967        int amt;
 968        char *s = d;
 969        char *e = d + slen;
 970
 971        if (path_l > slen)
 972                path_l = slen;
 973        if (memcpy_from_user(p, d, path, path_l)) {
 974                s = seprintf(s, e, "Invalid exec path");
 975                return s - d;
 976        }
 977        s += path_l;
 978
 979        /* yes, this code is cloned from below. I wrote a helper but
 980         * Barret and I concluded after talking about it that the
 981         * helper was not really helper-ful, as it has almost 10
 982         * arguments. Please, don't suggest a cpp macro. Thank you. */
 983        /* Check the size of the argenv array, error out if too large. */
 984        if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
 985                s = seprintf(s, e,
 986                             "The argenv array has an invalid size: %lu\n",
 987                             argenv_l);
 988                return s - d;
 989        }
 990        /* Copy the argenv array into a kernel buffer. */
 991        kargenv = user_memdup_errno(p, argenv, argenv_l);
 992        if (!kargenv) {
 993                s = seprintf(s, e,
 994                             "Failed to copy in the args and environment");
 995                return s - d;
 996        }
 997        /* Unpack the argenv array into more usable variables. Integrity
 998         * checking done along side this as well. */
 999        if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
1000                s = seprintf(s, e, "Failed to unpack the args");
1001                user_memdup_free(p, kargenv);
1002                return s - d;
1003        }
1004        s = seprintf(s, e, "[%d]{", argc);
1005        for (i = 0; i < argc; i++)
1006                s = seprintf(s, e, "%s, ", argv[i]);
1007        s = seprintf(s, e, "}");
1008
1009        user_memdup_free(p, kargenv);
1010        return s - d;
1011}
1012
1013/* Load the binary "path" into the current process, and start executing it.
1014 * argv and envp are magically bundled in procinfo for now.  Keep in sync with
1015 * glibc's sysdeps/ros/execve.c.  Once past a certain point, this function won't
1016 * return.  It assumes (and checks) that it is current.  Don't give it an extra
1017 * refcnt'd *p (syscall won't do that).
1018 * Note: if someone batched syscalls with this call, they could clobber their
1019 * old memory (and will likely PF and die).  Don't do it... */
1020static int sys_exec(struct proc *p, char *path, size_t path_l,
1021                    char *argenv, size_t argenv_l)
1022{
1023        int ret = -1;
1024        char *t_path = NULL;
1025        struct file_or_chan *program;
1026        int argc, envc;
1027        char **argv, **envp;
1028        struct argenv *kargenv;
1029
1030        /* We probably want it to never be allowed to exec if it ever was _M */
1031        if (p->state != PROC_RUNNING_S) {
1032                set_error(EINVAL, "Can't exec an MCP");
1033                return -1;
1034        }
1035        /* Check the size of the argenv array, error out if too large. */
1036        if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
1037                set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
1038                                  argenv_l);
1039                return -1;
1040        }
1041
1042        if (p != this_pcpui_var(owning_proc)) {
1043                warn("Proc %d tried to exec and wasn't owning_proc", p->pid);
1044                set_error(EAGAIN, "exec may have blocked during execution");
1045                return -1;
1046        }
1047        assert(current_ctx);
1048        /* Before this, we shouldn't have blocked (maybe with strace, though we
1049         * explicitly don't block exec for strace).  The owning proc, cur_proc,
1050         * and cur_ctx checks should catch that.  After this, we might still
1051         * block, such as on accessing the filesystem.
1052         *
1053         * After this point, we're treated like a yield - we're waiting until
1054         * something wakes us.  The kthread might block, error and fail, or
1055         * succeed.  We shouldn't return to userspace before one of those.  The
1056         * only way out of this function is via smp_idle, not returning the way
1057         * we came.
1058         *
1059         * Under normal situations, the only thing that will wake us is this
1060         * kthread completing.  I think you can trigger wakeups with events and
1061         * async syscalls started before the exec.  I'm not sure if that could
1062         * trigger more bugs or if that would hurt the kernel.  If so, we could
1063         * add an EXEC_LIMBO state.
1064         *
1065         * Note that we will 'hard block' if we block at all.  We can't return
1066         * to userspace and then asynchronously finish the exec later. */
1067        spin_lock(&p->proc_lock);
1068        /* We only need the context for the error case.  We have to save it now,
1069         * since once we leave this core, such as when the kthread blocks, the
1070         * old SCP's context will be gone. */
1071        __proc_save_context_s(p);
1072        /* We are no longer owning, but we are still current, like any
1073         * kthread-that-blocked-on-behalf of a process.  I think one invariant
1074         * for SCPs is: "RUNNING_S <==> is the owning proc". */
1075        clear_owning_proc(core_id());
1076        __proc_set_state(p, PROC_WAITING);
1077        spin_unlock(&p->proc_lock);
1078
1079        /* Copy the argenv array into a kernel buffer. */
1080        kargenv = user_memdup_errno(p, argenv, argenv_l);
1081        if (!kargenv) {
1082                set_error(EINVAL, "Failed to copy in the args and environment");
1083                goto out_error;
1084        }
1085        /* Unpack the argenv array into more usable variables. Integrity
1086         * checking done along side this as well. */
1087        if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
1088                set_error(EINVAL, "Failed to unpack the args");
1089                goto out_error_kargenv;
1090        }
1091        t_path = copy_in_path(p, path, path_l);
1092        if (!t_path) {
1093                user_memdup_free(p, kargenv);
1094                goto out_error_kargenv;
1095        }
1096        program = foc_open(t_path, O_EXEC | O_READ, 0);
1097        if (!program)
1098                goto out_error_tpath;
1099        if (!is_valid_elf(program)) {
1100                set_error(ENOEXEC, "Program was not a valid ELF");
1101                goto out_error_program;
1102        }
1103
1104        /* This is the point of no return for the process.  Any errors here lead
1105         * to destruction. */
1106
1107        /* progname is argv0, which accounts for symlinks */
1108        proc_replace_binary_path(p, t_path);
1109        /* p now owns the t_path, and it'll get freed when we destroy p. */
1110        t_path = NULL;
1111        proc_set_progname(p, argc ? argv[0] : NULL);
1112        proc_init_procdata(p);
1113        p->procinfo->program_end = 0;
1114        /* When we destroy our memory regions, accessing cur_sysc would PF */
1115        current_kthread->sysc = 0;
1116        unmap_and_destroy_vmrs(p);
1117        /* close the CLOEXEC ones */
1118        close_fdt(&p->open_files, TRUE);
1119        env_user_mem_free(p, 0, UMAPTOP);
1120        if (load_elf(p, program, argc, argv, envc, envp)) {
1121                set_error(EINVAL, "Failed to load elf");
1122                /* At this point, we destroyed memory and can't return to the
1123                 * app.  We can't use the error cases, since they assume we'll
1124                 * return. */
1125                foc_decref(program);
1126                user_memdup_free(p, kargenv);
1127                /* We finish the trace and not the sysc, since the sysc is gone.
1128                 */
1129                systrace_finish_trace(current_kthread, -1);
1130                /* Note this is an inedible reference, but proc_destroy now
1131                 * returns */
1132                proc_destroy(p);
1133                /* We don't want to do anything else - we just need to not
1134                 * accidentally return to the user (hence the all_out) */
1135                goto all_out;
1136        }
1137        printd("[PID %d] exec %s\n", p->pid, foc_to_name(program));
1138        foc_decref(program);
1139        user_memdup_free(p, kargenv);
1140        systrace_finish_trace(current_kthread, 0);
1141        proc_wakeup(p);
1142
1143        goto all_out;
1144
1145out_error_program:
1146        foc_decref(program);
1147out_error_tpath:
1148        /* Note the t_path is passed to proc_replace_binary_path in the non
1149         * out_error cases. */
1150        free_path(p, t_path);
1151out_error_kargenv:
1152        user_memdup_free(p, kargenv);
1153out_error:
1154        finish_current_sysc(-1);
1155        proc_wakeup(p);
1156
1157all_out:
1158        /* This free and setting sysc = NULL may happen twice (early errors do
1159         * it), but they are idempotent. */
1160        free_sysc_str(current_kthread);
1161        current_kthread->sysc = NULL;
1162        /* we can't return, since we'd write retvals to the old location of the
1163         * syscall struct (which has been freed and is in the old userspace) (or
1164         * has already been written to).*/
1165        disable_irq();          /* abandon_core/clear_own wants irqs disabled */
1166        abandon_core();
1167        smp_idle();             /* will reenable interrupts */
1168}
1169
1170/* Helper, will attempt a particular wait on a proc.  Returns the pid of the
1171 * process if we waited on it successfully, and the status will be passed back
1172 * in ret_status (kernel memory).  Returns 0 if the wait failed and we should
1173 * try again.  Returns -1 if we should abort.  Only handles DYING.  Callers
1174 * need to lock to protect the children tailq and reaping bits.  Callers must
1175 * decref the child on success. */
1176static pid_t __try_wait(struct proc *parent, struct proc *child,
1177                        int *ret_status, int options)
1178{
1179        if (proc_is_dying(child)) {
1180                /* Disown returns -1 if it's already been disowned or we should
1181                 * o/w abort.  This can happen if we have concurrent waiters,
1182                 * both with pointers to the child (only one should reap).  Note
1183                 * that if we don't do this, we could go to sleep and never
1184                 * receive a cv_signal. */
1185                if (__proc_disown_child(parent, child))
1186                        return -1;
1187                /* despite disowning, the child won't be freed til we drop this
1188                 * ref held by this function, so it is safe to access the
1189                 * memory.
1190                 *
1191                 * Note the exit code one byte in the 0xff00 spot.  Check out
1192                 * glibc's posix/sys/wait.h and bits/waitstatus.h for more info.
1193                 * If we ever deal with signalling and stopping, we'll need to
1194                 * do some more work here.*/
1195                *ret_status = (child->exitcode & 0xff) << 8;
1196                return child->pid;
1197        }
1198        return 0;
1199}
1200
1201/* Helper, like __try_wait, but attempts a wait on any of the children,
1202 * returning the specific PID we waited on, 0 to try again (a waitable exists),
1203 * and -1 to abort (no children/waitables exist).  Callers need to lock to
1204 * protect the children tailq and reaping bits.  Callers must decref the child,
1205 * if successful. */
1206static pid_t __try_wait_any(struct proc *parent, int *ret_status, int options,
1207                            struct proc **child)
1208{
1209        struct proc *i, *temp;
1210        pid_t retval;
1211
1212        if (TAILQ_EMPTY(&parent->children))
1213                return -1;
1214        /* Could have concurrent waiters mucking with the tailq, caller must
1215         * lock */
1216        TAILQ_FOREACH_SAFE(i, &parent->children, sibling_link, temp) {
1217                retval = __try_wait(parent, i, ret_status, options);
1218                /* This catches a thread causing a wait to fail but not taking
1219                 * the child off the list before unlocking.  Should never
1220                 * happen. */
1221                assert(retval != -1);
1222                /* Succeeded, return the pid of the child we waited on */
1223                if (retval) {
1224                        *child = i;
1225                        return retval;
1226                }
1227        }
1228        assert(retval == 0);
1229        return 0;
1230}
1231
1232/* Waits on a particular child, returns the pid of the child waited on, and
1233 * puts the ret status in *ret_status.  Returns the pid if we succeeded, 0 if
1234 * the child was not waitable and WNOHANG, and -1 on error. */
1235static pid_t wait_one(struct proc *parent, struct proc *child, int *ret_status,
1236                      int options)
1237{
1238        pid_t retval;
1239        struct cv_lookup_elm cle;
1240
1241        cv_lock(&parent->child_wait);
1242        __reg_abortable_cv(&cle, &parent->child_wait);
1243        /* retval == 0 means we should block */
1244        retval = __try_wait(parent, child, ret_status, options);
1245        if ((retval == 0) && (options & WNOHANG))
1246                goto out_unlock;
1247        while (!retval) {
1248                if (should_abort(&cle)) {
1249                        retval = -1;
1250                        set_error(EINTR, "wait aborted");
1251                        goto out_unlock;
1252                }
1253                cv_wait(&parent->child_wait);
1254                /* Any child can wake us up, but we check for the particular
1255                 * child we care about */
1256                retval = __try_wait(parent, child, ret_status, options);
1257        }
1258        if (retval == -1) {
1259                /* Child was already waited on by a concurrent syscall. */
1260                set_errno(ECHILD);
1261        }
1262        /* Fallthrough */
1263out_unlock:
1264        cv_unlock(&parent->child_wait);
1265        dereg_abortable_cv(&cle);
1266        if (retval > 0)
1267                proc_decref(child);
1268        return retval;
1269}
1270
1271/* Waits on any child, returns the pid of the child waited on, and puts the ret
1272 * status in *ret_status.  Is basically a waitpid(-1, ... );  See wait_one for
1273 * more details.  Returns -1 if there are no children to wait on, and returns 0
1274 * if there are children and we need to block but WNOHANG was set. */
1275static pid_t wait_any(struct proc *parent, int *ret_status, int options)
1276{
1277        pid_t retval;
1278        struct cv_lookup_elm cle;
1279        struct proc *child;
1280
1281        cv_lock(&parent->child_wait);
1282        __reg_abortable_cv(&cle, &parent->child_wait);
1283        retval = __try_wait_any(parent, ret_status, options, &child);
1284        if ((retval == 0) && (options & WNOHANG))
1285                goto out_unlock;
1286        while (!retval) {
1287                if (should_abort(&cle)) {
1288                        retval = -1;
1289                        set_error(EINTR, "wait aborted");
1290                        goto out_unlock;
1291                }
1292                cv_wait(&parent->child_wait);
1293                /* Any child can wake us up from the CV.  This is a linear
1294                 * __try_wait scan.  If we have a lot of children, we could
1295                 * optimize this. */
1296                retval = __try_wait_any(parent, ret_status, options, &child);
1297        }
1298        if (retval == -1)
1299                assert(TAILQ_EMPTY(&parent->children));
1300        /* Fallthrough */
1301out_unlock:
1302        cv_unlock(&parent->child_wait);
1303        dereg_abortable_cv(&cle);
1304        if (retval > 0)
1305                proc_decref(child);
1306        return retval;
1307}
1308
1309/* Note: we only allow waiting on children (no such thing as threads, for
1310 * instance).  Right now we only allow waiting on termination (not signals),
1311 * and we don't have a way for parents to disown their children (such as
1312 * ignoring SIGCHLD, see man 2 waitpid's Notes).
1313 *
1314 * We don't bother with stop/start signals here, though we can probably build
1315 * it in the helper above.
1316 *
1317 * Returns the pid of who we waited on, or -1 on error, or 0 if we couldn't
1318 * wait (WNOHANG). */
1319static pid_t sys_waitpid(struct proc *parent, pid_t pid, int *status,
1320                         int options)
1321{
1322        struct proc *child;
1323        pid_t retval = 0;
1324        int ret_status = 0;
1325
1326        sysc_save_str("waitpid on %d", pid);
1327        /* -1 is the signal for 'any child' */
1328        if (pid == -1) {
1329                retval = wait_any(parent, &ret_status, options);
1330                goto out;
1331        }
1332        child = pid2proc(pid);
1333        if (!child) {
1334                set_errno(ECHILD);      /* ECHILD also used for no proc */
1335                retval = -1;
1336                goto out;
1337        }
1338        if (!(parent->pid == child->ppid)) {
1339                set_errno(ECHILD);
1340                retval = -1;
1341                goto out_decref;
1342        }
1343        retval = wait_one(parent, child, &ret_status, options);
1344        /* fall-through */
1345out_decref:
1346        proc_decref(child);
1347out:
1348        /* ignoring / don't care about memcpy's retval here. */
1349        if (status)
1350                memcpy_to_user(parent, status, &ret_status, sizeof(ret_status));
1351        printd("[PID %d] waited for PID %d, got retval %d (status 0x%x)\n",
1352               parent->pid, pid, retval, ret_status);
1353        return retval;
1354}
1355
1356/************** Memory Management Syscalls **************/
1357
1358static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
1359                      int flags, int fd, off_t offset)
1360{
1361        return mmap(p, addr, len, prot, flags, fd, offset);
1362}
1363
1364static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
1365{
1366        return mprotect(p, (uintptr_t)addr, len, prot);
1367}
1368
1369static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
1370{
1371        return munmap(p, (uintptr_t)addr, len);
1372}
1373
1374static ssize_t sys_shared_page_alloc(env_t* p1,
1375                                     void **_addr, pid_t p2_id,
1376                                     int p1_flags, int p2_flags
1377                                    )
1378{
1379        printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
1380        return -1;
1381}
1382
1383static int sys_shared_page_free(env_t* p1, void *addr, pid_t p2)
1384{
1385        return -1;
1386}
1387
1388/* Helper, to do the actual provisioning of a resource to a proc */
1389static int prov_resource(struct proc *target, unsigned int res_type,
1390                         long res_val)
1391{
1392        switch (res_type) {
1393        case (RES_CORES):
1394                /* in the off chance we have a kernel scheduler that can't
1395                 * provision, we'll need to change this. */
1396                return provision_core(target, res_val);
1397        default:
1398                printk("[kernel] got provisioning for unknown resource %d\n",
1399                       res_type);
1400                set_errno(ENOENT);      /* or EINVAL? */
1401                return -1;
1402        }
1403}
1404
1405/* Rough syscall to provision res_val of type res_type to target_pid */
1406static int sys_provision(struct proc *p, int target_pid,
1407                         unsigned int res_type, long res_val)
1408{
1409        struct proc *target = pid2proc(target_pid);
1410        int retval;
1411
1412        if (!target) {
1413                if (target_pid == 0)
1414                        return prov_resource(0, res_type, res_val);
1415                /* debugging interface */
1416                if (target_pid == -1)
1417                        print_coreprov_map();
1418                set_errno(ESRCH);
1419                return -1;
1420        }
1421        retval = prov_resource(target, res_type, res_val);
1422        proc_decref(target);
1423        return retval;
1424}
1425
1426/* Untested.  Will notify the target on the given vcore, if the caller controls
1427 * the target.  Will honor the target's wanted/vcoreid.  u_ne can be NULL. */
1428static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
1429                      struct event_msg *u_msg)
1430{
1431        struct event_msg local_msg = {0};
1432        struct proc *target = get_controllable_proc(p, target_pid);
1433
1434        if (!target)
1435                return -1;
1436        /* if the user provided an ev_msg, copy it in and use that */
1437        if (u_msg) {
1438                if (memcpy_from_user(p, &local_msg, u_msg,
1439                                     sizeof(struct event_msg))) {
1440                        proc_decref(target);
1441                        set_errno(EINVAL);
1442                        return -1;
1443                }
1444        } else {
1445                local_msg.ev_type = ev_type;
1446        }
1447        send_kernel_event(target, &local_msg, 0);
1448        proc_decref(target);
1449        return 0;
1450}
1451
1452/* Will notify the calling process on the given vcore, independently of WANTED
1453 * or advertised vcoreid.  If you change the parameters, change pop_user_ctx().
1454 */
1455static int sys_self_notify(struct proc *p, uint32_t vcoreid,
1456                           unsigned int ev_type, struct event_msg *u_msg,
1457                           bool priv)
1458{
1459        struct event_msg local_msg = {0};
1460
1461        /* if the user provided an ev_msg, copy it in and use that */
1462        if (u_msg) {
1463                if (memcpy_from_user(p, &local_msg, u_msg,
1464                                     sizeof(struct event_msg))) {
1465                        set_errno(EINVAL);
1466                        return -1;
1467                }
1468        } else {
1469                local_msg.ev_type = ev_type;
1470        }
1471        if (local_msg.ev_type >= MAX_NR_EVENT) {
1472                printk("[kernel] received self-notify for vcoreid %d, "
1473                       "ev_type %d, u_msg %p, u_msg->type %d\n", vcoreid,
1474                       ev_type, u_msg, u_msg ? u_msg->ev_type : 0);
1475                return -1;
1476        }
1477        if (!proc_vcoreid_is_safe(p, vcoreid)) {
1478                set_error(EINVAL, "vcoreid %d out of range %d", vcoreid,
1479                          p->procinfo->max_vcores);
1480                return -1;
1481        }
1482        /* this will post a message and IPI, regardless of
1483         * wants/needs/debutantes.*/
1484        post_vcore_event(p, &local_msg, vcoreid,
1485                         priv ? EVENT_VCORE_PRIVATE : 0);
1486        proc_notify(p, vcoreid);
1487        return 0;
1488}
1489
1490static int sys_send_event(struct proc *p, struct event_queue *ev_q,
1491                          struct event_msg *u_msg, uint32_t vcoreid)
1492{
1493        struct event_msg local_msg = {0};
1494
1495        if (memcpy_from_user_errno(p, &local_msg, u_msg,
1496                                   sizeof(struct event_msg))) {
1497                return -1;
1498        }
1499        if (!is_user_rwaddr(ev_q, sizeof(struct event_queue))) {
1500                set_error(EINVAL, "bad event_queue %p", ev_q);
1501                return -1;
1502        }
1503        if (!proc_vcoreid_is_safe(p, vcoreid)) {
1504                set_error(EINVAL, "vcoreid %d out of range %d", vcoreid,
1505                          p->procinfo->max_vcores);
1506                return -1;
1507        }
1508        send_event(p, ev_q, &local_msg, vcoreid);
1509        return 0;
1510}
1511
1512/* Puts the calling core into vcore context, if it wasn't already, via a
1513 * self-IPI / active notification.  Barring any weird unmappings, we just send
1514 * ourselves a __notify. */
1515static int sys_vc_entry(struct proc *p)
1516{
1517        send_kernel_message(core_id(), __notify, (long)p, 0, 0, KMSG_ROUTINE);
1518        return 0;
1519}
1520
1521/* This will halt the core, waking on an IRQ.  These could be kernel IRQs for
1522 * things like timers or devices, or they could be IPIs for RKMs (__notify for
1523 * an evq with IPIs for a syscall completion, etc).  With arch support, this
1524 * will also wake on a write to notif_pending.
1525 *
1526 * We don't need to finish the syscall early (worried about the syscall struct,
1527 * on the vcore's stack).  The syscall will finish before any __preempt RKM
1528 * executes, so the vcore will not restart somewhere else before the syscall
1529 * completes (unlike with yield, where the syscall itself adjusts the vcore
1530 * structures).
1531 *
1532 * In the future, RKM code might avoid sending IPIs if the core is already in
1533 * the kernel.  That code will need to check the CPU's state in some manner, and
1534 * send if the core is halted/idle.  Or perhaps use mwait, if there's arch
1535 * support.
1536 *
1537 * The core must wake up for RKMs, including RKMs that arrive while the kernel
1538 * is trying to halt.
1539 *
1540 * If our hardware supports something like monitor/mwait, we'll abort if
1541 * notif_pending was or gets set.  Note that whoever writes notif_pending may
1542 * send an IPI regardless of whether or not we have mwait.  That's up to the
1543 * ev_q settings (so basically userspace).  If userspace doesn't want an IPI, a
1544 * notif will wake it up, but it won't break it out of a uthread loop. */
1545static int sys_halt_core(struct proc *p, unsigned long usec)
1546{
1547        struct per_cpu_info *pcpui = this_pcpui_ptr();
1548        struct preempt_data *vcpd;
1549
1550        /* The user can only halt CG cores!  (ones it owns) */
1551        if (management_core())
1552                return -1;
1553        rcu_report_qs();
1554        disable_irq();
1555        /* both for accounting and possible RKM optimizations */
1556        __set_cpu_state(pcpui, CPU_STATE_IDLE);
1557        wrmb();
1558        if (has_routine_kmsg()) {
1559                __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1560                enable_irq();
1561                return 0;
1562        }
1563        vcpd = &p->procdata->vcore_preempt_data[pcpui->owning_vcoreid];
1564        /* We pretend to not be in vcore context so other cores will send us
1565         * IPIs (__notify).  If we do get a __notify, we'll have set
1566         * notif_disabled back on before we handle the message, since it's a
1567         * routine KMSG.  Note that other vcores will think we are not in vcore
1568         * context.  This is no different to when we pop contexts: 'briefly'
1569         * leave VC ctx, check notif_pending, and (possibly) abort and set
1570         * notif_disabled. */
1571        vcpd->notif_disabled = false;
1572        cpu_halt_notif_pending(vcpd);
1573        __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1574        vcpd->notif_disabled = true;
1575        enable_irq();
1576        return 0;
1577}
1578
1579/* Changes a process into _M mode, or -EINVAL if it already is an mcp.
1580 * __proc_change_to_m() returns and we'll eventually finish the sysc later.  The
1581 * original context may restart on a remote core before we return and finish,
1582 * but that's fine thanks to the async kernel interface. */
1583static int sys_change_to_m(struct proc *p)
1584{
1585        int retval = proc_change_to_m(p);
1586
1587        /* convert the kernel error code into (-1, errno) */
1588        if (retval) {
1589                set_errno(-retval);
1590                retval = -1;
1591        }
1592        return retval;
1593}
1594
1595/* Assists the user/2LS by atomically running *ctx and leaving vcore context.
1596 * Normally, the user can do this themselves, but x86 VM contexts need kernel
1597 * support.  The caller ought to be in vcore context, and if a notif is pending,
1598 * then the calling vcore will restart in a fresh VC ctx (as if it was notified
1599 * or did a sys_vc_entry).
1600 *
1601 * Note that this will set the TLS too, which is part of the context.  Parlib's
1602 * pop_user_ctx currently does *not* do this, since the TLS is managed
1603 * separately.  If you want to use this syscall for testing, you'll need to 0
1604 * out fsbase and conditionally write_msr in proc_pop_ctx(). */
1605static int sys_pop_ctx(struct proc *p, struct user_context *ctx)
1606{
1607        int pcoreid = core_id();
1608        struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1609        int vcoreid = pcpui->owning_vcoreid;
1610        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1611
1612        /* With change_to, there's a bunch of concerns about changing the vcore
1613         * map, since the kernel may have already locked and sent preempts,
1614         * deaths, etc.
1615         *
1616         * In this case, we don't care as much.  Other than notif_pending and
1617         * notif_disabled, it's more like we're just changing a few registers in
1618         * cur_ctx.  We can safely order-after any kernel messages or other
1619         * changes, as if the user had done all of the changes we'll make and
1620         * then did a no-op syscall.
1621         *
1622         * Since we are mucking with current_ctx, it is important that we don't
1623         * block before or during this syscall. */
1624        arch_finalize_ctx(pcpui->cur_ctx);
1625        if (copy_from_user(pcpui->cur_ctx, ctx, sizeof(struct user_context))) {
1626                /* The 2LS isn't really in a position to handle errors.  At the
1627                 * very least, we can print something and give them a fresh vc
1628                 * ctx. */
1629                printk("[kernel] unable to copy user_ctx, 2LS bug\n");
1630                memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
1631                proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
1632                              vcpd->vcore_stack, vcpd->vcore_tls_desc);
1633                return -1;
1634        }
1635        proc_secure_ctx(pcpui->cur_ctx);
1636        /* The caller leaves vcore context no matter what.  We'll put them back
1637         * in if they missed a message. */
1638        vcpd->notif_disabled = FALSE;
1639        wrmb(); /* order disabled write before pending read */
1640        if (vcpd->notif_pending)
1641                send_kernel_message(pcoreid, __notify, (long)p, 0, 0,
1642                                    KMSG_ROUTINE);
1643        return 0;
1644}
1645
1646static int sys_vmm_add_gpcs(struct proc *p, unsigned int nr_more_gpcs,
1647                            struct vmm_gpcore_init *gpcis)
1648{
1649        ERRSTACK(1);
1650        struct vmm *vmm = &p->vmm;
1651
1652        /* We do a copy_from_user in __vmm_add_gpcs, but it ought to be clear
1653         * from the syscall.c code if we did our error checking. */
1654        if (!is_user_rwaddr(gpcis, sizeof(struct vmm_gpcore_init) *
1655                                   nr_more_gpcs)) {
1656                set_error(EINVAL, "bad user addr %p + %p", gpcis,
1657                          sizeof(struct vmm_gpcore_init) * nr_more_gpcs);
1658                return -1;
1659        }
1660        qlock(&vmm->qlock);
1661        if (waserror()) {
1662                qunlock(&vmm->qlock);
1663                poperror();
1664                return -1;
1665        }
1666        __vmm_struct_init(p);
1667        __vmm_add_gpcs(p, nr_more_gpcs, gpcis);
1668        qunlock(&vmm->qlock);
1669        poperror();
1670        return nr_more_gpcs;
1671}
1672
1673static int sys_vmm_poke_guest(struct proc *p, int guest_pcoreid)
1674{
1675        return vmm_poke_guest(p, guest_pcoreid);
1676}
1677
1678static int sys_vmm_ctl(struct proc *p, int cmd, unsigned long arg1,
1679                       unsigned long arg2, unsigned long arg3,
1680                       unsigned long arg4)
1681{
1682        ERRSTACK(1);
1683        int ret;
1684        struct vmm *vmm = &p->vmm;
1685
1686        /* Protects against concurrent setters and for gets that are not atomic
1687         * reads (say, multiple exec ctls). */
1688        qlock(&vmm->qlock);
1689        if (waserror()) {
1690                qunlock(&vmm->qlock);
1691                poperror();
1692                return -1;
1693        }
1694        __vmm_struct_init(p);
1695        switch (cmd) {
1696        case VMM_CTL_GET_EXITS:
1697                if (vmm->amd)
1698                        error(ENOTSUP, "AMD VMMs unsupported");
1699                ret = vmx_ctl_get_exits(&vmm->vmx);
1700                break;
1701        case VMM_CTL_SET_EXITS:
1702                if (arg1 & ~VMM_CTL_ALL_EXITS)
1703                        error(EINVAL, "Bad vmm_ctl_exits %x (%x)", arg1,
1704                              VMM_CTL_ALL_EXITS);
1705                if (vmm->amd)
1706                        error(ENOTSUP, "AMD VMMs unsupported");
1707                ret = vmx_ctl_set_exits(&vmm->vmx, arg1);
1708                break;
1709        case VMM_CTL_GET_FLAGS:
1710                ret = vmm->flags;
1711                break;
1712        case VMM_CTL_SET_FLAGS:
1713                if (arg1 & ~VMM_CTL_ALL_FLAGS)
1714                        error(EINVAL,
1715                              "Bad vmm_ctl flags.  Got 0x%lx, allowed 0x%lx\n",
1716                              arg1, VMM_CTL_ALL_FLAGS);
1717                vmm->flags = arg1;
1718                ret = 0;
1719                break;
1720        default:
1721                error(EINVAL, "Bad vmm_ctl cmd %d", cmd);
1722        }
1723        qunlock(&vmm->qlock);
1724        poperror();
1725        return ret;
1726}
1727
1728/* Pokes the ksched for the given resource for target_pid.  If the target pid
1729 * == 0, we just poke for the calling process.  The common case is poking for
1730 * self, so we avoid the lookup.
1731 *
1732 * Not sure if you could harm someone via asking the kernel to look at them, so
1733 * we'll do a 'controls' check for now.  In the future, we might have something
1734 * in the ksched that limits or penalizes excessive pokes. */
1735static int sys_poke_ksched(struct proc *p, int target_pid,
1736                           unsigned int res_type)
1737{
1738        struct proc *target;
1739        int retval = 0;
1740
1741        if (!target_pid) {
1742                poke_ksched(p, res_type);
1743                return 0;
1744        }
1745        target = pid2proc(target_pid);
1746        if (!target) {
1747                set_errno(ESRCH);
1748                return -1;
1749        }
1750        if (!proc_controls(p, target)) {
1751                set_errno(EPERM);
1752                retval = -1;
1753                goto out;
1754        }
1755        poke_ksched(target, res_type);
1756out:
1757        proc_decref(target);
1758        return retval;
1759}
1760
1761static int sys_abort_sysc(struct proc *p, struct syscall *sysc)
1762{
1763        return abort_sysc(p, (uintptr_t)sysc);
1764}
1765
1766static int sys_abort_sysc_fd(struct proc *p, int fd)
1767{
1768        /* Consider checking for a bad fd.  Doesn't matter now, since we only
1769         * look for actual syscalls blocked that had used fd. */
1770        return abort_all_sysc_fd(p, fd);
1771}
1772
1773static unsigned long sys_populate_va(struct proc *p, uintptr_t va,
1774                                     unsigned long nr_pgs)
1775{
1776        return populate_va(p, ROUNDDOWN(va, PGSIZE), nr_pgs);
1777}
1778
1779static intreg_t sys_read(struct proc *p, int fd, void *buf, size_t len)
1780{
1781        if (!is_user_rwaddr(buf, len)) {
1782                set_error(EINVAL, "bad user addr %p + %p", buf, len);
1783                return -1;
1784        }
1785        sysc_save_str("read on fd %d", fd);
1786        return sysread(fd, buf, len);
1787}
1788
1789static intreg_t sys_write(struct proc *p, int fd, const void *buf, size_t len)
1790{
1791        /* We'll let this one include read-only areas, unlike most other
1792         * syscalls that take bufs created and written by the user. */
1793        if (!is_user_raddr(buf, len)) {
1794                set_error(EINVAL, "bad user addr %p + %p", buf, len);
1795                return -1;
1796        }
1797        sysc_save_str("write on fd %d", fd);
1798        return syswrite(fd, (void*)buf, len);
1799}
1800
1801/* Checks args/reads in the path, opens the file (relative to fromfd if the path
1802 * is not absolute), and inserts it into the process's open file list. */
1803static intreg_t sys_openat(struct proc *p, int fromfd, const char *path,
1804                           size_t path_l, int oflag, int mode)
1805{
1806        int fd;
1807        char *t_path;
1808
1809        printd("File %s Open attempt oflag %x mode %x\n", path, oflag, mode);
1810        if ((oflag & O_PATH) && (oflag & O_ACCMODE)) {
1811                set_error(EINVAL, "Cannot open O_PATH with any I/O perms (O%o)",
1812                          oflag);
1813                return -1;
1814        }
1815        if (oflag & O_EXCL && !(oflag & O_CREATE)) {
1816                set_error(EINVAL, "Cannot open O_EXCL without O_CREATE");
1817                return -1;
1818        }
1819        t_path = copy_in_path(p, path, path_l);
1820        if (!t_path)
1821                return -1;
1822        sysc_save_str("open %s at fd %d", t_path, fromfd);
1823        mode &= ~p->umask;
1824        mode &= S_PMASK;
1825        static_assert(!(DMMODE_BITS & S_PMASK));
1826        fd = sysopenat(fromfd, t_path, oflag, mode);
1827        free_path(p, t_path);
1828        printd("File %s Open, fd=%d\n", path, fd);
1829        return fd;
1830}
1831
1832static intreg_t sys_close(struct proc *p, int fd)
1833{
1834        return sysclose(fd);
1835}
1836
1837static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
1838{
1839        struct kstat *kbuf;
1840
1841        kbuf = kmalloc(sizeof(struct kstat), 0);
1842        if (!kbuf) {
1843                set_errno(ENOMEM);
1844                return -1;
1845        }
1846        if (sysfstatakaros(fd, (struct kstat *)kbuf) < 0) {
1847                kfree(kbuf);
1848                return -1;
1849        }
1850        /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer
1851         */
1852        if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1853                kfree(kbuf);
1854                return -1;
1855        }
1856        kfree(kbuf);
1857        return 0;
1858}
1859
1860/* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
1861 * treat a symlink for the final item, which (probably) will be controlled by
1862 * the lookup flags */
1863static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
1864                            struct kstat *u_stat, int flags)
1865{
1866        struct kstat *kbuf;
1867        char *t_path = copy_in_path(p, path, path_l);
1868        int retval = 0;
1869
1870        if (!t_path)
1871                return -1;
1872        kbuf = kmalloc(sizeof(struct kstat), 0);
1873        if (!kbuf) {
1874                set_errno(ENOMEM);
1875                retval = -1;
1876                goto out_with_path;
1877        }
1878        retval = sysstatakaros(t_path, (struct kstat *)kbuf, flags);
1879        if (retval < 0)
1880                goto out_with_kbuf;
1881        /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer
1882         */
1883        if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat)))
1884                retval = -1;
1885        /* Fall-through */
1886out_with_kbuf:
1887        kfree(kbuf);
1888out_with_path:
1889        free_path(p, t_path);
1890        return retval;
1891}
1892
1893/* Follow a final symlink */
1894static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1895                         struct kstat *u_stat)
1896{
1897        return stat_helper(p, path, path_l, u_stat, 0);
1898}
1899
1900/* Don't follow a final symlink */
1901static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1902                          struct kstat *u_stat)
1903{
1904        return stat_helper(p, path, path_l, u_stat, O_NOFOLLOW);
1905}
1906
1907intreg_t sys_fcntl(struct proc *p, int fd, int cmd, unsigned long arg1,
1908                   unsigned long arg2, unsigned long arg3, unsigned long arg4)
1909{
1910        switch (cmd) {
1911        case (F_DUPFD):
1912                /* TODO: glibc uses regular DUPFD for dup2, which is racy. */
1913                return sysdup(fd, arg1, FALSE);
1914        case (F_GETFD):
1915                return fd_get_fd_flags(&p->open_files, fd);
1916        case (F_SETFD):
1917                if (arg1 & ~FD_VALID_FLAGS) {
1918                        set_error(EINVAL, "Bad FD flags %p, valid are %p", arg1,
1919                                  FD_VALID_FLAGS);
1920                        return -1;
1921                }
1922                return fd_set_fd_flags(&p->open_files, fd, arg1);
1923        case (F_SYNC):
1924                return fd_chan_ctl(fd, CCTL_SYNC, 0, 0, 0, 0);
1925        case (F_GETFL):
1926                return fd_getfl(fd);
1927        case (F_SETFL):
1928                return fd_chan_ctl(fd, CCTL_SET_FL, arg1, 0, 0, 0);
1929        default:
1930                /* chanctl and fcntl share flags */
1931                if (cmd >= F_CHANCTL_BASE)
1932                        return fd_chan_ctl(fd, cmd, arg1, arg2, arg3, arg4);
1933                set_error(EINVAL, "Unsupported fcntl cmd %d", cmd);
1934                return -1;
1935        }
1936}
1937
1938static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1939                           int mode)
1940{
1941        int retval;
1942        struct dir *dir;
1943        char *t_path = copy_in_path(p, path, path_l);
1944
1945        if (!t_path)
1946                return -1;
1947        dir = sysdirstat(t_path);
1948        if (!dir)
1949                goto out;
1950        if ((mode == F_OK) ||
1951            caller_has_dir_perms(dir, access_bits_to_omode(mode)))
1952                retval = 0;
1953        kfree(dir);
1954out:
1955        free_path(p, t_path);
1956        return retval;
1957}
1958
1959intreg_t sys_umask(struct proc *p, int mask)
1960{
1961        int old_mask = p->umask;
1962
1963        p->umask = mask & S_PMASK;
1964        return old_mask;
1965}
1966
1967/* 64 bit seek, with the off64_t passed in via two (potentially 32 bit) off_ts.
1968 * We're supporting both 32 and 64 bit kernels/userspaces, but both use the
1969 * llseek syscall with 64 bit parameters. */
1970static intreg_t sys_llseek(struct proc *p, int fd, off_t offset_hi,
1971                           off_t offset_lo, off64_t *result, int whence)
1972{
1973        off64_t retoff = 0;
1974        off64_t tempoff = 0;
1975        int ret = 0;
1976
1977        tempoff = offset_hi;
1978        tempoff <<= 32;
1979        tempoff |= offset_lo;
1980        retoff = sysseek(fd, tempoff, whence);
1981        ret = (retoff < 0);
1982        if (ret)
1983                return -1;
1984        if (memcpy_to_user_errno(p, result, &retoff, sizeof(off64_t)))
1985                return -1;
1986        return 0;
1987}
1988
1989intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1990                  char *new_path, size_t new_l)
1991{
1992        int ret;
1993        char *t_oldpath = copy_in_path(p, old_path, old_l);
1994
1995        if (t_oldpath == NULL)
1996                return -1;
1997        char *t_newpath = copy_in_path(p, new_path, new_l);
1998
1999        if (t_newpath == NULL) {
2000                free_path(p, t_oldpath);
2001                return -1;
2002        }
2003        set_error(ENOSYS, "no link");
2004        ret = -1;
2005        free_path(p, t_oldpath);
2006        free_path(p, t_newpath);
2007        return ret;
2008}
2009
2010intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
2011{
2012        int retval;
2013        char *t_path = copy_in_path(p, path, path_l);
2014
2015        if (!t_path)
2016                return -1;
2017        retval = sysremove(t_path);
2018        free_path(p, t_path);
2019        return retval;
2020}
2021
2022intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
2023                     char *new_path, size_t new_l)
2024{
2025        int ret;
2026        char *t_oldpath = copy_in_path(p, old_path, old_l);
2027
2028        if (t_oldpath == NULL)
2029                return -1;
2030        char *t_newpath = copy_in_path(p, new_path, new_l);
2031
2032        if (t_newpath == NULL) {
2033                free_path(p, t_oldpath);
2034                return -1;
2035        }
2036        ret = syssymlink(t_newpath, t_oldpath);
2037        free_path(p, t_oldpath);
2038        free_path(p, t_newpath);
2039        return ret;
2040}
2041
2042intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
2043                      char *u_buf, size_t buf_l)
2044{
2045        char *symname = NULL;
2046        ssize_t copy_amt;
2047        int ret = -1;
2048        char *t_path = copy_in_path(p, path, path_l);
2049        struct dir *dir;
2050
2051        if (t_path == NULL)
2052                return -1;
2053        dir = sysdirlstat(t_path);
2054        if (!dir)
2055                return -1;
2056        if (!(dir->mode & DMSYMLINK))
2057                set_error(EINVAL, "not a symlink: %s", t_path);
2058        else
2059                symname = dir->ext;
2060        free_path(p, t_path);
2061        if (symname){
2062                copy_amt = strnlen(symname, buf_l - 1) + 1;
2063                if (!memcpy_to_user_errno(p, u_buf, symname, copy_amt))
2064                        ret = copy_amt - 1;
2065        }
2066        kfree(dir);
2067        return ret;
2068}
2069
2070static intreg_t sys_chdir(struct proc *p, pid_t pid, const char *path,
2071                          size_t path_l)
2072{
2073        int retval;
2074        char *t_path;
2075        struct proc *target = get_controllable_proc(p, pid);
2076
2077        if (!target)
2078                return -1;
2079        if ((target != p) && (target->state != PROC_CREATED)) {
2080                proc_decref(target);
2081                set_error(EINVAL, "pid %d has already started", pid);
2082                return -1;
2083        }
2084        t_path = copy_in_path(p, path, path_l);
2085        if (!t_path) {
2086                proc_decref(target);
2087                return -1;
2088        }
2089        retval = syschdir(target, t_path);
2090        free_path(p, t_path);
2091        proc_decref(target);
2092        return retval;
2093}
2094
2095static intreg_t sys_fchdir(struct proc *p, pid_t pid, int fd)
2096{
2097        int retval;
2098        struct proc *target = get_controllable_proc(p, pid);
2099
2100        if (!target)
2101                return -1;
2102        if ((target != p) && (target->state != PROC_CREATED)) {
2103                proc_decref(target);
2104                set_error(EINVAL, "pid %d has already started", pid);
2105                return -1;
2106        }
2107        retval = sysfchdir(target, fd);
2108        proc_decref(target);
2109        return retval;
2110}
2111
2112/* Note cwd_l is not a strlen, it's an absolute size.
2113 * Same as with readlink, we give them a null-terminated string, and we return
2114 * strlen, which doesn't include the \0.  If we can't give them the \0, we'll
2115 * error out.  Our readlink also does that, which is not POSIX-like. */
2116intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
2117{
2118        ssize_t retval = -1;
2119        size_t copy_amt;
2120        char *k_cwd;
2121
2122        k_cwd = sysgetcwd();
2123        if (!k_cwd) {
2124                set_error(EINVAL, "unable to getcwd");
2125                return -1;
2126        }
2127        copy_amt = strlen(k_cwd) + 1;
2128        if (copy_amt > cwd_l) {
2129                set_error(ERANGE, "getcwd buf too small, needed %d", copy_amt);
2130                goto out;
2131        }
2132        if (!memcpy_to_user_errno(p, u_cwd, k_cwd, copy_amt))
2133                retval = copy_amt - 1;
2134out:
2135        kfree(k_cwd);
2136        return retval;
2137}
2138
2139intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
2140{
2141        int retval;
2142        char *t_path = copy_in_path(p, path, path_l);
2143
2144        if (!t_path)
2145                return -1;
2146        mode &= ~p->umask;
2147        mode &= S_PMASK;
2148        static_assert(!(DMMODE_BITS & S_PMASK));
2149        retval = syscreate(t_path, O_READ, DMDIR | mode);
2150        if (retval >= 0) {
2151                sysclose(retval);
2152                retval = 0;
2153        }
2154        free_path(p, t_path);
2155        return retval;
2156}
2157
2158intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
2159{
2160        int retval;
2161        char *t_path = copy_in_path(p, path, path_l);
2162
2163        if (!t_path)
2164                return -1;
2165        retval = sysremove(t_path);
2166        free_path(p, t_path);
2167        return retval;
2168}
2169
2170intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
2171{
2172        int retval = 0;
2173        /* TODO: actually support this call on tty FDs.  Right now, we just fake
2174         * what my linux box reports for a bash pty. */
2175        struct termios *kbuf = kmalloc(sizeof(struct termios), 0);
2176
2177        kbuf->c_iflag = 0x2d02;
2178        kbuf->c_oflag = 0x0005;
2179        kbuf->c_cflag = 0x04bf;
2180        kbuf->c_lflag = 0x8a3b;
2181        kbuf->c_line = 0x0;
2182        kbuf->c_ispeed = 0xf;
2183        kbuf->c_ospeed = 0xf;
2184        kbuf->c_cc[0] = 0x03;
2185        kbuf->c_cc[1] = 0x1c;
2186        kbuf->c_cc[2] = 0x7f;
2187        kbuf->c_cc[3] = 0x15;
2188        kbuf->c_cc[4] = 0x04;
2189        kbuf->c_cc[5] = 0x00;
2190        kbuf->c_cc[6] = 0x01;
2191        kbuf->c_cc[7] = 0xff;
2192        kbuf->c_cc[8] = 0x11;
2193        kbuf->c_cc[9] = 0x13;
2194        kbuf->c_cc[10] = 0x1a;
2195        kbuf->c_cc[11] = 0xff;
2196        kbuf->c_cc[12] = 0x12;
2197        kbuf->c_cc[13] = 0x0f;
2198        kbuf->c_cc[14] = 0x17;
2199        kbuf->c_cc[15] = 0x16;
2200        kbuf->c_cc[16] = 0xff;
2201        kbuf->c_cc[17] = 0x00;
2202        kbuf->c_cc[18] = 0x00;
2203        kbuf->c_cc[19] = 0x00;
2204        kbuf->c_cc[20] = 0x00;
2205        kbuf->c_cc[21] = 0x00;
2206        kbuf->c_cc[22] = 0x00;
2207        kbuf->c_cc[23] = 0x00;
2208        kbuf->c_cc[24] = 0x00;
2209        kbuf->c_cc[25] = 0x00;
2210        kbuf->c_cc[26] = 0x00;
2211        kbuf->c_cc[27] = 0x00;
2212        kbuf->c_cc[28] = 0x00;
2213        kbuf->c_cc[29] = 0x00;
2214        kbuf->c_cc[30] = 0x00;
2215        kbuf->c_cc[31] = 0x00;
2216
2217        if (memcpy_to_user_errno(p, termios_p, kbuf, sizeof(struct termios)))
2218                retval = -1;
2219        kfree(kbuf);
2220        return retval;
2221}
2222
2223intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
2224                       const void *termios_p)
2225{
2226        /* TODO: do this properly too.  For now, we just say 'it worked' */
2227        return 0;
2228}
2229
2230/* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
2231 * process from thinking it can do these.  The other alternative is to have
2232 * glibc return 0 right away, though someone might want to do something with
2233 * these calls.  Someday. */
2234intreg_t sys_setuid(struct proc *p, uid_t uid)
2235{
2236        return 0;
2237}
2238
2239intreg_t sys_setgid(struct proc *p, gid_t gid)
2240{
2241        return 0;
2242}
2243
2244/* long bind(char* src_path, char* onto_path, int flag);
2245 *
2246 * The naming for the args in bind is messy historically.  We do:
2247 *              bind src_path onto_path
2248 * plan9 says bind NEW OLD, where new is *src*, and old is *onto*.
2249 * Linux says mount --bind OLD NEW, where OLD is *src* and NEW is *onto*. */
2250intreg_t sys_nbind(struct proc *p,
2251                   char *src_path, size_t src_l,
2252                   char *onto_path, size_t onto_l,
2253                   unsigned int flag)
2254
2255{
2256        int ret;
2257        char *t_srcpath = copy_in_path(p, src_path, src_l);
2258
2259        if (t_srcpath == NULL) {
2260                printd("srcpath dup failed ptr %p size %d\n", src_path, src_l);
2261                return -1;
2262        }
2263        char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2264
2265        if (t_ontopath == NULL) {
2266                free_path(p, t_srcpath);
2267                printd("ontopath dup failed ptr %p size %d\n", onto_path,
2268                       onto_l);
2269                return -1;
2270        }
2271        printd("sys_nbind: %s -> %s flag %d\n", t_srcpath, t_ontopath, flag);
2272        ret = sysbind(t_srcpath, t_ontopath, flag);
2273        free_path(p, t_srcpath);
2274        free_path(p, t_ontopath);
2275        return ret;
2276}
2277
2278/* int mount(int fd, int afd, char* onto_path, int flag, char* aname); */
2279intreg_t sys_nmount(struct proc *p,
2280                    int fd,
2281                    char *onto_path, size_t onto_l,
2282                    unsigned int flag
2283                        /* we ignore these */
2284                        /* no easy way to pass this many args anyway. *
2285                    int afd,
2286                    char *auth, size_t auth_l*/)
2287{
2288        int ret;
2289        int afd;
2290
2291        afd = -1;
2292        char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2293
2294        if (t_ontopath == NULL)
2295                return -1;
2296        /* TODO: if we ever pass in the spec/auth, copy those in. */
2297        ret = sysmount(fd, afd, t_ontopath, flag, /* spec or auth */"/");
2298        free_path(p, t_ontopath);
2299        return ret;
2300}
2301
2302/* Unmount undoes the operation of a bind or mount.  Check out
2303 * http://plan9.bell-labs.com/magic/man2html/1/bind .  Though our mount takes an
2304 * FD, not servename (aka src_path), so it's not quite the same.
2305 *
2306 * To translate between Plan 9 and Akaros, old -> onto_path.  new -> src_path.
2307 *
2308 * For unmount, src_path / new is optional.  If set, we only unmount the
2309 * bindmount that came from src_path. */
2310intreg_t sys_nunmount(struct proc *p, char *src_path, int src_l,
2311                      char *onto_path, int onto_l)
2312{
2313        int ret;
2314        char *t_ontopath, *t_srcpath;
2315
2316        t_ontopath = copy_in_path(p, onto_path, onto_l);
2317        if (t_ontopath == NULL)
2318                return -1;
2319        if (src_path) {
2320                t_srcpath = copy_in_path(p, src_path, src_l);
2321                if (t_srcpath == NULL) {
2322                        free_path(p, t_ontopath);
2323                        return -1;
2324                }
2325        } else {
2326                t_srcpath = 0;
2327        }
2328        ret = sysunmount(t_srcpath, t_ontopath);
2329        free_path(p, t_ontopath);
2330        free_path(p, t_srcpath);        /* you can free a null path */
2331        return ret;
2332}
2333
2334intreg_t sys_fd2path(struct proc *p, int fd, void *u_buf, size_t len)
2335{
2336        int ret = 0;
2337        struct chan *ch;
2338        ERRSTACK(1);
2339
2340        /* UMEM: Check the range, can PF later and kill if the page isn't
2341         * present */
2342        if (!is_user_rwaddr(u_buf, len)) {
2343                set_error(EINVAL, "bad user addr %p + %p", u_buf, len);
2344                return -1;
2345        }
2346        /* fdtochan throws */
2347        if (waserror()) {
2348                poperror();
2349                return -1;
2350        }
2351        ch = fdtochan(&current->open_files, fd, -1, FALSE, TRUE);
2352        if (snprintf(u_buf, len, "%s", channame(ch)) >= len) {
2353                set_error(ERANGE, "fd2path buf too small, needed %d", ret);
2354                ret = -1;
2355        }
2356        cclose(ch);
2357        poperror();
2358        return ret;
2359}
2360
2361intreg_t sys_wstat(struct proc *p, char *path, size_t path_l,
2362                   uint8_t *stat_m, size_t stat_sz, int flags)
2363{
2364        int retval = 0;
2365        char *t_path;
2366
2367        if (!is_user_rwaddr(stat_m, stat_sz)) {
2368                set_error(EINVAL, "bad user addr %p + %p", stat_m, stat_sz);
2369                return -1;
2370        }
2371        t_path = copy_in_path(p, path, path_l);
2372        if (!t_path)
2373                return -1;
2374        retval = syswstat(t_path, stat_m, stat_sz);
2375        free_path(p, t_path);
2376        return retval;
2377}
2378
2379intreg_t sys_fwstat(struct proc *p, int fd, uint8_t *stat_m, size_t stat_sz,
2380                    int flags)
2381{
2382        if (!is_user_rwaddr(stat_m, stat_sz)) {
2383                set_error(EINVAL, "bad user addr %p + %p", stat_m, stat_sz);
2384                return -1;
2385        }
2386        return sysfwstat(fd, stat_m, stat_sz);
2387}
2388
2389intreg_t sys_rename(struct proc *p, char *old_path, size_t old_path_l,
2390                    char *new_path, size_t new_path_l)
2391{
2392        char *from_path = copy_in_path(p, old_path, old_path_l);
2393        char *to_path = copy_in_path(p, new_path, new_path_l);
2394        int ret;
2395
2396        if ((!from_path) || (!to_path))
2397                return -1;
2398        ret = sysrename(from_path, to_path);
2399        free_path(p, from_path);
2400        free_path(p, to_path);
2401        return ret;
2402}
2403
2404/* Careful: if an FD is busy, we don't close the old object, it just fails */
2405static intreg_t sys_dup_fds_to(struct proc *p, unsigned int pid,
2406                               struct childfdmap *map, unsigned int nentries)
2407{
2408        ssize_t ret = 0;
2409        struct proc *child;
2410        int slot;
2411
2412        if (!is_user_rwaddr(map, sizeof(struct childfdmap) * nentries)) {
2413                set_error(EINVAL, "bad user addr %p + %p", map,
2414                          sizeof(struct childfdmap) * nentries);
2415                return -1;
2416        }
2417        child = get_controllable_proc(p, pid);
2418        if (!child)
2419                return -1;
2420        for (int i = 0; i < nentries; i++) {
2421                map[i].ok = -1;
2422                if (!sys_dup_to(p, map[i].parentfd, child, map[i].childfd)) {
2423                        map[i].ok = 0;
2424                        ret++;
2425                        continue;
2426                }
2427                /* probably a bug, could send EBADF, maybe via 'ok' */
2428                printk("[kernel] dup_fds_to: couldn't find %d\n", map[i].parentfd);
2429        }
2430        proc_decref(child);
2431        return ret;
2432}
2433
2434/* 0 on success, anything else is an error, with errno/errstr set */
2435static int handle_tap_req(struct proc *p, struct fd_tap_req *req)
2436{
2437        switch (req->cmd) {
2438        case (FDTAP_CMD_ADD):
2439                return add_fd_tap(p, req);
2440        case (FDTAP_CMD_REM):
2441                return remove_fd_tap(p, req->fd);
2442        default:
2443                set_error(ENOSYS, "FD Tap Command %d not supported", req->cmd);
2444                return -1;
2445        }
2446}
2447
2448/* Processes up to nr_reqs tap requests.  If a request errors out, we stop
2449 * immediately.  Returns the number processed.  If done != nr_reqs, check errno
2450 * and errstr for the last failure, which is for tap_reqs[done]. */
2451static intreg_t sys_tap_fds(struct proc *p, struct fd_tap_req *tap_reqs,
2452                            size_t nr_reqs)
2453{
2454        struct fd_tap_req *req_i = tap_reqs;
2455        int done;
2456
2457        if (!is_user_rwaddr(tap_reqs, sizeof(struct fd_tap_req) * nr_reqs)) {
2458                set_error(EINVAL, "bad user addr %p + %p", tap_reqs,
2459                          sizeof(struct fd_tap_req) * nr_reqs);
2460                return 0;
2461        }
2462        for (done = 0; done < nr_reqs; done++, req_i++) {
2463                if (handle_tap_req(p, req_i))
2464                        break;
2465        }
2466        return done;
2467}
2468
2469/************** Syscall Invokation **************/
2470
2471const struct sys_table_entry syscall_table[] = {
2472        [SYS_null] = {(syscall_t)sys_null, "null"},
2473        [SYS_block] = {(syscall_t)sys_block, "block"},
2474        [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
2475        [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
2476        [SYS_getpcoreid] = {(syscall_t)sys_getpcoreid, "getpcoreid"},
2477        [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
2478        [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
2479        [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
2480        [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
2481        [SYS_proc_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
2482        [SYS_change_vcore] = {(syscall_t)sys_change_vcore, "change_vcore"},
2483        [SYS_fork] = {(syscall_t)sys_fork, "fork"},
2484        [SYS_exec] = {(syscall_t)sys_exec, "exec"},
2485        [SYS_waitpid] = {(syscall_t)sys_waitpid, "waitpid"},
2486        [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
2487        [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
2488        [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
2489        [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
2490        [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
2491        [SYS_provision] = {(syscall_t)sys_provision, "provision"},
2492        [SYS_notify] = {(syscall_t)sys_notify, "notify"},
2493        [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
2494        [SYS_send_event] = {(syscall_t)sys_send_event, "send_event"},
2495        [SYS_vc_entry] = {(syscall_t)sys_vc_entry, "vc_entry"},
2496        [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
2497#ifdef CONFIG_ARSC_SERVER
2498        [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
2499#endif
2500        [SYS_change_to_m] = {(syscall_t)sys_change_to_m, "change_to_m"},
2501        [SYS_vmm_add_gpcs] = {(syscall_t)sys_vmm_add_gpcs, "vmm_add_gpcs"},
2502        [SYS_vmm_poke_guest] = {(syscall_t)sys_vmm_poke_guest, "vmm_poke_guest"},
2503        [SYS_vmm_ctl] = {(syscall_t)sys_vmm_ctl, "vmm_ctl"},
2504        [SYS_poke_ksched] = {(syscall_t)sys_poke_ksched, "poke_ksched"},
2505        [SYS_abort_sysc] = {(syscall_t)sys_abort_sysc, "abort_sysc"},
2506        [SYS_abort_sysc_fd] = {(syscall_t)sys_abort_sysc_fd, "abort_sysc_fd"},
2507        [SYS_populate_va] = {(syscall_t)sys_populate_va, "populate_va"},
2508        [SYS_nanosleep] = {(syscall_t)sys_nanosleep, "nanosleep"},
2509        [SYS_pop_ctx] = {(syscall_t)sys_pop_ctx, "pop_ctx"},
2510
2511        [SYS_read] = {(syscall_t)sys_read, "read"},
2512        [SYS_write] = {(syscall_t)sys_write, "write"},
2513        [SYS_openat] = {(syscall_t)sys_openat, "openat"},
2514        [SYS_close] = {(syscall_t)sys_close, "close"},
2515        [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
2516        [SYS_stat] = {(syscall_t)sys_stat, "stat"},
2517        [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
2518        [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
2519        [SYS_access] = {(syscall_t)sys_access, "access"},
2520        [SYS_umask] = {(syscall_t)sys_umask, "umask"},
2521        [SYS_llseek] = {(syscall_t)sys_llseek, "llseek"},
2522        [SYS_link] = {(syscall_t)sys_link, "link"},
2523        [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
2524        [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
2525        [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
2526        [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
2527        [SYS_fchdir] = {(syscall_t)sys_fchdir, "fchdir"},
2528        [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
2529        [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdir"},
2530        [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
2531        [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
2532        [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
2533        [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
2534        [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"},
2535        /* special! */
2536        [SYS_nbind] ={(syscall_t)sys_nbind, "nbind"},
2537        [SYS_nmount] ={(syscall_t)sys_nmount, "nmount"},
2538        [SYS_nunmount] ={(syscall_t)sys_nunmount, "nunmount"},
2539        [SYS_fd2path] ={(syscall_t)sys_fd2path, "fd2path"},
2540        [SYS_wstat] ={(syscall_t)sys_wstat, "wstat"},
2541        [SYS_fwstat] ={(syscall_t)sys_fwstat, "fwstat"},
2542        [SYS_rename] ={(syscall_t)sys_rename, "rename"},
2543        [SYS_dup_fds_to] = {(syscall_t)sys_dup_fds_to, "dup_fds_to"},
2544        [SYS_tap_fds] = {(syscall_t)sys_tap_fds, "tap_fds"},
2545};
2546const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
2547
2548/* Executes the given syscall.
2549 *
2550 * Note tf is passed in, which points to the tf of the context on the kernel
2551 * stack.  If any syscall needs to block, it needs to save this info, as well as
2552 * any silly state.
2553 *
2554 * This syscall function is used by both local syscall and arsc, and should
2555 * remain oblivious of the caller. */
2556intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
2557                 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
2558{
2559        intreg_t ret = -1;
2560        ERRSTACK(1);
2561
2562        if (sc_num > max_syscall || syscall_table[sc_num].call == NULL) {
2563                printk("[kernel] Invalid syscall %d for proc %d\n", sc_num,
2564                       p->pid);
2565                printk("\tArgs: %p, %p, %p, %p, %p, %p\n", a0, a1, a2, a3, a4,
2566                       a5);
2567                print_user_ctx(this_pcpui_var(cur_ctx));
2568                return -1;
2569        }
2570
2571        /* N.B. This is going away. */
2572        if (waserror()){
2573                printk("Plan 9 system call returned via waserror()\n");
2574                printk("String: '%s'\n", current_errstr());
2575                /* if we got here, then the errbuf was right.
2576                 * no need to check!
2577                 */
2578                return -1;
2579        }
2580        //printd("before syscall errstack %p\n", errstack);
2581        //printd("before syscall errstack base %p\n", get_cur_errbuf());
2582        ret = syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
2583        //printd("after syscall errstack base %p\n", get_cur_errbuf());
2584        if (get_cur_errbuf() != &errstack[0]) {
2585                /* Can't trust coreid and vcoreid anymore, need to check the
2586                 * trace */
2587                printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, "
2588                       "%p, %p) proc: %d\n", read_tsc(),
2589                       sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
2590                       a4, a5, p->pid);
2591                if (sc_num != SYS_fork)
2592                        panic("errstack mismatch");
2593        }
2594        return ret;
2595}
2596
2597/* Execute the syscall on the local core */
2598void run_local_syscall(struct syscall *sysc)
2599{
2600        struct per_cpu_info *pcpui = this_pcpui_ptr();
2601        struct proc *p = pcpui->cur_proc;
2602        long retval;
2603
2604        /* In lieu of pinning, we just check the sysc and will PF on the user
2605         * addr later (if the addr was unmapped).  Which is the plan for all
2606         * UMEM. */
2607        if (!is_user_rwaddr(sysc, sizeof(struct syscall))) {
2608                printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n",
2609                       sysc, sizeof(struct syscall), __FUNCTION__);
2610                return;
2611        }
2612        pcpui->cur_kthread->sysc = sysc;/* let the core know which sysc it is */
2613        unset_errno();
2614        systrace_start_trace(pcpui->cur_kthread, sysc);
2615        pcpui = this_pcpui_ptr();       /* reload again */
2616        alloc_sysc_str(pcpui->cur_kthread);
2617        /* syscall() does not return for exec and yield, so put any cleanup in
2618         * there too. */
2619        retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
2620                         sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
2621        finish_current_sysc(retval);
2622}
2623
2624/* A process can trap and call this function, which will set up the core to
2625 * handle all the syscalls.  a.k.a. "sys_debutante(needs, wants)".  If there is
2626 * at least one, it will run it directly. */
2627void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
2628{
2629        /* Careful with pcpui here, we could have migrated */
2630        if (!nr_syscs) {
2631                printk("[kernel] No nr_sysc, probably a bug, user!\n");
2632                return;
2633        }
2634        /* For all after the first call, send ourselves a KMSG (TODO). */
2635        if (nr_syscs != 1)
2636                warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
2637        /* Call the first one directly.  (we already checked to make sure there
2638         * is 1) */
2639        run_local_syscall(sysc);
2640}
2641
2642/* Call this when something happens on the syscall where userspace might want to
2643 * get signaled.  Passing p, since the caller should know who the syscall
2644 * belongs to (probably is current).
2645 *
2646 * You need to have SC_K_LOCK set when you call this. */
2647void __signal_syscall(struct syscall *sysc, struct proc *p)
2648{
2649        struct event_queue *ev_q;
2650        struct event_msg local_msg;
2651
2652        /* User sets the ev_q then atomically sets the flag (races with SC_DONE)
2653         */
2654        if (atomic_read(&sysc->flags) & SC_UEVENT) {
2655                rmb();  /* read the ev_q after reading the flag */
2656                ev_q = sysc->ev_q;
2657                if (ev_q) {
2658                        memset(&local_msg, 0, sizeof(struct event_msg));
2659                        local_msg.ev_type = EV_SYSCALL;
2660                        local_msg.ev_arg3 = sysc;
2661                        if (!is_user_rwaddr(ev_q, sizeof(struct event_queue))) {
2662                                printk("[kernel] syscall had bad ev_q %p\n",
2663                                       ev_q);
2664                                return;
2665                        }
2666                        send_event(p, ev_q, &local_msg, 0);
2667                }
2668        }
2669}
2670
2671bool syscall_uses_fd(struct syscall *sysc, int fd)
2672{
2673        switch (sysc->num) {
2674        case (SYS_read):
2675        case (SYS_write):
2676        case (SYS_close):
2677        case (SYS_fstat):
2678        case (SYS_fcntl):
2679        case (SYS_llseek):
2680        case (SYS_nmount):
2681        case (SYS_fd2path):
2682                if (sysc->arg0 == fd)
2683                        return TRUE;
2684                return FALSE;
2685        case (SYS_mmap):
2686                /* mmap always has to be special. =) */
2687                if (sysc->arg4 == fd)
2688                        return TRUE;
2689                return FALSE;
2690        default:
2691                return FALSE;
2692        }
2693}
2694
2695void print_sysc(struct proc *p, struct syscall *sysc)
2696{
2697        uintptr_t old_p = switch_to(p);
2698
2699        printk("SYS_%d, flags %p, a0 %p, a1 %p, a2 %p, a3 %p, a4 %p, a5 %p\n",
2700               sysc->num, atomic_read(&sysc->flags),
2701               sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
2702               sysc->arg5);
2703        switch_back(p, old_p);
2704}
2705
2706/* Called when we try to return from a panic. */
2707void kth_panic_sysc(struct kthread *kth)
2708{
2709        kth->sysc = NULL;
2710        /* We actually could block here, but that might be OK, since we cleared
2711         * cur_kthread->sysc.  As OK as anything is after a panic... */
2712        systrace_finish_trace(kth, -12345);
2713}
2714