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        assert(!ret);
 899        assert(env != NULL);
 900        proc_set_progname(env, e->progname);
 901
 902        /* Can't really fork if we don't have a current_ctx to fork */
 903        if (!current_ctx) {
 904                proc_destroy(env);
 905                proc_decref(env);
 906                set_errno(EINVAL);
 907                return -1;
 908        }
 909        assert(current == this_pcpui_var(owning_proc));
 910        copy_current_ctx_to(&env->scp_ctx);
 911
 912        /* Make the new process have the same VMRs as the older.  This will copy
 913         * the contents of non MAP_SHARED pages to the new VMRs. */
 914        if (duplicate_vmrs(e, env)) {
 915                proc_destroy(env);
 916                proc_decref(env);
 917                set_errno(ENOMEM);
 918                return -1;
 919        }
 920        /* Switch to the new proc's address space and finish the syscall.  We'll
 921         * never naturally finish this syscall for the new proc, since its
 922         * memory is cloned before we return for the original process.  If we
 923         * ever do CoW for forked memory, this will be the first place that gets
 924         * CoW'd. */
 925        temp = switch_to(env);
 926        finish_sysc(current_kthread->sysc, env, 0);
 927        switch_back(env, temp);
 928
 929        /* Copy some state from the original proc into the new proc. */
 930        env->env_flags = e->env_flags;
 931
 932        inherit_strace(e, env);
 933
 934        /* In general, a forked process should be a fresh process, and we copy
 935         * over whatever stuff is needed between procinfo/procdata. */
 936        *env->procdata = *e->procdata;
 937        env->procinfo->program_end = e->procinfo->program_end;
 938
 939        /* FYI: once we call ready, the proc is open for concurrent usage */
 940        __proc_ready(env);
 941        proc_wakeup(env);
 942
 943        // don't decref the new process.
 944        // that will happen when the parent waits for it.
 945        // TODO: if the parent doesn't wait, we need to change the child's
 946        // parent when the parent dies, or at least decref it
 947
 948        printd("[PID %d] fork PID %d\n", e->pid, env->pid);
 949        ret = env->pid;
 950        profiler_notify_new_process(env);
 951        proc_decref(env); /* give up the reference created in proc_alloc() */
 952        return ret;
 953}
 954
 955/* string for sys_exec arguments. Assumes that d is pointing to zero'd
 956 * storage or storage that does not require null termination or
 957 * provides the null. */
 958static int execargs_stringer(struct proc *p, char *d, size_t slen,
 959                             char *path, size_t path_l,
 960                             char *argenv, size_t argenv_l)
 961{
 962        int argc, envc, i;
 963        char **argv, **envp;
 964        struct argenv *kargenv;
 965        int amt;
 966        char *s = d;
 967        char *e = d + slen;
 968
 969        if (path_l > slen)
 970                path_l = slen;
 971        if (memcpy_from_user(p, d, path, path_l)) {
 972                s = seprintf(s, e, "Invalid exec path");
 973                return s - d;
 974        }
 975        s += path_l;
 976
 977        /* yes, this code is cloned from below. I wrote a helper but
 978         * Barret and I concluded after talking about it that the
 979         * helper was not really helper-ful, as it has almost 10
 980         * arguments. Please, don't suggest a cpp macro. Thank you. */
 981        /* Check the size of the argenv array, error out if too large. */
 982        if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
 983                s = seprintf(s, e,
 984                             "The argenv array has an invalid size: %lu\n",
 985                             argenv_l);
 986                return s - d;
 987        }
 988        /* Copy the argenv array into a kernel buffer. */
 989        kargenv = user_memdup_errno(p, argenv, argenv_l);
 990        if (!kargenv) {
 991                s = seprintf(s, e,
 992                             "Failed to copy in the args and environment");
 993                return s - d;
 994        }
 995        /* Unpack the argenv array into more usable variables. Integrity
 996         * checking done along side this as well. */
 997        if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
 998                s = seprintf(s, e, "Failed to unpack the args");
 999                user_memdup_free(p, kargenv);
