1 /* See COPYRIGHT for copyright information. */
8 #include <ros/common.h>
9 #include <arch/types.h>
10 #include <arch/arch.h>
12 #include <arch/console.h>
29 #include <colored_caches.h>
30 #include <hashtable.h>
35 #include <arsc_server.h>
41 int systrace_flags = 0;
42 struct systrace_record *systrace_buffer = 0;
43 uint32_t systrace_bufidx = 0;
44 size_t systrace_bufsize = 0;
45 struct proc *systrace_procs[MAX_NUM_TRACED] = {0};
46 spinlock_t systrace_lock = SPINLOCK_INITIALIZER_IRQSAVE;
48 // for now, only want this visible here.
49 void kprof_write_sysrecord(char *pretty_buf, size_t len);
51 /* Not enforcing the packing of systrace_procs yet, but don't rely on that */
52 static bool proc_is_traced(struct proc *p)
54 for (int i = 0; i < MAX_NUM_TRACED; i++)
55 if (systrace_procs[i] == p)
60 static bool __trace_this_proc(struct proc *p)
62 return (systrace_flags & SYSTRACE_ON) &&
63 ((systrace_flags & SYSTRACE_ALLPROC) || (proc_is_traced(p)));
66 static size_t systrace_fill_pretty_buf(struct systrace_record *trace)
69 struct timespec ts_start;
70 struct timespec ts_end;
71 tsc2timespec(trace->start_timestamp, &ts_start);
72 tsc2timespec(trace->end_timestamp, &ts_end);
74 len = snprintf(trace->pretty_buf, SYSTR_PRETTY_BUF_SZ - len,
75 "[%7d.%09d]-[%7d.%09d] Syscall %3d (%12s):(0x%llx, 0x%llx, "
76 "0x%llx, 0x%llx, 0x%llx, 0x%llx) ret: 0x%llx proc: %d core: %d "
83 syscall_table[trace->syscallno].name,
94 /* if we have extra data, print it out on the next line, lined up nicely.
95 * this is only useful for looking at the dump in certain terminals. if we
96 * have a tool that processes the info, we shouldn't do this. */
98 len += snprintf(trace->pretty_buf + len, SYSTR_PRETTY_BUF_SZ - len,
100 len += printdump(trace->pretty_buf + len,
101 MIN(trace->datalen, SYSTR_PRETTY_BUF_SZ - len - 1),
103 len += snprintf(trace->pretty_buf + len, SYSTR_PRETTY_BUF_SZ - len, "\n");
107 static void systrace_start_trace(struct kthread *kthread, struct syscall *sysc)
109 struct systrace_record *trace;
111 struct proc *p = current;
113 if (!__trace_this_proc(p))
115 assert(!kthread->trace); /* catch memory leaks */
117 vcoreid = proc_get_vcoreid(p);
118 if (systrace_flags & SYSTRACE_LOUD) {
119 printk("ENTER [%16llu] Syscall %3d (%12s):(0x%llx, 0x%llx, 0x%llx, "
120 "0x%llx, 0x%llx, 0x%llx) proc: %d core: %d vcore: %d\n",
122 sysc->num, syscall_table[sysc->num].name,
123 sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
124 sysc->arg5, p->pid, coreid, vcoreid);
126 trace = kmalloc(SYSTR_BUF_SZ, 0);
129 kthread->trace = trace;
130 trace->start_timestamp = read_tsc();
131 trace->syscallno = sysc->num;
132 trace->arg0 = sysc->arg0;
133 trace->arg1 = sysc->arg1;
134 trace->arg2 = sysc->arg2;
135 trace->arg3 = sysc->arg3;
136 trace->arg4 = sysc->arg4;
137 trace->arg5 = sysc->arg5;
139 trace->coreid = coreid;
140 trace->vcoreid = vcoreid;
141 trace->pretty_buf = (char*)trace + sizeof(struct systrace_record);
146 static void systrace_finish_trace(struct kthread *kthread, long retval)
148 struct systrace_record *trace = kthread->trace;
151 trace->end_timestamp = read_tsc();
152 trace->retval = retval;
154 pretty_len = systrace_fill_pretty_buf(trace);
155 kprof_write_sysrecord(trace->pretty_buf, pretty_len);
156 if (systrace_flags & SYSTRACE_LOUD)
157 printk("EXIT %s", trace->pretty_buf);
162 #ifdef CONFIG_SYSCALL_STRING_SAVING
164 static void alloc_sysc_str(struct kthread *kth)
166 kth->name = kmalloc(SYSCALL_STRLEN, KMALLOC_WAIT);
170 static void free_sysc_str(struct kthread *kth)
172 char *str = kth->name;
177 #define sysc_save_str(...) \
179 struct per_cpu_info *pcpui = &per_cpu_info[core_id()]; \
180 snprintf(pcpui->cur_kthread->name, SYSCALL_STRLEN, __VA_ARGS__); \
185 static void alloc_sysc_str(struct kthread *kth)
189 static void free_sysc_str(struct kthread *kth)
193 #define sysc_save_str(...)
195 #endif /* CONFIG_SYSCALL_STRING_SAVING */
197 /* Helper to finish a syscall, signalling if appropriate */
198 static void finish_sysc(struct syscall *sysc, struct proc *p)
200 /* Atomically turn on the LOCK and SC_DONE flag. The lock tells userspace
201 * we're messing with the flags and to not proceed. We use it instead of
202 * CASing with userspace. We need the atomics since we're racing with
203 * userspace for the event_queue registration. The 'lock' tells userspace
204 * to not muck with the flags while we're signalling. */
205 atomic_or(&sysc->flags, SC_K_LOCK | SC_DONE);
206 __signal_syscall(sysc, p);
207 atomic_and(&sysc->flags, ~SC_K_LOCK);
210 /* Helper that "finishes" the current async syscall. This should be used with
211 * care when we are not using the normal syscall completion path.
213 * Do *NOT* complete the same syscall twice. This is catastrophic for _Ms, and
216 * It is possible for another user thread to see the syscall being done early -
217 * they just need to be careful with the weird proc management calls (as in,
218 * don't trust an async fork).
220 * *sysc is in user memory, and should be pinned (TODO: UMEM). There may be
221 * issues with unpinning this if we never return. */
222 static void finish_current_sysc(int retval)
224 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
225 assert(pcpui->cur_kthread->sysc);
226 pcpui->cur_kthread->sysc->retval = retval;
227 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
230 /* Callable by any function while executing a syscall (or otherwise, actually).
232 void set_errno(int errno)
234 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
235 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
236 pcpui->cur_kthread->sysc->err = errno;
239 /* Callable by any function while executing a syscall (or otherwise, actually).
243 /* if there's no errno to get, that's not an error I guess. */
245 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
246 if (pcpui->cur_kthread && pcpui->cur_kthread->sysc)
247 errno = pcpui->cur_kthread->sysc->err;
251 void unset_errno(void)
253 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
254 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
256 pcpui->cur_kthread->sysc->err = 0;
257 pcpui->cur_kthread->sysc->errstr[0] = '\0';
260 void set_errstr(const char *fmt, ...)
265 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
266 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
270 rc = vsnprintf(pcpui->cur_kthread->sysc->errstr, MAX_ERRSTR_LEN, fmt, ap);
273 /* TODO: likely not needed */
274 pcpui->cur_kthread->sysc->errstr[MAX_ERRSTR_LEN - 1] = '\0';
277 char *current_errstr(void)
279 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
280 if (!pcpui->cur_kthread || !pcpui->cur_kthread->sysc)
282 return pcpui->cur_kthread->sysc->errstr;
285 struct errbuf *get_cur_errbuf(void)
287 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
288 return (struct errbuf*)pcpui->cur_kthread->errbuf;
291 void set_cur_errbuf(struct errbuf *ebuf)
293 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
294 pcpui->cur_kthread->errbuf = ebuf;
297 char *get_cur_genbuf(void)
299 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
300 assert(pcpui->cur_kthread);
301 return pcpui->cur_kthread->generic_buf;
304 /* Helper, looks up proc* for pid and ensures p controls that proc. 0 o/w */
305 static struct proc *get_controllable_proc(struct proc *p, pid_t pid)
307 struct proc *target = pid2proc(pid);
312 if (!proc_controls(p, target)) {
320 /************** Utility Syscalls **************/
322 static int sys_null(void)
327 /* Diagnostic function: blocks the kthread/syscall, to help userspace test its
328 * async I/O handling. */
329 static int sys_block(struct proc *p, unsigned int usec)
331 /* Note printing takes a few ms, so your printds won't be perfect. */
332 printd("[kernel] sys_block(), sleeping at %llu\n", read_tsc());
333 kthread_usleep(usec);
334 printd("[kernel] sys_block(), waking up at %llu\n", read_tsc());
338 // Writes 'val' to 'num_writes' entries of the well-known array in the kernel
339 // address space. It's just #defined to be some random 4MB chunk (which ought
340 // to be boot_alloced or something). Meant to grab exclusive access to cache
341 // lines, to simulate doing something useful.
342 static int sys_cache_buster(struct proc *p, uint32_t num_writes,
343 uint32_t num_pages, uint32_t flags)
345 #define BUSTER_ADDR 0xd0000000L // around 512 MB deep
346 #define MAX_WRITES 1048576*8
348 #define INSERT_ADDR (UINFO + 2*PGSIZE) // should be free for these tests
349 uint32_t* buster = (uint32_t*)BUSTER_ADDR;
350 static spinlock_t buster_lock = SPINLOCK_INITIALIZER;
352 page_t* a_page[MAX_PAGES];
354 /* Strided Accesses or Not (adjust to step by cachelines) */
356 if (flags & BUSTER_STRIDED) {
361 /* Shared Accesses or Not (adjust to use per-core regions)
362 * Careful, since this gives 8MB to each core, starting around 512MB.
363 * Also, doesn't separate memory for core 0 if it's an async call.
365 if (!(flags & BUSTER_SHARED))
366 buster = (uint32_t*)(BUSTER_ADDR + core_id() * 0x00800000);
368 /* Start the timer, if we're asked to print this info*/
369 if (flags & BUSTER_PRINT_TICKS)
370 ticks = start_timing();
372 /* Allocate num_pages (up to MAX_PAGES), to simulate doing some more
373 * realistic work. Note we don't write to these pages, even if we pick
374 * unshared. Mostly due to the inconvenience of having to match up the
375 * number of pages with the number of writes. And it's unnecessary.
378 spin_lock(&buster_lock);
379 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
380 upage_alloc(p, &a_page[i],1);
381 page_insert(p->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
383 page_decref(a_page[i]);
385 spin_unlock(&buster_lock);
388 if (flags & BUSTER_LOCKED)
389 spin_lock(&buster_lock);
390 for (int i = 0; i < MIN(num_writes, MAX_WRITES); i=i+stride)
391 buster[i] = 0xdeadbeef;
392 if (flags & BUSTER_LOCKED)
393 spin_unlock(&buster_lock);
396 spin_lock(&buster_lock);
397 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
398 page_remove(p->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
399 page_decref(a_page[i]);
401 spin_unlock(&buster_lock);
405 if (flags & BUSTER_PRINT_TICKS) {
406 ticks = stop_timing(ticks);
407 printk("%llu,", ticks);
412 static int sys_cache_invalidate(void)
420 /* sys_reboot(): called directly from dispatch table. */
422 /* Print a string to the system console. */
423 static ssize_t sys_cputs(struct proc *p, const char *DANGEROUS string,
427 t_string = user_strdup_errno(p, string, strlen);
430 printk("%.*s", strlen, t_string);
431 user_memdup_free(p, t_string);
432 return (ssize_t)strlen;
435 // Read a character from the system console.
436 // Returns the character.
437 /* TODO: remove me */
438 static uint16_t sys_cgetc(struct proc *p)
442 // The cons_get_any_char() primitive doesn't wait for a character,
443 // but the sys_cgetc() system call does.
444 while ((c = cons_get_any_char()) == 0)
450 /* Returns the id of the physical core this syscall is executed on. */
451 static uint32_t sys_getpcoreid(void)
456 // TODO: Temporary hack until thread-local storage is implemented on i386 and
457 // this is removed from the user interface
458 static size_t sys_getvcoreid(struct proc *p)
460 return proc_get_vcoreid(p);
463 /************** Process management syscalls **************/
465 /* Returns the calling process's pid */
466 static pid_t sys_getpid(struct proc *p)
471 /* Creates a process from the file 'path'. The process is not runnable by
472 * default, so it needs it's status to be changed so that the next call to
473 * schedule() will try to run it. TODO: take args/envs from userspace. */
474 static int sys_proc_create(struct proc *p, char *path, size_t path_l,
475 struct procinfo *pi, int flags)
479 struct file *program;
482 /* Copy in the path. Consider putting an upper bound on path_l. */
483 t_path = user_strdup_errno(p, path, path_l);
486 /* TODO: 9ns support */
487 program = do_file_open(t_path, 0, 0);
488 user_memdup_free(p, t_path);
490 return -1; /* presumably, errno is already set */
491 /* TODO: need to split the proc creation, since you must load after setting
492 * args/env, since auxp gets set up there. */
493 //new_p = proc_create(program, 0, 0);
494 if (proc_alloc(&new_p, current, flags)) {
495 set_errstr("Failed to alloc new proc");
498 /* close the CLOEXEC ones, even though this isn't really an exec */
499 close_9ns_files(new_p, TRUE);
500 close_all_files(&new_p->open_files, TRUE);
501 /* Set the argument stuff needed by glibc */
502 if (memcpy_from_user_errno(p, new_p->procinfo->argp, pi->argp,
504 set_errstr("Failed to memcpy argp");
507 if (memcpy_from_user_errno(p, new_p->procinfo->argbuf, pi->argbuf,
508 sizeof(pi->argbuf))) {
509 set_errstr("Failed to memcpy argbuf");
512 if (load_elf(new_p, program)) {
513 set_errstr("Failed to load elf");
516 /* progname is argv0, which accounts for symlinks */
517 proc_set_progname(p, p->procinfo->argbuf);
518 kref_put(&program->f_kref);
521 proc_decref(new_p); /* give up the reference created in proc_create() */
525 /* proc_destroy will decref once, which is for the ref created in
526 * proc_create(). We don't decref again (the usual "+1 for existing"),
527 * since the scheduler, which usually handles that, hasn't heard about the
528 * process (via __proc_ready()). */
531 kref_put(&program->f_kref);
535 /* Makes process PID runnable. Consider moving the functionality to process.c */
536 static error_t sys_proc_run(struct proc *p, unsigned pid)
539 struct proc *target = get_controllable_proc(p, pid);
542 if (target->state != PROC_CREATED) {
547 /* Note a proc can spam this for someone it controls. Seems safe - if it
548 * isn't we can change it. */
554 /* Destroy proc pid. If this is called by the dying process, it will never
555 * return. o/w it will return 0 on success, or an error. Errors include:
556 * - ESRCH: if there is no such process with pid
557 * - EPERM: if caller does not control pid */
558 static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
561 struct proc *p_to_die = get_controllable_proc(p, pid);
565 p->exitcode = exitcode;
566 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
568 p_to_die->exitcode = exitcode; /* so its parent has some clue */
569 printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
571 proc_destroy(p_to_die);
572 /* we only get here if we weren't the one to die */
573 proc_decref(p_to_die);
577 static int sys_proc_yield(struct proc *p, bool being_nice)
579 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
580 /* proc_yield() often doesn't return - we need to set the syscall retval
581 * early. If it doesn't return, it expects to eat our reference (for now).
583 free_sysc_str(pcpui->cur_kthread);
584 systrace_finish_trace(pcpui->cur_kthread, 0);
585 finish_sysc(pcpui->cur_kthread->sysc, pcpui->cur_proc);
586 pcpui->cur_kthread->sysc = 0; /* don't touch sysc again */
588 proc_yield(p, being_nice);
590 /* Shouldn't return, to prevent the chance of mucking with cur_sysc. */
595 static int sys_change_vcore(struct proc *p, uint32_t vcoreid,
596 bool enable_my_notif)
598 /* Note retvals can be negative, but we don't mess with errno in case
599 * callers use this in low-level code and want to extract the 'errno'. */
600 return proc_change_to_vcore(p, vcoreid, enable_my_notif);
603 static ssize_t sys_fork(env_t* e)
609 // TODO: right now we only support fork for single-core processes
610 if (e->state != PROC_RUNNING_S) {
615 ret = proc_alloc(&env, current, PROC_DUP_FGRP);
618 proc_set_progname(env, e->progname);
620 env->heap_top = e->heap_top;
622 disable_irqsave(&state); /* protect cur_ctx */
623 /* Can't really fork if we don't have a current_ctx to fork */
630 env->scp_ctx = *current_ctx;
631 enable_irqsave(&state);
633 env->cache_colors_map = cache_colors_map_alloc();
634 for(int i=0; i < llc_cache->num_colors; i++)
635 if(GET_BITMASK_BIT(e->cache_colors_map,i))
636 cache_color_alloc(llc_cache, env->cache_colors_map);
638 /* Make the new process have the same VMRs as the older. This will copy the
639 * contents of non MAP_SHARED pages to the new VMRs. */
640 if (duplicate_vmrs(e, env)) {
641 proc_destroy(env); /* this is prob what you want, not decref by 2 */
646 /* Switch to the new proc's address space and finish the syscall. We'll
647 * never naturally finish this syscall for the new proc, since its memory
648 * is cloned before we return for the original process. If we ever do CoW
649 * for forked memory, this will be the first place that gets CoW'd. */
650 temp = switch_to(env);
651 finish_current_sysc(0);
652 switch_back(env, temp);
654 /* In general, a forked process should be a fresh process, and we copy over
655 * whatever stuff is needed between procinfo/procdata. */
656 /* Copy over the procinfo argument stuff in case they don't exec */
657 memcpy(env->procinfo->argp, e->procinfo->argp, sizeof(e->procinfo->argp));
658 memcpy(env->procinfo->argbuf, e->procinfo->argbuf,
659 sizeof(e->procinfo->argbuf));
661 /* new guy needs to know about ldt (everything else in procdata is fresh */
662 env->procdata->ldt = e->procdata->ldt;
665 /* FYI: once we call ready, the proc is open for concurrent usage */
669 // don't decref the new process.
670 // that will happen when the parent waits for it.
671 // TODO: if the parent doesn't wait, we need to change the child's parent
672 // when the parent dies, or at least decref it
674 printd("[PID %d] fork PID %d\n", e->pid, env->pid);
676 proc_decref(env); /* give up the reference created in proc_alloc() */
680 /* Load the binary "path" into the current process, and start executing it.
681 * argv and envp are magically bundled in procinfo for now. Keep in sync with
682 * glibc's sysdeps/ros/execve.c. Once past a certain point, this function won't
683 * return. It assumes (and checks) that it is current. Don't give it an extra
684 * refcnt'd *p (syscall won't do that).
685 * Note: if someone batched syscalls with this call, they could clobber their
686 * old memory (and will likely PF and die). Don't do it... */
687 static int sys_exec(struct proc *p, char *path, size_t path_l,
692 struct file *program;
693 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
696 /* We probably want it to never be allowed to exec if it ever was _M */
697 if (p->state != PROC_RUNNING_S) {
701 if (p != pcpui->cur_proc) {
705 /* Copy in the path. Consider putting an upper bound on path_l. */
706 t_path = user_strdup_errno(p, path, path_l);
709 disable_irqsave(&state); /* protect cur_ctx */
710 /* Can't exec if we don't have a current_ctx to restart (if we fail). This
711 * isn't 100% true, but I'm okay with it. */
712 if (!pcpui->cur_ctx) {
713 enable_irqsave(&state);
717 /* Preemptively copy out the cur_ctx, in case we fail later (easier on
718 * cur_ctx if we do this now) */
719 p->scp_ctx = *pcpui->cur_ctx;
720 /* Clear the current_ctx. We won't be returning the 'normal' way. Even if
721 * we want to return with an error, we need to go back differently in case
722 * we succeed. This needs to be done before we could possibly block, but
723 * unfortunately happens before the point of no return.
725 * Note that we will 'hard block' if we block at all. We can't return to
726 * userspace and then asynchronously finish the exec later. */
727 clear_owning_proc(core_id());
728 enable_irqsave(&state);
729 /* This could block: */
730 /* TODO: 9ns support */
731 program = do_file_open(t_path, 0, 0);
732 user_memdup_free(p, t_path);
735 if (!is_valid_elf(program)) {
739 /* Set the argument stuff needed by glibc */
740 if (memcpy_from_user_errno(p, p->procinfo->argp, pi->argp,
743 if (memcpy_from_user_errno(p, p->procinfo->argbuf, pi->argbuf,
746 /* This is the point of no return for the process. */
747 /* progname is argv0, which accounts for symlinks */
748 proc_set_progname(p, p->procinfo->argbuf);
750 /* clear this, so the new program knows to get an LDT */
751 p->procdata->ldt = 0;
753 /* When we destroy our memory regions, accessing cur_sysc would PF */
754 pcpui->cur_kthread->sysc = 0;
755 unmap_and_destroy_vmrs(p);
756 /* close the CLOEXEC ones */
757 close_9ns_files(p, TRUE);
758 close_all_files(&p->open_files, TRUE);
759 env_user_mem_free(p, 0, UMAPTOP);
760 if (load_elf(p, program)) {
761 kref_put(&program->f_kref);
762 /* Note this is an inedible reference, but proc_destroy now returns */
764 /* We don't want to do anything else - we just need to not accidentally
765 * return to the user (hence the all_out) */
768 printd("[PID %d] exec %s\n", p->pid, file_name(program));
769 kref_put(&program->f_kref);
770 systrace_finish_trace(pcpui->cur_kthread, 0);
772 /* These error and out paths are so we can handle the async interface, both
773 * for when we want to error/return to the proc, as well as when we succeed
774 * and want to start the newly exec'd _S */
776 /* These two error paths are for when we want to restart the process with an
777 * error value (errno is already set). */
778 kref_put(&program->f_kref);
780 finish_current_sysc(-1);
781 systrace_finish_trace(pcpui->cur_kthread, -1);
783 free_sysc_str(pcpui->cur_kthread);
784 /* Here's how we restart the new (on success) or old (on failure) proc: */
785 spin_lock(&p->proc_lock);
786 __unmap_vcore(p, 0); /* VC# keep in sync with proc_run_s */
787 __proc_set_state(p, PROC_WAITING); /* fake a yield */
788 spin_unlock(&p->proc_lock);
791 /* we can't return, since we'd write retvals to the old location of the
792 * syscall struct (which has been freed and is in the old userspace) (or has
793 * already been written to).*/
794 disable_irq(); /* abandon_core/clear_own wants irqs disabled */
796 smp_idle(); /* will reenable interrupts */
799 /* Helper, will attempt a particular wait on a proc. Returns the pid of the
800 * process if we waited on it successfully, and the status will be passed back
801 * in ret_status (kernel memory). Returns 0 if the wait failed and we should
802 * try again. Returns -1 if we should abort. Only handles DYING. Callers
803 * need to lock to protect the children tailq and reaping bits. */
804 static pid_t try_wait(struct proc *parent, struct proc *child, int *ret_status,
807 if (child->state == PROC_DYING) {
808 /* Disown returns -1 if it's already been disowned or we should o/w
809 * abort. This can happen if we have concurrent waiters, both with
810 * pointers to the child (only one should reap). Note that if we don't
811 * do this, we could go to sleep and never receive a cv_signal. */
812 if (__proc_disown_child(parent, child))
814 /* despite disowning, the child won't be freed til we drop this ref
815 * held by this function, so it is safe to access the memory.
817 * Note the exit code one byte in the 0xff00 spot. Check out glibc's
818 * posix/sys/wait.h and bits/waitstatus.h for more info. If we ever
819 * deal with signalling and stopping, we'll need to do some more work
821 *ret_status = (child->exitcode & 0xff) << 8;
827 /* Helper, like try_wait, but attempts a wait on any of the children, returning
828 * the specific PID we waited on, 0 to try again (a waitable exists), and -1 to
829 * abort (no children/waitables exist). Callers need to lock to protect the
830 * children tailq and reaping bits.*/
831 static pid_t try_wait_any(struct proc *parent, int *ret_status, int options)
833 struct proc *i, *temp;
835 if (TAILQ_EMPTY(&parent->children))
837 /* Could have concurrent waiters mucking with the tailq, caller must lock */
838 TAILQ_FOREACH_SAFE(i, &parent->children, sibling_link, temp) {
839 retval = try_wait(parent, i, ret_status, options);
840 /* This catches a thread causing a wait to fail but not taking the
841 * child off the list before unlocking. Should never happen. */
842 assert(retval != -1);
843 /* Succeeded, return the pid of the child we waited on */
851 /* Waits on a particular child, returns the pid of the child waited on, and
852 * puts the ret status in *ret_status. Returns the pid if we succeeded, 0 if
853 * the child was not waitable and WNOHANG, and -1 on error. */
854 static pid_t wait_one(struct proc *parent, struct proc *child, int *ret_status,
858 cv_lock(&parent->child_wait);
859 /* retval == 0 means we should block */
860 retval = try_wait(parent, child, ret_status, options);
861 if ((retval == 0) && (options & WNOHANG))
865 cv_wait(&parent->child_wait);
866 /* If we're dying, then we don't need to worry about waiting. We don't
867 * do this yet, but we'll need this outlet when we deal with orphaned
868 * children and having init inherit them. */
869 if (parent->state == PROC_DYING)
871 /* Any child can wake us up, but we check for the particular child we
873 retval = try_wait(parent, child, ret_status, options);
876 /* Child was already waited on by a concurrent syscall. */
881 cv_unlock(&parent->child_wait);
885 /* Waits on any child, returns the pid of the child waited on, and puts the ret
886 * status in *ret_status. Is basically a waitpid(-1, ... ); See wait_one for
887 * more details. Returns -1 if there are no children to wait on, and returns 0
888 * if there are children and we need to block but WNOHANG was set. */
889 static pid_t wait_any(struct proc *parent, int *ret_status, int options)
892 cv_lock(&parent->child_wait);
893 retval = try_wait_any(parent, ret_status, options);
894 if ((retval == 0) && (options & WNOHANG))
898 cv_wait(&parent->child_wait);
899 if (parent->state == PROC_DYING)
901 /* Any child can wake us up from the CV. This is a linear try_wait
902 * scan. If we have a lot of children, we could optimize this. */
903 retval = try_wait_any(parent, ret_status, options);
906 assert(TAILQ_EMPTY(&parent->children));
909 cv_unlock(&parent->child_wait);
913 /* Note: we only allow waiting on children (no such thing as threads, for
914 * instance). Right now we only allow waiting on termination (not signals),
915 * and we don't have a way for parents to disown their children (such as
916 * ignoring SIGCHLD, see man 2 waitpid's Notes).
918 * We don't bother with stop/start signals here, though we can probably build
919 * it in the helper above.
921 * Returns the pid of who we waited on, or -1 on error, or 0 if we couldn't
923 static pid_t sys_waitpid(struct proc *parent, pid_t pid, int *status,
930 /* -1 is the signal for 'any child' */
932 retval = wait_any(parent, &ret_status, options);
935 child = pid2proc(pid);
937 set_errno(ECHILD); /* ECHILD also used for no proc */
941 if (!(parent->pid == child->ppid)) {
946 retval = wait_one(parent, child, &ret_status, options);
951 /* ignoring / don't care about memcpy's retval here. */
953 memcpy_to_user(parent, status, &ret_status, sizeof(ret_status));
954 printd("[PID %d] waited for PID %d, got retval %d (status 0x%x)\n",
955 parent->pid, pid, retval, ret_status);
959 /************** Memory Management Syscalls **************/
961 static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
962 int flags, int fd, off_t offset)
964 return mmap(p, addr, len, prot, flags, fd, offset);
967 static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
969 return mprotect(p, (uintptr_t)addr, len, prot);
972 static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
974 return munmap(p, (uintptr_t)addr, len);
977 static ssize_t sys_shared_page_alloc(env_t* p1,
978 void**DANGEROUS _addr, pid_t p2_id,
979 int p1_flags, int p2_flags
982 printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
986 static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
991 /* Helper, to do the actual provisioning of a resource to a proc */
992 static int prov_resource(struct proc *target, unsigned int res_type,
997 /* in the off chance we have a kernel scheduler that can't
998 * provision, we'll need to change this. */
999 return provision_core(target, res_val);
1001 printk("[kernel] received provisioning for unknown resource %d\n",
1003 set_errno(ENOENT); /* or EINVAL? */
1008 /* Rough syscall to provision res_val of type res_type to target_pid */
1009 static int sys_provision(struct proc *p, int target_pid,
1010 unsigned int res_type, long res_val)
1012 struct proc *target = pid2proc(target_pid);
1015 if (target_pid == 0)
1016 return prov_resource(0, res_type, res_val);
1017 /* debugging interface */
1018 if (target_pid == -1)
1023 retval = prov_resource(target, res_type, res_val);
1024 proc_decref(target);
1028 /* Untested. Will notify the target on the given vcore, if the caller controls
1029 * the target. Will honor the target's wanted/vcoreid. u_ne can be NULL. */
1030 static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
1031 struct event_msg *u_msg)
1033 struct event_msg local_msg = {0};
1034 struct proc *target = get_controllable_proc(p, target_pid);
1037 /* if the user provided an ev_msg, copy it in and use that */
1039 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1040 proc_decref(target);
1045 local_msg.ev_type = ev_type;
1047 send_kernel_event(target, &local_msg, 0);
1048 proc_decref(target);
1052 /* Will notify the calling process on the given vcore, independently of WANTED
1053 * or advertised vcoreid. If you change the parameters, change pop_user_ctx().
1055 static int sys_self_notify(struct proc *p, uint32_t vcoreid,
1056 unsigned int ev_type, struct event_msg *u_msg,
1059 struct event_msg local_msg = {0};
1060 /* if the user provided an ev_msg, copy it in and use that */
1062 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
1067 local_msg.ev_type = ev_type;
1069 if (local_msg.ev_type >= MAX_NR_EVENT) {
1070 printk("[kernel] received self-notify for vcoreid %d, ev_type %d, "
1071 "u_msg %p, u_msg->type %d\n", vcoreid, ev_type, u_msg,
1072 u_msg ? u_msg->ev_type : 0);
1075 /* this will post a message and IPI, regardless of wants/needs/debutantes.*/
1076 post_vcore_event(p, &local_msg, vcoreid, priv ? EVENT_VCORE_PRIVATE : 0);
1077 proc_notify(p, vcoreid);
1081 /* Puts the calling core into vcore context, if it wasn't already, via a
1082 * self-IPI / active notification. Barring any weird unmappings, we just send
1083 * ourselves a __notify. */
1084 static int sys_vc_entry(struct proc *p)
1086 send_kernel_message(core_id(), __notify, (long)p, 0, 0, KMSG_ROUTINE);
1090 /* This will halt the core, waking on an IRQ. These could be kernel IRQs for
1091 * things like timers or devices, or they could be IPIs for RKMs (__notify for
1092 * an evq with IPIs for a syscall completion, etc).
1094 * We don't need to finish the syscall early (worried about the syscall struct,
1095 * on the vcore's stack). The syscall will finish before any __preempt RKM
1096 * executes, so the vcore will not restart somewhere else before the syscall
1097 * completes (unlike with yield, where the syscall itself adjusts the vcore
1100 * In the future, RKM code might avoid sending IPIs if the core is already in
1101 * the kernel. That code will need to check the CPU's state in some manner, and
1102 * send if the core is halted/idle.
1104 * The core must wake up for RKMs, including RKMs that arrive while the kernel
1105 * is trying to halt. The core need not abort the halt for notif_pending for
1106 * the vcore, only for a __notify or other RKM. Anyone setting notif_pending
1107 * should then attempt to __notify (o/w it's probably a bug). */
1108 static int sys_halt_core(struct proc *p, unsigned int usec)
1110 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1111 struct preempt_data *vcpd;
1112 /* The user can only halt CG cores! (ones it owns) */
1113 if (management_core())
1116 /* both for accounting and possible RKM optimizations */
1117 __set_cpu_state(pcpui, CPU_STATE_IDLE);
1119 if (has_routine_kmsg()) {
1120 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1124 /* This situation possible, though the check is not necessary. We can't
1125 * assert notif_pending isn't set, since another core may be in the
1126 * proc_notify. Thus we can't tell if this check here caught a bug, or just
1128 vcpd = &p->procdata->vcore_preempt_data[pcpui->owning_vcoreid];
1129 if (vcpd->notif_pending) {
1130 __set_cpu_state(pcpui, CPU_STATE_KERNEL);
1134 /* CPU_STATE is reset to KERNEL by the IRQ handler that wakes us */
1139 /* Changes a process into _M mode, or -EINVAL if it already is an mcp.
1140 * __proc_change_to_m() returns and we'll eventually finish the sysc later. The
1141 * original context may restart on a remote core before we return and finish,
1142 * but that's fine thanks to the async kernel interface. */
1143 static int sys_change_to_m(struct proc *p)
1145 int retval = proc_change_to_m(p);
1146 /* convert the kernel error code into (-1, errno) */
1154 /* Pokes the ksched for the given resource for target_pid. If the target pid
1155 * == 0, we just poke for the calling process. The common case is poking for
1156 * self, so we avoid the lookup.
1158 * Not sure if you could harm someone via asking the kernel to look at them, so
1159 * we'll do a 'controls' check for now. In the future, we might have something
1160 * in the ksched that limits or penalizes excessive pokes. */
1161 static int sys_poke_ksched(struct proc *p, int target_pid,
1162 unsigned int res_type)
1164 struct proc *target;
1167 poke_ksched(p, res_type);
1170 target = pid2proc(target_pid);
1175 if (!proc_controls(p, target)) {
1180 poke_ksched(target, res_type);
1182 proc_decref(target);
1186 static int sys_abort_sysc(struct proc *p, struct syscall *sysc)
1188 return abort_sysc(p, sysc);
1191 static int sys_abort_sysc_fd(struct proc *p, int fd)
1193 /* Consider checking for a bad fd. Doesn't matter now, since we only look
1194 * for actual syscalls blocked that had used fd. */
1195 return abort_all_sysc_fd(p, fd);
1198 static unsigned long sys_populate_va(struct proc *p, uintptr_t va,
1199 unsigned long nr_pgs)
1201 return populate_va(p, ROUNDDOWN(va, PGSIZE), nr_pgs);
1204 static intreg_t sys_read(struct proc *p, int fd, void *buf, int len)
1206 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1207 struct systrace_record *t = pcpui->cur_kthread->trace;
1209 struct file *file = get_file_from_fd(&p->open_files, fd);
1210 sysc_save_str("read on fd %d", fd);
1213 if (!file->f_op->read) {
1214 kref_put(&file->f_kref);
1218 /* TODO: (UMEM) currently, read() handles user memcpy
1219 * issues, but we probably should user_mem_check and
1220 * pin the region here, so read doesn't worry about
1222 ret = file->f_op->read(file, buf, len, &file->f_pos);
1223 kref_put(&file->f_kref);
1225 /* plan9, should also handle errors (EBADF) */
1226 ret = sysread(fd, buf, len);
1229 if ((ret > 0) && t) {
1230 t->datalen = MIN(sizeof(t->data), ret);
1231 memmove(t->data, buf, t->datalen);
1237 static intreg_t sys_write(struct proc *p, int fd, const void *buf, int len)
1239 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1240 struct systrace_record *t = pcpui->cur_kthread->trace;
1242 struct file *file = get_file_from_fd(&p->open_files, fd);
1243 sysc_save_str("write on fd %d", fd);
1246 if (!file->f_op->write) {
1247 kref_put(&file->f_kref);
1252 ret = file->f_op->write(file, buf, len, &file->f_pos);
1253 kref_put(&file->f_kref);
1255 /* plan9, should also handle errors */
1256 ret = syswrite(fd, (void*)buf, len);
1260 t->datalen = MIN(sizeof(t->data), ret);
1261 memmove(t->data, buf, t->datalen);
1267 /* Checks args/reads in the path, opens the file, and inserts it into the
1268 * process's open file list. */
1269 static intreg_t sys_open(struct proc *p, const char *path, size_t path_l,
1270 int oflag, int mode)
1272 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1273 struct systrace_record *t = pcpui->cur_kthread->trace;
1277 printd("File %s Open attempt oflag %x mode %x\n", path, oflag, mode);
1278 char *t_path = user_strdup_errno(p, path, path_l);
1282 t->datalen = MIN(sizeof(t->data), path_l);
1283 memmove(t->data, t_path, path_l);
1286 /* Make sure only one of O_RDONLY, O_WRONLY, O_RDWR is specified in flag */
1287 if (((oflag & (O_RDONLY | O_WRONLY | O_RDWR)) != O_RDONLY) &&
1288 ((oflag & (O_RDONLY | O_WRONLY | O_RDWR)) != O_WRONLY) &&
1289 ((oflag & (O_RDONLY | O_WRONLY | O_RDWR)) != O_RDWR)) {
1291 user_memdup_free(p, t_path);
1295 sysc_save_str("open %s", t_path);
1296 mode &= ~p->fs_env.umask;
1297 file = do_file_open(t_path, oflag, mode);
1300 /* stores the ref to file */
1301 fd = insert_file(&p->open_files, file, 0, FALSE, oflag & O_CLOEXEC);
1302 kref_put(&file->f_kref); /* drop our ref */
1304 warn("File insertion failed");
1305 } else if (get_errno() == ENOENT) {
1306 unset_errno(); /* Go can't handle extra errnos */
1307 fd = sysopen(t_path, oflag);
1308 /* successful lookup with CREATE and EXCL is an error */
1310 if ((oflag & O_CREATE) && (oflag & O_EXCL)) {
1313 user_memdup_free(p, t_path);
1317 if (oflag & O_CREATE) {
1319 fd = syscreate(t_path, oflag, mode);
1323 user_memdup_free(p, t_path);
1324 printd("File %s Open, fd=%d\n", path, fd);
1328 static intreg_t sys_close(struct proc *p, int fd)
1330 struct file *file = get_file_from_fd(&p->open_files, fd);
1332 printd("sys_close %d\n", fd);
1335 put_file_from_fd(&p->open_files, fd);
1336 kref_put(&file->f_kref); /* Drop the ref from get_file */
1339 /* 9ns, should also handle errors (bad FD, etc) */
1340 retval = sysclose(fd);
1342 /* no one checks their retvals. a double close will cause problems. */
1343 printk("[kernel] sys_close failed: proc %d fd %d. Check your rets.\n",
1349 /* kept around til we remove the last ufe */
1350 #define ufe(which,a0,a1,a2,a3) \
1351 frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
1352 (int)(a0),(int)(a1),(int)(a2),(int)(a3))
1354 static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
1358 kbuf = kmalloc(sizeof(struct kstat), 0);
1363 file = get_file_from_fd(&p->open_files, fd);
1366 stat_inode(file->f_dentry->d_inode, kbuf);
1367 kref_put(&file->f_kref);
1369 unset_errno(); /* Go can't handle extra errnos */
1370 if (sysfstatakaros(fd, (struct kstat *)kbuf) < 0) {
1375 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1376 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1384 /* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
1385 * treat a symlink for the final item, which (probably) will be controlled by
1386 * the lookup flags */
1387 static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
1388 struct kstat *u_stat, int flags)
1391 struct dentry *path_d;
1392 char *t_path = user_strdup_errno(p, path, path_l);
1396 kbuf = kmalloc(sizeof(struct kstat), 0);
1402 /* Check VFS for path */
1403 path_d = lookup_dentry(t_path, flags);
1405 stat_inode(path_d->d_inode, kbuf);
1406 kref_put(&path_d->d_kref);
1408 /* VFS failed, checking 9ns */
1409 unset_errno(); /* Go can't handle extra errnos */
1410 retval = sysstatakaros(t_path, (struct stat *)kbuf);
1411 printd("sysstat returns %d\n", retval);
1412 /* both VFS and 9ns failed, bail out */
1416 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1417 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat)))
1423 user_memdup_free(p, t_path);
1427 /* Follow a final symlink */
1428 static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1429 struct kstat *u_stat)
1431 return stat_helper(p, path, path_l, u_stat, LOOKUP_FOLLOW);
1434 /* Don't follow a final symlink */
1435 static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1436 struct kstat *u_stat)
1438 return stat_helper(p, path, path_l, u_stat, 0);
1441 intreg_t sys_fcntl(struct proc *p, int fd, int cmd, int arg)
1445 struct file *file = get_file_from_fd(&p->open_files, fd);
1451 return sysdup(fd, -1);
1456 return fd_getfl(fd);
1458 return fd_setfl(fd, arg);
1460 warn("Unsupported fcntl cmd %d\n", cmd);
1462 /* not really ever calling this, even for badf, due to the switch */
1467 /* TODO: these are racy */
1470 retval = insert_file(&p->open_files, file, arg, FALSE, FALSE);
1477 retval = p->open_files.fd[fd].fd_flags;
1480 /* I'm considering not supporting this at all. They must do it at
1481 * open time or fix their buggy/racy code. */
1482 spin_lock(&p->open_files.lock);
1483 if (arg & FD_CLOEXEC)
1484 p->open_files.fd[fd].fd_flags |= FD_CLOEXEC;
1485 retval = p->open_files.fd[fd].fd_flags;
1486 spin_unlock(&p->open_files.lock);
1489 retval = file->f_flags;
1492 /* only allowed to set certain flags. */
1493 arg &= O_FCNTL_FLAGS;
1494 file->f_flags = (file->f_flags & ~O_FCNTL_FLAGS) | arg;
1497 warn("Unsupported fcntl cmd %d\n", cmd);
1499 kref_put(&file->f_kref);
1503 static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1507 char *t_path = user_strdup_errno(p, path, path_l);
1510 /* TODO: 9ns support */
1511 retval = do_access(t_path, mode);
1512 user_memdup_free(p, t_path);
1513 printd("Access for path: %s retval: %d\n", path, retval);
1521 intreg_t sys_umask(struct proc *p, int mask)
1523 int old_mask = p->fs_env.umask;
1524 p->fs_env.umask = mask & S_PMASK;
1528 /* 64 bit seek, with the off64_t passed in via two (potentially 32 bit) off_ts.
1529 * We're supporting both 32 and 64 bit kernels/userspaces, but both use the
1530 * llseek syscall with 64 bit parameters. */
1531 static intreg_t sys_llseek(struct proc *p, int fd, off_t offset_hi,
1532 off_t offset_lo, off64_t *result, int whence)
1535 off64_t tempoff = 0;
1538 tempoff = offset_hi;
1540 tempoff |= offset_lo;
1541 file = get_file_from_fd(&p->open_files, fd);
1543 ret = file->f_op->llseek(file, tempoff, &retoff, whence);
1544 kref_put(&file->f_kref);
1546 /* won't return here if error ... */
1547 ret = sysseek(fd, tempoff, whence);
1554 if (memcpy_to_user_errno(p, result, &retoff, sizeof(off64_t)))
1559 intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1560 char *new_path, size_t new_l)
1563 char *t_oldpath = user_strdup_errno(p, old_path, old_l);
1564 if (t_oldpath == NULL)
1566 char *t_newpath = user_strdup_errno(p, new_path, new_l);
1567 if (t_newpath == NULL) {
1568 user_memdup_free(p, t_oldpath);
1571 ret = do_link(t_oldpath, t_newpath);
1572 user_memdup_free(p, t_oldpath);
1573 user_memdup_free(p, t_newpath);
1577 intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
1580 char *t_path = user_strdup_errno(p, path, path_l);
1583 retval = do_unlink(t_path);
1584 if (retval && (get_errno() == ENOENT)) {
1586 retval = sysremove(t_path);
1588 user_memdup_free(p, t_path);
1592 intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
1593 char *new_path, size_t new_l)
1596 char *t_oldpath = user_strdup_errno(p, old_path, old_l);
1597 if (t_oldpath == NULL)
1599 char *t_newpath = user_strdup_errno(p, new_path, new_l);
1600 if (t_newpath == NULL) {
1601 user_memdup_free(p, t_oldpath);
1604 ret = do_symlink(t_newpath, t_oldpath, S_IRWXU | S_IRWXG | S_IRWXO);
1605 user_memdup_free(p, t_oldpath);
1606 user_memdup_free(p, t_newpath);
1610 intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
1611 char *u_buf, size_t buf_l)
1613 char *symname = NULL;
1614 uint8_t *buf = NULL;
1617 struct dentry *path_d;
1618 char *t_path = user_strdup_errno(p, path, path_l);
1621 /* TODO: 9ns support */
1622 path_d = lookup_dentry(t_path, 0);
1625 buf = kmalloc(n*2, KMALLOC_WAIT);
1626 struct dir *d = (void *)&buf[n];
1628 if (sysstat(t_path, buf, n) > 0) {
1629 printk("sysstat t_path %s\n", t_path);
1630 convM2D(buf, n, d, (char *)&d[1]);
1631 /* will be NULL if things did not work out */
1635 symname = path_d->d_inode->i_op->readlink(path_d);
1637 user_memdup_free(p, t_path);
1640 copy_amt = strnlen(symname, buf_l - 1) + 1;
1641 if (! memcpy_to_user_errno(p, u_buf, symname, copy_amt))
1645 kref_put(&path_d->d_kref);
1648 printd("READLINK returning %s\n", u_buf);
1652 static intreg_t sys_chdir(struct proc *p, pid_t pid, const char *path, size_t path_l)
1656 struct proc *target = get_controllable_proc(p, pid);
1659 t_path = user_strdup_errno(p, path, path_l);
1661 proc_decref(target);
1664 /* TODO: 9ns support */
1665 retval = do_chdir(&target->fs_env, t_path);
1666 user_memdup_free(p, t_path);
1667 proc_decref(target);
1671 static intreg_t sys_fchdir(struct proc *p, pid_t pid, int fd)
1675 struct proc *target = get_controllable_proc(p, pid);
1678 file = get_file_from_fd(&p->open_files, fd);
1682 proc_decref(target);
1685 retval = do_fchdir(&target->fs_env, file);
1686 kref_put(&file->f_kref);
1687 proc_decref(target);
1691 /* Note cwd_l is not a strlen, it's an absolute size */
1692 intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
1696 char *k_cwd = do_getcwd(&p->fs_env, &kfree_this, cwd_l);
1698 return -1; /* errno set by do_getcwd */
1699 if (memcpy_to_user_errno(p, u_cwd, k_cwd, strnlen(k_cwd, cwd_l - 1) + 1))
1701 retval = strnlen(k_cwd, cwd_l - 1);
1706 intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
1709 char *t_path = user_strdup_errno(p, path, path_l);
1713 mode &= ~p->fs_env.umask;
1714 retval = do_mkdir(t_path, mode);
1715 if (retval && (get_errno() == ENOENT)) {
1717 /* mixing plan9 and glibc here, make sure DMDIR doesn't overlap with any
1719 static_assert(!(S_PMASK & DMDIR));
1720 retval = syscreate(t_path, O_RDWR, DMDIR | mode);
1722 user_memdup_free(p, t_path);
1726 intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
1729 char *t_path = user_strdup_errno(p, path, path_l);
1732 /* TODO: 9ns support */
1733 retval = do_rmdir(t_path);
1734 user_memdup_free(p, t_path);
1738 intreg_t sys_pipe(struct proc *p, int *u_pipefd, int flags)
1740 int pipefd[2] = {0};
1741 int retval = syspipe(pipefd);
1745 if (memcpy_to_user_errno(p, u_pipefd, pipefd, sizeof(pipefd))) {
1746 sysclose(pipefd[0]);
1747 sysclose(pipefd[1]);
1754 intreg_t sys_gettimeofday(struct proc *p, int *buf)
1756 static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
1759 spin_lock(>od_lock);
1762 #if (defined CONFIG_APPSERVER)
1763 t0 = ufe(time,0,0,0,0);
1765 // Nanwan's birthday, bitches!!
1768 spin_unlock(>od_lock);
1770 long long dt = read_tsc();
1771 /* TODO: This probably wants its own function, using a struct timeval */
1772 long kbuf[2] = {t0+dt/system_timing.tsc_freq,
1773 (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
1775 return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
1778 intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
1781 /* TODO: actually support this call on tty FDs. Right now, we just fake
1782 * what my linux box reports for a bash pty. */
1783 struct termios *kbuf = kmalloc(sizeof(struct termios), 0);
1784 kbuf->c_iflag = 0x2d02;
1785 kbuf->c_oflag = 0x0005;
1786 kbuf->c_cflag = 0x04bf;
1787 kbuf->c_lflag = 0x8a3b;
1789 kbuf->c_ispeed = 0xf;
1790 kbuf->c_ospeed = 0xf;
1791 kbuf->c_cc[0] = 0x03;
1792 kbuf->c_cc[1] = 0x1c;
1793 kbuf->c_cc[2] = 0x7f;
1794 kbuf->c_cc[3] = 0x15;
1795 kbuf->c_cc[4] = 0x04;
1796 kbuf->c_cc[5] = 0x00;
1797 kbuf->c_cc[6] = 0x01;
1798 kbuf->c_cc[7] = 0xff;
1799 kbuf->c_cc[8] = 0x11;
1800 kbuf->c_cc[9] = 0x13;
1801 kbuf->c_cc[10] = 0x1a;
1802 kbuf->c_cc[11] = 0xff;
1803 kbuf->c_cc[12] = 0x12;
1804 kbuf->c_cc[13] = 0x0f;
1805 kbuf->c_cc[14] = 0x17;
1806 kbuf->c_cc[15] = 0x16;
1807 kbuf->c_cc[16] = 0xff;
1808 kbuf->c_cc[17] = 0x00;
1809 kbuf->c_cc[18] = 0x00;
1810 kbuf->c_cc[19] = 0x00;
1811 kbuf->c_cc[20] = 0x00;
1812 kbuf->c_cc[21] = 0x00;
1813 kbuf->c_cc[22] = 0x00;
1814 kbuf->c_cc[23] = 0x00;
1815 kbuf->c_cc[24] = 0x00;
1816 kbuf->c_cc[25] = 0x00;
1817 kbuf->c_cc[26] = 0x00;
1818 kbuf->c_cc[27] = 0x00;
1819 kbuf->c_cc[28] = 0x00;
1820 kbuf->c_cc[29] = 0x00;
1821 kbuf->c_cc[30] = 0x00;
1822 kbuf->c_cc[31] = 0x00;
1824 if (memcpy_to_user_errno(p, termios_p, kbuf, sizeof(struct termios)))
1830 intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
1831 const void *termios_p)
1833 /* TODO: do this properly too. For now, we just say 'it worked' */
1837 /* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
1838 * process from thinking it can do these. The other alternative is to have
1839 * glibc return 0 right away, though someone might want to do something with
1840 * these calls. Someday. */
1841 intreg_t sys_setuid(struct proc *p, uid_t uid)
1846 intreg_t sys_setgid(struct proc *p, gid_t gid)
1851 /* long bind(char* src_path, char* onto_path, int flag);
1853 * The naming for the args in bind is messy historically. We do:
1854 * bind src_path onto_path
1855 * plan9 says bind NEW OLD, where new is *src*, and old is *onto*.
1856 * Linux says mount --bind OLD NEW, where OLD is *src* and NEW is *onto*. */
1857 intreg_t sys_nbind(struct proc *p,
1858 char *src_path, size_t src_l,
1859 char *onto_path, size_t onto_l,
1864 char *t_srcpath = user_strdup_errno(p, src_path, src_l);
1865 if (t_srcpath == NULL) {
1866 printd("srcpath dup failed ptr %p size %d\n", src_path, src_l);
1869 char *t_ontopath = user_strdup_errno(p, onto_path, onto_l);
1870 if (t_ontopath == NULL) {
1871 user_memdup_free(p, t_srcpath);
1872 printd("ontopath dup failed ptr %p size %d\n", onto_path, onto_l);
1875 printd("sys_nbind: %s -> %s flag %d\n", t_srcpath, t_ontopath, flag);
1876 ret = sysbind(t_srcpath, t_ontopath, flag);
1877 user_memdup_free(p, t_srcpath);
1878 user_memdup_free(p, t_ontopath);
1882 /* int mount(int fd, int afd, char* onto_path, int flag, char* aname); */
1883 intreg_t sys_nmount(struct proc *p,
1885 char *onto_path, size_t onto_l,
1887 /* we ignore these */
1888 /* no easy way to pass this many args anyway. *
1890 char *auth, size_t auth_l*/)
1896 char *t_ontopath = user_strdup_errno(p, onto_path, onto_l);
1897 if (t_ontopath == NULL)
1899 ret = sysmount(fd, afd, t_ontopath, flag, /* spec or auth */"");
1900 user_memdup_free(p, t_ontopath);
1904 /* int mount(int fd, int afd, char* old, int flag, char* aname); */
1905 intreg_t sys_nunmount(struct proc *p, char *name, int name_l, char *old_path, int old_l)
1908 char *t_oldpath = user_strdup_errno(p, old_path, old_l);
1909 if (t_oldpath == NULL)
1911 char *t_name = user_strdup_errno(p, name, name_l);
1912 if (t_name == NULL) {
1913 user_memdup_free(p, t_oldpath);
1916 ret = sysunmount(t_name, t_oldpath);
1917 printd("go do it\n");
1918 user_memdup_free(p, t_oldpath);
1919 user_memdup_free(p, t_name);
1923 intreg_t sys_fd2path(struct proc *p, int fd, void *u_buf, size_t len)
1928 /* UMEM: Check the range, can PF later and kill if the page isn't present */
1929 if (!is_user_rwaddr(u_buf, len)) {
1930 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", u_buf,
1934 /* fdtochan throws */
1939 ch = fdtochan(current->fgrp, fd, -1, FALSE, TRUE);
1940 ret = snprintf(u_buf, len, "%s", channame(ch));
1946 /* Helper, interprets the wstat and performs the VFS action. Returns stat_sz on
1947 * success for all ops, -1 or 0 o/w. If one op fails, it'll skip the remaining
1949 static int vfs_wstat(struct file *file, uint8_t *stat_m, size_t stat_sz,
1956 dir = kzmalloc(sizeof(struct dir) + stat_sz, KMALLOC_WAIT);
1957 m_sz = convM2D(stat_m, stat_sz, &dir[0], (char*)&dir[1]);
1958 if (m_sz != stat_sz) {
1959 set_errstr(Eshortstat);
1964 if (flags & WSTAT_MODE) {
1965 retval = do_file_chmod(file, dir->mode);
1969 if (flags & WSTAT_LENGTH) {
1970 retval = do_truncate(file->f_dentry->d_inode, dir->length);
1974 if (flags & WSTAT_ATIME) {
1975 /* wstat only gives us seconds */
1976 file->f_dentry->d_inode->i_atime.tv_sec = dir->atime;
1977 file->f_dentry->d_inode->i_atime.tv_nsec = 0;
1979 if (flags & WSTAT_MTIME) {
1980 file->f_dentry->d_inode->i_mtime.tv_sec = dir->mtime;
1981 file->f_dentry->d_inode->i_mtime.tv_nsec = 0;
1986 /* convert vfs retval to wstat retval */
1992 intreg_t sys_wstat(struct proc *p, char *path, size_t path_l,
1993 uint8_t *stat_m, size_t stat_sz, int flags)
1996 char *t_path = user_strdup_errno(p, path, path_l);
2001 retval = syswstat(t_path, stat_m, stat_sz);
2002 if (retval == stat_sz) {
2003 user_memdup_free(p, t_path);
2006 /* 9ns failed, we'll need to check the VFS */
2007 file = do_file_open(t_path, 0, 0);
2008 user_memdup_free(p, t_path);
2011 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2012 kref_put(&file->f_kref);
2016 intreg_t sys_fwstat(struct proc *p, int fd, uint8_t *stat_m, size_t stat_sz,
2022 retval = sysfwstat(fd, stat_m, stat_sz);
2023 if (retval == stat_sz)
2025 /* 9ns failed, we'll need to check the VFS */
2026 file = get_file_from_fd(&p->open_files, fd);
2029 retval = vfs_wstat(file, stat_m, stat_sz, flags);
2030 kref_put(&file->f_kref);
2034 intreg_t sys_rename(struct proc *p, char *old_path, size_t old_path_l,
2035 char *new_path, size_t new_path_l)
2037 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2038 struct systrace_record *t = pcpui->cur_kthread->trace;
2040 int mountpointlen = 0;
2041 char *from_path = user_strdup_errno(p, old_path, old_path_l);
2042 char *to_path = user_strdup_errno(p, new_path, new_path_l);
2043 struct chan *oldchan = 0, *newchan = NULL;
2046 if ((!from_path) || (!to_path))
2048 printd("sys_rename :%s: to :%s: : ", from_path, to_path);
2050 t->datalen = snprintf((char *)t->data, sizeof(t->data), "Rename :%s: to :%s:", from_path, to_path);
2053 /* we need a fid for the wstat. */
2054 /* TODO: maybe wrap the 9ns stuff better. sysrename maybe? */
2056 /* discard namec error */
2058 oldchan = namec(from_path, Aaccess, 0, 0);
2062 retval = do_rename(from_path, to_path);
2063 user_memdup_free(p, from_path);
2064 user_memdup_free(p, to_path);
2068 printd("Oldchan: %C\n", oldchan);
2069 printd("Oldchan: mchan %C\n", oldchan->mchan);
2071 /* If walked through a mountpoint, we need to take that
2072 * into account for the Twstat.
2074 if (oldchan->mountpoint) {
2075 printd("mountpoint: %C\n", oldchan->mountpoint);
2076 if (oldchan->mountpoint->name)
2077 mountpointlen = oldchan->mountpoint->name->len;
2080 /* This test makes sense even when mountpointlen is 0 */
2081 if (strlen(to_path) < mountpointlen) {
2086 /* the omode and perm are of no importance. */
2087 newchan = namec(to_path, Acreatechan, 0, 0);
2088 if (newchan == NULL) {
2089 printd("sys_rename %s to %s found no chan\n", from_path, to_path);
2093 printd("Newchan: %C\n", newchan);
2094 printd("Newchan: mchan %C\n", newchan->mchan);
2096 if ((newchan->dev != oldchan->dev) ||
2097 (newchan->type != oldchan->type)) {
2098 printd("Old chan and new chan do not match\n");
2105 uint8_t mbuf[STATFIXLEN + MAX_PATH_LEN + 1];
2107 init_empty_dir(&dir);
2109 /* absolute paths need the mountpoint name stripped from them.
2110 * Once stripped, it still has to be an absolute path.
2112 if (dir.name[0] == '/') {
2113 dir.name = to_path + mountpointlen;
2114 if (dir.name[0] != '/') {
2120 mlen = convD2M(&dir, mbuf, sizeof(mbuf));
2122 printk("convD2M failed\n");
2128 printk("validstat failed: %s\n", current_errstr());
2132 validstat(mbuf, mlen, 1);
2140 retval = devtab[oldchan->type].wstat(oldchan, mbuf, mlen);
2143 if (retval == mlen) {
2146 printk("syswstat did not go well\n");
2149 printk("syswstat returns %d\n", retval);
2152 user_memdup_free(p, from_path);
2153 user_memdup_free(p, to_path);
2159 static intreg_t sys_dup_fds_to(struct proc *p, unsigned int pid,
2160 struct childfdmap *map, unsigned int nentries)
2167 if (!is_user_rwaddr(map, sizeof(struct childfdmap) * nentries)) {
2171 child = get_controllable_proc(p, pid);
2174 for (int i = 0; i < nentries; i++) {
2176 file = get_file_from_fd(&p->open_files, map[i].parentfd);
2178 slot = insert_file(&child->open_files, file, map[i].childfd, TRUE,
2180 if (slot == map[i].childfd) {
2184 kref_put(&file->f_kref);
2187 if (!sys_dup_to(p, map[i].parentfd, child, map[i].childfd)) {
2192 /* probably a bug, could send EBADF, maybe via 'ok' */
2193 printk("[kernel] dup_fds_to: couldn't find %d\n", map[i].parentfd);
2199 /************** Syscall Invokation **************/
2201 const struct sys_table_entry syscall_table[] = {
2202 [SYS_null] = {(syscall_t)sys_null, "null"},
2203 [SYS_block] = {(syscall_t)sys_block, "block"},
2204 [SYS_cache_buster] = {(syscall_t)sys_cache_buster, "buster"},
2205 [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
2206 [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
2207 [SYS_cputs] = {(syscall_t)sys_cputs, "cputs"},
2208 [SYS_cgetc] = {(syscall_t)sys_cgetc, "cgetc"},
2209 [SYS_getpcoreid] = {(syscall_t)sys_getpcoreid, "getpcoreid"},
2210 [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
2211 [SYS_getpid] = {(syscall_t)sys_getpid, "getpid"},
2212 [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
2213 [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
2214 [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
2215 [SYS_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
2216 [SYS_change_vcore] = {(syscall_t)sys_change_vcore, "change_vcore"},
2217 [SYS_fork] = {(syscall_t)sys_fork, "fork"},
2218 [SYS_exec] = {(syscall_t)sys_exec, "exec"},
2219 [SYS_waitpid] = {(syscall_t)sys_waitpid, "waitpid"},
2220 [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
2221 [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
2222 [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
2223 [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
2224 [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
2225 [SYS_provision] = {(syscall_t)sys_provision, "provision"},
2226 [SYS_notify] = {(syscall_t)sys_notify, "notify"},
2227 [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
2228 [SYS_vc_entry] = {(syscall_t)sys_vc_entry, "vc_entry"},
2229 [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
2230 #ifdef CONFIG_ARSC_SERVER
2231 [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
2233 [SYS_change_to_m] = {(syscall_t)sys_change_to_m, "change_to_m"},
2234 [SYS_poke_ksched] = {(syscall_t)sys_poke_ksched, "poke_ksched"},
2235 [SYS_abort_sysc] = {(syscall_t)sys_abort_sysc, "abort_sysc"},
2236 [SYS_abort_sysc_fd] = {(syscall_t)sys_abort_sysc_fd, "abort_sysc_fd"},
2237 [SYS_populate_va] = {(syscall_t)sys_populate_va, "populate_va"},
2239 [SYS_read] = {(syscall_t)sys_read, "read"},
2240 [SYS_write] = {(syscall_t)sys_write, "write"},
2241 [SYS_open] = {(syscall_t)sys_open, "open"},
2242 [SYS_close] = {(syscall_t)sys_close, "close"},
2243 [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
2244 [SYS_stat] = {(syscall_t)sys_stat, "stat"},
2245 [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
2246 [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
2247 [SYS_access] = {(syscall_t)sys_access, "access"},
2248 [SYS_umask] = {(syscall_t)sys_umask, "umask"},
2249 [SYS_llseek] = {(syscall_t)sys_llseek, "llseek"},
2250 [SYS_link] = {(syscall_t)sys_link, "link"},
2251 [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
2252 [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
2253 [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
2254 [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
2255 [SYS_fchdir] = {(syscall_t)sys_fchdir, "fchdir"},
2256 [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
2257 [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdir"},
2258 [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
2259 [SYS_pipe] = {(syscall_t)sys_pipe, "pipe"},
2260 [SYS_gettimeofday] = {(syscall_t)sys_gettimeofday, "gettime"},
2261 [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
2262 [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
2263 [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
2264 [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"},
2266 [SYS_nbind] ={(syscall_t)sys_nbind, "nbind"},
2267 [SYS_nmount] ={(syscall_t)sys_nmount, "nmount"},
2268 [SYS_nunmount] ={(syscall_t)sys_nunmount, "nunmount"},
2269 [SYS_fd2path] ={(syscall_t)sys_fd2path, "fd2path"},
2270 [SYS_wstat] ={(syscall_t)sys_wstat, "wstat"},
2271 [SYS_fwstat] ={(syscall_t)sys_fwstat, "fwstat"},
2272 [SYS_rename] ={(syscall_t)sys_rename, "rename"},
2273 [SYS_dup_fds_to] = {(syscall_t)sys_dup_fds_to, "dup_fds_to"},
2275 const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
2276 /* Executes the given syscall.
2278 * Note tf is passed in, which points to the tf of the context on the kernel
2279 * stack. If any syscall needs to block, it needs to save this info, as well as
2282 * This syscall function is used by both local syscall and arsc, and should
2283 * remain oblivious of the caller. */
2284 intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
2285 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
2287 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2291 if (sc_num > max_syscall || syscall_table[sc_num].call == NULL) {
2292 printk("[kernel] Invalid syscall %d for proc %d\n", sc_num, p->pid);
2293 printk("\tArgs: %p, %p, %p, %p, %p, %p\n", a0, a1, a2, a3, a4, a5);
2294 print_user_ctx(per_cpu_info[core_id()].cur_ctx);
2298 /* N.B. This is going away. */
2300 printk("Plan 9 system call returned via waserror()\n");
2301 printk("String: '%s'\n", current_errstr());
2302 /* if we got here, then the errbuf was right.
2307 //printd("before syscall errstack %p\n", errstack);
2308 //printd("before syscall errstack base %p\n", get_cur_errbuf());
2309 ret = syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
2310 //printd("after syscall errstack base %p\n", get_cur_errbuf());
2311 if (get_cur_errbuf() != &errstack[0]) {
2312 /* Can't trust coreid and vcoreid anymore, need to check the trace */
2313 printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, "
2314 "%p, %p) proc: %d\n", read_tsc(),
2315 sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
2317 if (sc_num != SYS_fork)
2318 printk("YOU SHOULD PANIC: errstack mismatch");
2323 /* Execute the syscall on the local core */
2324 void run_local_syscall(struct syscall *sysc)
2326 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
2328 assert(irq_is_enabled()); /* in case we proc destroy */
2329 /* In lieu of pinning, we just check the sysc and will PF on the user addr
2330 * later (if the addr was unmapped). Which is the plan for all UMEM. */
2331 if (!is_user_rwaddr(sysc, sizeof(struct syscall))) {
2332 printk("[kernel] bad user addr %p (+%p) in %s (user bug)\n", sysc,
2333 sizeof(struct syscall), __FUNCTION__);
2336 pcpui->cur_kthread->sysc = sysc; /* let the core know which sysc it is */
2337 systrace_start_trace(pcpui->cur_kthread, sysc);
2338 alloc_sysc_str(pcpui->cur_kthread);
2339 /* syscall() does not return for exec and yield, so put any cleanup in there
2341 sysc->retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
2342 sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
2343 /* Need to re-load pcpui, in case we migrated */
2344 pcpui = &per_cpu_info[core_id()];
2345 free_sysc_str(pcpui->cur_kthread);
2346 systrace_finish_trace(pcpui->cur_kthread, sysc->retval);
2347 /* Some 9ns paths set errstr, but not errno. glibc will ignore errstr.
2348 * this is somewhat hacky, since errno might get set unnecessarily */
2349 if ((current_errstr()[0] != 0) && (!sysc->err))
2350 sysc->err = EUNSPECIFIED;
2351 finish_sysc(sysc, pcpui->cur_proc);
2352 pcpui->cur_kthread->sysc = 0; /* no longer working on sysc */
2355 /* A process can trap and call this function, which will set up the core to
2356 * handle all the syscalls. a.k.a. "sys_debutante(needs, wants)". If there is
2357 * at least one, it will run it directly. */
2358 void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
2361 /* Careful with pcpui here, we could have migrated */
2363 printk("[kernel] No nr_sysc, probably a bug, user!\n");
2366 /* For all after the first call, send ourselves a KMSG (TODO). */
2368 warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
2369 /* Call the first one directly. (we already checked to make sure there is
2371 run_local_syscall(sysc);
2374 /* Call this when something happens on the syscall where userspace might want to
2375 * get signaled. Passing p, since the caller should know who the syscall
2376 * belongs to (probably is current).
2378 * You need to have SC_K_LOCK set when you call this. */
2379 void __signal_syscall(struct syscall *sysc, struct proc *p)
2381 struct event_queue *ev_q;
2382 struct event_msg local_msg;
2383 /* User sets the ev_q then atomically sets the flag (races with SC_DONE) */
2384 if (atomic_read(&sysc->flags) & SC_UEVENT) {
2385 rmb(); /* read the ev_q after reading the flag */
2388 memset(&local_msg, 0, sizeof(struct event_msg));
2389 local_msg.ev_type = EV_SYSCALL;
2390 local_msg.ev_arg3 = sysc;
2391 send_event(p, ev_q, &local_msg, 0);
2396 /* Syscall tracing */
2397 static void __init_systrace(void)
2399 systrace_buffer = kmalloc(MAX_SYSTRACES*sizeof(struct systrace_record), 0);
2400 if (!systrace_buffer)
2401 panic("Unable to alloc a trace buffer\n");
2402 systrace_bufidx = 0;
2403 systrace_bufsize = MAX_SYSTRACES;
2404 /* Note we never free the buffer - it's around forever. Feel free to change
2405 * this if you want to change the size or something dynamically. */
2408 /* If you call this while it is running, it will change the mode */
2409 void systrace_start(bool silent)
2411 static bool init = FALSE;
2412 spin_lock_irqsave(&systrace_lock);
2417 systrace_flags = silent ? SYSTRACE_ON : SYSTRACE_ON | SYSTRACE_LOUD;
2418 spin_unlock_irqsave(&systrace_lock);
2421 int systrace_reg(bool all, struct proc *p)
2424 spin_lock_irqsave(&systrace_lock);
2426 printk("Tracing syscalls for all processes\n");
2427 systrace_flags |= SYSTRACE_ALLPROC;
2430 for (int i = 0; i < MAX_NUM_TRACED; i++) {
2431 if (!systrace_procs[i]) {
2432 printk("Tracing syscalls for process %d\n", p->pid);
2433 systrace_procs[i] = p;
2439 spin_unlock_irqsave(&systrace_lock);
2443 int systrace_trace_pid(struct proc *p)
2445 if (systrace_reg(false, p))
2446 error("no more processes");
2447 systrace_start(true);
2451 void systrace_stop(void)
2453 spin_lock_irqsave(&systrace_lock);
2455 for (int i = 0; i < MAX_NUM_TRACED; i++)
2456 systrace_procs[i] = 0;
2457 spin_unlock_irqsave(&systrace_lock);
2460 /* If you registered a process specifically, then you need to dereg it
2461 * specifically. Or just fully stop, which will do it for all. */
2462 int systrace_dereg(bool all, struct proc *p)
2464 spin_lock_irqsave(&systrace_lock);
2466 printk("No longer tracing syscalls for all processes.\n");
2467 systrace_flags &= ~SYSTRACE_ALLPROC;
2469 for (int i = 0; i < MAX_NUM_TRACED; i++) {
2470 if (systrace_procs[i] == p) {
2471 systrace_procs[i] = 0;
2472 printk("No longer tracing syscalls for process %d\n", p->pid);
2476 spin_unlock_irqsave(&systrace_lock);
2480 /* Regardless of locking, someone could be writing into the buffer */
2481 void systrace_print(bool all, struct proc *p)
2483 spin_lock_irqsave(&systrace_lock);
2484 /* if you want to be clever, you could make this start from the earliest
2485 * timestamp and loop around. Careful of concurrent writes. */
2486 for (int i = 0; i < systrace_bufsize; i++)
2487 if (systrace_buffer[i].start_timestamp)
2488 printk("[%16llu] Syscall %3d (%12s):(%p, %p, %p, %p, %p,"
2489 "%p) proc: %d core: %d vcore: %d\n",
2490 systrace_buffer[i].start_timestamp,
2491 systrace_buffer[i].syscallno,
2492 syscall_table[systrace_buffer[i].syscallno].name,
2493 systrace_buffer[i].arg0,
2494 systrace_buffer[i].arg1,
2495 systrace_buffer[i].arg2,
2496 systrace_buffer[i].arg3,
2497 systrace_buffer[i].arg4,
2498 systrace_buffer[i].arg5,
2499 systrace_buffer[i].pid,
2500 systrace_buffer[i].coreid,
2501 systrace_buffer[i].vcoreid);
2502 spin_unlock_irqsave(&systrace_lock);
2505 void systrace_clear_buffer(void)
2507 spin_lock_irqsave(&systrace_lock);
2508 memset(systrace_buffer, 0, sizeof(struct systrace_record) * MAX_SYSTRACES);
2509 spin_unlock_irqsave(&systrace_lock);
2512 bool syscall_uses_fd(struct syscall *sysc, int fd)
2514 switch (sysc->num) {
2523 if (sysc->arg0 == fd)
2527 /* mmap always has to be special. =) */
2528 if (sysc->arg4 == fd)
2536 void print_sysc(struct proc *p, struct syscall *sysc)
2538 struct proc *old_p = switch_to(p);
2539 printk("SYS_%d, flags %p, a0 %p, a1 %p, a2 %p, a3 %p, a4 %p, a5 %p\n",
2540 sysc->num, atomic_read(&sysc->flags),
2541 sysc->arg0, sysc->arg1, sysc->arg2, sysc->arg3, sysc->arg4,
2543 switch_back(p, old_p);