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 <colored_caches.h>
28 #include <hashtable.h>
33 #include <arsc_server.h>
38 #include <ros/procinfo.h>
40 static int execargs_stringer(struct proc *p, char *d, size_t slen,
41 char *path, size_t path_l,
42 char *argenv, size_t argenv_l);
44 /* Global, used by the kernel monitor for syscall debugging. */
45 bool systrace_loud = FALSE;
47 /* Helper, given the trace record, pretty-print the trace's contents into the
48 * trace's pretty buf. 'entry' says whether we're an entry record or not
49 * (exit). Returns the number of bytes put into the pretty_buf. */
50 static size_t systrace_fill_pretty_buf(struct systrace_record *trace,
54 struct timespec ts_start = tsc2timespec(trace->start_timestamp);
55 struct timespec ts_end = tsc2timespec(trace->end_timestamp);
57 /* Slightly different formats between entry and exit. Entry has retval set
58 * to ---, and begins with E. Exit begins with X. */
60 len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
61 "E [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, 0x%llx, "
62 "0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: --- proc: %d core: %d "
69 syscall_table[trace->syscallno].name,
80 len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
81 "X [%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, 0x%llx, "
82 "0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: 0x%llx proc: %d core: %d "
89 syscall_table[trace->syscallno].name,
101 len += printdump(trace->pretty_buf + len, trace->datalen,
102 SYSTR_PRETTY_BUF_SZ - len - 1,
104 len += snprintf(trace->pretty_buf + len, SYSTR_PRETTY_BUF_SZ - len, "\n");
108 /* Helper: spits out our trace to the various sinks. */
109 static void systrace_output(struct systrace_record *trace,
110 struct strace *strace, bool entry)
114 pretty_len = systrace_fill_pretty_buf(trace, entry);
116 qiwrite(strace->q, trace->pretty_buf, pretty_len);
118 printk("%s", trace->pretty_buf);
121 /* Starts a trace for p running sysc, attaching it to kthread. Pairs with
122 * systrace_finish_trace(). */
123 static void systrace_start_trace(struct kthread *kthread, struct syscall *sysc)
125 struct proc *p = current;
126 struct systrace_record *trace;
131 if (!p->strace_on && !systrace_loud)
133 trace = kmalloc(SYSTR_BUF_SZ, MEM_ATOMIC);
135 /* We're using qiwrite below, which has no flow control. We'll do it
136 * manually. TODO: consider a block_alloc and qpass, though note that
137 * we actually write the same trace in twice (entry and exit).
138 * Alternatively, we can add another qio method that has flow control
139 * and non blocking. */
140 if (qfull(p->strace->q)) {
141 atomic_inc(&p->strace->nr_drops);
146 atomic_inc(&p->strace->nr_drops);
147 /* Avoiding the atomic op. We sacrifice accuracy for less overhead. */
148 p->strace->appx_nr_sysc++;
152 /* if you ever need to debug just one strace function, this is
153 * handy way to do it: just bail out if it's not the one you
155 * if (sysc->num != SYS_exec)
157 trace->start_timestamp = read_tsc();
158 trace->end_timestamp = 0;
159 trace->syscallno = sysc->num;
160 trace->arg0 = sysc->arg0;
161 trace->arg1 = sysc->arg1;
162 trace->arg2 = sysc->arg2;
163 trace->arg3 = sysc->arg3;
164 trace->arg4 = sysc->arg4;
165 trace->arg5 = sysc->arg5;
168 trace->coreid = core_id();
169 trace->vcoreid = proc_get_vcoreid(p);
170 trace->pretty_buf = (char*)trace + sizeof(struct systrace_record);
176 data_arg = sysc->arg1;
177 data_len = sysc->arg2;
180 data_arg = sysc->arg1;
181 data_len = sysc->arg2;
184 trace->datalen = execargs_stringer(current,
192 case SYS_proc_create:
193 trace->datalen = execargs_stringer(current,
203 trace->datalen = MIN(sizeof(trace->data), data_len);
204 copy_from_user(trace->data, (void*)data_arg, trace->datalen);
207 systrace_output(trace, p->strace, TRUE);
209 kthread->strace = trace;
212 /* Finishes the trace on kthread for p, with retval being the return from the
213 * syscall we're tracing. Pairs with systrace_start_trace(). */
214 static void systrace_finish_trace(struct kthread *kthread, long retval)
216 struct proc *p = current;
217 struct systrace_record *trace;
221 if (!kthread->strace)
223 trace = kthread->strace;
224 trace->end_timestamp = read_tsc();
225 trace->retval = retval;
227 /* Only try to do the trace data if we didn't do it on entry */
228 if (!trace->datalen) {
229 switch (trace->syscallno) {
231 data_arg = trace->arg1;
232 data_len = retval < 0 ? 0 : retval;
235 trace->datalen = MIN(sizeof(trace->data), data_len);
237 copy_from_user(trace->data, (void*)data_arg, trace->datalen);
240 systrace_output(trace, p->strace, FALSE);
241 kfree(kthread->strace);
245 #ifdef CONFIG_SYSCALL_STRING_SAVING
247 static void alloc_sysc_str(struct kthread *kth)
249 kth->name = kmalloc(SYSCALL_STRLEN, MEM_WAIT);
253 static void free_sysc_str(struct kthread *kth)
255 char *str = kth->name;
260 #define sysc_save_str(...) \
262 struct per_cpu_info *pcpui = &per_cpu_info[core_id()]; \
263 snprintf(pcpui->cur_kthread->name, SYSCALL_STRLEN, __VA_ARGS__); \
268 static void alloc_sysc_str(struct kthread *kth)
272 static void free_sysc_str(struct kthread *kth)
276 #define sysc_save_str(...)
278 #endif /* CONFIG_SYSCALL_STRING_SAVING */
280 /* Helper to finish a syscall, signalling if appropriate */
281 static void finish_sysc(struct syscall *sysc, struct proc *p)
283 /* Atomically turn on the LOCK and SC_DONE flag. The lock tells userspace
284 * we're messing with the flags and to not proceed. We use it instead of
285 * CASing with userspace. We need the atomics since we're racing with
286 * userspace for the event_queue registration. The 'lock' tells userspace
287 * to not muck with the flags while we're signalling. */
288 atomic_or(&sysc->flags, SC_K_LOCK | SC_DONE);
289 __signal_syscall(sysc, p);
290 atomic_and(&sysc->flags, ~SC_K_LOCK);
293 /* Helper that "finishes" the current async syscall. This should be used with
294 * care when we are not using the normal syscall completion path.
296 * Do *NOT* complete the same syscall twice. This is catastrophic for _Ms, and
299 * It is possible for another user thread to see the syscall being done early -
300 * they just need to be careful with the weird proc management calls (as in,
301 * don't trust an async fork).
303 * *sysc is in user memory, and should be pinned (TODO: UMEM). There may be
304 * issues with unpinning this if we never return. */
305 static void finish_current_sysc(int retval)
307 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
308 assert(pcpui->cur_kthread->sysc);
309 pcpui->cur_kthread->sysc->retval = retval;
310 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
313 /* Callable by any function while executing a syscall (or otherwise, actually).
315 void set_errno(int errno)
317 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
318 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
319 pcpui->cur_kthread->sysc->err = errno;
322 /* Callable by any function while executing a syscall (or otherwise, actually).
326 /* if there's no errno to get, that's not an error I guess. */
328 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
329 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
330 errno = pcpui->cur_kthread->sysc->err;
334 void unset_errno(void)
336 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
337 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
339 pcpui->cur_kthread->sysc->err = 0;
340 pcpui->cur_kthread->sysc->errstr[0] = '\0';
343 void vset_errstr(const char *fmt, va_list ap)
345 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
347 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
350 vsnprintf(pcpui->cur_kthread->sysc->errstr, MAX_ERRSTR_LEN, fmt, ap);
352 /* TODO: likely not needed */
353 pcpui->cur_kthread->sysc->errstr[MAX_ERRSTR_LEN - 1] = '\0';
356 void set_errstr(const char *fmt, ...)
362 vset_errstr(fmt, ap);
366 char *current_errstr(void)
368 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
369 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
371 return pcpui->cur_kthread->sysc->errstr;
374 void set_error(int error, const char *fmt, ...)
382 vset_errstr(fmt, ap);
386 struct errbuf *get_cur_errbuf(void)
388 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
389 return pcpui->cur_kthread->errbuf;
392 void set_cur_errbuf(struct errbuf *ebuf)
394 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
395 pcpui->cur_kthread->errbuf = ebuf;
398 char *get_cur_genbuf(void)
400 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
401 assert(pcpui->cur_kthread);
402 return pcpui->cur_kthread->generic_buf;
405 /* Helper, looks up proc* for pid and ensures p controls that proc. 0 o/w */
406 static struct proc *get_controllable_proc(struct proc *p, pid_t pid)
408 struct proc *target = pid2proc(pid);
413 if (!proc_controls(p, target)) {
421 static int unpack_argenv(struct argenv *argenv, size_t argenv_l,
422 int *argc_p, char ***argv_p,
423 int *envc_p, char ***envp_p)
425 int argc = argenv->argc;
426 int envc = argenv->envc;
427 char **argv = (char**)argenv->buf;
428 char **envp = argv + argc;
429 char *argbuf = (char*)(envp + envc);
430 uintptr_t argbuf_offset = (uintptr_t)(argbuf - (char*)(argenv));
432 if (((char*)argv - (char*)argenv) > argenv_l)
434 if (((char*)argv + (argc * sizeof(char**)) - (char*)argenv) > argenv_l)
436 if (((char*)envp - (char*)argenv) > argenv_l)
438 if (((char*)envp + (envc * sizeof(char**)) - (char*)argenv) > argenv_l)
440 if (((char*)argbuf - (char*)argenv) > argenv_l)
442 for (int i = 0; i < argc; i++) {
443 if ((uintptr_t)(argv[i] + argbuf_offset) > argenv_l)
445 argv[i] += (uintptr_t)argbuf;
447 for (int i = 0; i < envc; i++) {
448 if ((uintptr_t)(envp[i] + argbuf_offset) > argenv_l)
450 envp[i] += (uintptr_t)argbuf;
459 /************** Utility Syscalls **************/
461 static int sys_null(void)
466 /* Diagnostic function: blocks the kthread/syscall, to help userspace test its
467 * async I/O handling. */
468 static int sys_block(struct proc *p, unsigned long usec)
470 sysc_save_str("block for %lu usec", usec);
471 kthread_usleep(usec);
475 /* Pause execution for a number of nanoseconds.
476 * The current implementation rounds up to the nearest microsecond. If the
477 * syscall is aborted, we return the remaining time the call would have ran
478 * in the 'rem' parameter. */
479 static int sys_nanosleep(struct proc *p,
480 const struct timespec *req,
481 struct timespec *rem)
485 struct timespec kreq, krem = {0, 0};
486 uint64_t tsc = read_tsc();
488 /* Check the input arguments. */
489 if (memcpy_from_user(p, &kreq, req, sizeof(struct timespec))) {
493 if (rem && memcpy_to_user(p, rem, &krem, sizeof(struct timespec))) {
497 if (kreq.tv_sec < 0) {
501 if ((kreq.tv_nsec < 0) || (kreq.tv_nsec > 999999999)) {
506 /* Convert timespec to usec. Ignore overflow on the tv_sec field. */
507 usec = kreq.tv_sec * 1000000;
508 usec += DIV_ROUND_UP(kreq.tv_nsec, 1000);
510 /* Attempt to sleep. If we get aborted, copy the remaining time into
511 * 'rem' and return. We assume the tsc is sufficient to tell how much
512 * time is remaining (i.e. it only overflows on the order of hundreds of
513 * years, which should be sufficiently long enough to ensure we don't
516 krem = tsc2timespec(read_tsc() - tsc);
517 if (rem && memcpy_to_user(p, rem, &krem, sizeof(struct timespec)))
522 sysc_save_str("nanosleep for %d usec", usec);
523 kthread_usleep(usec);
528 // Writes 'val' to 'num_writes' entries of the well-known array in the kernel
529 // address space. It's just #defined to be some random 4MB chunk (which ought
530 // to be boot_alloced or something). Meant to grab exclusive access to cache
531 // lines, to simulate doing something useful.
532 static int sys_cache_buster(struct proc *p, uint32_t num_writes,
533 uint32_t num_pages, uint32_t flags)
535 #define BUSTER_ADDR 0xd0000000L // around 512 MB deep
536 #define MAX_WRITES 1048576*8
538 #define INSERT_ADDR (UINFO + 2*PGSIZE) // should be free for these tests
539 uint32_t* buster = (uint32_t*)BUSTER_ADDR;
540 static spinlock_t buster_lock = SPINLOCK_INITIALIZER;
542 page_t* a_page[MAX_PAGES];
544 /* Strided Accesses or Not (adjust to step by cachelines) */
546 if (flags & BUSTER_STRIDED) {
551 /* Shared Accesses or Not (adjust to use per-core regions)
552 * Careful, since this gives 8MB to each core, starting around 512MB.
553 * Also, doesn't separate memory for core 0 if it's an async call.
555 if (!(flags & BUSTER_SHARED))
556 buster = (uint32_t*)(BUSTER_ADDR + core_id() * 0x00800000);
558 /* Start the timer, if we're asked to print this info*/
559 if (flags & BUSTER_PRINT_TICKS)
560 ticks = start_timing();
562 /* Allocate num_pages (up to MAX_PAGES), to simulate doing some more
563 * realistic work. Note we don't write to these pages, even if we pick
564 * unshared. Mostly due to the inconvenience of having to match up the
565 * number of pages with the number of writes. And it's unnecessary.
568 spin_lock(&buster_lock);
569 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
570 upage_alloc(p, &a_page[i],1);
571 page_insert(p->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
573 page_decref(a_page[i]);
575 spin_unlock(&buster_lock);
578 if (flags & BUSTER_LOCKED)
579 spin_lock(&buster_lock);
580 for (int i = 0; i < MIN(num_writes, MAX_WRITES); i=i+stride)
581 buster[i] = 0xdeadbeef;
582 if (flags & BUSTER_LOCKED)
583 spin_unlock(&buster_lock);
586 spin_lock(&buster_lock);
587 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
588 page_remove(p->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
589 page_decref(a_page[i]);
591 spin_unlock(&buster_lock);
595 if (flags & BUSTER_PRINT_TICKS) {
596 ticks = stop_timing(ticks);
597 printk("%llu,", ticks);
602 static int sys_cache_invalidate(void)
610 /* sys_reboot(): called directly from dispatch table. */
612 /* Returns the id of the physical core this syscall is executed on. */
613 static uint32_t sys_getpcoreid(void)
618 // TODO: Temporary hack until thread-local storage is implemented on i386 and
619 // this is removed from the user interface
620 static size_t sys_getvcoreid(struct proc *p)
622 return proc_get_vcoreid(p);
625 /************** Process management syscalls **************/
627 /* Helper for proc_create and fork */
628 static void inherit_strace(struct proc *parent, struct proc *child)
630 if (parent->strace && parent->strace_inherit) {
631 /* Refcnt on both, put in the child's ->strace. */
632 kref_get(&parent->strace->users, 1);
633 kref_get(&parent->strace->procs, 1);
634 child->strace = parent->strace;
635 child->strace_on = TRUE;
636 child->strace_inherit = TRUE;
640 /* Creates a process from the file 'path'. The process is not runnable by
641 * default, so it needs it's status to be changed so that the next call to
642 * schedule() will try to run it. */
643 static int sys_proc_create(struct proc *p, char *path, size_t path_l,
644 char *argenv, size_t argenv_l, int flags)
648 struct file *program;
652 struct argenv *kargenv;
654 t_path = copy_in_path(p, path, path_l);
657 /* TODO: 9ns support */
658 program = do_file_open(t_path, O_READ, 0);
660 goto error_with_path;
661 if (!is_valid_elf(program)) {
663 goto error_with_file;
665 /* Check the size of the argenv array, error out if too large. */
666 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
667 set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
669 goto error_with_file;
671 /* Copy the argenv array into a kernel buffer. Delay processing of the
672 * array to load_elf(). */
673 kargenv = user_memdup_errno(p, argenv, argenv_l);
675 set_error(EINVAL, "Failed to copy in the args");
676 goto error_with_file;
678 /* Unpack the argenv array into more usable variables. Integrity checking
679 * done along side this as well. */
680 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
681 set_error(EINVAL, "Failed to unpack the args");
682 goto error_with_kargenv;
684 /* TODO: need to split the proc creation, since you must load after setting
685 * args/env, since auxp gets set up there. */
686 //new_p = proc_create(program, 0, 0);
687 if (proc_alloc(&new_p, current, flags)) {
688 set_error(ENOMEM, "Failed to alloc new proc");
689 goto error_with_kargenv;
691 inherit_strace(p, new_p);
692 /* close the CLOEXEC ones, even though this isn't really an exec */
693 close_fdt(&new_p->open_files, TRUE);
695 if (load_elf(new_p, program, argc, argv, envc, envp)) {
696 set_error(EINVAL, "Failed to load elf");
697 goto error_with_proc;
699 /* progname is argv0, which accounts for symlinks */
700 proc_set_progname(new_p, argc ? argv[0] : NULL);
701 proc_replace_binary_path(new_p, t_path);
702 kref_put(&program->f_kref);
703 user_memdup_free(p, kargenv);
706 profiler_notify_new_process(new_p);
707 proc_decref(new_p); /* give up the reference created in proc_create() */
710 /* proc_destroy will decref once, which is for the ref created in
711 * proc_create(). We don't decref again (the usual "+1 for existing"),
712 * since the scheduler, which usually handles that, hasn't heard about the
713 * process (via __proc_ready()). */
716 user_memdup_free(p, kargenv);
718 kref_put(&program->f_kref);
720 free_path(p, t_path);
724 /* Makes process PID runnable. Consider moving the functionality to process.c */
725 static error_t sys_proc_run(struct proc *p, unsigned pid)
728 struct proc *target = get_controllable_proc(p, pid);
731 if (target->state != PROC_CREATED) {
736 /* Note a proc can spam this for someone it controls. Seems safe - if it
737 * isn't we can change it. */
743 /* Destroy proc pid. If this is called by the dying process, it will never
744 * return. o/w it will return 0 on success, or an error. Errors include:
745 * - ESRCH: if there is no such process with pid
746 * - EPERM: if caller does not control pid */
747 static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
750 struct proc *p_to_die = get_controllable_proc(p, pid);
754 p->exitcode = exitcode;
755 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
757 p_to_die->exitcode = exitcode; /* so its parent has some clue */
758 printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
760 proc_destroy(p_to_die);
761 /* we only get here if we weren't the one to die */
762 proc_decref(p_to_die);
766 static int sys_proc_yield(struct proc *p, bool being_nice)
768 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
769 /* proc_yield() often doesn't return - we need to set the syscall retval
770 * early. If it doesn't return, it expects to eat our reference (for now).
772 free_sysc_str(pcpui->cur_kthread);
773 systrace_finish_trace(pcpui->cur_kthread, 0);
774 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
775 pcpui->cur_kthread->sysc = 0; /* don't touch sysc again */
777 proc_yield(p, being_nice);
779 /* Shouldn't return, to prevent the chance of mucking with cur_sysc. */
784 static int sys_change_vcore(struct proc *p, uint32_t vcoreid,
785 bool enable_my_notif)
787 /* Note retvals can be negative, but we don't mess with errno in case
788 * callers use this in low-level code and want to extract the 'errno'. */
789 return proc_change_to_vcore(p, vcoreid, enable_my_notif);
792 static ssize_t sys_fork(env_t* e)
797 // TODO: right now we only support fork for single-core processes
798 if (e->state != PROC_RUNNING_S) {
803 ret = proc_alloc(&env, current, PROC_DUP_FGRP);
806 proc_set_progname(env, e->progname);
808 /* Can't really fork if we don't have a current_ctx to fork */
815 copy_current_ctx_to(&env->scp_ctx);
817 env->cache_colors_map = cache_colors_map_alloc();
818 for (int i = 0; i < llc_cache->num_colors; i++)
819 if (GET_BITMASK_BIT(e->cache_colors_map,i))
820 cache_color_alloc(llc_cache, env->cache_colors_map);
822 /* Make the new process have the same VMRs as the older. This will copy the
823 * contents of non MAP_SHARED pages to the new VMRs. */
824 if (duplicate_vmrs(e, env)) {
825 proc_destroy(env); /* this is prob what you want, not decref by 2 */
830 /* Switch to the new proc's address space and finish the syscall. We'll
831 * never naturally finish this syscall for the new proc, since its memory
832 * is cloned before we return for the original process. If we ever do CoW
833 * for forked memory, this will be the first place that gets CoW'd. */
834 temp = switch_to(env);
835 finish_current_sysc(0);
836 switch_back(env, temp);
838 /* Copy some state from the original proc into the new proc. */
839 env->heap_top = e->heap_top;
840 env->env_flags = e->env_flags;
842 inherit_strace(e, env);
844 /* In general, a forked process should be a fresh process, and we copy over
845 * whatever stuff is needed between procinfo/procdata. */
846 *env->procdata = *e->procdata;
847 env->procinfo->heap_bottom = e->procinfo->heap_bottom;
849 /* FYI: once we call ready, the proc is open for concurrent usage */
853 // don't decref the new process.
854 // that will happen when the parent waits for it.
855 // TODO: if the parent doesn't wait, we need to change the child's parent
856 // when the parent dies, or at least decref it
858 printd("[PID %d] fork PID %d\n", e->pid, env->pid);
860 profiler_notify_new_process(env);
861 proc_decref(env); /* give up the reference created in proc_alloc() */
865 /* string for sys_exec arguments. Assumes that d is pointing to zero'd
866 * storage or storage that does not require null termination or
867 * provides the null. */
868 static int execargs_stringer(struct proc *p, char *d, size_t slen,
869 char *path, size_t path_l,
870 char *argenv, size_t argenv_l)
874 struct argenv *kargenv;
881 if (memcpy_from_user(p, d, path, path_l)) {
882 s = seprintf(s, e, "Invalid exec path");
887 /* yes, this code is cloned from below. I wrote a helper but
888 * Barret and I concluded after talking about it that the
889 * helper was not really helper-ful, as it has almost 10
890 * arguments. Please, don't suggest a cpp macro. Thank you. */
891 /* Check the size of the argenv array, error out if too large. */
892 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
893 s = seprintf(s, e, "The argenv array has an invalid size: %lu\n",
897 /* Copy the argenv array into a kernel buffer. */
898 kargenv = user_memdup_errno(p, argenv, argenv_l);
900 s = seprintf(s, e, "Failed to copy in the args and environment");
903 /* Unpack the argenv array into more usable variables. Integrity checking
904 * done along side this as well. */
905 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
906 s = seprintf(s, e, "Failed to unpack the args");
907 user_memdup_free(p, kargenv);
910 s = seprintf(s, e, "[%d]{", argc);
911 for (i = 0; i < argc; i++)
912 s = seprintf(s, e, "%s, ", argv[i]);
913 s = seprintf(s, e, "}");
915 user_memdup_free(p, kargenv);
919 /* Load the binary "path" into the current process, and start executing it.
920 * argv and envp are magically bundled in procinfo for now. Keep in sync with
921 * glibc's sysdeps/ros/execve.c. Once past a certain point, this function won't
922 * return. It assumes (and checks) that it is current. Don't give it an extra
923 * refcnt'd *p (syscall won't do that).
924 * Note: if someone batched syscalls with this call, they could clobber their
925 * old memory (and will likely PF and die). Don't do it... */
926 static int sys_exec(struct proc *p, char *path, size_t path_l,
927 char *argenv, size_t argenv_l)
931 struct file *program;
932 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
935 struct argenv *kargenv;
937 /* We probably want it to never be allowed to exec if it ever was _M */
938 if (p->state != PROC_RUNNING_S) {
942 if (p != pcpui->cur_proc) {
947 /* Can't exec if we don't have a current_ctx to restart (if we fail). This
948 * isn't 100% true, but I'm okay with it. */
949 if (!pcpui->cur_ctx) {
953 /* Preemptively copy out the cur_ctx, in case we fail later (easier on
954 * cur_ctx if we do this now) */
955 copy_current_ctx_to(&p->scp_ctx);
956 /* Check the size of the argenv array, error out if too large. */
957 if ((argenv_l < sizeof(struct argenv)) || (argenv_l > ARG_MAX)) {
958 set_error(EINVAL, "The argenv array has an invalid size: %lu\n",
962 /* Copy the argenv array into a kernel buffer. */
963 kargenv = user_memdup_errno(p, argenv, argenv_l);
965 set_errstr("Failed to copy in the args and environment");
968 /* Unpack the argenv array into more usable variables. Integrity checking
969 * done along side this as well. */
970 if (unpack_argenv(kargenv, argenv_l, &argc, &argv, &envc, &envp)) {
971 user_memdup_free(p, kargenv);
972 set_error(EINVAL, "Failed to unpack the args");
975 t_path = copy_in_path(p, path, path_l);
977 user_memdup_free(p, kargenv);
980 /* This could block: */
981 /* TODO: 9ns support */
982 program = do_file_open(t_path, O_READ, 0);
983 /* Clear the current_ctx. We won't be returning the 'normal' way. Even if
984 * we want to return with an error, we need to go back differently in case
985 * we succeed. This needs to be done before we could possibly block, but
986 * unfortunately happens before the point of no return.
988 * Note that we will 'hard block' if we block at all. We can't return to
989 * userspace and then asynchronously finish the exec later. */
990 clear_owning_proc(core_id());
993 if (!is_valid_elf(program)) {
997 /* This is the point of no return for the process. */
998 /* progname is argv0, which accounts for symlinks */
999 proc_replace_binary_path(p, t_path);
1000 proc_set_progname(p, argc ? argv[0] : NULL);
1001 proc_init_procdata(p);
1002 p->procinfo->heap_bottom = 0;
1003 /* When we destroy our memory regions, accessing cur_sysc would PF */
1004 pcpui->cur_kthread->sysc = 0;
1005 unmap_and_destroy_vmrs(p);
1006 /* close the CLOEXEC ones */
1007 close_fdt(&p->open_files, TRUE);
1008 env_user_mem_free(p, 0, UMAPTOP);
1009 if (load_elf(p, program, argc, argv, envc, envp)) {
1010 kref_put(&program->f_kref);
1011 user_memdup_free(p, kargenv);
1012 /* Note this is an inedible reference, but proc_destroy now returns */
1014 /* We don't want to do anything else - we just need to not accidentally
1015 * return to the user (hence the all_out) */
1018 printd("[PID %d] exec %s\n", p->pid, file_name(program));
1019 kref_put(&program->f_kref);
1020 systrace_finish_trace(pcpui->cur_kthread, 0);
1022 /* These error and out paths are so we can handle the async interface, both
1023 * for when we want to error/return to the proc, as well as when we succeed
1024 * and want to start the newly exec'd _S */
1026 /* These two error paths are for when we want to restart the process with an
1027 * error value (errno is already set). */
1028 kref_put(&program->f_kref);
1030 free_path(p, t_path);
1031 finish_current_sysc(-1);
1032 systrace_finish_trace(pcpui->cur_kthread, -1);
1034 user_memdup_free(p, kargenv);
1035 free_sysc_str(pcpui->cur_kthread);
1036 /* Here's how we restart the new (on success) or old (on failure) proc: */
1037 spin_lock(&p->proc_lock);
1038 __seq_start_write(&p->procinfo->coremap_seqctr);
1039 __unmap_vcore(p, 0);
1040 __seq_end_write(&p->procinfo->coremap_seqctr);
1041 __proc_set_state(p, PROC_WAITING); /* fake a yield */
1042 spin_unlock(&p->proc_lock);
1045 /* we can't return, since we'd write retvals to the old location of the
1046 * syscall struct (which has been freed and is in the old userspace) (or has
1047 * already been written to).*/
1048 disable_irq(); /* abandon_core/clear_own wants irqs disabled */
1050 smp_idle(); /* will reenable interrupts */
1053 /* Helper, will attempt a particular wait on a proc. Returns the pid of the
1054 * process if we waited on it successfully, and the status will be passed back
1055 * in ret_status (kernel memory). Returns 0 if the wait failed and we should
1056 * try again. Returns -1 if we should abort. Only handles DYING. Callers
1057 * need to lock to protect the children tailq and reaping bits. */
1058 static pid_t try_wait(struct proc *parent, struct proc *child, int *ret_status,
1061 if (proc_is_dying(child)) {
1062 /* Disown returns -1 if it's already been disowned or we should o/w
1063 * abort. This can happen if we have concurrent waiters, both with
1064 * pointers to the child (only one should reap). Note that if we don't
1065 * do this, we could go to sleep and never receive a cv_signal. */
1066 if (__proc_disown_child(parent, child))
1068 /* despite disowning, the child won't be freed til we drop this ref
1069 * held by this function, so it is safe to access the memory.
1071 * Note the exit code one byte in the 0xff00 spot. Check out glibc's
1072 * posix/sys/wait.h and bits/waitstatus.h for more info. If we ever
1073 * deal with signalling and stopping, we'll need to do some more work
1075 *ret_status = (child->exitcode & 0xff) << 8;
1081 /* Helper, like try_wait, but attempts a wait on any of the children, returning
1082 * the specific PID we waited on, 0 to try again (a waitable exists), and -1 to
1083 * abort (no children/waitables exist). Callers need to lock to protect the
1084 * children tailq and reaping bits.*/
1085 static pid_t try_wait_any(struct proc *parent, int *ret_status, int options)
1087 struct proc *i, *temp;
1089 if (TAILQ_EMPTY(&parent->children))
1091 /* Could have concurrent waiters mucking with the tailq, caller must lock */
1092 TAILQ_FOREACH_SAFE(i, &parent->children, sibling_link, temp) {
1093 retval = try_wait(parent, i, ret_status, options);
1094 /* This catches a thread causing a wait to fail but not taking the
1095 * child off the list before unlocking. Should never happen. */
1096 assert(retval != -1);
1097 /* Succeeded, return the pid of the child we waited on */
1101 assert(retval == 0);
1105 /* Waits on a particular child, returns the pid of the child waited on, and
1106 * puts the ret status in *ret_status. Returns the pid if we succeeded, 0 if
1107 * the child was not waitable and WNOHANG, and -1 on error. */
1108 static pid_t wait_one(struct proc *parent, struct proc *child, int *ret_status,
1112 cv_lock(&parent->child_wait);
1113 /* retval == 0 means we should block */
1114 retval = try_wait(parent, child, ret_status, options);
1115 if ((retval == 0) && (options & WNOHANG))
1119 cv_wait(&parent->child_wait);
1120 /* If we're dying, then we don't need to worry about waiting. We don't
1121 * do this yet, but we'll need this outlet when we deal with orphaned
1122 * children and having init inherit them. */
1123 if (proc_is_dying(parent))
1125 /* Any child can wake us up, but we check for the particular child we
1127 retval = try_wait(parent, child, ret_status, options);
1130 /* Child was already waited on by a concurrent syscall. */
1135 cv_unlock(&parent->child_wait);
1139 /* Waits on any child, returns the pid of the child waited on, and puts the ret
1140 * status in *ret_status. Is basically a waitpid(-1, ... ); See wait_one for
1141 * more details. Returns -1 if there are no children to wait on, and returns 0
1142 * if there are children and we need to block but WNOHANG was set. */
1143 static pid_t wait_any(struct proc *parent, int *ret_status, int options)
1146 cv_lock(&parent->child_wait);
1147 retval = try_wait_any(parent, ret_status, options);
1148 if ((retval == 0) && (options & WNOHANG))
1152 cv_wait(&parent->child_wait);
1153 if (proc_is_dying(parent))
1155 /* Any child can wake us up from the CV. This is a linear try_wait
1156 * scan. If we have a lot of children, we could optimize this. */
1157 retval = try_wait_any(parent, ret_status, options);
1160 assert(TAILQ_EMPTY(&parent->children));
1163 cv_unlock(&parent->child_wait);
1167 /* Note: we only allow waiting on children (no such thing as threads, for
1168 * instance). Right now we only allow waiting on termination (not signals),
1169 * and we don't have a way for parents to disown their children (such as
1170 * ignoring SIGCHLD, see man 2 waitpid's Notes).
1172 * We don't bother with stop/start signals here, though we can probably build
1173 * it in the helper above.
1175 * Returns the pid of who we waited on, or -1 on error, or 0 if we couldn't
1176 * wait (WNOHANG). */
1177 static pid_t sys_waitpid(struct proc *parent, pid_t pid, int *status,
1184 sysc_save_str("waitpid on %d", pid);
1185 /* -1 is the signal for 'any child' */
1187 retval = wait_any(parent, &ret_status, options);
1190 child = pid2proc(pid);
1192 set_errno(ECHILD); /* ECHILD also used for no proc */
1196 if (!(parent->pid == child->ppid)) {
1201 retval = wait_one(parent, child, &ret_status, options);
1206 /* ignoring / don't care about memcpy's retval here. */
1208 memcpy_to_user(parent, status, &ret_status, sizeof(ret_status));
1209 printd("[PID %d] waited for PID %d, got retval %d (status 0x%x)\n",
1210 parent->pid, pid, retval, ret_status);
1214 /************** Memory Management Syscalls **************/
1216 static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
1217 int flags, int fd, off_t offset)
1219 return mmap(p, addr, len, prot, flags, fd, offset);
1222 static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
1224 return mprotect(p, (uintptr_t)addr, len, prot);
1227 static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
1229 return munmap(p, (uintptr_t)addr, len);
1232 static ssize_t sys_shared_page_alloc(env_t* p1,
1233 void **_addr, pid_t p2_id,
1234 int p1_flags, int p2_flags
1237 printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
1241 static int sys_shared_page_free(env_t* p1, void *addr, pid_t p2)
1246 /* Helper, to do the actual provisioning of a resource to a proc */
1247 static int prov_resource(struct proc *target, unsigned int res_type,
1252 /* in the off chance we have a kernel scheduler that can't
1253 * provision, we'll need to change this. */
1254 return provision_core(target, res_val);
1256 printk("[kernel] received provisioning for unknown resource %d\n",
1258 set_errno(ENOENT); /* or EINVAL? */
1263 /* Rough syscall to provision res_val of type res_type to target_pid */
1264 static int sys_provision(struct proc *p, int target_pid,
1265 unsigned int res_type, long res_val)
1267 struct proc *target = pid2proc(target_pid);
1270 if (target_pid == 0)
1271 return prov_resource(0, res_type, res_val);
1272 /* debugging interface */
1273 if (target_pid == -1)
1274 print_coreprov_map();
1278 retval = prov_resource(target, res_type, res_val);
1279 proc_decref(target);
1283 /* Untested. Will notify the target on the given vcore, if the caller controls
1284 * the target. Will honor the target's wanted/vcoreid. u_ne can be NULL. */
1285 static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
1286 struct event_msg *u_msg)
1288 struct event_msg local_msg = {0};
1289 struct proc *target = get_controllable_proc(p, target_pid);
1292 /* if the user provided an ev_msg, copy it in and use that */
1294 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1295 proc_decref(target);
1300 local_msg.ev_type = ev_type;
1302 send_kernel_event(target, &local_msg, 0);
1303 proc_decref(target);
1307 /* Will notify the calling process on the given vcore, independently of WANTED
1308 * or advertised vcoreid. If you change the parameters, change pop_user_ctx().
1310 static int sys_self_notify(struct proc *p, uint32_t vcoreid,
1311 unsigned int ev_type, struct event_msg *u_msg,
1314 struct event_msg local_msg = {0};
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))) {
1322 local_msg.ev_type = ev_type;
1324 if (local_msg.ev_type >= MAX_NR_EVENT) {
1325 printk("[kernel] received self-notify for vcoreid %d, ev_type %d, "
1326 "u_msg %p, u_msg->type %d\n", vcoreid, ev_type, u_msg,
1327 u_msg ? u_msg->ev_type : 0);
1330 /* this will post a message and IPI, regardless of wants/needs/debutantes.*/
1331 post_vcore_event(p, &local_msg, vcoreid, priv ? EVENT_VCORE_PRIVATE : 0);
1332 proc_notify(p, vcoreid);
1336 /* Puts the calling core into vcore context, if it wasn't already, via a
1337 * self-IPI / active notification. Barring any weird unmappings, we just send
1338 * ourselves a __notify. */
1339 static int sys_vc_entry(struct proc *p)
1341 send_kernel_message(core_id(), __notify, (long)p, 0, 0, KMSG_ROUTINE);
1345 /* This will halt the core, waking on an IRQ. These could be kernel IRQs for
1346 * things like timers or devices, or they could be IPIs for RKMs (__notify for
1347 * an evq with IPIs for a syscall completion, etc).
1349 * We don't need to finish the syscall early (worried about the syscall struct,
1350 * on the vcore's stack). The syscall will finish before any __preempt RKM
1351 * executes, so the vcore will not restart somewhere else before the syscall
1352 * completes (unlike with yield, where the syscall itself adjusts the vcore
1355 * In the future, RKM code might avoid sending IPIs if the core is already in
1356 * the kernel. That code will need to check the CPU's state in some manner, and
1357 * send if the core is halted/idle.
1359 * The core must wake up for RKMs, including RKMs that arrive while the kernel
1360 * is trying to halt. The core need not abort the halt for notif_pending for
1361 * the vcore, only for a __notify or other RKM. Anyone setting notif_pending
1362 * should then attempt to __notify (o/w it's probably a bug). */
1363 static int sys_halt_core(struct proc *p, unsigned long usec)
1365 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1366 struct preempt_data *vcpd;
1367 /* The user can only halt CG cores! (ones it owns) */
1368 if (management_core())
1371 /* both for accounting and possible RKM optimizations */
1372 __set_cpu_state(pcpui, CPU_STATE_IDLE);
1374 if (has_routine_kmsg()) {
1375 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1379 /* This situation possible, though the check is not necessary. We can't
1380 * assert notif_pending isn't set, since another core may be in the
1381 * proc_notify. Thus we can't tell if this check here caught a bug, or just
1383 vcpd = &p->procdata->vcore_preempt_data[pcpui->owning_vcoreid];
1384 if (vcpd->notif_pending) {
1385 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1389 /* CPU_STATE is reset to KERNEL by the IRQ handler that wakes us */
1394 /* Changes a process into _M mode, or -EINVAL if it already is an mcp.
1395 * __proc_change_to_m() returns and we'll eventually finish the sysc later. The
1396 * original context may restart on a remote core before we return and finish,
1397 * but that's fine thanks to the async kernel interface. */
1398 static int sys_change_to_m(struct proc *p)
1400 int retval = proc_change_to_m(p);
1401 /* convert the kernel error code into (-1, errno) */
1409 /* Assists the user/2LS by atomically running *ctx and leaving vcore context.
1410 * Normally, the user can do this themselves, but x86 VM contexts need kernel
1411 * support. The caller ought to be in vcore context, and if a notif is pending,
1412 * then the calling vcore will restart in a fresh VC ctx (as if it was notified
1413 * or did a sys_vc_entry).
1415 * Note that this will set the TLS too, which is part of the context. Parlib's
1416 * pop_user_ctx currently does *not* do this, since the TLS is managed
1417 * separately. If you want to use this syscall for testing, you'll need to 0
1418 * out fsbase and conditionally write_msr in proc_pop_ctx(). */
1419 static int sys_pop_ctx(struct proc *p, struct user_context *ctx)
1421 int pcoreid = core_id();
1422 struct per_cpu_info *pcpui = &per_cpu_info[pcoreid];
1423 int vcoreid = pcpui->owning_vcoreid;
1424 struct preempt_data *vcpd = &p->procdata->vcore_preempt_data[vcoreid];
1426 /* With change_to, there's a bunch of concerns about changing the vcore map,
1427 * since the kernel may have already locked and sent preempts, deaths, etc.
1429 * In this case, we don't care as much. Other than notif_pending and
1430 * notif_disabled, it's more like we're just changing a few registers in
1431 * cur_ctx. We can safely order-after any kernel messages or other changes,
1432 * as if the user had done all of the changes we'll make and then did a
1435 * Since we are mucking with current_ctx, it is important that we don't
1436 * block before or during this syscall. */
1437 arch_finalize_ctx(pcpui->cur_ctx);
1438 if (copy_from_user(pcpui->cur_ctx, ctx, sizeof(struct user_context))) {
1439 /* The 2LS isn't really in a position to handle errors. At the very
1440 * least, we can print something and give them a fresh vc ctx. */
1441 printk("[kernel] unable to copy user_ctx, 2LS bug\n");
1442 memset(pcpui->cur_ctx, 0, sizeof(struct user_context));
1443 proc_init_ctx(pcpui->cur_ctx, vcoreid, vcpd->vcore_entry,
1444 vcpd->vcore_stack, vcpd->vcore_tls_desc);
1447 proc_secure_ctx(pcpui->cur_ctx);
1448 /* The caller leaves vcore context no matter what. We'll put them back in
1449 * if they missed a message. */
1450 vcpd->notif_disabled = FALSE;
1451 wrmb(); /* order disabled write before pending read */
1452 if (vcpd->notif_pending)
1453 send_kernel_message(pcoreid, __notify, (long)p, 0, 0, KMSG_ROUTINE);
1457 /* Initializes a process to run virtual machine contexts, returning the number
1458 * initialized, optionally setting errno */
1459 static int sys_vmm_setup(struct proc *p, unsigned int nr_guest_pcores,
1460 struct vmm_gpcore_init *gpcis, int flags)
1469 ret = vmm_struct_init(p, nr_guest_pcores, gpcis, flags);
1474 static int sys_vmm_poke_guest(struct proc *p, int guest_pcoreid)
1476 return vmm_poke_guest(p, guest_pcoreid);
1479 /* Pokes the ksched for the given resource for target_pid. If the target pid
1480 * == 0, we just poke for the calling process. The common case is poking for
1481 * self, so we avoid the lookup.
1483 * Not sure if you could harm someone via asking the kernel to look at them, so
1484 * we'll do a 'controls' check for now. In the future, we might have something
1485 * in the ksched that limits or penalizes excessive pokes. */
1486 static int sys_poke_ksched(struct proc *p, int target_pid,
1487 unsigned int res_type)
1489 struct proc *target;
1492 poke_ksched(p, res_type);
1495 target = pid2proc(target_pid);
1500 if (!proc_controls(p, target)) {
1505 poke_ksched(target, res_type);
1507 proc_decref(target);
1511 static int sys_abort_sysc(struct proc *p, struct syscall *sysc)
1513 return abort_sysc(p, sysc);
1516 static int sys_abort_sysc_fd(struct proc *p, int fd)
1518 /* Consider checking for a bad fd. Doesn't matter now, since we only look
1519 * for actual syscalls blocked that had used fd. */
1520 return abort_all_sysc_fd(p, fd);
1523 static unsigned long sys_populate_va(struct proc *p, uintptr_t va,
1524 unsigned long nr_pgs)
1526 return populate_va(p, ROUNDDOWN(va, PGSIZE), nr_pgs);
1529 static intreg_t sys_read(struct proc *p, int fd, void *buf, size_t len)
1531 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1533 struct file *file = get_file_from_fd(&p->open_files, fd);
1534 sysc_save_str("read on fd %d", fd);
1537 if (!file->f_op->read) {
1538 kref_put(&file->f_kref);
1542 /* TODO: (UMEM) currently, read() handles user memcpy
1543 * issues, but we probably should user_mem_check and
1544 * pin the region here, so read doesn't worry about
1546 ret = file->f_op->read(file, buf, len, &file->f_pos);
1547 kref_put(&file->f_kref);
1549 /* plan9, should also handle errors (EBADF) */
1550 ret = sysread(fd, buf, len);
1555 static intreg_t sys_write(struct proc *p, int fd, const void *buf, size_t len)
1557 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1559 struct file *file = get_file_from_fd(&p->open_files, fd);
1561 sysc_save_str("write on fd %d", fd);
1564 if (!file->f_op->write) {
1565 kref_put(&file->f_kref);
1570 ret = file->f_op->write(file, buf, len, &file->f_pos);
1571 kref_put(&file->f_kref);
1573 /* plan9, should also handle errors */
1574 ret = syswrite(fd, (void*)buf, len);
1579 /* Checks args/reads in the path, opens the file (relative to fromfd if the path
1580 * is not absolute), and inserts it into the process's open file list. */
1581 static intreg_t sys_openat(struct proc *p, int fromfd, const char *path,
1582 size_t path_l, int oflag, int mode)
1585 struct file *file = 0;
1588 printd("File %s Open attempt oflag %x mode %x\n", path, oflag, mode);
1589 if ((oflag & O_PATH) && (oflag & O_ACCMODE)) {
1590 set_error(EINVAL, "Cannot open O_PATH with any I/O perms (O%o)", oflag);
1593 t_path = copy_in_path(p, path, path_l);
1596 sysc_save_str("open %s at fd %d", t_path, fromfd);
1597 mode &= ~p->fs_env.umask;
1598 /* Only check the VFS for legacy opens. It doesn't support openat. Actual
1599 * openats won't check here, and file == 0. */
1600 #define REMOVE_BEFORE_FLIGHT 1
1601 #if REMOVE_BEFORE_FLIGHT
1603 * HACK. This is another stopgap until we move away from the
1604 * vfs. People need to see /dev. This is written in such a way
1605 * as to fail quickly, be easily removed, and still do what we
1608 if ((fromfd == AT_FDCWD) && (path_l == 4) && (t_path[0] == '/')
1609 && (t_path[1] == 'd') && (t_path[2] == 'e') && (t_path[3] == 'v')) {
1613 if ((t_path[0] == '/') || (fromfd == AT_FDCWD))
1614 file = do_file_open(t_path, oflag, mode);
1616 set_errno(ENOENT); /* was not in the VFS. */
1619 /* VFS lookup succeeded */
1620 /* stores the ref to file */
1621 fd = insert_file(&p->open_files, file, 0, FALSE, oflag & O_CLOEXEC);
1622 kref_put(&file->f_kref); /* drop our ref */
1624 warn("File insertion failed");
1625 } else if (get_errno() == ENOENT) {
1626 /* VFS failed due to ENOENT. Other errors don't fall back to 9ns */
1627 unset_errno(); /* Go can't handle extra errnos */
1628 fd = sysopenat(fromfd, t_path, oflag);
1629 /* successful lookup with CREATE and EXCL is an error */
1631 if ((oflag & O_CREATE) && (oflag & O_EXCL)) {
1634 free_path(p, t_path);
1638 if (oflag & O_CREATE) {
1640 fd = syscreate(t_path, oflag, mode);
1644 free_path(p, t_path);
1645 printd("File %s Open, fd=%d\n", path, fd);
1649 static intreg_t sys_close(struct proc *p, int fd)
1651 struct file *file = get_file_from_fd(&p->open_files, fd);
1653 printd("sys_close %d\n", fd);
1656 put_file_from_fd(&p->open_files, fd);
1657 kref_put(&file->f_kref); /* Drop the ref from get_file */
1660 /* 9ns, should also handle errors (bad FD, etc) */
1661 retval = sysclose(fd);
1665 /* kept around til we remove the last ufe */
1666 #define ufe(which,a0,a1,a2,a3) \
1667 frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
1668 (int)(a0),(int)(a1),(int)(a2),(int)(a3))
1670 static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
1674 kbuf = kmalloc(sizeof(struct kstat), 0);
1679 file = get_file_from_fd(&p->open_files, fd);
1682 stat_inode(file->f_dentry->d_inode, kbuf);
1683 kref_put(&file->f_kref);
1685 unset_errno(); /* Go can't handle extra errnos */
1686 if (sysfstatakaros(fd, (struct kstat *)kbuf) < 0) {
1691 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1692 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1700 /* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
1701 * treat a symlink for the final item, which (probably) will be controlled by
1702 * the lookup flags */
1703 static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
1704 struct kstat *u_stat, int flags)
1707 struct dentry *path_d;
1708 char *t_path = copy_in_path(p, path, path_l);
1712 kbuf = kmalloc(sizeof(struct kstat), 0);
1718 /* Check VFS for path */
1719 path_d = lookup_dentry(t_path, flags);
1721 stat_inode(path_d->d_inode, kbuf);
1722 kref_put(&path_d->d_kref);
1724 /* VFS failed, checking 9ns */
1725 unset_errno(); /* Go can't handle extra errnos */
1726 retval = sysstatakaros(t_path, (struct stat *)kbuf);
1727 printd("sysstat returns %d\n", retval);
1728 /* both VFS and 9ns failed, bail out */
1732 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1733 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat)))
1739 free_path(p, t_path);
1743 /* Follow a final symlink */
1744 static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1745 struct kstat *u_stat)
1747 return stat_helper(p, path, path_l, u_stat, LOOKUP_FOLLOW);
1750 /* Don't follow a final symlink */
1751 static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1752 struct kstat *u_stat)
1754 return stat_helper(p, path, path_l, u_stat, 0);
1757 intreg_t sys_fcntl(struct proc *p, int fd, int cmd, unsigned long arg1,
1758 unsigned long arg2, unsigned long arg3, unsigned long arg4)
1762 struct file *file = get_file_from_fd(&p->open_files, fd);
1773 /* TODO: 9ns versions */
1776 return fd_getfl(fd);
1778 return fd_setfl(fd, arg1);
1780 warn("Unsupported fcntl cmd %d\n", cmd);
1782 /* not really ever calling this, even for badf, due to the switch */
1787 /* TODO: these are racy */
1790 retval = insert_file(&p->open_files, file, arg1, FALSE, FALSE);
1797 retval = p->open_files.fd[fd].fd_flags;
1800 /* I'm considering not supporting this at all. They must do it at
1801 * open time or fix their buggy/racy code. */
1802 spin_lock(&p->open_files.lock);
1803 if (arg1 & FD_CLOEXEC)
1804 p->open_files.fd[fd].fd_flags |= FD_CLOEXEC;
1805 retval = p->open_files.fd[fd].fd_flags;
1806 spin_unlock(&p->open_files.lock);
1809 retval = file->f_flags;
1812 /* only allowed to set certain flags. */
1813 arg1 &= O_FCNTL_SET_FLAGS;
1814 file->f_flags = (file->f_flags & ~O_FCNTL_SET_FLAGS) | arg1;
1817 /* TODO (if we keep the VFS) */
1821 /* TODO (if we keep the VFS)*/
1825 warn("Unsupported fcntl cmd %d\n", cmd);
1827 kref_put(&file->f_kref);
1831 static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1835 char *t_path = copy_in_path(p, path, path_l);
1838 /* TODO: 9ns support */
1839 retval = do_access(t_path, mode);
1840 free_path(p, t_path);
1841 printd("Access for path: %s retval: %d\n", path, retval);
1849 intreg_t sys_umask(struct proc *p, int mask)
1851 int old_mask = p->fs_env.umask;
1852 p->fs_env.umask = mask & S_PMASK;
1856 /* 64 bit seek, with the off64_t passed in via two (potentially 32 bit) off_ts.
1857 * We're supporting both 32 and 64 bit kernels/userspaces, but both use the
1858 * llseek syscall with 64 bit parameters. */
1859 static intreg_t sys_llseek(struct proc *p, int fd, off_t offset_hi,
1860 off_t offset_lo, off64_t *result, int whence)
1863 off64_t tempoff = 0;
1866 tempoff = offset_hi;
1868 tempoff |= offset_lo;
1869 file = get_file_from_fd(&p->open_files, fd);
1871 ret = file->f_op->llseek(file, tempoff, &retoff, whence);
1872 kref_put(&file->f_kref);
1874 retoff = sysseek(fd, tempoff, whence);
1880 if (memcpy_to_user_errno(p, result, &retoff, sizeof(off64_t)))
1885 intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1886 char *new_path, size_t new_l)
1889 char *t_oldpath = copy_in_path(p, old_path, old_l);
1890 if (t_oldpath == NULL)
1892 char *t_newpath = copy_in_path(p, new_path, new_l);
1893 if (t_newpath == NULL) {
1894 free_path(p, t_oldpath);
1897 ret = do_link(t_oldpath, t_newpath);
1898 free_path(p, t_oldpath);
1899 free_path(p, t_newpath);
1903 intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
1906 char *t_path = copy_in_path(p, path, path_l);
1909 retval = do_unlink(t_path);
1910 if (retval && (get_errno() == ENOENT)) {
1912 retval = sysremove(t_path);
1914 free_path(p, t_path);
1918 intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
1919 char *new_path, size_t new_l)
1922 char *t_oldpath = copy_in_path(p, old_path, old_l);
1923 if (t_oldpath == NULL)
1925 char *t_newpath = copy_in_path(p, new_path, new_l);
1926 if (t_newpath == NULL) {
1927 free_path(p, t_oldpath);
1930 ret = do_symlink(t_newpath, t_oldpath, S_IRWXU | S_IRWXG | S_IRWXO);
1931 free_path(p, t_oldpath);
1932 free_path(p, t_newpath);
1936 intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
1937 char *u_buf, size_t buf_l)
1939 char *symname = NULL;
1940 uint8_t *buf = NULL;
1943 struct dentry *path_d;
1944 char *t_path = copy_in_path(p, path, path_l);
1947 /* TODO: 9ns support */
1948 path_d = lookup_dentry(t_path, 0);
1951 buf = kmalloc(n*2, MEM_WAIT);
1952 struct dir *d = (void *)&buf[n];
1954 if (sysstat(t_path, buf, n) > 0) {
1955 printk("sysstat t_path %s\n", t_path);
1956 convM2D(buf, n, d, (char *)&d[1]);
1957 /* will be NULL if things did not work out */
1961 symname = path_d->d_inode->i_op->readlink(path_d);
1963 free_path(p, t_path);
1966 copy_amt = strnlen(symname, buf_l - 1) + 1;
1967 if (!memcpy_to_user_errno(p, u_buf, symname, copy_amt))
1971 kref_put(&path_d->d_kref);
1974 printd("READLINK returning %s\n", u_buf);
1978 static intreg_t sys_chdir(struct proc *p, pid_t pid, const char *path,
1983 struct proc *target = get_controllable_proc(p, pid);
1986 t_path = copy_in_path(p, path, path_l);
1988 proc_decref(target);
1991 /* TODO: 9ns support */
1992 retval = do_chdir(&target->fs_env, t_path);
1993 free_path(p, t_path);
1994 proc_decref(target);
1998 static intreg_t sys_fchdir(struct proc *p, pid_t pid, int fd)
2002 struct proc *target = get_controllable_proc(p, pid);
2005 file = get_file_from_fd(&p->open_files, fd);
2009 proc_decref(target);
2012 retval = do_fchdir(&target->fs_env, file);
2013 kref_put(&file->f_kref);
2014 proc_decref(target);
2018 /* Note cwd_l is not a strlen, it's an absolute size */
2019 intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
2024 k_cwd = do_getcwd(&p->fs_env, &kfree_this, cwd_l);
2026 return -1; /* errno set by do_getcwd */
2027 if (strlen(k_cwd) + 1 > cwd_l) {
2028 set_error(ERANGE, "getcwd buf too small, needed %d", strlen(k_cwd) + 1);
2032 if (memcpy_to_user_errno(p, u_cwd, k_cwd, strlen(k_cwd) + 1))
2039 intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
2042 char *t_path = copy_in_path(p, path, path_l);
2046 mode &= ~p->fs_env.umask;
2047 retval = do_mkdir(t_path, mode);
2048 if (retval && (get_errno() == ENOENT)) {
2050 /* mixing plan9 and glibc here, make sure DMDIR doesn't overlap with any
2052 static_assert(!(S_PMASK & DMDIR));
2053 retval = syscreate(t_path, O_RDWR, DMDIR | mode);
2055 free_path(p, t_path);
2059 intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
2062 char *t_path = copy_in_path(p, path, path_l);
2065 /* TODO: 9ns support */
2066 retval = do_rmdir(t_path);
2067 free_path(p, t_path);
2071 intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
2074 /* TODO: actually support this call on tty FDs. Right now, we just fake
2075 * what my linux box reports for a bash pty. */
2076 struct termios *kbuf = kmalloc(sizeof(struct termios), 0);
2077 kbuf->c_iflag = 0x2d02;
2078 kbuf->c_oflag = 0x0005;
2079 kbuf->c_cflag = 0x04bf;
2080 kbuf->c_lflag = 0x8a3b;
2082 kbuf->c_ispeed = 0xf;
2083 kbuf->c_ospeed = 0xf;
2084 kbuf->c_cc[0] = 0x03;
2085 kbuf->c_cc[1] = 0x1c;
2086 kbuf->c_cc[2] = 0x7f;
2087 kbuf->c_cc[3] = 0x15;
2088 kbuf->c_cc[4] = 0x04;
2089 kbuf->c_cc[5] = 0x00;
2090 kbuf->c_cc[6] = 0x01;
2091 kbuf->c_cc[7] = 0xff;
2092 kbuf->c_cc[8] = 0x11;
2093 kbuf->c_cc[9] = 0x13;
2094 kbuf->c_cc[10] = 0x1a;
2095 kbuf->c_cc[11] = 0xff;
2096 kbuf->c_cc[12] = 0x12;
2097 kbuf->c_cc[13] = 0x0f;
2098 kbuf->c_cc[14] = 0x17;
2099 kbuf->c_cc[15] = 0x16;
2100 kbuf->c_cc[16] = 0xff;
2101 kbuf->c_cc[17] = 0x00;
2102 kbuf->c_cc[18] = 0x00;
2103 kbuf->c_cc[19] = 0x00;
2104 kbuf->c_cc[20] = 0x00;
2105 kbuf->c_cc[21] = 0x00;
2106 kbuf->c_cc[22] = 0x00;
2107 kbuf->c_cc[23] = 0x00;
2108 kbuf->c_cc[24] = 0x00;
2109 kbuf->c_cc[25] = 0x00;
2110 kbuf->c_cc[26] = 0x00;
2111 kbuf->c_cc[27] = 0x00;
2112 kbuf->c_cc[28] = 0x00;
2113 kbuf->c_cc[29] = 0x00;
2114 kbuf->c_cc[30] = 0x00;
2115 kbuf->c_cc[31] = 0x00;
2117 if (memcpy_to_user_errno(p, termios_p, kbuf, sizeof(struct termios)))
2123 intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
2124 const void *termios_p)
2126 /* TODO: do this properly too. For now, we just say 'it worked' */
2130 /* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
2131 * process from thinking it can do these. The other alternative is to have
2132 * glibc return 0 right away, though someone might want to do something with
2133 * these calls. Someday. */
2134 intreg_t sys_setuid(struct proc *p, uid_t uid)
2139 intreg_t sys_setgid(struct proc *p, gid_t gid)
2144 /* long bind(char* src_path, char* onto_path, int flag);
2146 * The naming for the args in bind is messy historically. We do:
2147 * bind src_path onto_path
2148 * plan9 says bind NEW OLD, where new is *src*, and old is *onto*.
2149 * Linux says mount --bind OLD NEW, where OLD is *src* and NEW is *onto*. */
2150 intreg_t sys_nbind(struct proc *p,
2151 char *src_path, size_t src_l,
2152 char *onto_path, size_t onto_l,
2157 char *t_srcpath = copy_in_path(p, src_path, src_l);
2158 if (t_srcpath == NULL) {
2159 printd("srcpath dup failed ptr %p size %d\n", src_path, src_l);
2162 char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2163 if (t_ontopath == NULL) {
2164 free_path(p, t_srcpath);
2165 printd("ontopath dup failed ptr %p size %d\n", onto_path, onto_l);
2168 printd("sys_nbind: %s -> %s flag %d\n", t_srcpath, t_ontopath, flag);
2169 ret = sysbind(t_srcpath, t_ontopath, flag);
2170 free_path(p, t_srcpath);
2171 free_path(p, t_ontopath);
2175 /* int mount(int fd, int afd, char* onto_path, int flag, char* aname); */
2176 intreg_t sys_nmount(struct proc *p,
2178 char *onto_path, size_t onto_l,
2180 /* we ignore these */
2181 /* no easy way to pass this many args anyway. *
2183 char *auth, size_t auth_l*/)
2189 char *t_ontopath = copy_in_path(p, onto_path, onto_l);
2190 if (t_ontopath == NULL)
2192 ret = sysmount(fd, afd, t_ontopath, flag, /* spec or auth */"/");
2193 free_path(p, t_ontopath);
2197 /* Unmount undoes the operation of a bind or mount. Check out
2198 * http://plan9.bell-labs.com/magic/man2html/1/bind . Though our mount takes an
2199 * FD, not servename (aka src_path), so it's not quite the same.
2201 * To translate between Plan 9 and Akaros, old -> onto_path. new -> src_path.
2203 * For unmount, src_path / new is optional. If set, we only unmount the
2204 * bindmount that came from src_path. */
2205 intreg_t sys_nunmount(struct proc *p, char *src_path, int src_l,
2206 char *onto_path, int onto_l)
2209 char *t_ontopath, *t_srcpath;
2210 t_ontopath = copy_in_path(p, onto_path, onto_l);
2211 if (t_ontopath == NULL)
2214 t_srcpath = copy_in_path(p, src_path, src_l);
2215 if (t_srcpath == NULL) {
2216 free_path(p, t_ontopath);
2222 ret = sysunmount(t_srcpath, t_ontopath);
2223 free_path(p, t_ontopath);
2224 free_path(p, t_srcpath); /* you can free a null path */
2228 intreg_t sys_fd2path(struct proc *p, int fd, void *u_buf, size_t len)
2233 /* UMEM: Check the range, can PF later and kill if the page isn't present */
2234 if (!is_user_rwaddr(u_buf, len)) {
2235 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", u_buf,
2239 /* fdtochan throws */
2244 ch = fdtochan(¤t->open_files, fd, -1, FALSE, TRUE);
2245 if (snprintf(u_buf, len, "%s", channame(ch)) >= len) {
2246 set_error(ERANGE, "fd2path buf too small, needed %d", ret);
2254 /* Helper, interprets the wstat and performs the VFS action. Returns stat_sz on
2255 * success for all ops, -1 or 0 o/w. If one op fails, it'll skip the remaining
2257 static int vfs_wstat(struct file *file, uint8_t *stat_m, size_t stat_sz,
2264 dir = kzmalloc(sizeof(struct dir) + stat_sz, MEM_WAIT);
2265 m_sz = convM2D(stat_m, stat_sz, &dir[0], (char*)&dir[1]);
2266 if (m_sz != stat_sz) {
2267 set_error(EINVAL, ERROR_FIXME);
2271 if (flags & WSTAT_MODE) {
2272 retval = do_file_chmod(file, dir->mode);
2276 if (flags & WSTAT_LENGTH) {
2277 retval = do_truncate(file->f_dentry->d_inode, dir->length);
2281 if (flags & WSTAT_ATIME) {
2282 /* wstat only gives us seconds */
2283 file->f_dentry->d_inode->i_atime.tv_sec = dir->atime;
2284 file->f_dentry->d_inode->i_atime.tv_nsec = 0;
2286 if (flags & WSTAT_MTIME) {
2287 file->f_dentry->d_inode->i_mtime.tv_sec = dir->mtime;
2288 file->f_dentry->d_inode->i_mtime.tv_nsec = 0;
2293 /* convert vfs retval to wstat retval */
2299 intreg_t sys_wstat(struct proc *p, char *path, size_t path_l,
2300 uint8_t *stat_m, size_t stat_sz, int flags)
2303 char *t_path = copy_in_path(p, path, path_l);
2308 retval = syswstat(t_path, stat_m, stat_sz);
2309 if (retval == stat_sz) {
2310 free_path(p, t_path);
2313 /* 9ns failed, we'll need to check the VFS */
2314 file = do_file_open(t_path, O_READ, 0);
2315 free_path(p, t_path);
2318 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2319 kref_put(&file->f_kref);
2323 intreg_t sys_fwstat(struct proc *p, int fd, uint8_t *stat_m, size_t stat_sz,
2329 retval = sysfwstat(fd, stat_m, stat_sz);
2330 if (retval == stat_sz)
2332 /* 9ns failed, we'll need to check the VFS */
2333 file = get_file_from_fd(&p->open_files, fd);
2336 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2337 kref_put(&file->f_kref);
2341 intreg_t sys_rename(struct proc *p, char *old_path, size_t old_path_l,
2342 char *new_path, size_t new_path_l)
2344 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2346 int mountpointlen = 0;
2347 char *from_path = copy_in_path(p, old_path, old_path_l);
2348 char *to_path = copy_in_path(p, new_path, new_path_l);
2349 struct chan *oldchan = 0, *newchan = NULL;
2352 if ((!from_path) || (!to_path))
2354 printd("sys_rename :%s: to :%s: : ", from_path, to_path);
2356 /* we need a fid for the wstat. */
2357 /* TODO: maybe wrap the 9ns stuff better. sysrename maybe? */
2359 /* discard namec error */
2361 oldchan = namec(from_path, Aaccess, 0, 0);
2365 retval = do_rename(from_path, to_path);
2366 free_path(p, from_path);
2367 free_path(p, to_path);
2371 printd("Oldchan: %C\n", oldchan);
2372 printd("Oldchan: mchan %C\n", oldchan->mchan);
2374 /* If walked through a mountpoint, we need to take that
2375 * into account for the Twstat.
2377 if (oldchan->mountpoint) {
2378 printd("mountpoint: %C\n", oldchan->mountpoint);
2379 if (oldchan->mountpoint->name)
2380 mountpointlen = oldchan->mountpoint->name->len;
2383 /* This test makes sense even when mountpointlen is 0 */
2384 if (strlen(to_path) < mountpointlen) {
2389 /* the omode and perm are of no importance. */
2390 newchan = namec(to_path, Acreatechan, 0, 0);
2391 if (newchan == NULL) {
2392 printd("sys_rename %s to %s found no chan\n", from_path, to_path);
2396 printd("Newchan: %C\n", newchan);
2397 printd("Newchan: mchan %C\n", newchan->mchan);
2399 if ((newchan->dev != oldchan->dev) ||
2400 (newchan->type != oldchan->type)) {
2401 printd("Old chan and new chan do not match\n");
2408 uint8_t mbuf[STATFIXLEN + MAX_PATH_LEN + 1];
2410 init_empty_dir(&dir);
2412 /* absolute paths need the mountpoint name stripped from them.
2413 * Once stripped, it still has to be an absolute path.
2415 if (dir.name[0] == '/') {
2416 dir.name = to_path + mountpointlen;
2417 if (dir.name[0] != '/') {
2423 mlen = convD2M(&dir, mbuf, sizeof(mbuf));
2425 printk("convD2M failed\n");
2431 printk("validstat failed: %s\n", current_errstr());
2435 validstat(mbuf, mlen, 1);
2443 retval = devtab[oldchan->type].wstat(oldchan, mbuf, mlen);
2446 if (retval == mlen) {
2449 printk("syswstat did not go well\n");
2452 printk("syswstat returns %d\n", retval);
2455 free_path(p, from_path);
2456 free_path(p, to_path);
2462 /* Careful: if an FD is busy, we don't close the old object, it just fails */
2463 static intreg_t sys_dup_fds_to(struct proc *p, unsigned int pid,
2464 struct childfdmap *map, unsigned int nentries)
2471 if (!is_user_rwaddr(map, sizeof(struct childfdmap) * nentries)) {
2475 child = get_controllable_proc(p, pid);
2478 for (int i = 0; i < nentries; i++) {
2480 file = get_file_from_fd(&p->open_files, map[i].parentfd);
2482 slot = insert_file(&child->open_files, file, map[i].childfd, TRUE,
2484 if (slot == map[i].childfd) {
2488 kref_put(&file->f_kref);
2491 if (!sys_dup_to(p, map[i].parentfd, child, map[i].childfd)) {
2496 /* probably a bug, could send EBADF, maybe via 'ok' */
2497 printk("[kernel] dup_fds_to: couldn't find %d\n", map[i].parentfd);
2503 /* 0 on success, anything else is an error, with errno/errstr set */
2504 static int handle_tap_req(struct proc *p, struct fd_tap_req *req)
2507 case (FDTAP_CMD_ADD):
2508 return add_fd_tap(p, req);
2509 case (FDTAP_CMD_REM):
2510 return remove_fd_tap(p, req->fd);
2512 set_error(ENOSYS, "FD Tap Command %d not supported", req->cmd);
2517 /* Processes up to nr_reqs tap requests. If a request errors out, we stop
2518 * immediately. Returns the number processed. If done != nr_reqs, check errno
2519 * and errstr for the last failure, which is for tap_reqs[done]. */
2520 static intreg_t sys_tap_fds(struct proc *p, struct fd_tap_req *tap_reqs,
2523 struct fd_tap_req *req_i = tap_reqs;
2525 if (!is_user_rwaddr(tap_reqs, sizeof(struct fd_tap_req) * nr_reqs)) {
2529 for (done = 0; done < nr_reqs; done++, req_i++) {
2530 if (handle_tap_req(p, req_i))
2536 /************** Syscall Invokation **************/
2538 const struct sys_table_entry syscall_table[] = {
2539 [SYS_null] = {(syscall_t)sys_null, "null"},
2540 [SYS_block] = {(syscall_t)sys_block, "block"},
2541 [SYS_cache_buster] = {(syscall_t)sys_cache_buster, "buster"},
2542 [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
2543 [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
2544 [SYS_getpcoreid] = {(syscall_t)sys_getpcoreid, "getpcoreid"},
2545 [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
2546 [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
2547 [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
2548 [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
2549 [SYS_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
2550 [SYS_change_vcore] = {(syscall_t)sys_change_vcore, "change_vcore"},
2551 [SYS_fork] = {(syscall_t)sys_fork, "fork"},
2552 [SYS_exec] = {(syscall_t)sys_exec, "exec"},
2553 [SYS_waitpid] = {(syscall_t)sys_waitpid, "waitpid"},
2554 [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
2555 [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
2556 [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
2557 [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
2558 [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
2559 [SYS_provision] = {(syscall_t)sys_provision, "provision"},
2560 [SYS_notify] = {(syscall_t)sys_notify, "notify"},
2561 [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
2562 [SYS_vc_entry] = {(syscall_t)sys_vc_entry, "vc_entry"},
2563 [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
2564 #ifdef CONFIG_ARSC_SERVER
2565 [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
2567 [SYS_change_to_m] = {(syscall_t)sys_change_to_m, "change_to_m"},
2568 [SYS_vmm_setup] = {(syscall_t)sys_vmm_setup, "vmm_setup"},
2569 [SYS_vmm_poke_guest] = {(syscall_t)sys_vmm_poke_guest, "vmm_poke_guest"},
2570 [SYS_poke_ksched] = {(syscall_t)sys_poke_ksched, "poke_ksched"},
2571 [SYS_abort_sysc] = {(syscall_t)sys_abort_sysc, "abort_sysc"},
2572 [SYS_abort_sysc_fd] = {(syscall_t)sys_abort_sysc_fd, "abort_sysc_fd"},
2573 [SYS_populate_va] = {(syscall_t)sys_populate_va, "populate_va"},
2574 [SYS_nanosleep] = {(syscall_t)sys_nanosleep, "nanosleep"},
2575 [SYS_pop_ctx] = {(syscall_t)sys_pop_ctx, "pop_ctx"},
2577 [SYS_read] = {(syscall_t)sys_read, "read"},
2578 [SYS_write] = {(syscall_t)sys_write, "write"},
2579 [SYS_openat] = {(syscall_t)sys_openat, "openat"},
2580 [SYS_close] = {(syscall_t)sys_close, "close"},
2581 [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
2582 [SYS_stat] = {(syscall_t)sys_stat, "stat"},
2583 [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
2584 [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
2585 [SYS_access] = {(syscall_t)sys_access, "access"},
2586 [SYS_umask] = {(syscall_t)sys_umask, "umask"},
2587 [SYS_llseek] = {(syscall_t)sys_llseek, "llseek"},
2588 [SYS_link] = {(syscall_t)sys_link, "link"},
2589 [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
2590 [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
2591 [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
2592 [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
2593 [SYS_fchdir] = {(syscall_t)sys_fchdir, "fchdir"},
2594 [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
2595 [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdir"},
2596 [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
2597 [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
2598 [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
2599 [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
2600 [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"},
2602 [SYS_nbind] ={(syscall_t)sys_nbind, "nbind"},
2603 [SYS_nmount] ={(syscall_t)sys_nmount, "nmount"},
2604 [SYS_nunmount] ={(syscall_t)sys_nunmount, "nunmount"},
2605 [SYS_fd2path] ={(syscall_t)sys_fd2path, "fd2path"},
2606 [SYS_wstat] ={(syscall_t)sys_wstat, "wstat"},
2607 [SYS_fwstat] ={(syscall_t)sys_fwstat, "fwstat"},
2608 [SYS_rename] ={(syscall_t)sys_rename, "rename"},
2609 [SYS_dup_fds_to] = {(syscall_t)sys_dup_fds_to, "dup_fds_to"},
2610 [SYS_tap_fds] = {(syscall_t)sys_tap_fds, "tap_fds"},
2612 const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
2614 /* Executes the given syscall.
2616 * Note tf is passed in, which points to the tf of the context on the kernel
2617 * stack. If any syscall needs to block, it needs to save this info, as well as
2620 * This syscall function is used by both local syscall and arsc, and should
2621 * remain oblivious of the caller. */
2622 intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
2623 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
2625 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2629 if (sc_num > max_syscall || syscall_table[sc_num].call == NULL) {
2630 printk("[kernel] Invalid syscall %d for proc %d\n", sc_num, p->pid);
2631 printk("\tArgs: %p, %p, %p, %p, %p, %p\n", a0, a1, a2, a3, a4, a5);
2632 print_user_ctx(per_cpu_info[core_id()].cur_ctx);
2636 /* N.B. This is going away. */
2638 printk("Plan 9 system call returned via waserror()\n");
2639 printk("String: '%s'\n", current_errstr());
2640 /* if we got here, then the errbuf was right.
2645 //printd("before syscall errstack %p\n", errstack);
2646 //printd("before syscall errstack base %p\n", get_cur_errbuf());
2647 ret = syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
2648 //printd("after syscall errstack base %p\n", get_cur_errbuf());
2649 if (get_cur_errbuf() != &errstack[0]) {
2650 /* Can't trust coreid and vcoreid anymore, need to check the trace */
2651 printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, "
2652 "%p, %p) proc: %d\n", read_tsc(),
2653 sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
2655 if (sc_num != SYS_fork)
2656 printk("YOU SHOULD PANIC: errstack mismatch");
2661 /* Execute the syscall on the local core */
2662 void run_local_syscall(struct syscall *sysc)
2664 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2665 struct proc *p = pcpui->cur_proc;
2667 /* In lieu of pinning, we just check the sysc and will PF on the user addr
2668 * later (if the addr was unmapped). Which is the plan for all UMEM. */
2669 if (!is_user_rwaddr(sysc, sizeof(struct syscall))) {
2670 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", sysc,
2671 sizeof(struct syscall), __FUNCTION__);
2674 pcpui->cur_kthread->sysc = sysc; /* let the core know which sysc it is */
2675 systrace_start_trace(pcpui->cur_kthread, sysc);
2676 alloc_sysc_str(pcpui->cur_kthread);
2677 /* syscall() does not return for exec and yield, so put any cleanup in there
2679 sysc->retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
2680 sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
2681 /* Need to re-load pcpui, in case we migrated */
2682 pcpui = &per_cpu_info[core_id()];
2683 free_sysc_str(pcpui->cur_kthread);
2684 systrace_finish_trace(pcpui->cur_kthread, sysc->retval);
2685 /* Some 9ns paths set errstr, but not errno. glibc will ignore errstr.
2686 * this is somewhat hacky, since errno might get set unnecessarily */
2687 if ((current_errstr()[0] != 0) && (!sysc->err))
2688 sysc->err = EUNSPECIFIED;
2689 finish_sysc(sysc, pcpui->cur_proc);
2690 pcpui->cur_kthread->sysc = NULL; /* No longer working on sysc */
2693 /* A process can trap and call this function, which will set up the core to
2694 * handle all the syscalls. a.k.a. "sys_debutante(needs, wants)". If there is
2695 * at least one, it will run it directly. */
2696 void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
2698 /* Careful with pcpui here, we could have migrated */
2700 printk("[kernel] No nr_sysc, probably a bug, user!\n");
2703 /* For all after the first call, send ourselves a KMSG (TODO). */
2705 warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
2706 /* Call the first one directly. (we already checked to make sure there is
2708 run_local_syscall(sysc);
2711 /* Call this when something happens on the syscall where userspace might want to
2712 * get signaled. Passing p, since the caller should know who the syscall
2713 * belongs to (probably is current).
2715 * You need to have SC_K_LOCK set when you call this. */
2716 void __signal_syscall(struct syscall *sysc, struct proc *p)
2718 struct event_queue *ev_q;
2719 struct event_msg local_msg;
2720 /* User sets the ev_q then atomically sets the flag (races with SC_DONE) */
2721 if (atomic_read(&sysc->flags) & SC_UEVENT) {
2722 rmb(); /* read the ev_q after reading the flag */
2725 memset(&local_msg, 0, sizeof(struct event_msg));
2726 local_msg.ev_type = EV_SYSCALL;
2727 local_msg.ev_arg3 = sysc;
2728 send_event(p, ev_q, &local_msg, 0);
2733 bool syscall_uses_fd(struct syscall *sysc, int fd)
2735 switch (sysc->num) {
2744 if (sysc->arg0 == fd)
2748 /* mmap always has to be special. =) */
2749 if (sysc->arg4 == fd)
2757 void print_sysc(struct proc *p, struct syscall *sysc)
2759 uintptr_t old_p = switch_to(p);
2760 printk("SYS_%d, flags %p, a0 %p, a1 %p, a2 %p, a3 %p, a4 %p, a5 %p\n",
2761 sysc->num, atomic_read(&sysc->flags),
2762 sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
2764 switch_back(p, old_p);