1000                return s - d;
1001        }
1002        s = seprintf(s, e, "[%d]{", argc);
1003        for (i = 0; i < argc; i++)
1004                s = seprintf(s, e, "%s, ", argv[i]);
1005        s = seprintf(s, e, "}");
1006
1007        user_memdup_free(p, kargenv);
1008        return s - d;
1009}
1010
1011/* Load the binary "path" into the current process, and start executing it.
1012 * argv and envp are magically bundled in procinfo for now.  Keep in sync with
1013 * glibc's sysdeps/ros/execve.c.  Once past a certain point, this function won't
1014 * return.  It assumes (and checks) that it is current.  Don't give it an extra
1015 * refcnt'd *p (syscall won't do that).
1016 * Note: if someone batched syscalls with this call, they could clobber their
1017 * old memory (and will likely PF and die).  Don't do it... */
1018static int sys_exec(struct proc *p, char *path, size_t path_l,
1019                    char *argenv, size_t argenv_l)
1020{
1021        int ret = -1;
1022        char *t_path = NULL;
1023        struct file_or_chan *program;
1024        int argc, envc;
1025        char **argv, **envp;
1026        struct argenv *kargenv;
1027
1028        /* We probably want it to never be allowed to exec if it ever was _M */
1029        if (p->state != PROC_RUNNING_S) {
1030                set_error(EINVAL, "Can't exec an MCP");
1031                return -1;
1032        }
1033        /* Check the size of the argenv array, error out if too large. */
1034        if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
1035                set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
1036                                  argenv_l);
1037                return -1;
1038        }
1039
1040        if (p != this_pcpui_var(owning_proc)) {
1041                warn("Proc %d tried to exec and wasn't owning_proc", p->pid);
1042                set_error(EAGAIN, "exec may have blocked during execution");
1043                return -1;
1044        }
1045        assert(current_ctx);
1046        /* Before this, we shouldn't have blocked (maybe with strace, though we
1047         * explicitly don't block exec for strace).  The owning proc, cur_proc,
1048         * and cur_ctx checks should catch that.  After this, we might still
1049         * block, such as on accessing the filesystem.
1050         *
1051         * After this point, we're treated like a yield - we're waiting until
1052         * something wakes us.  The kthread might block, error and fail, or
1053         * succeed.  We shouldn't return to userspace before one of those.  The
1054         * only way out of this function is via smp_idle, not returning the way
1055         * we came.
1056         *
1057         * Under normal situations, the only thing that will wake us is this
1058         * kthread completing.  I think you can trigger wakeups with events and
1059         * async syscalls started before the exec.  I'm not sure if that could
1060         * trigger more bugs or if that would hurt the kernel.  If so, we could
1061         * add an EXEC_LIMBO state.
1062         *
1063         * Note that we will 'hard block' if we block at all.  We can't return
1064         * to userspace and then asynchronously finish the exec later. */
1065        spin_lock(&p->proc_lock);
1066        /* We only need the context for the error case.  We have to save it now,
1067         * since once we leave this core, such as when the kthread blocks, the
1068         * old SCP's context will be gone. */
1069        __proc_save_context_s(p);
1070        /* We are no longer owning, but we are still current, like any
1071         * kthread-that-blocked-on-behalf of a process.  I think one invariant
1072         * for SCPs is: "RUNNING_S <==> is the owning proc". */
1073        clear_owning_proc(core_id());
1074        __proc_set_state(p, PROC_WAITING);
1075        spin_unlock(&p->proc_lock);
1076
1077        /* Copy the argenv array into a kernel buffer. */
1078        kargenv = user_memdup_errno(p, argenv, argenv_l);
1079        if (!kargenv) {
1080                set_error(EINVAL, "Failed to copy in the args and environment");
1081                goto out_error;
1082        }
1083        /* Unpack the argenv array into more usable variables. Integrity
1084         * checking done along side this as well. */
1085        if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
1086                set_error(EINVAL, "Failed to unpack the args");
1087                goto out_error_kargenv;
1088        }
1089        t_path = copy_in_path(p, path, path_l);
1090        if (!t_path) {
1091                user_memdup_free(p, kargenv);
1092                goto out_error_kargenv;
1093        }
1094        program = foc_open(t_path, O_EXEC | O_READ, 0);
1095        if (!program)
1096                goto out_error_tpath;
1097        if (!is_valid_elf(program)) {
1098                set_error(ENOEXEC, "Program was not a valid ELF");
1099                goto out_error_program;
1100        }
1101
1102        /* This is the point of no return for the process.  Any errors here lead
1103         * to destruction. */
1104
1105        /* progname is argv0, which accounts for symlinks */
1106        proc_replace_binary_path(p, t_path);
1107        /* p now owns the t_path, and it'll get freed when we destroy p. */
1108        t_path = NULL;
1109        proc_set_progname(p, argc ? argv[0] : NULL);
1110        proc_init_procdata(p);
1111        p->procinfo->program_end = 0;
1112        /* When we destroy our memory regions, accessing cur_sysc would PF */
1113        current_kthread->sysc = 0;
1114        unmap_and_destroy_vmrs(p);
1115        /* close the CLOEXEC ones */
1116        close_fdt(&p->open_files, TRUE);
1117        env_user_mem_free(p, 0, UMAPTOP);
1118        if (load_elf(p, program, argc, argv, envc, envp)) {
1119                set_error(EINVAL, "Failed to load elf");
1120                /* At this point, we destroyed memory and can't return to the
1121                 * app.  We can't use the error cases, since they assume we'll
1122                 * return. */
1123                foc_decref(program);
1124                user_memdup_free(p, kargenv);
1125                /* We finish the trace and not the sysc, since the sysc is gone.
1126                 */
1127                systrace_finish_trace(current_kthread, -1);
1128                /* Note this is an inedible reference, but proc_destroy now
1129                 * returns */
1130                proc_destroy(p);
1131                /* We don't want to do anything else - we just need to not
1132                 * accidentally return to the user (hence the all_out) */
1133                goto all_out;
1134        }
1135        printd("[PID %d] exec %s\n", p->pid, foc_to_name(program));
1136        foc_decref(program);
1137        user_memdup_free(p, kargenv);
1138        systrace_finish_trace(current_kthread, 0);
1139        proc_wakeup(p);
1140
1141        goto all_out;
1142
1143out_error_program:
1144        foc_decref(program);
1145out_error_tpath:
1146        /* Note the t_path is passed to proc_replace_binary_path in the non
1147         * out_error cases. */
1148        free_path(p, t_path);
1149out_error_kargenv:
1150        user_memdup_free(p, kargenv);
1151out_error:
1152        finish_current_sysc(-1);
1153        proc_wakeup(p);
1154
1155all_out:
1156        /* This free and setting sysc = NULL may happen twice (early errors do
1157         * it), but they are idempotent. */
1158        free_sysc_str(current_kthread);
1159        current_kthread->sysc = NULL;
1160        /* we can't return, since we'd write retvals to the old location of the
1161         * syscall struct (which has been freed and is in the old userspace) (or
1162         * has already been written to).*/
1163        disable_irq();          /* abandon_core/clear_own wants irqs disabled */
1164        abandon_core();
1165        smp_idle();             /* will reenable interrupts */
1166}
1167
1168/* Helper, will attempt a particular wait on a proc.  Returns the pid of the
1169 * process if we waited on it successfully, and the status will be passed back
1170 * in ret_status (kernel memory).  Returns 0 if the wait failed and we should
1171 * try again.  Returns -1 if we should abort.  Only handles DYING.  Callers
1172 * need to lock to protect the children tailq and reaping bits.  Callers must
1173 * decref the child on success. */
1174static pid_t __try_wait(struct proc *parent, struct proc *child,
1175                        int *ret_status, int options)
1176{
1177        if (proc_is_dying(child)) {
1178                /* Disown returns -1 if it's already been disowned or we should
1179                 * o/w abort.  This can happen if we have concurrent waiters,
1180                 * both with pointers to the child (only one should reap).  Note
1181                 * that if we don't do this, we could go to sleep and never
1182                 * receive a cv_signal. */
1183                if (__proc_disown_child(parent, child))
1184                        return -1;
1185                /* despite disowning, the child won't be freed til we drop this
1186                 * ref held by this function, so it is safe to access the
1187                 * memory.
1188                 *
1189                 * Note the exit code one byte in the 0xff00 spot.  Check out
1190                 * glibc's posix/sys/wait.h and bits/waitstatus.h for more info.
1191                 * If we ever deal with signalling and stopping, we'll need to
1192                 * do some more work here.*/
1193                *ret_status = (child->exitcode & 0xff) << 8;
1194                return child->pid;
1195        }
1196        return 0;
1197}
1198
1199/* Helper, like __try_wait, but attempts a wait on any of the children,
1200 * returning the specific PID we waited on, 0 to try again (a waitable exists),
1201 * and -1 to abort (no children/waitables exist).  Callers need to lock to
1202 * protect the children tailq and reaping bits.  Callers must decref the child,
1203 * if successful. */
1204static pid_t __try_wait_any(struct proc *parent, int *ret_status, int options,
1205                            struct proc **child)
1206{
1207        struct proc *i, *temp;
1208        pid_t retval;
1209
1210        if (TAILQ_EMPTY(&parent->children))
1211                return -1;
1212        /* Could have concurrent waiters mucking with the tailq, caller must
1213         * lock */
1214        TAILQ_FOREACH_SAFE(i, &parent->children, sibling_link, temp) {
1215                retval = __try_wait(parent, i, ret_status, options);
1216                /* This catches a thread causing a wait to fail but not taking
1217                 * the child off the list before unlocking.  Should never
1218                 * happen. */
1219                assert(retval != -1);
1220                /* Succeeded, return the pid of the child we waited on */
1221                if (retval) {
1222                        *child = i;
1223                        return retval;
1224                }
1225        }
1226        assert(retval == 0);
1227        return 0;
1228}
1229
1230/* Waits on a particular child, returns the pid of the child waited on, and
1231 * puts the ret status in *ret_status.  Returns the pid if we succeeded, 0 if
1232 * the child was not waitable and WNOHANG, and -1 on error. */
1233static pid_t wait_one(struct proc *parent, struct proc *child, int *ret_status,
1234                      int options)
1235{
1236        pid_t retval;
1237        struct cv_lookup_elm cle;
1238
1239        cv_lock(&parent->child_wait);
1240        __reg_abortable_cv(&cle, &parent->child_wait);
1241        /* retval == 0 means we should block */
1242        retval = __try_wait(parent, child, ret_status, options);
1243        if ((retval == 0) && (options & WNOHANG))
1244                goto out_unlock;
1245        while (!retval) {
1246                if (should_abort(&cle)) {
1247                        retval = -1;
1248                        set_error(EINTR, "wait aborted");
1249                        goto out_unlock;
1250                }
1251                cv_wait(&parent->child_wait);
1252                /* Any child can wake us up, but we check for the particular
1253                 * child we care about */
1254                retval = __try_wait(parent, child, ret_status, options);
1255        }
1256        if (retval == -1) {
1257                /* Child was already waited on by a concurrent syscall. */
1258                set_errno(ECHILD);
1259        }
1260        /* Fallthrough */
1261out_unlock:
1262        cv_unlock(&parent->child_wait);
1263        dereg_abortable_cv(&cle);
1264        if (retval > 0)
1265                proc_decref(child);
1266        return retval;
1267}
1268
1269/* Waits on any child, returns the pid of the child waited on, and puts the ret
1270 * status in *ret_status.  Is basically a waitpid(-1, ... );  See wait_one for
1271 * more details.  Returns -1 if there are no children to wait on, and returns 0
1272 * if there are children and we need to block but WNOHANG was set. */
1273static pid_t wait_any(struct proc *parent, int *ret_status, int options)
1274{
1275        pid_t retval;
1276        struct cv_lookup_elm cle;
1277        struct proc *child;
1278
1279        cv_lock(&parent->child_wait);
1280        __reg_abortable_cv(&cle, &parent->child_wait);
1281        retval = __try_wait_any(parent, ret_status, options, &child);
1282        if ((retval == 0) && (options & WNOHANG))
1283                goto out_unlock;
1284        while (!retval) {
1285                if (should_abort(&cle)) {
1286                        retval = -1;
1287                        set_error(EINTR, "wait aborted");
1288                        goto out_unlock;
1289                }
1290                cv_wait(&parent->child_wait);
1291                /* Any child can wake us up from the CV.  This is a linear
1292                 * __try_wait scan.  If we have a lot of children, we could
1293                 * optimize this. */
1294                retval = __try_wait_any(parent, ret_status, options, &child);
1295        }
1296        if (retval == -1)
1297                assert(TAILQ_EMPTY(&parent->children));
1298        /* Fallthrough */
1299out_unlock:
1300        cv_unlock(&parent->child_wait);
1301        dereg_abortable_cv(&cle);
1302        if (retval > 0)
1303                proc_decref(child);
1304        return retval;
1305}
1306
1307/* Note: we only allow waiting on children (no such thing as threads, for
1308 * instance).  Right now we only allow waiting on termination (not signals),
1309 * and we don't have a way for parents to disown their children (such as
1310 * ignoring SIGCHLD, see man 2 waitpid's Notes).
1311 *
1312 * We don't bother with stop/start signals here, though we can probably build
1313 * it in the helper above.
1314 *
1315 * Returns the pid of who we waited on, or -1 on error, or 0 if we couldn't
1316 * wait (WNOHANG). */
1317static pid_t sys_waitpid(struct proc *parent, pid_t pid, int *status,
1318                         int options)
1319{
1320        struct proc *child;
1321        pid_t retval = 0;
1322        int ret_status = 0;
1323
1324        sysc_save_str("waitpid on %d", pid);
1325        /* -1 is the signal for 'any child' */
1326        if (pid == -1) {
1327                retval = wait_any(parent, &ret_status, options);
1328                goto out;
1329        }
1330        child = pid2proc(pid);
1331        if (!child) {
1332                set_errno(ECHILD);      /* ECHILD also used for no proc */
1333                retval = -1;
1334                goto out;
1335        }
1336        if (!(parent->pid == child->ppid)) {
1337                set_errno(ECHILD);
1338                retval = -1;
1339                goto out_decref;
1340        }
1341        retval = wait_one(parent, child, &ret_status, options);
1342        /* fall-through */
1343out_decref:
1344        proc_decref(child);
1345out:
1346        /* ignoring / don't care about memcpy's retval here. */
1347        if (status)
1348                memcpy_to_user(parent, status, &ret_status, sizeof(ret_status));
1349        printd("[PID %d] waited for PID %d, got retval %d (status 0x%x)\n",
1350               parent->pid, pid, retval, ret_status);
1351        return retval;
1352}
1353
1354/************** Memory Management Syscalls **************/
1355
1356static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
1357                      int flags, int fd, off_t offset)
1358{
1359        return mmap(p, addr, len, prot, flags, fd, offset);
1360}
1361
1362static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
1363{
1364        return mprotect(p, (uintptr_t)addr, len, prot);
1365}
1366
1367static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
1368{
1369        return munmap(p, (uintptr_t)addr, len);
1370}
1371
1372static ssize_t sys_shared_page_alloc(env_t* p1,
1373                                     void **_addr, pid_t p2_id,
1374                                     int p1_flags, int p2_flags
1375                                    )
1376{
1377        printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
1378        return -1;
1379}
1380
1381static int sys_shared_page_free(env_t* p1, void *addr, pid_t p2)
1382{
1383        return -1;
1384}
1385
1386/* Helper, to do the actual provisioning of a resource to a proc */
1387static int prov_resource(struct proc *target, unsigned int res_type,
1388                         long res_val)
1389{
1390        switch (res_type) {
1391        case (RES_CORES):
1392                /* in the off chance we have a kernel scheduler that can't
1393                 * provision, we'll need to change this. */
1394                return provision_core(target, res_val);
1395        default:
1396                printk("[kernel] got provisioning for unknown resource %d\n",
1397                       res_type);
1398                set_errno(ENOENT);      /* or EINVAL? */
1399                return -1;
1400        }
1401}
1402
1403/* Rough syscall to provision res_val of type res_type to target_pid */
1404static int sys_provision(struct proc *p, int target_pid,
1405                         unsigned int res_type, long res_val)
1406{
1407        struct proc *target = pid2proc(target_pid);
1408        int retval;
1409
1410        if (!target) {
1411                if (target_pid == 0)
1412                        return prov_resource(0, res_type, res_val);
1413                /* debugging interface */
1414                if (target_pid == -1)
1415                        print_coreprov_map();
1416                set_errno(ESRCH);
1417                return -1;
1418        }
1419        retval = prov_resource(target, res_type, res_val);
1420        proc_decref(target);
1421        return retval;
1422}
1423
1424/* Untested.  Will notify the target on the given vcore, if the caller controls
1425 * the target.  Will honor the target's wanted/vcoreid.  u_ne can be NULL. */
1426static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
1427                      struct event_msg *u_msg)
1428{
1429        struct event_msg local_msg = {0};
1430        struct proc *target = get_controllable_proc(p, target_pid);
1431
1432        if (!target)
1433                return -1;
1434        /* if the user provided an ev_msg, copy it in and use that */
1435        if (u_msg) {
1436                if (memcpy_from_user(p, &local_msg, u_msg,
1437                                     sizeof(struct event_msg))) {
1438                        proc_decref(target);
1439                        set_errno(EINVAL);
1440                        return -1;
1441                }
1442        } else {
1443                local_msg.ev_type = ev_type;
1444        }
1445        send_kernel_event(target, &local_msg, 0);
1446        proc_decref(target);
1447        return 0;
1448}
1449
1450/* Will notify the calling process on the given vcore, independently of WANTED
1451 * or advertised vcoreid.  If you change the parameters, change pop_user_ctx().
1452 */
1453static int sys_self_notify(struct proc *p, uint32_t vcoreid,
1454                           unsigned int ev_type, struct event_msg *u_msg,
1455                           bool priv)
1456{
1457        struct event_msg local_msg = {0};
1458
1459        /* if the user provided an ev_msg, copy it in and use that */
1460        if (u_msg) {
1461                if (memcpy_from_user(p, &local_msg, u_msg,
1462                                     sizeof(struct event_msg))) {
1463                        set_errno(EINVAL);
1464                        return -1;
1465                }
1466        } else {
1467                local_msg.ev_type = ev_type;
1468        }
1469        if (local_msg.ev_type >= MAX_NR_EVENT) {
1470                printk("[kernel] received self-notify for vcoreid %d, "
1471                       "ev_type %d, u_msg %p, u_msg->type %d\n", vcoreid,
1472                       ev_type, u_msg, u_msg ? u_msg->ev_type : 0);
1473                return -1;
1474        }
1475        if (!proc_vcoreid_is_safe(p, vcoreid)) {
1476                set_error(EINVAL, "vcoreid %d out of range %d", vcoreid,
1477                          p->procinfo->max_vcores);
1478                return -1;
1479        }
1480        /* this will post a message and IPI, regardless of
1481         * wants/needs/debutantes.*/
1482        post_vcore_event(p, &local_msg, vcoreid,
1483                         priv ? EVENT_VCORE_PRIVATE : 0);
1484        proc_notify(p, vcoreid);
1485        return 0;
1486}
1487
1488static int sys_send_event(struct proc *p, struct event_queue *ev_q,
1489                          struct event_msg *u_msg, uint32_t vcoreid)
1490{
1491        struct event_msg local_msg = {0};
1492
1493        if (memcpy_from_user_errno(p, &local_msg, u_msg,
1494                                   sizeof(struct event_msg))) {
1495                return -1;
1496        }
1497        if (!is_user_rwaddr(ev_q, sizeof(struct event_queue))) {
1498                set_error(EINVAL, "bad event_queue %p", ev_q);
1499                return -1;
1500        }
1501        if (!proc_vcoreid_is_safe(p, vcoreid)) {
1502                set_error(EINVAL, "vcoreid %d out of range %d", vcoreid,
1503                          p->procinfo->max_vcores);
1504                return -1;
1505        }
1506        send_event(p, ev_q, &local_msg, vcoreid);
1507        return 0;
1508}
1509
1510/* Puts the calling core into vcore context, if it wasn't already, via a
1511 * self-IPI / active notification.  Barring any weird unmappings, we just send
1512 * ourselves a __notify. */
1513static int sys_vc_entry(struct proc *p)
1514{
1515        send_kernel_message(core_id(), __notify, (long)p, 0, 0, KMSG_ROUTINE);
1516        return 0;
1517}
1518
1519/* This will halt the core, waking on an IRQ.  These could be kernel IRQs for
1520 * things like timers or devices, or they could be IPIs for RKMs (__notify for
1521 * an evq with IPIs for a syscall completion, etc).  With arch support, this
1522 * will also wake on a write to notif_pending.
1523 *
1524 * We don't need to finish the syscall early (worried about the syscall struct,
1525 * on the vcore's stack).  The syscall will finish before any __preempt RKM
1526 * executes, so the vcore will not restart somewhere else before the syscall
1527 * completes (unlike with yield, where the syscall itself adjusts the vcore
1528 * structures).
1529 *
1530 * In the future, RKM code might avoid sending IPIs if the core is already in
1531 * the kernel.  That code will need to check the CPU's state in some manner, and
1532 * send if the core is halted/idle.  Or perhaps use mwait, if there's arch
1533 * support.
1534 *
1535 * The core must wake up for RKMs, including RKMs that arrive while the kernel
1536 * is trying to halt.
1537 *
1538 * If our hardware supports something like monitor/mwait, we'll abort if
1539 * notif_pending was or gets set.  Note that whoever writes notif_pending may
1540 * send an IPI regardless of whether or not we have mwait.  That's up to the
1541 * ev_q settings (so basically userspace).  If userspace doesn't want an IPI, a
1542 * notif will wake it up, but it won't break it out of a uthread loop. */
1543static int sys_halt_core(struct proc *p, unsigned long usec)
1544{
1545        struct per_cpu_info *pcpui = this_pcpui_ptr();
1546        struct preempt_data *vcpd;
1547
1548        /* The user can only halt CG cores!  (ones it owns) */
1549        if (management_core())
1550                return -1;
1551        rcu_report_qs();
1552        disable_irq();
1553        /* both for accounting and possible RKM optimizations */
1554        __set_cpu_state(pcpui, CPU_STATE_IDLE);
1555        wrmb();
1556        if (has_routine_kmsg()) {
1557                __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1558                enable_irq();
1559                return 0;
1560        }
1561        vcpd = &p->procdata->vcore_preempt_data[pcpui->owning_vcoreid];
1562        /* We pretend to not be in vcore context so other cores will send us
1563         * IPIs (__notify).  If we do get a __notify, we'll have set
1564         * notif_disabled back on before we handle the message, since it's a
1565         * routine KMSG.  Note that other vcores will think we are not in vcore
1566         * context.  This is no different to when we pop contexts: 'briefly'
1567         * leave VC ctx, check notif_pending, and (possibly) abort and set
1568         * notif_disabled. */
1569        vcpd->notif_disabled = false;
1570        cpu_halt_notif_pending(vcpd);
1571        __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1572        vcpd->notif_disabled = true;
1573        enable_irq();
1574        return 0;
1575}
1576
1577/* Changes a process into _M mode, or -EINVAL if it already is an mcp.
1578 * __proc_change_to_m() returns and we'll eventually finish the sysc later.  The
1579 * original context may restart on a remote core before we return and finish,
1580 * but that's fine thanks to the async kernel interface. */
1581static int sys_change_to_m(struct proc *p)
1582{
1583        int retval = proc_change_to_m(p);
1584
1585        /* convert the kernel error code into (-1, errno) */
1586        if (retval) {
1587                set_errno(-retval);
1588                retval = -1;
1589        }
1590        return retval;
1591}
1592
1593/* Assists the user/2LS by atomically running *ctx and leaving vcore context.
1594 * Normally, the user can do this themselves, but x86 VM contexts need kernel
1595 * support.  The caller ought to be in vcore context, and if a notif is pending,
1596 * then the calling vcore will restart in a fresh VC ctx (as if it was notified
1597 * or did a sys_vc_entry).
1598 *
1599 * Note that this will set the TLS too, which is part of the context.  Parlib's
1600 * pop_user_ctx currently does *not* do this, since the TLS is managed
1601 * separately.  If you want to use this syscall for testing, you'll need to 0
1602 * out fsbase and conditionally write_msr in proc_pop_ctx(). */
1603static int sys_pop_ctx(struct proc *p, struct user_context *ctx)
1604{
1605        int pcoreid = core_id();
1606        struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1607        int vcoreid = pcpui->owning_vcoreid;
1608        struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1609
1610        /* With change_to, there's a bunch of concerns about changing the vcore
1611         * map, since the kernel may have already locked and sent preempts,
1612         * deaths, etc.
1613         *
1614         * In this case, we don't care as much.  Other than notif_pending and
1615         * notif_disabled, it's more like we're just changing a few registers in
1616         * cur_ctx.  We can safely order-after any kernel messages or other
1617         * changes, as if the user had done all of the changes we'll make and
1618         * then did a no-op syscall.
1619         *
1620         * Since we are mucking with current_ctx, it is important that we don't
1621         * block before or during this syscall. */
1622        arch_finalize_ctx(pcpui->cur_ctx);
1623        if (copy_from_user(pcpui->cur_ctx, ctx, sizeof(struct user_context))) {
1624                /* The 2LS isn't really in a position to handle errors.  At the
1625                 * very least, we can print something and give them a fresh vc
1626                 * ctx. */
1627                printk("[kernel] unable to copy user_ctx, 2LS bug\n");
1628                memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
1629                proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
1630                              vcpd->vcore_stack, vcpd->vcore_tls_desc);
1631                return -1;
1632        }
1633        proc_secure_ctx(pcpui->cur_ctx);
1634        /* The caller leaves vcore context no matter what.  We'll put them back
1635         * in if they missed a message. */
1636        vcpd->notif_disabled = FALSE;
1637        wrmb(); /* order disabled write before pending read */
1638        if (vcpd->notif_pending)
1639                send_kernel_message(pcoreid, __notify, (long)p, 0, 0,
1640                                    KMSG_ROUTINE);
1641        return 0;
1642}
1643
1644static int sys_vmm_add_gpcs(struct proc *p, unsigned int nr_more_gpcs,
1645                            struct vmm_gpcore_init *gpcis)
1646{
1647        ERRSTACK(1);
1648        struct vmm *vmm = &p->vmm;
1649
1650        /* We do a copy_from_user in __vmm_add_gpcs, but it ought to be clear
1651         * from the syscall.c code if we did our error checking. */
1652        if (!is_user_rwaddr(gpcis, sizeof(struct vmm_gpcore_init) *
1653                                   nr_more_gpcs)) {
1654                set_error(EINVAL, "bad user addr %p + %p", gpcis,
1655                          sizeof(struct vmm_gpcore_init) * nr_more_gpcs);
1656                return -1;
1657        }
1658        qlock(&vmm->qlock);
1659        if (waserror()) {
1660                qunlock(&vmm->qlock);
1661                poperror();
1662                return -1;
1663        }
1664        __vmm_struct_init(p);
1665        __vmm_add_gpcs(p, nr_more_gpcs, gpcis);
1666        qunlock(&vmm->qlock);
1667        poperror();
1668        return nr_more_gpcs;
1669}
1670
1671static int sys_vmm_poke_guest(struct proc *p, int guest_pcoreid)
1672{
1673        return vmm_poke_guest(p, guest_pcoreid);
1674}
1675
1676static int sys_vmm_ctl(struct proc *p, int cmd, unsigned long arg1,
1677                       unsigned long arg2, unsigned long arg3,
1678                       unsigned long arg4)
1679{
1680        ERRSTACK(1);
1681        int ret;
1682        struct vmm *vmm = &p->vmm;
1683
1684        /* Protects against concurrent setters and for gets that are not atomic
1685         * reads (say, multiple exec ctls). */
1686        qlock(&vmm->qlock);
1687        if (waserror()) {
1688                qunlock(&vmm->qlock);
1689                poperror();
1690                return -1;
1691        }
1692        __vmm_struct_init(p);
1693        switch (cmd) {
1694        case VMM_CTL_GET_EXITS:
1695                if (vmm->amd)
1696                        error(ENOTSUP, "AMD VMMs unsupported");
1697                ret = vmx_ctl_get_exits(&vmm->vmx);
1698                break;
1699        case VMM_CTL_SET_EXITS:
1700                if (arg1 & ~VMM_CTL_ALL_EXITS)
1701                        error(EINVAL, "Bad vmm_ctl_exits %x (%x)", arg1,
1702                              VMM_CTL_ALL_EXITS);
1703                if (vmm->amd)
1704                        error(ENOTSUP, "AMD VMMs unsupported");
1705                ret = vmx_ctl_set_exits(&vmm->vmx, arg1);
1706                break;
1707        case VMM_CTL_GET_FLAGS:
1708                ret = vmm->flags;
1709                break;
1710        case VMM_CTL_SET_FLAGS:
1711                if (arg1 & ~VMM_CTL_ALL_FLAGS)
1712                        error(EINVAL,
1713                              "Bad vmm_ctl flags.  Got 0x%lx, allowed 0x%lx\n",
1714                              arg1, VMM_CTL_ALL_FLAGS);
1715                vmm->flags = arg1;
1716                ret = 0;
1717                break;
1718        default:
1719                error(EINVAL, "Bad vmm_ctl cmd %d", cmd);
1720        }
1721        qunlock(&vmm->qlock);
1722        poperror();
1723        return ret;
1724}
1725
1726/* Pokes the ksched for the given resource for target_pid.  If the target pid
1727 * == 0, we just poke for the calling process.  The common case is poking for
1728 * self, so we avoid the lookup.
1729 *
1730 * Not sure if you could harm someone via asking the kernel to look at them, so
1731 * we'll do a 'controls' check for now.  In the future, we might have something
1732 * in the ksched that limits or penalizes excessive pokes. */
1733static int sys_poke_ksched(struct proc *p, int target_pid,
1734                           unsigned int res_type)
1735{
1736        struct proc *target;
1737        int retval = 0;
1738
1739        if (!target_pid) {
1740                poke_ksched(p, res_type);
1741                return 0;
1742        }
1743        target = pid2proc(target_pid);
1744        if (!target) {
1745                set_errno(ESRCH);
1746                return -1;
1747        }
1748        if (!proc_controls(p, target)) {
1749                set_errno(EPERM);
1750                retval = -1;
1751                goto out;
1752        }
1753        poke_ksched(target, res_type);
1754out:
1755        proc_decref(target);
1756        return retval;
1757}
1758
1759static int sys_abort_sysc(struct proc *p, struct syscall *sysc)
1760{
1761        return abort_sysc(p, (uintptr_t)sysc);
1762}
1763
1764static int sys_abort_sysc_fd(struct proc *p, int fd)
1765{
1766        /* Consider checking for a bad fd.  Doesn't matter now, since we only
1767         * look for actual syscalls blocked that had used fd. */
1768        return abort_all_sysc_fd(p, fd);
1769}
1770
1771static unsigned long sys_populate_va(struct proc *p, uintptr_t va,
1772                                     unsigned long nr_pgs)
1773{
1774        return populate_va(p, ROUNDDOWN(va, PGSIZE), nr_pgs);
1775}
1776
1777static intreg_t sys_read(struct proc *p, int fd, void *buf, size_t len)
1778{
1779        if (!is_user_rwaddr(buf, len)) {
1780                set_error(EINVAL, "bad user addr %p + %p", buf, len);
1781                return -1;
1782        }
1783        sysc_save_str("read on fd %d", fd);
1784        return sysread(fd, buf, len);
1785}
1786
1787static intreg_t sys_write(struct proc *p, int fd, const void *buf, size_t len)
1788{
1789        /* We'll let this one include read-only areas, unlike most other
1790         * syscalls that take bufs created and written by the user. */
1791        if (!is_user_raddr(buf, len)) {
1792                set_error(EINVAL, "bad user addr %p + %p", buf, len);
1793                return -1;
1794        }
1795        sysc_save_str("write on fd %d", fd);
1796        return syswrite(fd, (void*)buf, len);
1797}
1798
1799/* Checks args/reads in the path, opens the file (relative to fromfd if the path
1800 * is not absolute), and inserts it into the process's open file list. */
1801static intreg_t sys_openat(struct proc *p, int fromfd, const char *path,
1802                           size_t path_l, int oflag, int mode)
1803{
1804        int fd;
1805        char *t_path;
1806
1807        printd("File %s Open attempt oflag %x mode %x\n", path, oflag, mode);
1808        if ((oflag & O_PATH) && (oflag & O_ACCMODE)) {
1809                set_error(EINVAL, "Cannot open O_PATH with any I/O perms (O%o)",
1810                          oflag);
1811                return -1;
1812        }
1813        if (oflag & O_EXCL && !(oflag & O_CREATE)) {
1814                set_error(EINVAL, "Cannot open O_EXCL without O_CREATE");
1815                return -1;
1816        }
1817        t_path = copy_in_path(p, path, path_l);
1818        if (!t_path)
1819                return -1;
1820        sysc_save_str("open %s at fd %d", t_path, fromfd);
1821        mode &= ~p->umask;
1822        mode &= S_PMASK;
1823        static_assert(!(DMMODE_BITS & S_PMASK));
1824        fd = sysopenat(fromfd, t_path, oflag, mode);
1825        free_path(p, t_path);
1826        printd("File %s Open, fd=%d\n", path, fd);
1827        return fd;
1828}
1829
1830static intreg_t sys_close(struct proc *p, int fd)
1831{
1832        return sysclose(fd);
1833}
1834
1835static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
1836{
1837        struct kstat *kbuf;
1838
1839        kbuf = kmalloc(sizeof(struct kstat), 0);
1840        if (!kbuf) {
1841                set_errno(ENOMEM);
1842                return -1;
1843        }
1844        if (sysfstatakaros(fd, (struct kstat *)kbuf) < 0) {
1845                kfree(kbuf);
1846                return -1;
1847        }
1848        /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer
1849         */
1850        if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1851                kfree(kbuf);
1852                return -1;
1853        }
1854        kfree(kbuf);
1855        return 0;
1856}
1857
1858/* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
1859 * treat a symlink for the final item, which (probably) will be controlled by
1860 * the lookup flags */
1861static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
1862                            struct kstat *u_stat, int flags)
1863{
1864        struct kstat *kbuf;
1865        char *t_path = copy_in_path(p, path, path_l);
1866        int retval = 0;
1867
1868        if (!t_path)
1869                return -1;
1870        kbuf = kmalloc(sizeof(struct kstat), 0);
1871        if (!kbuf) {
1872                set_errno(ENOMEM);
1873                retval = -1;
1874                goto out_with_path;
1875        }
1876        retval = sysstatakaros(t_path, (struct kstat *)kbuf, flags);
1877        if (retval < 0)
1878                goto out_with_kbuf;
1879        /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer
1880         */
1881        if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat)))
1882                retval = -1;
1883        /* Fall-through */
1884out_with_kbuf:
1885        kfree(kbuf);
1886out_with_path:
1887        free_path(p, t_path);
1888        return retval;
1889}
1890
1891/* Follow a final symlink */
1892static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1893                         struct kstat *u_stat)
1894{
1895        return stat_helper(p, path, path_l, u_stat, 0);
1896}
1897
1898/* Don't follow a final symlink */
1899static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1900                          struct kstat *u_stat)
1901{
1902        return stat_helper(p, path, path_l, u_stat, O_NOFOLLOW);
1903}
1904
1905intreg_t sys_fcntl(struct proc *p, int fd, int cmd, unsigned long arg1,
1906                   unsigned long arg2, unsigned long arg3, unsigned long arg4)
1907{
1908        switch (cmd) {
1909        case (F_DUPFD):
1910                /* TODO: glibc uses regular DUPFD for dup2, which is racy. */
1911                return sysdup(fd, arg1, FALSE);
1912        case (F_GETFD):
1913                return fd_get_fd_flags(&p->open_files, fd);
1914        case (F_SETFD):
1915                if (arg1 & ~FD_VALID_FLAGS) {
1916                        set_error(EINVAL, "Bad FD flags %p, valid are %p", arg1,
1917                                  FD_VALID_FLAGS);
1918                        return -1;
1919                }
1920                return fd_set_fd_flags(&p->open_files, fd, arg1);
1921        case (F_SYNC):
1922                return fd_chan_ctl(fd, CCTL_SYNC, 0, 0, 0, 0);
1923        case (F_GETFL):
1924                return fd_getfl(fd);
1925        case (F_SETFL):
1926                return fd_chan_ctl(fd, CCTL_SET_FL, arg1, 0, 0, 0);
1927        default:
1928                /* chanctl and fcntl share flags */
1929                if (cmd >= F_CHANCTL_BASE)
1930                        return fd_chan_ctl(fd, cmd, arg1, arg2, arg3, arg4);
1931                set_error(EINVAL, "Unsupported fcntl cmd %d", cmd);
1932                return -1;
1933        }
1934}
1935
1936static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1937                           int mode)
1938{
1939        int retval;
1940        struct dir *dir;
1941        char *t_path = copy_in_path(p, path, path_l);
1942
1943        if (!t_path)
1944                return -1;
1945        dir = sysdirstat(t_path);
1946        if (!dir)
1947                goto out;
1948        if ((mode == F_OK) ||
1949            caller_has_dir_perms(dir, access_bits_to_omode(mode)))
1950                retval = 0;
1951        kfree(dir);
1952out:
1953        free_path(p, t_path);
1954        return retval;
1955}
1956
1957intreg_t sys_umask(struct proc *p, int mask)
1958{
1959        int old_mask = p->umask;
1960
1961        p->umask = mask & S_PMASK;
1962        return old_mask;
1963}
1964
1965/* 64 bit seek, with the off64_t passed in via two (potentially 32 bit) off_ts.
1966 * We're supporting both 32 and 64 bit kernels/userspaces, but both use the
1967 * llseek syscall with 64 bit parameters. */
1968static intreg_t sys_llseek(struct proc *p, int fd, off_t offset_hi,
1969                           off_t offset_lo, off64_t *result, int whence)
1970{
1971        off64_t retoff = 0;
1972        off64_t tempoff = 0;
1973        int ret = 0;
1974
1975        tempoff = offset_hi;
1976        tempoff <<= 32;
1977        tempoff |= offset_lo;
1978        retoff = sysseek(fd, tempoff, whence);
1979        ret = (retoff < 0);
1980        if (ret)
1981                return -1;
1982        if (memcpy_to_user_errno(p, result, &retoff, sizeof(off64_t)))
1983                return -1;
1984        return 0;
1985}
1986
1987intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1988                  char *new_path, size_t new_l)
1989{
1990        int ret;
1991        char *t_oldpath = copy_in_path(p, old_path, old_l);
1992
1993        if (t_oldpath == NULL)
1994                return -1;
1995        char *t_newpath = copy_in_path(p, new_path, new_l);
1996
1997        if (t_newpath == NULL) {
1998                free_path(p, t_oldpath);
1999                return -1;
2000        }
2001        set_error(ENOSYS, "no link");
2002        ret = -1;
2003        free_path(p, t_oldpath);
2004        free_path(p, t_newpath);
2005        return ret;
2006}
2007
2008intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
2009{
2010        int retval;
2011        char *t_path = copy_in_path(p, path, path_l);
2012
2013        if (!t_path)
2014                return -1;
2015        retval = sysremove(t_path);
2016        free_path(p, t_path);
2017        return retval;
2018}
2019
2020intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
2021                     char *new_path, size_t new_l)
2022{
2023        int ret;
2024        char *t_oldpath = copy_in_path(p, old_path, old_l);
2025
2026        if (t_oldpath == NULL)
2027                return -1;
2028        char *t_newpath = copy_in_path(p, new_path, new_l);
2029
2030        if (t_newpath == NULL) {
2031                free_path(p, t_oldpath);
2032                return -1;
2033        }
2034        ret = syssymlink(t_newpath, t_oldpath);
2035        free_path(p, t_oldpath);
2036        free_path(p, t_newpath);
2037        return ret;
2038}
2039
2040intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
2041                      char *u_buf, size_t buf_l)
2042{
2043        char *symname = NULL;
2044        ssize_t copy_amt;
2045        int ret = -1;
2046        char *t_path = copy_in_path(p, path, path_l);
2047        struct dir *dir;
2048
2049        if (t_path == NULL)
2050                return -1;
2051        dir = sysdirlstat(t_path);
2052        if (!dir)
2053                return -1;
2054        if (!(dir->mode & DMSYMLINK))
2055                set_error(EINVAL, "not a symlink: %s", t_path);
2056        else
2057                symname = dir->ext;
2058        free_path(p, t_path);
2059        if (symname){
2060                copy_amt = strnlen(symname, buf_l - 1) + 1;
2061                if (!memcpy_to_user_errno(p, u_buf, symname, copy_amt))
2062                        ret = copy_amt - 1;
2063        }
2064        kfree(dir);
2065        return ret;
2066}
2067
2068static intreg_t sys_chdir(struct proc *p, pid_t pid, const char *path,
2069                          size_t path_l)
2070{
2071        int retval;
2072        char *t_path;
2073        struct proc *target = get_controllable_proc(p, pid);
2074
2075        if (!target)
2076                return -1;
2077        if ((target != p) && (target->state != PROC_CREATED)) {
2078                proc_decref(target);
2079                set_error(EINVAL, "pid %d has already started", pid);
2080                return -1;
2081        }
2082        t_path = copy_in_path(p, path, path_l);
2083        if (!t_path) {
2084                proc_decref(target);
2085                return -1;
2086        }
2087        retval = syschdir(target, t_path);
2088        free_path(p, t_path);
2089        proc_decref(target);
2090        return retval;
2091}
2092
2093static intreg_t sys_fchdir(struct proc *p, pid_t pid, int fd)
2094{
2095        int retval;
2096        struct proc *target = get_controllable_proc(p, pid);
2097
2098        if (!target)
2099                return -1;
2100        if ((target != p) && (target->state != PROC_CREATED)) {
2101                proc_decref(target);
2102                set_error(EINVAL, "pid %d has already started", pid);
2103                return -1;
2104        }
2105        retval = sysfchdir(target, fd);
2106        proc_decref(target);
2107        return retval;
2108}
2109
2110/* Note cwd_l is not a strlen, it's an absolute size.
2111 * Same as with readlink, we give them a null-terminated string, and we return
2112 * strlen, which doesn't include the \0.  If we can't give them the \0, we'll
2113 * error out.  Our readlink also does that, which is not POSIX-like. */
2114intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
2115{
2116        ssize_t retval = -1;
2117        size_t copy_amt;
2118        char *k_cwd;
2119
2120        k_cwd = sysgetcwd();
2121        if (!k_cwd) {
2122                set_error(EINVAL, "unable to getcwd");
2123                return -1;
2124        }
2125        copy_amt = strlen(k_cwd) + 1;
2126        if (copy_amt > cwd_l) {
2127                set_error(ERANGE, "getcwd buf too small, needed %d", copy_amt);
2128                goto out;
2129        }
2130        if (!memcpy_to_user_errno(p, u_cwd, k_cwd, copy_amt))
2131                retval = copy_amt - 1;
2132out:
2133        kfree(k_cwd);
2134        return retval;
2135}
2136
2137intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
2138{
2139        int retval;
2140        char *t_path = copy_in_path(p, path, path_l);
2141
2142        if (!t_path)
2143                return -1;
2144        mode &= ~p->umask;
2145        mode &= S_PMASK;
2146        static_assert(!(DMMODE_BITS & S_PMASK));
2147        retval = syscreate(t_path, O_READ, DMDIR | mode);
2148        if (retval >= 0) {
2149                sysclose(retval);
2150                retval = 0;
2151        }
2152        free_path(p, t_path);
2153        return retval;
2154}
2155
2156intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
2157{
2158        int retval;
2159        char *t_path = copy_in_path(p, path, path_l);
2160
2161        if (!t_path)
2162                return -1;
2163        retval = sysremove(t_path);
2164        free_path(p, t_path);
2165        return retval;
2166}
2167
2168intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
2169{
2170        int retval = 0;
2171        /* TODO: actually support this call on tty FDs.  Right now, we just fake
2172         * what my linux box reports for a bash pty. */
2173        struct termios *kbuf = kmalloc(sizeof(struct termios), 0);
2174
2175        kbuf->c_iflag = 0x2d02;
2176        kbuf->c_oflag = 0x0005;
2177        kbuf->c_cflag = 0x04bf;
2178        kbuf->c_lflag = 0x8a3b;
2179        kbuf->c_line = 0x0;
2180        kbuf->c_ispeed = 0xf;
2181        kbuf->c_ospeed = 0xf;
2182        kbuf->c_cc[0] = 0x03;
2183        kbuf->c_cc[1] = 0x1c;
2184        kbuf->c_cc[2] = 0x7f;
2185        kbuf->c_cc[3] = 0x15;
2186        kbuf->c_cc[4] = 0x04;
2187        kbuf->c_cc[5] = 0x00;
2188        kbuf->c_cc[6] = 0x01;
2189        kbuf->c_cc[7] = 0xff;
2190        kbuf->c_cc[8] = 0x11;
2191        kbuf->c_cc[9] = 0x13;
2192        kbuf->c_cc[10] = 0x1a;
2193        kbuf->c_cc[11] = 0xff;
2194        kbuf->c_cc[12] = 0x12;
2195        kbuf->c_cc[13] = 0x0f;
2196        kbuf->c_cc[14] = 0x17;
2197        kbuf->c_cc[15] = 0x16;
2198        kbuf->c_cc[16] = 0xff;
2199        kbuf->c_cc[17] = 0x00;
2200        kbuf->c_cc[18] = 0x00;
2201        kbuf->c_cc[19] = 0x00;
2202        kbuf->c_cc[20] = 0x00;
2203        kbuf->c_cc[21] = 0x00;
2204        kbuf->c_cc[22] = 0x00;
2205        kbuf->c_cc[23] = 0x00;
2206        kbuf->c_cc[24] = 0x00;
2207        kbuf->c_cc[25] = 0x00;
2208        kbuf->c_cc[26] = 0x00;
2209        kbuf->c_cc[27] = 0x00;
2210        kbuf->c_cc[28] = 0x00;
2211        kbuf->c_cc[29] = 0x00;
2212        kbuf->c_cc[30] = 0x00;
2213        kbuf->c_cc[31] = 0x00;
2214
2215        if (memcpy_to_user_errno(p, termios_p, kbuf, sizeof(struct termios)))
2216                retval = -1;
2217        kfree(kbuf);
2218        return retval;
2219}
2220
2221intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
2222                       const void *termios_p)
2223{
2224        /* TODO: do this properly too.  For now, we just say 'it worked' */
2225        return 0;
2226}
2227
2228/* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
2229 * process from thinking it can do these.  The other alternative is to have
2230 * glibc return 0 right away, though someone might want to do something with
2231 * these calls.  Someday. */
2232intreg_t sys_setuid(struct proc *p, uid_t uid)
2233{
2234        return 0;
2235}
2236
2237intreg_t sys_setgid(struct proc *p, gid_t gid)
2238{
2239        return 0;
2240}
2241
2242/* long bind(char* src_path, char* onto_path, int flag);
2243 *
2244 * The naming for the args in bind is messy historically.  We do:
2245 *              bind src_path onto_path
2246 * plan9 says bind NEW OLD, where new is *src*, and old is *onto*.
2247 * Linux says mount --bind OLD NEW, where OLD is *src* and NEW is *onto*. */
2248intreg_t sys_nbind(struct proc *p,
2249                   char *src_path, size_t src_l,
2250                   char *onto_path, size_t onto_l,
2251                   unsigned int flag)
2252
2253{
2254        int ret;
2255        char *t_srcpath = copy_in_path(p, src_path, src_l);
2256
2257        if (t_srcpath == NULL) {
2258                printd("srcpath dup failed ptr %p size %d\n", src_path, src_l);
2259                return -1;
2260        }
2261        char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2262
2263        if (t_ontopath == NULL) {
2264                free_path(p, t_srcpath);
2265                printd("ontopath dup failed ptr %p size %d\n", onto_path,
2266                       onto_l);
2267                return -1;
2268        }
2269        printd("sys_nbind: %s -> %s flag %d\n", t_srcpath, t_ontopath, flag);
2270        ret = sysbind(t_srcpath, t_ontopath, flag);
2271        free_path(p, t_srcpath);
2272        free_path(p, t_ontopath);
2273        return ret;
2274}
2275
2276/* int mount(int fd, int afd, char* onto_path, int flag, char* aname); */
2277intreg_t sys_nmount(struct proc *p,
2278                    int fd,
2279                    char *onto_path, size_t onto_l,
2280                    unsigned int flag
2281                        /* we ignore these */
2282                        /* no easy way to pass this many args anyway. *
2283                    int afd,
2284                    char *auth, size_t auth_l*/)
2285{
2286        int ret;
2287        int afd;
2288
2289        afd = -1;
2290        char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2291
2292        if (t_ontopath == NULL)
2293                return -1;
2294        /* TODO: if we ever pass in the spec/auth, copy those in. */
2295        ret = sysmount(fd, afd, t_ontopath, flag, /* spec or auth */"/");
2296        free_path(p, t_ontopath);
2297        return ret;
2298}
2299
2300/* Unmount undoes the operation of a bind or mount.  Check out
2301 * http://plan9.bell-labs.com/magic/man2html/1/bind .  Though our mount takes an
2302 * FD, not servename (aka src_path), so it's not quite the same.
2303 *
2304 * To translate between Plan 9 and Akaros, old -> onto_path.  new -> src_path.
2305 *
2306 * For unmount, src_path / new is optional.  If set, we only unmount the
2307 * bindmount that came from src_path. */
2308intreg_t sys_nunmount(struct proc *p, char *src_path, int src_l,
2309                      char *onto_path, int onto_l)
2310{
2311        int ret;
2312        char *t_ontopath, *t_srcpath;
2313
2314        t_ontopath = copy_in_path(p, onto_path, onto_l);
2315        if (t_ontopath == NULL)
2316                return -1;
2317        if (src_path) {
2318                t_srcpath = copy_in_path(p, src_path, src_l);
2319                if (t_srcpath == NULL) {
2320                        free_path(p, t_ontopath);
2321                        return -1;
2322                }
2323        } else {
2324                t_srcpath = 0;
2325        }
2326        ret = sysunmount(t_srcpath, t_ontopath);
2327        free_path(p, t_ontopath);
2328        free_path(p, t_srcpath);        /* you can free a null path */
2329        return ret;
2330}
2331
2332intreg_t sys_fd2path(struct proc *p, int fd, void *u_buf, size_t len)
2333{
2334        int ret = 0;
2335        struct chan *ch;
2336        ERRSTACK(1);
2337
2338        /* UMEM: Check the range, can PF later and kill if the page isn't
2339         * present */
2340        if (!is_user_rwaddr(u_buf, len)) {
2341                set_error(EINVAL, "bad user addr %p + %p", u_buf, len);
2342                return -1;
2343        }
2344        /* fdtochan throws */
2345        if (waserror()) {
2346                poperror();
2347                return -1;
2348        }
2349        ch = fdtochan(&current->open_files, fd, -1, FALSE, TRUE);
2350        if (snprintf(u_buf, len, "%s", channame(ch)) >= len) {
2351                set_error(ERANGE, "fd2path buf too small, needed %d", ret);
2352                ret = -1;
2353        }
2354        cclose(ch);
2355        poperror();
2356        return ret;
2357}
2358
2359intreg_t sys_wstat(struct proc *p, char *path, size_t path_l,
2360                   uint8_t *stat_m, size_t stat_sz, int flags)
2361{
2362        int retval = 0;
2363        char *t_path;
2364
2365        if (!is_user_rwaddr(stat_m, stat_sz)) {
2366                set_error(EINVAL, "bad user addr %p + %p", stat_m, stat_sz);
2367                return -1;
2368        }
2369        t_path = copy_in_path(p, path, path_l);
2370        if (!t_path)
2371                return -1;
2372        retval = syswstat(t_path, stat_m, stat_sz);
2373        free_path(p, t_path);
2374        return retval;
2375}
2376
2377intreg_t sys_fwstat(struct proc *p, int fd, uint8_t *stat_m, size_t stat_sz,
2378                    int flags)
2379{
2380        if (!is_user_rwaddr(stat_m, stat_sz)) {
2381                set_error(EINVAL, "bad user addr %p + %p", stat_m, stat_sz);
2382                return -1;
2383        }
2384        return sysfwstat(fd, stat_m, stat_sz);
2385}
2386
2387intreg_t sys_rename(struct proc *p, char *old_path, size_t old_path_l,
2388                    char *new_path, size_t new_path_l)
2389{
2390        char *from_path = copy_in_path(p, old_path, old_path_l);
2391        char *to_path = copy_in_path(p, new_path, new_path_l);
2392        int ret;
2393
2394        if ((!from_path) || (!to_path))
2395                return -1;
2396        ret = sysrename(from_path, to_path);
2397        free_path(p, from_path);
2398        free_path(p, to_path);
2399        return ret;
2400}
2401
2402/* Careful: if an FD is busy, we don't close the old object, it just fails */
2403static intreg_t sys_dup_fds_to(struct proc *p, unsigned int pid,
2404                               struct childfdmap *map, unsigned int nentries)
2405{
2406        ssize_t ret = 0;
2407        struct proc *child;
2408        int slot;
2409
2410        if (!is_user_rwaddr(map, sizeof(struct childfdmap) * nentries)) {
2411                set_error(EINVAL, "bad user addr %p + %p", map,
2412                          sizeof(struct childfdmap) * nentries);
2413                return -1;
2414        }
2415        child = get_controllable_proc(p, pid);
2416        if (!child)
2417                return -1;
2418        for (int i = 0; i < nentries; i++) {
2419                map[i].ok = -1;
2420                if (!sys_dup_to(p, map[i].parentfd, child, map[i].childfd)) {
2421                        map[i].ok = 0;
2422                        ret++;
2423                        continue;
2424                }
2425                /* probably a bug, could send EBADF, maybe via 'ok' */
2426                printk("[kernel] dup_fds_to: couldn't find %d\n", map[i].parentfd);
2427        }
2428        proc_decref(child);
2429        return ret;
2430}
2431
2432/* 0 on success, anything else is an error, with errno/errstr set */
2433static int handle_tap_req(struct proc *p, struct fd_tap_req *req)
2434{
2435        switch (req->cmd) {
2436        case (FDTAP_CMD_ADD):
2437                return add_fd_tap(p, req);
2438        case (FDTAP_CMD_REM):
2439                return remove_fd_tap(p, req->fd);
2440        default:
2441                set_error(ENOSYS, "FD Tap Command %d not supported", req->cmd);
2442                return -1;
2443        }
2444}
2445
2446/* Processes up to nr_reqs tap requests.  If a request errors out, we stop
2447 * immediately.  Returns the number processed.  If done != nr_reqs, check errno
2448 * and errstr for the last failure, which is for tap_reqs[done]. */
2449static intreg_t sys_tap_fds(struct proc *p, struct fd_tap_req *tap_reqs,
2450                            size_t nr_reqs)
2451{
2452        struct fd_tap_req *req_i = tap_reqs;
2453        int done;
2454
2455        if (!is_user_rwaddr(tap_reqs, sizeof(struct fd_tap_req) * nr_reqs)) {
2456                set_error(EINVAL, "bad user addr %p + %p", tap_reqs,
2457                          sizeof(struct fd_tap_req) * nr_reqs);
2458                return 0;
2459        }
2460        for (done = 0; done < nr_reqs; done++, req_i++) {
2461                if (handle_tap_req(p, req_i))
2462                        break;
2463        }
2464        return done;
2465}
2466
2467/************** Syscall Invokation **************/
2468
2469const struct sys_table_entry syscall_table[] = {
2470        [SYS_null] = {(syscall_t)sys_null, "null"},
2471        [SYS_block] = {(syscall_t)sys_block, "block"},
2472        [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
2473        [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
2474        [SYS_getpcoreid] = {(syscall_t)sys_getpcoreid, "getpcoreid"},
2475        [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
2476        [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
2477        [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
2478        [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
2479        [SYS_proc_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
2480        [SYS_change_vcore] = {(syscall_t)sys_change_vcore, "change_vcore"},
2481        [SYS_fork] = {(syscall_t)sys_fork, "fork"},
2482        [SYS_exec] = {(syscall_t)sys_exec, "exec"},
2483        [SYS_waitpid] = {(syscall_t)sys_waitpid, "waitpid"},
2484        [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
2485        [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
2486        [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
2487        [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
2488        [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
2489        [SYS_provision] = {(syscall_t)sys_provision, "provision"},
2490        [SYS_notify] = {(syscall_t)sys_notify, "notify"},
2491        [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
2492        [SYS_send_event] = {(syscall_t)sys_send_event, "send_event"},
2493        [SYS_vc_entry] = {(syscall_t)sys_vc_entry, "vc_entry"},
2494        [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
2495#ifdef CONFIG_ARSC_SERVER
2496        [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
2497#endif
2498        [SYS_change_to_m] = {(syscall_t)sys_change_to_m, "change_to_m"},
2499        [SYS_vmm_add_gpcs] = {(syscall_t)sys_vmm_add_gpcs, "vmm_add_gpcs"},
2500        [SYS_vmm_poke_guest] = {(syscall_t)sys_vmm_poke_guest, "vmm_poke_guest"},
2501        [SYS_vmm_ctl] = {(syscall_t)sys_vmm_ctl, "vmm_ctl"},
2502        [SYS_poke_ksched] = {(syscall_t)sys_poke_ksched, "poke_ksched"},
2503        [SYS_abort_sysc] = {(syscall_t)sys_abort_sysc, "abort_sysc"},
2504        [SYS_abort_sysc_fd] = {(syscall_t)sys_abort_sysc_fd, "abort_sysc_fd"},
2505        [SYS_populate_va] = {(syscall_t)sys_populate_va, "populate_va"},
2506        [SYS_nanosleep] = {(syscall_t)sys_nanosleep, "nanosleep"},
2507        [SYS_pop_ctx] = {(syscall_t)sys_pop_ctx, "pop_ctx"},
2508
2509        [SYS_read] = {(syscall_t)sys_read, "read"},
2510        [SYS_write] = {(syscall_t)sys_write, "write"},
2511        [SYS_openat] = {(syscall_t)sys_openat, "openat"},
2512        [SYS_close] = {(syscall_t)sys_close, "close"},
2513        [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
2514        [SYS_stat] = {(syscall_t)sys_stat, "stat"},
2515        [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
2516        [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
2517        [SYS_access] = {(syscall_t)sys_access, "access"},
2518        [SYS_umask] = {(syscall_t)sys_umask, "umask"},
2519        [SYS_llseek] = {(syscall_t)sys_llseek, "llseek"},
2520        [SYS_link] = {(syscall_t)sys_link, "link"},
2521        [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
2522        [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
2523        [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
2524        [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
2525        [SYS_fchdir] = {(syscall_t)sys_fchdir, "fchdir"},
2526        [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
2527        [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdir"},
2528        [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
2529        [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
2530        [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
2531        [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
2532        [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"},
2533        /* special! */
2534        [SYS_nbind] ={(syscall_t)sys_nbind, "nbind"},
2535        [SYS_nmount] ={(syscall_t)sys_nmount, "nmount"},
2536        [SYS_nunmount] ={(syscall_t)sys_nunmount, "nunmount"},
2537        [SYS_fd2path] ={(syscall_t)sys_fd2path, "fd2path"},
2538        [SYS_wstat] ={(syscall_t)sys_wstat, "wstat"},
2539        [SYS_fwstat] ={(syscall_t)sys_fwstat, "fwstat"},
2540        [SYS_rename] ={(syscall_t)sys_rename, "rename"},
2541        [SYS_dup_fds_to] = {(syscall_t)sys_dup_fds_to, "dup_fds_to"},
2542        [SYS_tap_fds] = {(syscall_t)sys_tap_fds, "tap_fds"},
2543};
2544const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
2545
2546/* Executes the given syscall.
2547 *
2548 * Note tf is passed in, which points to the tf of the context on the kernel
2549 * stack.  If any syscall needs to block, it needs to save this info, as well as
2550 * any silly state.
2551 *
2552 * This syscall function is used by both local syscall and arsc, and should
2553 * remain oblivious of the caller. */
2554intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
2555                 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
2556{
2557        intreg_t ret = -1;
2558        ERRSTACK(1);
2559
2560        if (sc_num > max_syscall || syscall_table[sc_num].call == NULL) {
2561                printk("[kernel] Invalid syscall %d for proc %d\n", sc_num,
2562                       p->pid);
2563                printk("\tArgs: %p, %p, %p, %p, %p, %p\n", a0, a1, a2, a3, a4,
2564                       a5);
2565                print_user_ctx(this_pcpui_var(cur_ctx));
2566                return -1;
2567        }
2568
2569        /* N.B. This is going away. */
2570        if (waserror()){
2571                printk("Plan 9 system call returned via waserror()\n");
2572                printk("String: '%s'\n", current_errstr());
2573                /* if we got here, then the errbuf was right.
2574                 * no need to check!
2575                 */
2576                return -1;
2577        }
2578        //printd("before syscall errstack %p\n", errstack);
2579        //printd("before syscall errstack base %p\n", get_cur_errbuf());
2580        ret = syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
2581        //printd("after syscall errstack base %p\n", get_cur_errbuf());
2582        if (get_cur_errbuf() != &errstack[0]) {
2583                /* Can't trust coreid and vcoreid anymore, need to check the
2584                 * trace */
2585                printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, "
2586                       "%p, %p) proc: %d\n", read_tsc(),
2587                       sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
2588                       a4, a5, p->pid);
2589                if (sc_num != SYS_fork)
2590                        panic("errstack mismatch");
2591        }
2592        return ret;
2593}
2594
2595/* Execute the syscall on the local core */
2596void run_local_syscall(struct syscall *sysc)
2597{
2598        struct per_cpu_info *pcpui = this_pcpui_ptr();
2599        struct proc *p = pcpui->cur_proc;
2600        long retval;
2601
2602        /* In lieu of pinning, we just check the sysc and will PF on the user
2603         * addr later (if the addr was unmapped).  Which is the plan for all
2604         * UMEM. */
2605        if (!is_user_rwaddr(sysc, sizeof(struct syscall))) {
2606                printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n",
2607                       sysc, sizeof(struct syscall), __FUNCTION__);
2608                return;
2609        }
2610        pcpui->cur_kthread->sysc = sysc;/* let the core know which sysc it is */
2611        unset_errno();
2612        systrace_start_trace(pcpui->cur_kthread, sysc);
2613        pcpui = this_pcpui_ptr();       /* reload again */
2614        alloc_sysc_str(pcpui->cur_kthread);
2615        /* syscall() does not return for exec and yield, so put any cleanup in
2616         * there too. */
2617        retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
2618                         sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
2619        finish_current_sysc(retval);
2620}
2621
2622/* A process can trap and call this function, which will set up the core to
2623 * handle all the syscalls.  a.k.a. "sys_debutante(needs, wants)".  If there is
2624 * at least one, it will run it directly. */
2625void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
2626{
2627        /* Careful with pcpui here, we could have migrated */
2628        if (!nr_syscs) {
2629                printk("[kernel] No nr_sysc, probably a bug, user!\n");
2630                return;
2631        }
2632        /* For all after the first call, send ourselves a KMSG (TODO). */
2633        if (nr_syscs != 1)
2634                warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
2635        /* Call the first one directly.  (we already checked to make sure there
2636         * is 1) */
2637        run_local_syscall(sysc);
2638}
2639
2640/* Call this when something happens on the syscall where userspace might want to
2641 * get signaled.  Passing p, since the caller should know who the syscall
2642 * belongs to (probably is current).
2643 *
2644 * You need to have SC_K_LOCK set when you call this. */
2645void __signal_syscall(struct syscall *sysc, struct proc *p)
2646{
2647        struct event_queue *ev_q;
2648        struct event_msg local_msg;
2649
2650        /* User sets the ev_q then atomically sets the flag (races with SC_DONE)
2651         */
2652        if (atomic_read(&sysc->flags) & SC_UEVENT) {
2653                rmb();  /* read the ev_q after reading the flag */
2654                ev_q = sysc->ev_q;
2655                if (ev_q) {
2656                        memset(&local_msg, 0, sizeof(struct event_msg));
2657                        local_msg.ev_type = EV_SYSCALL;
2658                        local_msg.ev_arg3 = sysc;
2659                        if (!is_user_rwaddr(ev_q, sizeof(struct event_queue))) {
2660                                printk("[kernel] syscall had bad ev_q %p\n",
2661                                       ev_q);
2662                                return;
2663                        }
2664                        send_event(p, ev_q, &local_msg, 0);
2665                }
2666        }
2667}
2668
2669bool syscall_uses_fd(struct syscall *sysc, int fd)
2670{
2671        switch (sysc->num) {
2672        case (SYS_read):
2673        case (SYS_write):
2674        case (SYS_close):
2675        case (SYS_fstat):
2676        case (SYS_fcntl):
2677        case (SYS_llseek):
2678        case (SYS_nmount):
2679        case (SYS_fd2path):
2680                if (sysc->arg0 == fd)
2681                        return TRUE;
2682                return FALSE;
2683        case (SYS_mmap):
2684                /* mmap always has to be special. =) */
2685                if (sysc->arg4 == fd)
2686                        return TRUE;
2687                return FALSE;
2688        default:
2689                return FALSE;
2690        }
2691}
2692
2693void print_sysc(struct proc *p, struct syscall *sysc)
2694{
2695        uintptr_t old_p = switch_to(p);
2696
2697        printk("SYS_%d, flags %p, a0 %p, a1 %p, a2 %p, a3 %p, a4 %p, a5 %p\n",
2698               sysc->num, atomic_read(&sysc->flags),
2699               sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
2700               sysc->arg5);
2701        switch_back(p, old_p);
2702}
2703
2704/* Called when we try to return from a panic. */
2705void kth_panic_sysc(struct kthread *kth)
2706{
2707        kth->sysc = NULL;
2708        /* We actually could block here, but that might be OK, since we cleared
2709         * cur_kthread->sysc.  As OK as anything is after a panic... */
2710        systrace_finish_trace(kth, -12345);
2711}
2712