1 /* See COPYRIGHT for copyright information. */
4 #include <ros/common.h>
5 #include <ros/limits.h>
6 #include <arch/types.h>
9 #include <arch/console.h>
27 #include <hashtable.h>
32 #include <arsc_server.h>
37 #include <ros/procinfo.h>
39 static int execargs_stringer(struct proc *p, char *d, size_t slen,
40 char *path, size_t path_l,
41 char *argenv, size_t argenv_l);
43 /* Global, used by the kernel monitor for syscall debugging. */
44 bool systrace_loud = FALSE;
46 /* Helper, given the trace record, pretty-print the trace's contents into the
47 * trace's pretty buf. 'entry' says whether we're an entry record or not
48 * (exit). Returns the number of bytes put into the pretty_buf. */
49 static size_t systrace_fill_pretty_buf(struct systrace_record *trace,
53 struct timespec ts_start = tsc2timespec(trace->start_timestamp);
54 struct timespec ts_end = tsc2timespec(trace->end_timestamp);
56 /* Slightly different formats between entry and exit. Entry has retval set
57 * to ---, and begins with E. Exit begins with X. */
59 len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
60 "E [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, 0x%llx, "
61 "0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: --- proc: %d core: %d "
68 syscall_table[trace->syscallno].name,
79 len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
80 "X [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, 0x%llx, "
81 "0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: 0x%llx proc: %d core: %d "
88 syscall_table[trace->syscallno].name,
100 len += printdump(trace->pretty_buf + len, trace->datalen,
101 SYSTR_PRETTY_BUF_SZ - len - 1,
103 len += snprintf(trace->pretty_buf + len, SYSTR_PRETTY_BUF_SZ - len, "\n");
107 /* If some syscalls block, then they can really hurt the user and the
108 * kernel. For instance, if you blocked another call because the trace queue is
109 * full, the 2LS will want to yield the vcore, but then *that* call would block
110 * too. Since that caller was in vcore context, the core will just spin
113 * Even worse, some syscalls operate on the calling core or current context,
114 * thus accessing pcpui. If we block, then that old context is gone. Worse, we
115 * could migrate and then be operating on a different core. Imagine
116 * SYS_halt_core. Doh! */
117 static bool sysc_can_block(unsigned int sysc_num)
127 case SYS_change_vcore:
128 case SYS_change_to_m:
134 /* Helper: spits out our trace to the various sinks. */
135 static void systrace_output(struct systrace_record *trace,
136 struct strace *strace, bool entry)
141 /* qio ops can throw, especially the blocking qwrite. I had it block on the
142 * outbound path of sys_proc_destroy(). The rendez immediately throws. */
147 pretty_len = systrace_fill_pretty_buf(trace, entry);
149 /* At this point, we're going to emit the exit trace. It's just a
150 * 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);
154 qwrite(strace->q, trace->pretty_buf, pretty_len);
157 printk("%s", trace->pretty_buf);
161 static bool should_strace(struct proc *p, struct syscall *sysc)
163 unsigned int sysc_num;
167 if (!p->strace || !p->strace->tracing)
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);
177 if (sysc_num > MAX_SYSCALL_NR)
179 return test_bit(sysc_num, p->strace->trace_set);
182 /* Helper, copies len bytes from u_data to the trace->data, if there's room. */
183 static void copy_tracedata_from_user(struct systrace_record *trace,
184 long u_data, size_t len)
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;
193 /* Helper, snprintfs to the trace, if there's room. */
194 static void snprintf_to_trace(struct systrace_record *trace, const char *fmt,
201 rc = vsnprintf((char*)trace->data + trace->datalen,
202 sizeof(trace->data) - trace->datalen, fmt, ap);
204 if (!snprintf_error(rc, sizeof(trace->data) - trace->datalen))
205 trace->datalen += rc;
208 /* Starts a trace for p running sysc, attaching it to kthread. Pairs with
209 * systrace_finish_trace(). */
210 static void systrace_start_trace(struct kthread *kthread, struct syscall *sysc)
212 struct proc *p = current;
213 struct systrace_record *trace;
216 if (!should_strace(p, sysc))
218 /* TODO: consider a block_alloc and qpass, though note that we actually
219 * write the same trace in twice (entry and exit). */
220 trace = kpages_alloc(SYSTR_BUF_SZ, MEM_ATOMIC);
223 atomic_inc(&p->strace->nr_drops);
226 /* Avoiding the atomic op. We sacrifice accuracy for less overhead. */
227 p->strace->appx_nr_sysc++;
232 /* if you ever need to debug just one strace function, this is
233 * handy way to do it: just bail out if it's not the one you
235 * if (sysc->num != SYS_exec)
237 trace->start_timestamp = read_tsc();
238 trace->end_timestamp = 0;
239 trace->syscallno = sysc->num;
240 trace->arg0 = sysc->arg0;
241 trace->arg1 = sysc->arg1;
242 trace->arg2 = sysc->arg2;
243 trace->arg3 = sysc->arg3;
244 trace->arg4 = sysc->arg4;
245 trace->arg5 = sysc->arg5;
248 trace->coreid = core_id();
249 trace->vcoreid = proc_get_vcoreid(p);
250 trace->pretty_buf = (char*)trace + sizeof(struct systrace_record);
256 copy_tracedata_from_user(trace, sysc->arg1, sysc->arg2);
262 copy_tracedata_from_user(trace, sysc->arg1, sysc->arg2);
270 copy_tracedata_from_user(trace, sysc->arg0, sysc->arg1);
276 copy_tracedata_from_user(trace, sysc->arg0, sysc->arg1);
277 snprintf_to_trace(trace, " -> ");
278 copy_tracedata_from_user(trace, sysc->arg2, sysc->arg3);
281 copy_tracedata_from_user(trace, sysc->arg2, sysc->arg3);
284 trace->datalen = execargs_stringer(current,
292 case SYS_proc_create:
293 trace->datalen = execargs_stringer(current,
302 systrace_output(trace, p->strace, TRUE);
304 kthread->strace = trace;
307 /* Finishes the trace on kthread for p, with retval being the return from the
308 * syscall we're tracing. Pairs with systrace_start_trace(). */
309 static void systrace_finish_trace(struct kthread *kthread, long retval)
311 struct proc *p = current;
312 struct systrace_record *trace;
314 if (!kthread->strace)
316 trace = kthread->strace;
317 trace->end_timestamp = read_tsc();
318 trace->retval = retval;
320 /* Only try to do the trace data if we didn't do it on entry */
321 if (!trace->datalen) {
322 switch (trace->syscallno) {
326 copy_tracedata_from_user(trace, trace->arg1, retval);
331 copy_tracedata_from_user(trace, trace->arg0, trace->arg1);
332 snprintf_to_trace(trace, " -> ");
333 copy_tracedata_from_user(trace, trace->arg2, trace->arg3);
338 systrace_output(trace, p->strace, FALSE);
339 kpages_free(kthread->strace, SYSTR_BUF_SZ);
343 #ifdef CONFIG_SYSCALL_STRING_SAVING
345 static void alloc_sysc_str(struct kthread *kth)
347 kth->name = kmalloc(SYSCALL_STRLEN, MEM_ATOMIC);
353 static void free_sysc_str(struct kthread *kth)
355 char *str = kth->name;
361 #define sysc_save_str(...) \
363 struct per_cpu_info *pcpui = &per_cpu_info[core_id()]; \
365 if (pcpui->cur_kthread->name) \
366 snprintf(pcpui->cur_kthread->name, SYSCALL_STRLEN, __VA_ARGS__); \
371 static void alloc_sysc_str(struct kthread *kth)
375 static void free_sysc_str(struct kthread *kth)
379 #define sysc_save_str(...)
381 #endif /* CONFIG_SYSCALL_STRING_SAVING */
383 /* Helper to finish a syscall, signalling if appropriate */
384 static void finish_sysc(struct syscall *sysc, struct proc *p)
386 /* Atomically turn on the LOCK and SC_DONE flag. The lock tells userspace
387 * we're messing with the flags and to not proceed. We use it instead of
388 * CASing with userspace. We need the atomics since we're racing with
389 * userspace for the event_queue registration. The 'lock' tells userspace
390 * to not muck with the flags while we're signalling. */
391 atomic_or(&sysc->flags, SC_K_LOCK | SC_DONE);
392 __signal_syscall(sysc, p);
393 atomic_and(&sysc->flags, ~SC_K_LOCK);
396 /* Helper that "finishes" the current async syscall. This should be used with
397 * care when we are not using the normal syscall completion path.
399 * Do *NOT* complete the same syscall twice. This is catastrophic for _Ms, and
402 * It is possible for another user thread to see the syscall being done early -
403 * they just need to be careful with the weird proc management calls (as in,
404 * don't trust an async fork).
406 * *sysc is in user memory, and should be pinned (TODO: UMEM). There may be
407 * issues with unpinning this if we never return. */
408 static void finish_current_sysc(int retval)
410 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
411 assert(pcpui->cur_kthread->sysc);
412 pcpui->cur_kthread->sysc->retval = retval;
413 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
416 /* Callable by any function while executing a syscall (or otherwise, actually).
418 void set_errno(int errno)
420 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
421 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
422 pcpui->cur_kthread->sysc->err = errno;
425 /* Callable by any function while executing a syscall (or otherwise, actually).
429 /* if there's no errno to get, that's not an error I guess. */
431 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
432 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
433 errno = pcpui->cur_kthread->sysc->err;
437 void unset_errno(void)
439 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
440 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
442 pcpui->cur_kthread->sysc->err = 0;
443 pcpui->cur_kthread->sysc->errstr[0] = '\0';
446 void vset_errstr(const char *fmt, va_list ap)
448 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
450 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
453 vsnprintf(pcpui->cur_kthread->sysc->errstr, MAX_ERRSTR_LEN, fmt, ap);
455 /* TODO: likely not needed */
456 pcpui->cur_kthread->sysc->errstr[MAX_ERRSTR_LEN - 1] = '\0';
459 void set_errstr(const char *fmt, ...)
465 vset_errstr(fmt, ap);
469 char *current_errstr(void)
471 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
472 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
474 return pcpui->cur_kthread->sysc->errstr;
477 void set_error(int error, const char *fmt, ...)
485 vset_errstr(fmt, ap);
489 struct errbuf *get_cur_errbuf(void)
491 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
492 return pcpui->cur_kthread->errbuf;
495 void set_cur_errbuf(struct errbuf *ebuf)
497 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
498 pcpui->cur_kthread->errbuf = ebuf;
501 char *get_cur_genbuf(void)
503 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
504 assert(pcpui->cur_kthread);
505 return pcpui->cur_kthread->generic_buf;
508 /* Helper, looks up proc* for pid and ensures p controls that proc. 0 o/w */
509 static struct proc *get_controllable_proc(struct proc *p, pid_t pid)
511 struct proc *target = pid2proc(pid);
516 if (!proc_controls(p, target)) {
524 static int unpack_argenv(struct argenv *argenv, size_t argenv_l,
525 int *argc_p, char ***argv_p,
526 int *envc_p, char ***envp_p)
528 int argc = argenv->argc;
529 int envc = argenv->envc;
530 char **argv = (char**)argenv->buf;
531 char **envp = argv + argc;
532 char *argbuf = (char*)(envp + envc);
533 uintptr_t argbuf_offset = (uintptr_t)(argbuf - (char*)(argenv));
535 if (((char*)argv - (char*)argenv) > argenv_l)
537 if (((char*)argv + (argc * sizeof(char**)) - (char*)argenv) > argenv_l)
539 if (((char*)envp - (char*)argenv) > argenv_l)
541 if (((char*)envp + (envc * sizeof(char**)) - (char*)argenv) > argenv_l)
543 if (((char*)argbuf - (char*)argenv) > argenv_l)
545 for (int i = 0; i < argc; i++) {
546 if ((uintptr_t)(argv[i] + argbuf_offset) > argenv_l)
548 argv[i] += (uintptr_t)argbuf;
550 for (int i = 0; i < envc; i++) {
551 if ((uintptr_t)(envp[i] + argbuf_offset) > argenv_l)
553 envp[i] += (uintptr_t)argbuf;
562 /************** Utility Syscalls **************/
564 static int sys_null(void)
569 /* Diagnostic function: blocks the kthread/syscall, to help userspace test its
570 * async I/O handling. */
571 static int sys_block(struct proc *p, unsigned long usec)
573 sysc_save_str("block for %lu usec", usec);
574 kthread_usleep(usec);
578 /* Pause execution for a number of nanoseconds.
579 * The current implementation rounds up to the nearest microsecond. If the
580 * syscall is aborted, we return the remaining time the call would have ran
581 * in the 'rem' parameter. */
582 static int sys_nanosleep(struct proc *p,
583 const struct timespec *req,
584 struct timespec *rem)
588 struct timespec kreq, krem = {0, 0};
589 uint64_t tsc = read_tsc();
591 /* Check the input arguments. */
592 if (memcpy_from_user(p, &kreq, req, sizeof(struct timespec))) {
596 if (rem && memcpy_to_user(p, rem, &krem, sizeof(struct timespec))) {
600 if (kreq.tv_sec < 0) {
604 if ((kreq.tv_nsec < 0) || (kreq.tv_nsec > 999999999)) {
609 /* Convert timespec to usec. Ignore overflow on the tv_sec field. */
610 usec = kreq.tv_sec * 1000000;
611 usec += DIV_ROUND_UP(kreq.tv_nsec, 1000);
613 /* Attempt to sleep. If we get aborted, copy the remaining time into
614 * 'rem' and return. We assume the tsc is sufficient to tell how much
615 * time is remaining (i.e. it only overflows on the order of hundreds of
616 * years, which should be sufficiently long enough to ensure we don't
619 krem = tsc2timespec(read_tsc() - tsc);
620 if (rem && memcpy_to_user(p, rem, &krem, sizeof(struct timespec)))
625 sysc_save_str("nanosleep for %d usec", usec);
626 kthread_usleep(usec);
631 static int sys_cache_invalidate(void)
639 /* sys_reboot(): called directly from dispatch table. */
641 /* Returns the id of the physical core this syscall is executed on. */
642 static uint32_t sys_getpcoreid(void)
647 // TODO: Temporary hack until thread-local storage is implemented on i386 and
648 // this is removed from the user interface
649 static size_t sys_getvcoreid(struct proc *p)
651 return proc_get_vcoreid(p);
654 /************** Process management syscalls **************/
656 /* Helper for proc_create and fork */
657 static void inherit_strace(struct proc *parent, struct proc *child)
659 if (parent->strace && parent->strace->inherit) {
660 /* Refcnt on both, put in the child's ->strace. */
661 kref_get(&parent->strace->users, 1);
662 kref_get(&parent->strace->procs, 1);
663 child->strace = parent->strace;
667 /* Creates a process from the file 'path'. The process is not runnable by
668 * default, so it needs it's status to be changed so that the next call to
669 * schedule() will try to run it. */
670 static int sys_proc_create(struct proc *p, char *path, size_t path_l,
671 char *argenv, size_t argenv_l, int flags)
675 struct file *program;
679 struct argenv *kargenv;
681 t_path = copy_in_path(p, path, path_l);
684 /* TODO: 9ns support */
685 program = do_file_open(t_path, O_READ, 0);
687 goto error_with_path;
688 if (!is_valid_elf(program)) {
690 goto error_with_file;
692 /* Check the size of the argenv array, error out if too large. */
693 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
694 set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
696 goto error_with_file;
698 /* Copy the argenv array into a kernel buffer. Delay processing of the
699 * array to load_elf(). */
700 kargenv = user_memdup_errno(p, argenv, argenv_l);
702 set_error(EINVAL, "Failed to copy in the args");
703 goto error_with_file;
705 /* Unpack the argenv array into more usable variables. Integrity checking
706 * done along side this as well. */
707 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
708 set_error(EINVAL, "Failed to unpack the args");
709 goto error_with_kargenv;
711 /* TODO: need to split the proc creation, since you must load after setting
712 * args/env, since auxp gets set up there. */
713 //new_p = proc_create(program, 0, 0);
714 if (proc_alloc(&new_p, current, flags)) {
715 set_error(ENOMEM, "Failed to alloc new proc");
716 goto error_with_kargenv;
718 inherit_strace(p, new_p);
719 /* close the CLOEXEC ones, even though this isn't really an exec */
720 close_fdt(&new_p->open_files, TRUE);
722 if (load_elf(new_p, program, argc, argv, envc, envp)) {
723 set_error(EINVAL, "Failed to load elf");
724 goto error_with_proc;
726 /* progname is argv0, which accounts for symlinks */
727 proc_set_progname(new_p, argc ? argv[0] : NULL);
728 proc_replace_binary_path(new_p, t_path);
729 kref_put(&program->f_kref);
730 user_memdup_free(p, kargenv);
733 profiler_notify_new_process(new_p);
734 proc_decref(new_p); /* give up the reference created in proc_create() */
737 /* proc_destroy will decref once, which is for the ref created in
738 * proc_create(). We don't decref again (the usual "+1 for existing"),
739 * since the scheduler, which usually handles that, hasn't heard about the
740 * process (via __proc_ready()). */
743 user_memdup_free(p, kargenv);
745 kref_put(&program->f_kref);
747 free_path(p, t_path);
751 /* Makes process PID runnable. Consider moving the functionality to process.c */
752 static error_t sys_proc_run(struct proc *p, unsigned pid)
755 struct proc *target = get_controllable_proc(p, pid);
758 if (target->state != PROC_CREATED) {
763 /* Note a proc can spam this for someone it controls. Seems safe - if it
764 * isn't we can change it. */
770 /* Destroy proc pid. If this is called by the dying process, it will never
771 * return. o/w it will return 0 on success, or an error. Errors include:
772 * - ESRCH: if there is no such process with pid
773 * - EPERM: if caller does not control pid */
774 static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
777 struct proc *p_to_die = get_controllable_proc(p, pid);
781 p->exitcode = exitcode;
782 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
784 p_to_die->exitcode = exitcode; /* so its parent has some clue */
785 printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
787 proc_destroy(p_to_die);
788 proc_decref(p_to_die);
792 static int sys_proc_yield(struct proc *p, bool being_nice)
794 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
795 /* proc_yield() often doesn't return - we need to set the syscall retval
796 * early. If it doesn't return, it expects to eat our reference (for now).
798 free_sysc_str(pcpui->cur_kthread);
799 systrace_finish_trace(pcpui->cur_kthread, 0);
800 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
801 pcpui->cur_kthread->sysc = 0; /* don't touch sysc again */
803 proc_yield(p, being_nice);
805 /* Shouldn't return, to prevent the chance of mucking with cur_sysc. */
810 static int sys_change_vcore(struct proc *p, uint32_t vcoreid,
811 bool enable_my_notif)
813 /* Note retvals can be negative, but we don't mess with errno in case
814 * callers use this in low-level code and want to extract the 'errno'. */
815 return proc_change_to_vcore(p, vcoreid, enable_my_notif);
818 static ssize_t sys_fork(env_t* e)
822 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
824 // TODO: right now we only support fork for single-core processes
825 if (e->state != PROC_RUNNING_S) {
830 ret = proc_alloc(&env, current, PROC_DUP_FGRP);
833 proc_set_progname(env, e->progname);
835 /* Can't really fork if we don't have a current_ctx to fork */
842 assert(pcpui->cur_proc == pcpui->owning_proc);
843 copy_current_ctx_to(&env->scp_ctx);
845 /* Make the new process have the same VMRs as the older. This will copy the
846 * contents of non MAP_SHARED pages to the new VMRs. */
847 if (duplicate_vmrs(e, env)) {
848 proc_destroy(env); /* this is prob what you want, not decref by 2 */
853 /* Switch to the new proc's address space and finish the syscall. We'll
854 * never naturally finish this syscall for the new proc, since its memory
855 * is cloned before we return for the original process. If we ever do CoW
856 * for forked memory, this will be the first place that gets CoW'd. */
857 temp = switch_to(env);
858 finish_current_sysc(0);
859 switch_back(env, temp);
861 /* Copy some state from the original proc into the new proc. */
862 env->env_flags = e->env_flags;
864 inherit_strace(e, env);
866 /* In general, a forked process should be a fresh process, and we copy over
867 * whatever stuff is needed between procinfo/procdata. */
868 *env->procdata = *e->procdata;
869 env->procinfo->program_end = e->procinfo->program_end;
871 /* FYI: once we call ready, the proc is open for concurrent usage */
875 // don't decref the new process.
876 // that will happen when the parent waits for it.
877 // TODO: if the parent doesn't wait, we need to change the child's parent
878 // when the parent dies, or at least decref it
880 printd("[PID %d] fork PID %d\n", e->pid, env->pid);
882 profiler_notify_new_process(env);
883 proc_decref(env); /* give up the reference created in proc_alloc() */
887 /* string for sys_exec arguments. Assumes that d is pointing to zero'd
888 * storage or storage that does not require null termination or
889 * provides the null. */
890 static int execargs_stringer(struct proc *p, char *d, size_t slen,
891 char *path, size_t path_l,
892 char *argenv, size_t argenv_l)
896 struct argenv *kargenv;
903 if (memcpy_from_user(p, d, path, path_l)) {
904 s = seprintf(s, e, "Invalid exec path");
909 /* yes, this code is cloned from below. I wrote a helper but
910 * Barret and I concluded after talking about it that the
911 * helper was not really helper-ful, as it has almost 10
912 * arguments. Please, don't suggest a cpp macro. Thank you. */
913 /* Check the size of the argenv array, error out if too large. */
914 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
915 s = seprintf(s, e, "The argenv array has an invalid size: %lu\n",
919 /* Copy the argenv array into a kernel buffer. */
920 kargenv = user_memdup_errno(p, argenv, argenv_l);
922 s = seprintf(s, e, "Failed to copy in the args and environment");
925 /* Unpack the argenv array into more usable variables. Integrity checking
926 * done along side this as well. */
927 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
928 s = seprintf(s, e, "Failed to unpack the args");
929 user_memdup_free(p, kargenv);
932 s = seprintf(s, e, "[%d]{", argc);
933 for (i = 0; i < argc; i++)
934 s = seprintf(s, e, "%s, ", argv[i]);
935 s = seprintf(s, e, "}");
937 user_memdup_free(p, kargenv);
941 /* Load the binary "path" into the current process, and start executing it.
942 * argv and envp are magically bundled in procinfo for now. Keep in sync with
943 * glibc's sysdeps/ros/execve.c. Once past a certain point, this function won't
944 * return. It assumes (and checks) that it is current. Don't give it an extra
945 * refcnt'd *p (syscall won't do that).
946 * Note: if someone batched syscalls with this call, they could clobber their
947 * old memory (and will likely PF and die). Don't do it... */
948 static int sys_exec(struct proc *p, char *path, size_t path_l,
949 char *argenv, size_t argenv_l)
953 struct file *program;
954 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
957 struct argenv *kargenv;
959 /* We probably want it to never be allowed to exec if it ever was _M */
960 if (p->state != PROC_RUNNING_S) {
964 if (p != pcpui->cur_proc) {
969 /* Can't exec if we don't have a current_ctx to restart (if we fail). This
970 * isn't 100% true, but I'm okay with it. */
971 if (!pcpui->cur_ctx) {
975 /* Preemptively copy out the cur_ctx, in case we fail later (easier on
976 * cur_ctx if we do this now) */
977 assert(pcpui->cur_proc == pcpui->owning_proc);
978 copy_current_ctx_to(&p->scp_ctx);
979 /* Check the size of the argenv array, error out if too large. */
980 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
981 set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
985 /* Copy the argenv array into a kernel buffer. */
986 kargenv = user_memdup_errno(p, argenv, argenv_l);
988 set_errstr("Failed to copy in the args and environment");
991 /* Unpack the argenv array into more usable variables. Integrity checking
992 * done along side this as well. */
993 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
994 user_memdup_free(p, kargenv);
995 set_error(EINVAL, "Failed to unpack the args");
998 t_path = copy_in_path(p, path, path_l);
1000 user_memdup_free(p, kargenv);
1003 /* This could block: */
1004 /* TODO: 9ns support */
1005 program = do_file_open(t_path, O_READ, 0);
1006 /* Clear the current_ctx. We won't be returning the 'normal' way. Even if
1007 * we want to return with an error, we need to go back differently in case
1008 * we succeed. This needs to be done before we could possibly block, but
1009 * unfortunately happens before the point of no return.
1011 * Note that we will 'hard block' if we block at all. We can't return to
1012 * userspace and then asynchronously finish the exec later. */
1013 clear_owning_proc(core_id());
1016 if (!is_valid_elf(program)) {
1020 /* This is the point of no return for the process. */
1021 /* progname is argv0, which accounts for symlinks */
1022 proc_replace_binary_path(p, t_path);
1023 proc_set_progname(p, argc ? argv[0] : NULL);
1024 proc_init_procdata(p);
1025 p->procinfo->program_end = 0;
1026 /* When we destroy our memory regions, accessing cur_sysc would PF */
1027 pcpui->cur_kthread->sysc = 0;
1028 unmap_and_destroy_vmrs(p);
1029 /* close the CLOEXEC ones */
1030 close_fdt(&p->open_files, TRUE);
1031 env_user_mem_free(p, 0, UMAPTOP);
1032 if (load_elf(p, program, argc, argv, envc, envp)) {
1033 kref_put(&program->f_kref);
1034 user_memdup_free(p, kargenv);
1035 /* Note this is an inedible reference, but proc_destroy now returns */
1037 /* We don't want to do anything else - we just need to not accidentally
1038 * return to the user (hence the all_out) */
1041 printd("[PID %d] exec %s\n", p->pid, file_name(program));
1042 kref_put(&program->f_kref);
1043 systrace_finish_trace(pcpui->cur_kthread, 0);
1045 /* These error and out paths are so we can handle the async interface, both
1046 * for when we want to error/return to the proc, as well as when we succeed
1047 * and want to start the newly exec'd _S */
1049 /* These two error paths are for when we want to restart the process with an
1050 * error value (errno is already set). */
1051 kref_put(&program->f_kref);
1053 free_path(p, t_path);
1054 finish_current_sysc(-1);
1055 systrace_finish_trace(pcpui->cur_kthread, -1);
1057 user_memdup_free(p, kargenv);
1058 free_sysc_str(pcpui->cur_kthread);
1059 /* Here's how we restart the new (on success) or old (on failure) proc: */
1060 spin_lock(&p->proc_lock);
1061 __seq_start_write(&p->procinfo->coremap_seqctr);
1062 __unmap_vcore(p, 0);
1063 __seq_end_write(&p->procinfo->coremap_seqctr);
1064 __proc_set_state(p, PROC_WAITING); /* fake a yield */
1065 spin_unlock(&p->proc_lock);
1068 /* we can't return, since we'd write retvals to the old location of the
1069 * syscall struct (which has been freed and is in the old userspace) (or has
1070 * already been written to).*/
1071 disable_irq(); /* abandon_core/clear_own wants irqs disabled */
1073 smp_idle(); /* will reenable interrupts */
1076 /* Helper, will attempt a particular wait on a proc. Returns the pid of the
1077 * process if we waited on it successfully, and the status will be passed back
1078 * in ret_status (kernel memory). Returns 0 if the wait failed and we should
1079 * try again. Returns -1 if we should abort. Only handles DYING. Callers
1080 * need to lock to protect the children tailq and reaping bits. */
1081 static pid_t try_wait(struct proc *parent, struct proc *child, int *ret_status,
1084 if (proc_is_dying(child)) {
1085 /* Disown returns -1 if it's already been disowned or we should o/w
1086 * abort. This can happen if we have concurrent waiters, both with
1087 * pointers to the child (only one should reap). Note that if we don't
1088 * do this, we could go to sleep and never receive a cv_signal. */
1089 if (__proc_disown_child(parent, child))
1091 /* despite disowning, the child won't be freed til we drop this ref
1092 * held by this function, so it is safe to access the memory.
1094 * Note the exit code one byte in the 0xff00 spot. Check out glibc's
1095 * posix/sys/wait.h and bits/waitstatus.h for more info. If we ever
1096 * deal with signalling and stopping, we'll need to do some more work
1098 *ret_status = (child->exitcode & 0xff) << 8;
1104 /* Helper, like try_wait, but attempts a wait on any of the children, returning
1105 * the specific PID we waited on, 0 to try again (a waitable exists), and -1 to
1106 * abort (no children/waitables exist). Callers need to lock to protect the
1107 * children tailq and reaping bits.*/
1108 static pid_t try_wait_any(struct proc *parent, int *ret_status, int options)
1110 struct proc *i, *temp;
1112 if (TAILQ_EMPTY(&parent->children))
1114 /* Could have concurrent waiters mucking with the tailq, caller must lock */
1115 TAILQ_FOREACH_SAFE(i, &parent->children, sibling_link, temp) {
1116 retval = try_wait(parent, i, ret_status, options);
1117 /* This catches a thread causing a wait to fail but not taking the
1118 * child off the list before unlocking. Should never happen. */
1119 assert(retval != -1);
1120 /* Succeeded, return the pid of the child we waited on */
1124 assert(retval == 0);
1128 /* Waits on a particular child, returns the pid of the child waited on, and
1129 * puts the ret status in *ret_status. Returns the pid if we succeeded, 0 if
1130 * the child was not waitable and WNOHANG, and -1 on error. */
1131 static pid_t wait_one(struct proc *parent, struct proc *child, int *ret_status,
1135 cv_lock(&parent->child_wait);
1136 /* retval == 0 means we should block */
1137 retval = try_wait(parent, child, ret_status, options);
1138 if ((retval == 0) && (options & WNOHANG))
1142 cv_wait(&parent->child_wait);
1143 /* If we're dying, then we don't need to worry about waiting. We don't
1144 * do this yet, but we'll need this outlet when we deal with orphaned
1145 * children and having init inherit them. */
1146 if (proc_is_dying(parent))
1148 /* Any child can wake us up, but we check for the particular child we
1150 retval = try_wait(parent, child, ret_status, options);
1153 /* Child was already waited on by a concurrent syscall. */
1158 cv_unlock(&parent->child_wait);
1162 /* Waits on any child, returns the pid of the child waited on, and puts the ret
1163 * status in *ret_status. Is basically a waitpid(-1, ... ); See wait_one for
1164 * more details. Returns -1 if there are no children to wait on, and returns 0
1165 * if there are children and we need to block but WNOHANG was set. */
1166 static pid_t wait_any(struct proc *parent, int *ret_status, int options)
1169 cv_lock(&parent->child_wait);
1170 retval = try_wait_any(parent, ret_status, options);
1171 if ((retval == 0) && (options & WNOHANG))
1175 cv_wait(&parent->child_wait);
1176 if (proc_is_dying(parent))
1178 /* Any child can wake us up from the CV. This is a linear try_wait
1179 * scan. If we have a lot of children, we could optimize this. */
1180 retval = try_wait_any(parent, ret_status, options);
1183 assert(TAILQ_EMPTY(&parent->children));
1186 cv_unlock(&parent->child_wait);
1190 /* Note: we only allow waiting on children (no such thing as threads, for
1191 * instance). Right now we only allow waiting on termination (not signals),
1192 * and we don't have a way for parents to disown their children (such as
1193 * ignoring SIGCHLD, see man 2 waitpid's Notes).
1195 * We don't bother with stop/start signals here, though we can probably build
1196 * it in the helper above.
1198 * Returns the pid of who we waited on, or -1 on error, or 0 if we couldn't
1199 * wait (WNOHANG). */
1200 static pid_t sys_waitpid(struct proc *parent, pid_t pid, int *status,
1207 sysc_save_str("waitpid on %d", pid);
1208 /* -1 is the signal for 'any child' */
1210 retval = wait_any(parent, &ret_status, options);
1213 child = pid2proc(pid);
1215 set_errno(ECHILD); /* ECHILD also used for no proc */
1219 if (!(parent->pid == child->ppid)) {
1224 retval = wait_one(parent, child, &ret_status, options);
1229 /* ignoring / don't care about memcpy's retval here. */
1231 memcpy_to_user(parent, status, &ret_status, sizeof(ret_status));
1232 printd("[PID %d] waited for PID %d, got retval %d (status 0x%x)\n",
1233 parent->pid, pid, retval, ret_status);
1237 /************** Memory Management Syscalls **************/
1239 static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
1240 int flags, int fd, off_t offset)
1242 return mmap(p, addr, len, prot, flags, fd, offset);
1245 static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
1247 return mprotect(p, (uintptr_t)addr, len, prot);
1250 static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
1252 return munmap(p, (uintptr_t)addr, len);
1255 static ssize_t sys_shared_page_alloc(env_t* p1,
1256 void **_addr, pid_t p2_id,
1257 int p1_flags, int p2_flags
1260 printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
1264 static int sys_shared_page_free(env_t* p1, void *addr, pid_t p2)
1269 /* Helper, to do the actual provisioning of a resource to a proc */
1270 static int prov_resource(struct proc *target, unsigned int res_type,
1275 /* in the off chance we have a kernel scheduler that can't
1276 * provision, we'll need to change this. */
1277 return provision_core(target, res_val);
1279 printk("[kernel] received provisioning for unknown resource %d\n",
1281 set_errno(ENOENT); /* or EINVAL? */
1286 /* Rough syscall to provision res_val of type res_type to target_pid */
1287 static int sys_provision(struct proc *p, int target_pid,
1288 unsigned int res_type, long res_val)
1290 struct proc *target = pid2proc(target_pid);
1293 if (target_pid == 0)
1294 return prov_resource(0, res_type, res_val);
1295 /* debugging interface */
1296 if (target_pid == -1)
1297 print_coreprov_map();
1301 retval = prov_resource(target, res_type, res_val);
1302 proc_decref(target);
1306 /* Untested. Will notify the target on the given vcore, if the caller controls
1307 * the target. Will honor the target's wanted/vcoreid. u_ne can be NULL. */
1308 static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
1309 struct event_msg *u_msg)
1311 struct event_msg local_msg = {0};
1312 struct proc *target = get_controllable_proc(p, target_pid);
1315 /* if the user provided an ev_msg, copy it in and use that */
1317 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1318 proc_decref(target);
1323 local_msg.ev_type = ev_type;
1325 send_kernel_event(target, &local_msg, 0);
1326 proc_decref(target);
1330 /* Will notify the calling process on the given vcore, independently of WANTED
1331 * or advertised vcoreid. If you change the parameters, change pop_user_ctx().
1333 static int sys_self_notify(struct proc *p, uint32_t vcoreid,
1334 unsigned int ev_type, struct event_msg *u_msg,
1337 struct event_msg local_msg = {0};
1338 /* if the user provided an ev_msg, copy it in and use that */
1340 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1345 local_msg.ev_type = ev_type;
1347 if (local_msg.ev_type >= MAX_NR_EVENT) {
1348 printk("[kernel] received self-notify for vcoreid %d, ev_type %d, "
1349 "u_msg %p, u_msg->type %d\n", vcoreid, ev_type, u_msg,
1350 u_msg ? u_msg->ev_type : 0);
1353 /* this will post a message and IPI, regardless of wants/needs/debutantes.*/
1354 post_vcore_event(p, &local_msg, vcoreid, priv ? EVENT_VCORE_PRIVATE : 0);
1355 proc_notify(p, vcoreid);
1359 static int sys_send_event(struct proc *p, struct event_queue *ev_q,
1360 struct event_msg *u_msg, uint32_t vcoreid)
1362 struct event_msg local_msg = {0};
1364 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1368 send_event(p, ev_q, &local_msg, vcoreid);
1372 /* Puts the calling core into vcore context, if it wasn't already, via a
1373 * self-IPI / active notification. Barring any weird unmappings, we just send
1374 * ourselves a __notify. */
1375 static int sys_vc_entry(struct proc *p)
1377 send_kernel_message(core_id(), __notify, (long)p, 0, 0, KMSG_ROUTINE);
1381 /* This will halt the core, waking on an IRQ. These could be kernel IRQs for
1382 * things like timers or devices, or they could be IPIs for RKMs (__notify for
1383 * an evq with IPIs for a syscall completion, etc).
1385 * We don't need to finish the syscall early (worried about the syscall struct,
1386 * on the vcore's stack). The syscall will finish before any __preempt RKM
1387 * executes, so the vcore will not restart somewhere else before the syscall
1388 * completes (unlike with yield, where the syscall itself adjusts the vcore
1391 * In the future, RKM code might avoid sending IPIs if the core is already in
1392 * the kernel. That code will need to check the CPU's state in some manner, and
1393 * send if the core is halted/idle.
1395 * The core must wake up for RKMs, including RKMs that arrive while the kernel
1396 * is trying to halt. The core need not abort the halt for notif_pending for
1397 * the vcore, only for a __notify or other RKM. Anyone setting notif_pending
1398 * should then attempt to __notify (o/w it's probably a bug). */
1399 static int sys_halt_core(struct proc *p, unsigned long usec)
1401 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1402 struct preempt_data *vcpd;
1403 /* The user can only halt CG cores! (ones it owns) */
1404 if (management_core())
1407 /* both for accounting and possible RKM optimizations */
1408 __set_cpu_state(pcpui, CPU_STATE_IDLE);
1410 if (has_routine_kmsg()) {
1411 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1415 /* This situation possible, though the check is not necessary. We can't
1416 * assert notif_pending isn't set, since another core may be in the
1417 * proc_notify. Thus we can't tell if this check here caught a bug, or just
1419 vcpd = &p->procdata->vcore_preempt_data[pcpui->owning_vcoreid];
1420 if (vcpd->notif_pending) {
1421 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1425 /* CPU_STATE is reset to KERNEL by the IRQ handler that wakes us */
1430 /* Changes a process into _M mode, or -EINVAL if it already is an mcp.
1431 * __proc_change_to_m() returns and we'll eventually finish the sysc later. The
1432 * original context may restart on a remote core before we return and finish,
1433 * but that's fine thanks to the async kernel interface. */
1434 static int sys_change_to_m(struct proc *p)
1436 int retval = proc_change_to_m(p);
1437 /* convert the kernel error code into (-1, errno) */
1445 /* Assists the user/2LS by atomically running *ctx and leaving vcore context.
1446 * Normally, the user can do this themselves, but x86 VM contexts need kernel
1447 * support. The caller ought to be in vcore context, and if a notif is pending,
1448 * then the calling vcore will restart in a fresh VC ctx (as if it was notified
1449 * or did a sys_vc_entry).
1451 * Note that this will set the TLS too, which is part of the context. Parlib's
1452 * pop_user_ctx currently does *not* do this, since the TLS is managed
1453 * separately. If you want to use this syscall for testing, you'll need to 0
1454 * out fsbase and conditionally write_msr in proc_pop_ctx(). */
1455 static int sys_pop_ctx(struct proc *p, struct user_context *ctx)
1457 int pcoreid = core_id();
1458 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1459 int vcoreid = pcpui->owning_vcoreid;
1460 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1462 /* With change_to, there's a bunch of concerns about changing the vcore map,
1463 * since the kernel may have already locked and sent preempts, deaths, etc.
1465 * In this case, we don't care as much. Other than notif_pending and
1466 * notif_disabled, it's more like we're just changing a few registers in
1467 * cur_ctx. We can safely order-after any kernel messages or other changes,
1468 * as if the user had done all of the changes we'll make and then did a
1471 * Since we are mucking with current_ctx, it is important that we don't
1472 * block before or during this syscall. */
1473 arch_finalize_ctx(pcpui->cur_ctx);
1474 if (copy_from_user(pcpui->cur_ctx, ctx, sizeof(struct user_context))) {
1475 /* The 2LS isn't really in a position to handle errors. At the very
1476 * least, we can print something and give them a fresh vc ctx. */
1477 printk("[kernel] unable to copy user_ctx, 2LS bug\n");
1478 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
1479 proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
1480 vcpd->vcore_stack, vcpd->vcore_tls_desc);
1483 proc_secure_ctx(pcpui->cur_ctx);
1484 /* The caller leaves vcore context no matter what. We'll put them back in
1485 * if they missed a message. */
1486 vcpd->notif_disabled = FALSE;
1487 wrmb(); /* order disabled write before pending read */
1488 if (vcpd->notif_pending)
1489 send_kernel_message(pcoreid, __notify, (long)p, 0, 0, KMSG_ROUTINE);
1493 /* Initializes a process to run virtual machine contexts, returning the number
1494 * initialized, optionally setting errno */
1495 static int sys_vmm_setup(struct proc *p, unsigned int nr_guest_pcores,
1496 struct vmm_gpcore_init *gpcis)
1505 ret = vmm_struct_init(p, nr_guest_pcores, gpcis);
1510 static int sys_vmm_poke_guest(struct proc *p, int guest_pcoreid)
1512 return vmm_poke_guest(p, guest_pcoreid);
1515 static int sys_vmm_ctl(struct proc *p, int cmd, unsigned long arg1,
1516 unsigned long arg2, unsigned long arg3,
1521 struct vmm *vmm = &p->vmm;
1523 /* Protects against concurrent setters and for gets that are not atomic
1524 * reads (say, multiple exec ctls). */
1527 qunlock(&vmm->qlock);
1531 /* TODO: have this also turn us into a VM */
1533 error(EINVAL, "Not a VMM yet.");
1535 case VMM_CTL_GET_EXITS:
1537 error(ENOTSUP, "AMD VMMs unsupported");
1538 ret = vmx_ctl_get_exits(&vmm->vmx);
1540 case VMM_CTL_SET_EXITS:
1541 if (arg1 & ~VMM_CTL_ALL_EXITS)
1542 error(EINVAL, "Bad vmm_ctl_exits %x (%x)", arg1,
1545 error(ENOTSUP, "AMD VMMs unsupported");
1546 ret = vmx_ctl_set_exits(&vmm->vmx, arg1);
1548 case VMM_CTL_GET_FLAGS:
1551 case VMM_CTL_SET_FLAGS:
1552 if (arg1 & ~VMM_CTL_ALL_FLAGS)
1553 error(EINVAL, "Bad vmm_ctl flags. Got 0x%lx, allowed 0x%lx\n",
1554 arg1, VMM_CTL_ALL_FLAGS);
1559 error(EINVAL, "Bad vmm_ctl cmd %d", cmd);
1561 qunlock(&vmm->qlock);
1566 /* Pokes the ksched for the given resource for target_pid. If the target pid
1567 * == 0, we just poke for the calling process. The common case is poking for
1568 * self, so we avoid the lookup.
1570 * Not sure if you could harm someone via asking the kernel to look at them, so
1571 * we'll do a 'controls' check for now. In the future, we might have something
1572 * in the ksched that limits or penalizes excessive pokes. */
1573 static int sys_poke_ksched(struct proc *p, int target_pid,
1574 unsigned int res_type)
1576 struct proc *target;
1579 poke_ksched(p, res_type);
1582 target = pid2proc(target_pid);
1587 if (!proc_controls(p, target)) {
1592 poke_ksched(target, res_type);
1594 proc_decref(target);
1598 static int sys_abort_sysc(struct proc *p, struct syscall *sysc)
1600 return abort_sysc(p, sysc);
1603 static int sys_abort_sysc_fd(struct proc *p, int fd)
1605 /* Consider checking for a bad fd. Doesn't matter now, since we only look
1606 * for actual syscalls blocked that had used fd. */
1607 return abort_all_sysc_fd(p, fd);
1610 static unsigned long sys_populate_va(struct proc *p, uintptr_t va,
1611 unsigned long nr_pgs)
1613 return populate_va(p, ROUNDDOWN(va, PGSIZE), nr_pgs);
1616 static intreg_t sys_read(struct proc *p, int fd, void *buf, size_t len)
1618 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1620 struct file *file = get_file_from_fd(&p->open_files, fd);
1621 sysc_save_str("read on fd %d", fd);
1624 if (!file->f_op->read) {
1625 kref_put(&file->f_kref);
1629 /* TODO: (UMEM) currently, read() handles user memcpy
1630 * issues, but we probably should user_mem_check and
1631 * pin the region here, so read doesn't worry about
1633 ret = file->f_op->read(file, buf, len, &file->f_pos);
1634 kref_put(&file->f_kref);
1636 /* plan9, should also handle errors (EBADF) */
1637 ret = sysread(fd, buf, len);
1642 static intreg_t sys_write(struct proc *p, int fd, const void *buf, size_t len)
1644 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1646 struct file *file = get_file_from_fd(&p->open_files, fd);
1648 sysc_save_str("write on fd %d", fd);
1651 if (!file->f_op->write) {
1652 kref_put(&file->f_kref);
1657 ret = file->f_op->write(file, buf, len, &file->f_pos);
1658 kref_put(&file->f_kref);
1660 /* plan9, should also handle errors */
1661 ret = syswrite(fd, (void*)buf, len);
1666 /* Checks args/reads in the path, opens the file (relative to fromfd if the path
1667 * is not absolute), and inserts it into the process's open file list. */
1668 static intreg_t sys_openat(struct proc *p, int fromfd, const char *path,
1669 size_t path_l, int oflag, int mode)
1672 struct file *file = 0;
1675 printd("File %s Open attempt oflag %x mode %x\n", path, oflag, mode);
1676 if ((oflag & O_PATH) && (oflag & O_ACCMODE)) {
1677 set_error(EINVAL, "Cannot open O_PATH with any I/O perms (O%o)", oflag);
1680 t_path = copy_in_path(p, path, path_l);
1683 sysc_save_str("open %s at fd %d", t_path, fromfd);
1684 mode &= ~p->fs_env.umask;
1685 /* Only check the VFS for legacy opens. It doesn't support openat. Actual
1686 * openats won't check here, and file == 0. */
1687 if ((t_path[0] == '/') || (fromfd == AT_FDCWD))
1688 file = do_file_open(t_path, oflag, mode);
1690 set_errno(ENOENT); /* was not in the VFS. */
1692 /* VFS lookup succeeded */
1693 /* stores the ref to file */
1694 fd = insert_file(&p->open_files, file, 0, FALSE, oflag & O_CLOEXEC);
1695 kref_put(&file->f_kref); /* drop our ref */
1697 warn("File insertion failed");
1698 } else if (get_errno() == ENOENT) {
1699 /* VFS failed due to ENOENT. Other errors don't fall back to 9ns */
1700 unset_errno(); /* Go can't handle extra errnos */
1701 fd = sysopenat(fromfd, t_path, oflag);
1702 /* successful lookup with CREATE and EXCL is an error */
1704 if ((oflag & O_CREATE) && (oflag & O_EXCL)) {
1707 free_path(p, t_path);
1711 if (oflag & O_CREATE) {
1713 fd = syscreate(t_path, oflag, mode);
1717 free_path(p, t_path);
1718 printd("File %s Open, fd=%d\n", path, fd);
1722 static intreg_t sys_close(struct proc *p, int fd)
1724 struct file *file = get_file_from_fd(&p->open_files, fd);
1726 printd("sys_close %d\n", fd);
1729 put_file_from_fd(&p->open_files, fd);
1730 kref_put(&file->f_kref); /* Drop the ref from get_file */
1733 /* 9ns, should also handle errors (bad FD, etc) */
1734 retval = sysclose(fd);
1738 /* kept around til we remove the last ufe */
1739 #define ufe(which,a0,a1,a2,a3) \
1740 frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
1741 (int)(a0),(int)(a1),(int)(a2),(int)(a3))
1743 static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
1747 kbuf = kmalloc(sizeof(struct kstat), 0);
1752 file = get_file_from_fd(&p->open_files, fd);
1755 stat_inode(file->f_dentry->d_inode, kbuf);
1756 kref_put(&file->f_kref);
1758 unset_errno(); /* Go can't handle extra errnos */
1759 if (sysfstatakaros(fd, (struct kstat *)kbuf) < 0) {
1764 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1765 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1773 /* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
1774 * treat a symlink for the final item, which (probably) will be controlled by
1775 * the lookup flags */
1776 static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
1777 struct kstat *u_stat, int flags)
1780 struct dentry *path_d;
1781 char *t_path = copy_in_path(p, path, path_l);
1785 kbuf = kmalloc(sizeof(struct kstat), 0);
1791 /* Check VFS for path */
1792 path_d = lookup_dentry(t_path, flags);
1794 stat_inode(path_d->d_inode, kbuf);
1795 kref_put(&path_d->d_kref);
1797 /* VFS failed, checking 9ns */
1798 unset_errno(); /* Go can't handle extra errnos */
1799 retval = sysstatakaros(t_path, (struct stat *)kbuf);
1800 printd("sysstat returns %d\n", retval);
1801 /* both VFS and 9ns failed, bail out */
1805 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1806 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat)))
1812 free_path(p, t_path);
1816 /* Follow a final symlink */
1817 static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1818 struct kstat *u_stat)
1820 return stat_helper(p, path, path_l, u_stat, LOOKUP_FOLLOW);
1823 /* Don't follow a final symlink */
1824 static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1825 struct kstat *u_stat)
1827 return stat_helper(p, path, path_l, u_stat, 0);
1830 intreg_t sys_fcntl(struct proc *p, int fd, int cmd, unsigned long arg1,
1831 unsigned long arg2, unsigned long arg3, unsigned long arg4)
1835 struct file *file = get_file_from_fd(&p->open_files, fd);
1846 /* TODO: 9ns versions */
1849 return fd_getfl(fd);
1851 return fd_setfl(fd, arg1);
1853 warn("Unsupported fcntl cmd %d\n", cmd);
1855 /* not really ever calling this, even for badf, due to the switch */
1860 /* TODO: these are racy */
1863 retval = insert_file(&p->open_files, file, arg1, FALSE, FALSE);
1870 retval = p->open_files.fd[fd].fd_flags;
1873 /* I'm considering not supporting this at all. They must do it at
1874 * open time or fix their buggy/racy code. */
1875 spin_lock(&p->open_files.lock);
1876 if (arg1 & FD_CLOEXEC)
1877 p->open_files.fd[fd].fd_flags |= FD_CLOEXEC;
1878 retval = p->open_files.fd[fd].fd_flags;
1879 spin_unlock(&p->open_files.lock);
1882 retval = file->f_flags;
1885 /* only allowed to set certain flags. */
1886 arg1 &= O_FCNTL_SET_FLAGS;
1887 file->f_flags = (file->f_flags & ~O_FCNTL_SET_FLAGS) | arg1;
1890 /* TODO (if we keep the VFS) */
1894 /* TODO (if we keep the VFS)*/
1898 warn("Unsupported fcntl cmd %d\n", cmd);
1900 kref_put(&file->f_kref);
1904 static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1908 char *t_path = copy_in_path(p, path, path_l);
1911 /* TODO: 9ns support */
1912 retval = do_access(t_path, mode);
1913 free_path(p, t_path);
1914 printd("Access for path: %s retval: %d\n", path, retval);
1922 intreg_t sys_umask(struct proc *p, int mask)
1924 int old_mask = p->fs_env.umask;
1925 p->fs_env.umask = mask & S_PMASK;
1929 /* 64 bit seek, with the off64_t passed in via two (potentially 32 bit) off_ts.
1930 * We're supporting both 32 and 64 bit kernels/userspaces, but both use the
1931 * llseek syscall with 64 bit parameters. */
1932 static intreg_t sys_llseek(struct proc *p, int fd, off_t offset_hi,
1933 off_t offset_lo, off64_t *result, int whence)
1936 off64_t tempoff = 0;
1939 tempoff = offset_hi;
1941 tempoff |= offset_lo;
1942 file = get_file_from_fd(&p->open_files, fd);
1944 ret = file->f_op->llseek(file, tempoff, &retoff, whence);
1945 kref_put(&file->f_kref);
1947 retoff = sysseek(fd, tempoff, whence);
1953 if (memcpy_to_user_errno(p, result, &retoff, sizeof(off64_t)))
1958 intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1959 char *new_path, size_t new_l)
1962 char *t_oldpath = copy_in_path(p, old_path, old_l);
1963 if (t_oldpath == NULL)
1965 char *t_newpath = copy_in_path(p, new_path, new_l);
1966 if (t_newpath == NULL) {
1967 free_path(p, t_oldpath);
1970 ret = do_link(t_oldpath, t_newpath);
1971 free_path(p, t_oldpath);
1972 free_path(p, t_newpath);
1976 intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
1979 char *t_path = copy_in_path(p, path, path_l);
1982 retval = do_unlink(t_path);
1983 if (retval && (get_errno() == ENOENT)) {
1985 retval = sysremove(t_path);
1987 free_path(p, t_path);
1991 intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
1992 char *new_path, size_t new_l)
1995 char *t_oldpath = copy_in_path(p, old_path, old_l);
1996 if (t_oldpath == NULL)
1998 char *t_newpath = copy_in_path(p, new_path, new_l);
1999 if (t_newpath == NULL) {
2000 free_path(p, t_oldpath);
2003 ret = do_symlink(t_newpath, t_oldpath, S_IRWXU | S_IRWXG | S_IRWXO);
2004 free_path(p, t_oldpath);
2005 free_path(p, t_newpath);
2009 intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
2010 char *u_buf, size_t buf_l)
2012 char *symname = NULL;
2013 uint8_t *buf = NULL;
2016 struct dentry *path_d;
2017 char *t_path = copy_in_path(p, path, path_l);
2020 /* TODO: 9ns support */
2021 path_d = lookup_dentry(t_path, 0);
2024 buf = kmalloc(n*2, MEM_WAIT);
2025 struct dir *d = (void *)&buf[n];
2027 if (sysstat(t_path, buf, n) > 0) {
2028 printk("sysstat t_path %s\n", t_path);
2029 convM2D(buf, n, d, (char *)&d[1]);
2030 /* will be NULL if things did not work out */
2034 symname = path_d->d_inode->i_op->readlink(path_d);
2036 free_path(p, t_path);
2039 copy_amt = strnlen(symname, buf_l - 1) + 1;
2040 if (!memcpy_to_user_errno(p, u_buf, symname, copy_amt))
2044 kref_put(&path_d->d_kref);
2047 printd("READLINK returning %s\n", u_buf);
2051 static intreg_t sys_chdir(struct proc *p, pid_t pid, const char *path,
2056 struct proc *target = get_controllable_proc(p, pid);
2059 t_path = copy_in_path(p, path, path_l);
2061 proc_decref(target);
2064 /* TODO: 9ns support */
2065 retval = do_chdir(&target->fs_env, t_path);
2066 free_path(p, t_path);
2067 proc_decref(target);
2071 static intreg_t sys_fchdir(struct proc *p, pid_t pid, int fd)
2075 struct proc *target = get_controllable_proc(p, pid);
2078 file = get_file_from_fd(&p->open_files, fd);
2082 proc_decref(target);
2085 retval = do_fchdir(&target->fs_env, file);
2086 kref_put(&file->f_kref);
2087 proc_decref(target);
2091 /* Note cwd_l is not a strlen, it's an absolute size */
2092 intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
2097 k_cwd = do_getcwd(&p->fs_env, &kfree_this, cwd_l);
2099 return -1; /* errno set by do_getcwd */
2100 if (strlen(k_cwd) + 1 > cwd_l) {
2101 set_error(ERANGE, "getcwd buf too small, needed %d", strlen(k_cwd) + 1);
2105 if (memcpy_to_user_errno(p, u_cwd, k_cwd, strlen(k_cwd) + 1))
2112 intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
2115 char *t_path = copy_in_path(p, path, path_l);
2119 mode &= ~p->fs_env.umask;
2120 retval = do_mkdir(t_path, mode);
2121 if (retval && (get_errno() == ENOENT)) {
2123 /* mixing plan9 and glibc here, make sure DMDIR doesn't overlap with any
2125 static_assert(!(S_PMASK & DMDIR));
2126 retval = syscreate(t_path, O_RDWR, DMDIR | mode);
2128 free_path(p, t_path);
2132 intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
2135 char *t_path = copy_in_path(p, path, path_l);
2138 /* TODO: 9ns support */
2139 retval = do_rmdir(t_path);
2140 free_path(p, t_path);
2144 intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
2147 /* TODO: actually support this call on tty FDs. Right now, we just fake
2148 * what my linux box reports for a bash pty. */
2149 struct termios *kbuf = kmalloc(sizeof(struct termios), 0);
2150 kbuf->c_iflag = 0x2d02;
2151 kbuf->c_oflag = 0x0005;
2152 kbuf->c_cflag = 0x04bf;
2153 kbuf->c_lflag = 0x8a3b;
2155 kbuf->c_ispeed = 0xf;
2156 kbuf->c_ospeed = 0xf;
2157 kbuf->c_cc[0] = 0x03;
2158 kbuf->c_cc[1] = 0x1c;
2159 kbuf->c_cc[2] = 0x7f;
2160 kbuf->c_cc[3] = 0x15;
2161 kbuf->c_cc[4] = 0x04;
2162 kbuf->c_cc[5] = 0x00;
2163 kbuf->c_cc[6] = 0x01;
2164 kbuf->c_cc[7] = 0xff;
2165 kbuf->c_cc[8] = 0x11;
2166 kbuf->c_cc[9] = 0x13;
2167 kbuf->c_cc[10] = 0x1a;
2168 kbuf->c_cc[11] = 0xff;
2169 kbuf->c_cc[12] = 0x12;
2170 kbuf->c_cc[13] = 0x0f;
2171 kbuf->c_cc[14] = 0x17;
2172 kbuf->c_cc[15] = 0x16;
2173 kbuf->c_cc[16] = 0xff;
2174 kbuf->c_cc[17] = 0x00;
2175 kbuf->c_cc[18] = 0x00;
2176 kbuf->c_cc[19] = 0x00;
2177 kbuf->c_cc[20] = 0x00;
2178 kbuf->c_cc[21] = 0x00;
2179 kbuf->c_cc[22] = 0x00;
2180 kbuf->c_cc[23] = 0x00;
2181 kbuf->c_cc[24] = 0x00;
2182 kbuf->c_cc[25] = 0x00;
2183 kbuf->c_cc[26] = 0x00;
2184 kbuf->c_cc[27] = 0x00;
2185 kbuf->c_cc[28] = 0x00;
2186 kbuf->c_cc[29] = 0x00;
2187 kbuf->c_cc[30] = 0x00;
2188 kbuf->c_cc[31] = 0x00;
2190 if (memcpy_to_user_errno(p, termios_p, kbuf, sizeof(struct termios)))
2196 intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
2197 const void *termios_p)
2199 /* TODO: do this properly too. For now, we just say 'it worked' */
2203 /* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
2204 * process from thinking it can do these. The other alternative is to have
2205 * glibc return 0 right away, though someone might want to do something with
2206 * these calls. Someday. */
2207 intreg_t sys_setuid(struct proc *p, uid_t uid)
2212 intreg_t sys_setgid(struct proc *p, gid_t gid)
2217 /* long bind(char* src_path, char* onto_path, int flag);
2219 * The naming for the args in bind is messy historically. We do:
2220 * bind src_path onto_path
2221 * plan9 says bind NEW OLD, where new is *src*, and old is *onto*.
2222 * Linux says mount --bind OLD NEW, where OLD is *src* and NEW is *onto*. */
2223 intreg_t sys_nbind(struct proc *p,
2224 char *src_path, size_t src_l,
2225 char *onto_path, size_t onto_l,
2230 char *t_srcpath = copy_in_path(p, src_path, src_l);
2231 if (t_srcpath == NULL) {
2232 printd("srcpath dup failed ptr %p size %d\n", src_path, src_l);
2235 char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2236 if (t_ontopath == NULL) {
2237 free_path(p, t_srcpath);
2238 printd("ontopath dup failed ptr %p size %d\n", onto_path, onto_l);
2241 printd("sys_nbind: %s -> %s flag %d\n", t_srcpath, t_ontopath, flag);
2242 ret = sysbind(t_srcpath, t_ontopath, flag);
2243 free_path(p, t_srcpath);
2244 free_path(p, t_ontopath);
2248 /* int mount(int fd, int afd, char* onto_path, int flag, char* aname); */
2249 intreg_t sys_nmount(struct proc *p,
2251 char *onto_path, size_t onto_l,
2253 /* we ignore these */
2254 /* no easy way to pass this many args anyway. *
2256 char *auth, size_t auth_l*/)
2262 char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2263 if (t_ontopath == NULL)
2265 ret = sysmount(fd, afd, t_ontopath, flag, /* spec or auth */"/");
2266 free_path(p, t_ontopath);
2270 /* Unmount undoes the operation of a bind or mount. Check out
2271 * http://plan9.bell-labs.com/magic/man2html/1/bind . Though our mount takes an
2272 * FD, not servename (aka src_path), so it's not quite the same.
2274 * To translate between Plan 9 and Akaros, old -> onto_path. new -> src_path.
2276 * For unmount, src_path / new is optional. If set, we only unmount the
2277 * bindmount that came from src_path. */
2278 intreg_t sys_nunmount(struct proc *p, char *src_path, int src_l,
2279 char *onto_path, int onto_l)
2282 char *t_ontopath, *t_srcpath;
2283 t_ontopath = copy_in_path(p, onto_path, onto_l);
2284 if (t_ontopath == NULL)
2287 t_srcpath = copy_in_path(p, src_path, src_l);
2288 if (t_srcpath == NULL) {
2289 free_path(p, t_ontopath);
2295 ret = sysunmount(t_srcpath, t_ontopath);
2296 free_path(p, t_ontopath);
2297 free_path(p, t_srcpath); /* you can free a null path */
2301 intreg_t sys_fd2path(struct proc *p, int fd, void *u_buf, size_t len)
2306 /* UMEM: Check the range, can PF later and kill if the page isn't present */
2307 if (!is_user_rwaddr(u_buf, len)) {
2308 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", u_buf,
2312 /* fdtochan throws */
2317 ch = fdtochan(¤t->open_files, fd, -1, FALSE, TRUE);
2318 if (snprintf(u_buf, len, "%s", channame(ch)) >= len) {
2319 set_error(ERANGE, "fd2path buf too small, needed %d", ret);
2327 /* Helper, interprets the wstat and performs the VFS action. Returns stat_sz on
2328 * success for all ops, -1 or 0 o/w. If one op fails, it'll skip the remaining
2330 static int vfs_wstat(struct file *file, uint8_t *stat_m, size_t stat_sz,
2337 dir = kzmalloc(sizeof(struct dir) + stat_sz, MEM_WAIT);
2338 m_sz = convM2D(stat_m, stat_sz, &dir[0], (char*)&dir[1]);
2339 if (m_sz != stat_sz) {
2340 set_error(EINVAL, ERROR_FIXME);
2344 if (flags & WSTAT_MODE) {
2345 retval = do_file_chmod(file, dir->mode);
2349 if (flags & WSTAT_LENGTH) {
2350 retval = do_truncate(file->f_dentry->d_inode, dir->length);
2354 if (flags & WSTAT_ATIME) {
2355 /* wstat only gives us seconds */
2356 file->f_dentry->d_inode->i_atime.tv_sec = dir->atime;
2357 file->f_dentry->d_inode->i_atime.tv_nsec = 0;
2359 if (flags & WSTAT_MTIME) {
2360 file->f_dentry->d_inode->i_mtime.tv_sec = dir->mtime;
2361 file->f_dentry->d_inode->i_mtime.tv_nsec = 0;
2366 /* convert vfs retval to wstat retval */
2372 intreg_t sys_wstat(struct proc *p, char *path, size_t path_l,
2373 uint8_t *stat_m, size_t stat_sz, int flags)
2376 char *t_path = copy_in_path(p, path, path_l);
2381 retval = syswstat(t_path, stat_m, stat_sz);
2382 if (retval == stat_sz) {
2383 free_path(p, t_path);
2386 /* 9ns failed, we'll need to check the VFS */
2387 file = do_file_open(t_path, O_READ, 0);
2388 free_path(p, t_path);
2391 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2392 kref_put(&file->f_kref);
2396 intreg_t sys_fwstat(struct proc *p, int fd, uint8_t *stat_m, size_t stat_sz,
2402 retval = sysfwstat(fd, stat_m, stat_sz);
2403 if (retval == stat_sz)
2405 /* 9ns failed, we'll need to check the VFS */
2406 file = get_file_from_fd(&p->open_files, fd);
2409 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2410 kref_put(&file->f_kref);
2414 intreg_t sys_rename(struct proc *p, char *old_path, size_t old_path_l,
2415 char *new_path, size_t new_path_l)
2417 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2419 int mountpointlen = 0;
2420 char *from_path = copy_in_path(p, old_path, old_path_l);
2421 char *to_path = copy_in_path(p, new_path, new_path_l);
2422 struct chan *oldchan = 0, *newchan = NULL;
2425 if ((!from_path) || (!to_path))
2427 printd("sys_rename :%s: to :%s: : ", from_path, to_path);
2429 /* we need a fid for the wstat. */
2430 /* TODO: maybe wrap the 9ns stuff better. sysrename maybe? */
2432 /* discard namec error */
2434 oldchan = namec(from_path, Aaccess, 0, 0);
2438 retval = do_rename(from_path, to_path);
2439 free_path(p, from_path);
2440 free_path(p, to_path);
2444 printd("Oldchan: %C\n", oldchan);
2445 printd("Oldchan: mchan %C\n", oldchan->mchan);
2447 /* If walked through a mountpoint, we need to take that
2448 * into account for the Twstat.
2450 if (oldchan->mountpoint) {
2451 printd("mountpoint: %C\n", oldchan->mountpoint);
2452 if (oldchan->mountpoint->name)
2453 mountpointlen = oldchan->mountpoint->name->len;
2456 /* This test makes sense even when mountpointlen is 0 */
2457 if (strlen(to_path) < mountpointlen) {
2462 /* the omode and perm are of no importance. */
2463 newchan = namec(to_path, Acreatechan, 0, 0);
2464 if (newchan == NULL) {
2465 printd("sys_rename %s to %s found no chan\n", from_path, to_path);
2469 printd("Newchan: %C\n", newchan);
2470 printd("Newchan: mchan %C\n", newchan->mchan);
2472 if ((newchan->dev != oldchan->dev) ||
2473 (newchan->type != oldchan->type)) {
2474 printd("Old chan and new chan do not match\n");
2481 uint8_t mbuf[STATFIXLEN + MAX_PATH_LEN + 1];
2483 init_empty_dir(&dir);
2485 /* absolute paths need the mountpoint name stripped from them.
2486 * Once stripped, it still has to be an absolute path.
2488 if (dir.name[0] == '/') {
2489 dir.name = to_path + mountpointlen;
2490 if (dir.name[0] != '/') {
2496 mlen = convD2M(&dir, mbuf, sizeof(mbuf));
2498 printk("convD2M failed\n");
2504 printk("validstat failed: %s\n", current_errstr());
2508 validstat(mbuf, mlen, 1);
2516 retval = devtab[oldchan->type].wstat(oldchan, mbuf, mlen);
2519 if (retval == mlen) {
2522 printk("syswstat did not go well\n");
2525 printk("syswstat returns %d\n", retval);
2528 free_path(p, from_path);
2529 free_path(p, to_path);
2535 /* Careful: if an FD is busy, we don't close the old object, it just fails */
2536 static intreg_t sys_dup_fds_to(struct proc *p, unsigned int pid,
2537 struct childfdmap *map, unsigned int nentries)
2544 if (!is_user_rwaddr(map, sizeof(struct childfdmap) * nentries)) {
2548 child = get_controllable_proc(p, pid);
2551 for (int i = 0; i < nentries; i++) {
2553 file = get_file_from_fd(&p->open_files, map[i].parentfd);
2555 slot = insert_file(&child->open_files, file, map[i].childfd, TRUE,
2557 if (slot == map[i].childfd) {
2561 kref_put(&file->f_kref);
2564 if (!sys_dup_to(p, map[i].parentfd, child, map[i].childfd)) {
2569 /* probably a bug, could send EBADF, maybe via 'ok' */
2570 printk("[kernel] dup_fds_to: couldn't find %d\n", map[i].parentfd);
2576 /* 0 on success, anything else is an error, with errno/errstr set */
2577 static int handle_tap_req(struct proc *p, struct fd_tap_req *req)
2580 case (FDTAP_CMD_ADD):
2581 return add_fd_tap(p, req);
2582 case (FDTAP_CMD_REM):
2583 return remove_fd_tap(p, req->fd);
2585 set_error(ENOSYS, "FD Tap Command %d not supported", req->cmd);
2590 /* Processes up to nr_reqs tap requests. If a request errors out, we stop
2591 * immediately. Returns the number processed. If done != nr_reqs, check errno
2592 * and errstr for the last failure, which is for tap_reqs[done]. */
2593 static intreg_t sys_tap_fds(struct proc *p, struct fd_tap_req *tap_reqs,
2596 struct fd_tap_req *req_i = tap_reqs;
2598 if (!is_user_rwaddr(tap_reqs, sizeof(struct fd_tap_req) * nr_reqs)) {
2602 for (done = 0; done < nr_reqs; done++, req_i++) {
2603 if (handle_tap_req(p, req_i))
2609 /************** Syscall Invokation **************/
2611 const struct sys_table_entry syscall_table[] = {
2612 [SYS_null] = {(syscall_t)sys_null, "null"},
2613 [SYS_block] = {(syscall_t)sys_block, "block"},
2614 [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
2615 [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
2616 [SYS_getpcoreid] = {(syscall_t)sys_getpcoreid, "getpcoreid"},
2617 [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
2618 [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
2619 [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
2620 [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
2621 [SYS_proc_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
2622 [SYS_change_vcore] = {(syscall_t)sys_change_vcore, "change_vcore"},
2623 [SYS_fork] = {(syscall_t)sys_fork, "fork"},
2624 [SYS_exec] = {(syscall_t)sys_exec, "exec"},
2625 [SYS_waitpid] = {(syscall_t)sys_waitpid, "waitpid"},
2626 [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
2627 [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
2628 [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
2629 [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
2630 [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
2631 [SYS_provision] = {(syscall_t)sys_provision, "provision"},
2632 [SYS_notify] = {(syscall_t)sys_notify, "notify"},
2633 [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
2634 [SYS_send_event] = {(syscall_t)sys_send_event, "send_event"},
2635 [SYS_vc_entry] = {(syscall_t)sys_vc_entry, "vc_entry"},
2636 [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
2637 #ifdef CONFIG_ARSC_SERVER
2638 [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
2640 [SYS_change_to_m] = {(syscall_t)sys_change_to_m, "change_to_m"},
2641 [SYS_vmm_setup] = {(syscall_t)sys_vmm_setup, "vmm_setup"},
2642 [SYS_vmm_poke_guest] = {(syscall_t)sys_vmm_poke_guest, "vmm_poke_guest"},
2643 [SYS_vmm_ctl] = {(syscall_t)sys_vmm_ctl, "vmm_ctl"},
2644 [SYS_poke_ksched] = {(syscall_t)sys_poke_ksched, "poke_ksched"},
2645 [SYS_abort_sysc] = {(syscall_t)sys_abort_sysc, "abort_sysc"},
2646 [SYS_abort_sysc_fd] = {(syscall_t)sys_abort_sysc_fd, "abort_sysc_fd"},
2647 [SYS_populate_va] = {(syscall_t)sys_populate_va, "populate_va"},
2648 [SYS_nanosleep] = {(syscall_t)sys_nanosleep, "nanosleep"},
2649 [SYS_pop_ctx] = {(syscall_t)sys_pop_ctx, "pop_ctx"},
2651 [SYS_read] = {(syscall_t)sys_read, "read"},
2652 [SYS_write] = {(syscall_t)sys_write, "write"},
2653 [SYS_openat] = {(syscall_t)sys_openat, "openat"},
2654 [SYS_close] = {(syscall_t)sys_close, "close"},
2655 [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
2656 [SYS_stat] = {(syscall_t)sys_stat, "stat"},
2657 [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
2658 [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
2659 [SYS_access] = {(syscall_t)sys_access, "access"},
2660 [SYS_umask] = {(syscall_t)sys_umask, "umask"},
2661 [SYS_llseek] = {(syscall_t)sys_llseek, "llseek"},
2662 [SYS_link] = {(syscall_t)sys_link, "link"},
2663 [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
2664 [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
2665 [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
2666 [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
2667 [SYS_fchdir] = {(syscall_t)sys_fchdir, "fchdir"},
2668 [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
2669 [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdir"},
2670 [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
2671 [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
2672 [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
2673 [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
2674 [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"},
2676 [SYS_nbind] ={(syscall_t)sys_nbind, "nbind"},
2677 [SYS_nmount] ={(syscall_t)sys_nmount, "nmount"},
2678 [SYS_nunmount] ={(syscall_t)sys_nunmount, "nunmount"},
2679 [SYS_fd2path] ={(syscall_t)sys_fd2path, "fd2path"},
2680 [SYS_wstat] ={(syscall_t)sys_wstat, "wstat"},
2681 [SYS_fwstat] ={(syscall_t)sys_fwstat, "fwstat"},
2682 [SYS_rename] ={(syscall_t)sys_rename, "rename"},
2683 [SYS_dup_fds_to] = {(syscall_t)sys_dup_fds_to, "dup_fds_to"},
2684 [SYS_tap_fds] = {(syscall_t)sys_tap_fds, "tap_fds"},
2686 const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
2688 /* Executes the given syscall.
2690 * Note tf is passed in, which points to the tf of the context on the kernel
2691 * stack. If any syscall needs to block, it needs to save this info, as well as
2694 * This syscall function is used by both local syscall and arsc, and should
2695 * remain oblivious of the caller. */
2696 intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
2697 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
2699 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2703 if (sc_num > max_syscall || syscall_table[sc_num].call == NULL) {
2704 printk("[kernel] Invalid syscall %d for proc %d\n", sc_num, p->pid);
2705 printk("\tArgs: %p, %p, %p, %p, %p, %p\n", a0, a1, a2, a3, a4, a5);
2706 print_user_ctx(per_cpu_info[core_id()].cur_ctx);
2710 /* N.B. This is going away. */
2712 printk("Plan 9 system call returned via waserror()\n");
2713 printk("String: '%s'\n", current_errstr());
2714 /* if we got here, then the errbuf was right.
2719 //printd("before syscall errstack %p\n", errstack);
2720 //printd("before syscall errstack base %p\n", get_cur_errbuf());
2721 ret = syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
2722 //printd("after syscall errstack base %p\n", get_cur_errbuf());
2723 if (get_cur_errbuf() != &errstack[0]) {
2724 /* Can't trust coreid and vcoreid anymore, need to check the trace */
2725 printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, "
2726 "%p, %p) proc: %d\n", read_tsc(),
2727 sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
2729 if (sc_num != SYS_fork)
2730 printk("YOU SHOULD PANIC: errstack mismatch");
2735 /* Execute the syscall on the local core */
2736 void run_local_syscall(struct syscall *sysc)
2738 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2739 struct proc *p = pcpui->cur_proc;
2741 /* In lieu of pinning, we just check the sysc and will PF on the user addr
2742 * later (if the addr was unmapped). Which is the plan for all UMEM. */
2743 if (!is_user_rwaddr(sysc, sizeof(struct syscall))) {
2744 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", sysc,
2745 sizeof(struct syscall), __FUNCTION__);
2748 pcpui->cur_kthread->sysc = sysc; /* let the core know which sysc it is */
2749 systrace_start_trace(pcpui->cur_kthread, sysc);
2750 pcpui = &per_cpu_info[core_id()]; /* reload again */
2751 alloc_sysc_str(pcpui->cur_kthread);
2752 /* syscall() does not return for exec and yield, so put any cleanup in there
2754 sysc->retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
2755 sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
2756 /* Need to re-load pcpui, in case we migrated */
2757 pcpui = &per_cpu_info[core_id()];
2758 free_sysc_str(pcpui->cur_kthread);
2759 systrace_finish_trace(pcpui->cur_kthread, sysc->retval);
2760 pcpui = &per_cpu_info[core_id()]; /* reload again */
2761 /* Some 9ns paths set errstr, but not errno. glibc will ignore errstr.
2762 * this is somewhat hacky, since errno might get set unnecessarily */
2763 if ((current_errstr()[0] != 0) && (!sysc->err))
2764 sysc->err = EUNSPECIFIED;
2765 finish_sysc(sysc, pcpui->cur_proc);
2766 pcpui->cur_kthread->sysc = NULL; /* No longer working on sysc */
2769 /* A process can trap and call this function, which will set up the core to
2770 * handle all the syscalls. a.k.a. "sys_debutante(needs, wants)". If there is
2771 * at least one, it will run it directly. */
2772 void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
2774 /* Careful with pcpui here, we could have migrated */
2776 printk("[kernel] No nr_sysc, probably a bug, user!\n");
2779 /* For all after the first call, send ourselves a KMSG (TODO). */
2781 warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
2782 /* Call the first one directly. (we already checked to make sure there is
2784 run_local_syscall(sysc);
2787 /* Call this when something happens on the syscall where userspace might want to
2788 * get signaled. Passing p, since the caller should know who the syscall
2789 * belongs to (probably is current).
2791 * You need to have SC_K_LOCK set when you call this. */
2792 void __signal_syscall(struct syscall *sysc, struct proc *p)
2794 struct event_queue *ev_q;
2795 struct event_msg local_msg;
2796 /* User sets the ev_q then atomically sets the flag (races with SC_DONE) */
2797 if (atomic_read(&sysc->flags) & SC_UEVENT) {
2798 rmb(); /* read the ev_q after reading the flag */
2801 memset(&local_msg, 0, sizeof(struct event_msg));
2802 local_msg.ev_type = EV_SYSCALL;
2803 local_msg.ev_arg3 = sysc;
2804 send_event(p, ev_q, &local_msg, 0);
2809 bool syscall_uses_fd(struct syscall *sysc, int fd)
2811 switch (sysc->num) {
2820 if (sysc->arg0 == fd)
2824 /* mmap always has to be special. =) */
2825 if (sysc->arg4 == fd)
2833 void print_sysc(struct proc *p, struct syscall *sysc)
2835 uintptr_t old_p = switch_to(p);
2836 printk("SYS_%d, flags %p, a0 %p, a1 %p, a2 %p, a3 %p, a4 %p, a5 %p\n",
2837 sysc->num, atomic_read(&sysc->flags),
2838 sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
2840 switch_back(p, old_p);