1 /* See COPYRIGHT for copyright information. */
7 #include <ros/common.h>
8 #include <arch/types.h>
11 #include <arch/console.h>
29 #include <colored_caches.h>
30 #include <hashtable.h>
35 #include <arsc_server.h>
39 #ifdef __CONFIG_NETWORKING__
40 #include <arch/nic_common.h>
41 extern int (*send_frame)(const char *CT(len) data, size_t len);
42 extern unsigned char device_mac[6];
46 int systrace_flags = 0;
47 struct systrace_record *systrace_buffer = 0;
48 uint32_t systrace_bufidx = 0;
49 size_t systrace_bufsize = 0;
50 struct proc *systrace_procs[MAX_NUM_TRACED] = {0};
51 spinlock_t systrace_lock = SPINLOCK_INITIALIZER;
53 /* Not enforcing the packing of systrace_procs yet, but don't rely on that */
54 static bool proc_is_traced(struct proc *p)
56 for (int i = 0; i < MAX_NUM_TRACED; i++)
57 if (systrace_procs[i] == p)
62 /* Helper to finish a syscall, signalling if appropriate */
63 static void finish_sysc(struct syscall *sysc, struct proc *p)
65 /* Atomically turn on the LOCK and SC_DONE flag. The lock tells userspace
66 * we're messing with the flags and to not proceed. We use it instead of
67 * CASing with userspace. We need the atomics since we're racing with
68 * userspace for the event_queue registration. The 'lock' tells userspace
69 * to not muck with the flags while we're signalling. */
70 atomic_or(&sysc->flags, SC_K_LOCK | SC_DONE);
71 __signal_syscall(sysc, p);
72 atomic_and(&sysc->flags, ~SC_K_LOCK);
75 /* Helper that "finishes" the current async syscall. This should be used when
76 * we are calling a function in a syscall that might not return and won't be
77 * able to use the normal syscall return path, such as proc_yield() and
78 * resource_req(). Call this from within syscall.c (I don't want it global).
80 * It is possible for another user thread to see the syscall being done early -
81 * they just need to be careful with the weird proc management calls (as in,
82 * don't trust an async fork).
84 * *sysc is in user memory, and should be pinned (TODO: UMEM). There may be
85 * issues with unpinning this if we never return. */
86 static void finish_current_sysc(int retval)
88 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
89 assert(pcpui->cur_sysc);
90 pcpui->cur_sysc->retval = retval;
91 finish_sysc(pcpui->cur_sysc, pcpui->cur_proc);
94 /* Callable by any function while executing a syscall (or otherwise, actually).
96 void set_errno(int errno)
98 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
100 pcpui->cur_sysc->err = errno;
103 /************** Utility Syscalls **************/
105 static int sys_null(void)
110 /* Diagnostic function: blocks the kthread/syscall, to help userspace test its
111 * async I/O handling. */
112 static int sys_block(struct proc *p, unsigned int usec)
114 struct timer_chain *tchain = &per_cpu_info[core_id()].tchain;
115 struct alarm_waiter a_waiter;
116 init_awaiter(&a_waiter, 0);
117 /* Note printing takes a few ms, so your printds won't be perfect. */
118 printd("[kernel] sys_block(), sleeping at %llu\n", read_tsc());
119 set_awaiter_rel(&a_waiter, usec);
120 set_alarm(tchain, &a_waiter);
121 sleep_on_awaiter(&a_waiter);
122 printd("[kernel] sys_block(), waking up at %llu\n", read_tsc());
126 // Writes 'val' to 'num_writes' entries of the well-known array in the kernel
127 // address space. It's just #defined to be some random 4MB chunk (which ought
128 // to be boot_alloced or something). Meant to grab exclusive access to cache
129 // lines, to simulate doing something useful.
130 static int sys_cache_buster(struct proc *p, uint32_t num_writes,
131 uint32_t num_pages, uint32_t flags)
132 { TRUSTEDBLOCK /* zra: this is not really part of the kernel */
133 #define BUSTER_ADDR 0xd0000000L // around 512 MB deep
134 #define MAX_WRITES 1048576*8
136 #define INSERT_ADDR (UINFO + 2*PGSIZE) // should be free for these tests
137 uint32_t* buster = (uint32_t*)BUSTER_ADDR;
138 static spinlock_t buster_lock = SPINLOCK_INITIALIZER;
140 page_t* a_page[MAX_PAGES];
142 /* Strided Accesses or Not (adjust to step by cachelines) */
144 if (flags & BUSTER_STRIDED) {
149 /* Shared Accesses or Not (adjust to use per-core regions)
150 * Careful, since this gives 8MB to each core, starting around 512MB.
151 * Also, doesn't separate memory for core 0 if it's an async call.
153 if (!(flags & BUSTER_SHARED))
154 buster = (uint32_t*)(BUSTER_ADDR + core_id() * 0x00800000);
156 /* Start the timer, if we're asked to print this info*/
157 if (flags & BUSTER_PRINT_TICKS)
158 ticks = start_timing();
160 /* Allocate num_pages (up to MAX_PAGES), to simulate doing some more
161 * realistic work. Note we don't write to these pages, even if we pick
162 * unshared. Mostly due to the inconvenience of having to match up the
163 * number of pages with the number of writes. And it's unnecessary.
166 spin_lock(&buster_lock);
167 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
168 upage_alloc(p, &a_page[i],1);
169 page_insert(p->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
171 page_decref(a_page[i]);
173 spin_unlock(&buster_lock);
176 if (flags & BUSTER_LOCKED)
177 spin_lock(&buster_lock);
178 for (int i = 0; i < MIN(num_writes, MAX_WRITES); i=i+stride)
179 buster[i] = 0xdeadbeef;
180 if (flags & BUSTER_LOCKED)
181 spin_unlock(&buster_lock);
184 spin_lock(&buster_lock);
185 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
186 page_remove(p->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
187 page_decref(a_page[i]);
189 spin_unlock(&buster_lock);
193 if (flags & BUSTER_PRINT_TICKS) {
194 ticks = stop_timing(ticks);
195 printk("%llu,", ticks);
200 static int sys_cache_invalidate(void)
208 /* sys_reboot(): called directly from dispatch table. */
210 /* Print a string to the system console. */
211 static ssize_t sys_cputs(struct proc *p, const char *DANGEROUS string,
215 t_string = user_strdup_errno(p, string, strlen);
218 printk("%.*s", strlen, t_string);
219 user_memdup_free(p, t_string);
220 return (ssize_t)strlen;
223 // Read a character from the system console.
224 // Returns the character.
225 static uint16_t sys_cgetc(struct proc *p)
229 // The cons_getc() primitive doesn't wait for a character,
230 // but the sys_cgetc() system call does.
231 while ((c = cons_getc()) == 0)
237 /* Returns the id of the cpu this syscall is executed on. */
238 static uint32_t sys_getcpuid(void)
243 // TODO: Temporary hack until thread-local storage is implemented on i386 and
244 // this is removed from the user interface
245 static size_t sys_getvcoreid(struct proc *p)
247 return proc_get_vcoreid(p, core_id());
250 /************** Process management syscalls **************/
252 /* Returns the calling process's pid */
253 static pid_t sys_getpid(struct proc *p)
258 /* Creates a process from the file 'path'. The process is not runnable by
259 * default, so it needs it's status to be changed so that the next call to
260 * schedule() will try to run it. TODO: take args/envs from userspace. */
261 static int sys_proc_create(struct proc *p, char *path, size_t path_l,
266 struct file *program;
269 /* Copy in the path. Consider putting an upper bound on path_l. */
270 t_path = user_strdup_errno(p, path, path_l);
273 program = do_file_open(t_path, 0, 0);
274 user_memdup_free(p, t_path);
276 return -1; /* presumably, errno is already set */
277 /* TODO: need to split the proc creation, since you must load after setting
278 * args/env, since auxp gets set up there. */
279 //new_p = proc_create(program, 0, 0);
280 if (proc_alloc(&new_p, current))
282 /* Set the argument stuff needed by glibc */
283 if (memcpy_from_user_errno(p, new_p->procinfo->argp, pi->argp,
286 if (memcpy_from_user_errno(p, new_p->procinfo->argbuf, pi->argbuf,
289 if (load_elf(new_p, program))
291 kref_put(&program->f_kref);
292 /* Connect to stdin, stdout, stderr (part of proc_create()) */
293 assert(insert_file(&new_p->open_files, dev_stdin, 0) == 0);
294 assert(insert_file(&new_p->open_files, dev_stdout, 0) == 1);
295 assert(insert_file(&new_p->open_files, dev_stderr, 0) == 2);
298 proc_decref(new_p); /* give up the reference created in proc_create() */
303 kref_put(&program->f_kref);
307 /* Makes process PID runnable. Consider moving the functionality to process.c */
308 static error_t sys_proc_run(struct proc *p, unsigned pid)
310 struct proc *target = pid2proc(pid);
315 // note we can get interrupted here. it's not bad.
316 spin_lock(&p->proc_lock);
317 // make sure we have access and it's in the right state to be activated
318 if (!proc_controls(p, target)) {
321 } else if (target->state != PROC_CREATED) {
325 __proc_set_state(target, PROC_RUNNABLE_S);
326 schedule_proc(target);
328 spin_unlock(&p->proc_lock);
333 /* Destroy proc pid. If this is called by the dying process, it will never
334 * return. o/w it will return 0 on success, or an error. Errors include:
335 * - EBADPROC: if there is no such process with pid
336 * - EPERM: if caller does not control pid */
337 static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
340 struct proc *p_to_die = pid2proc(pid);
346 if (!proc_controls(p, p_to_die)) {
347 proc_decref(p_to_die);
352 p->exitcode = exitcode;
353 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
355 p_to_die->exitcode = exitcode; /* so its parent has some clue */
356 printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
358 proc_destroy(p_to_die);
359 /* we only get here if we weren't the one to die */
360 proc_decref(p_to_die);
364 static int sys_proc_yield(struct proc *p, bool being_nice)
366 /* proc_yield() often doesn't return - we need to set the syscall retval
367 * early. If it doesn't return, it expects to eat our reference (for now).
369 finish_current_sysc(0);
371 proc_yield(p, being_nice);
376 static ssize_t sys_fork(env_t* e)
378 // TODO: right now we only support fork for single-core processes
379 if (e->state != PROC_RUNNING_S) {
384 assert(!proc_alloc(&env, current));
387 env->heap_top = e->heap_top;
389 /* Can't really fork if we don't have a current_tf to fork */
394 env->env_tf = *current_tf;
396 /* We need to speculatively say the syscall worked before copying the memory
397 * out, since the 'forked' process's call never actually goes through the
398 * syscall return path, and will never think it is done. This violates a
399 * few things. Just be careful with fork. */
400 finish_current_sysc(0);
402 env->cache_colors_map = cache_colors_map_alloc();
403 for(int i=0; i < llc_cache->num_colors; i++)
404 if(GET_BITMASK_BIT(e->cache_colors_map,i))
405 cache_color_alloc(llc_cache, env->cache_colors_map);
407 duplicate_vmrs(e, env);
409 int copy_page(env_t* e, pte_t* pte, void* va, void* arg)
411 env_t* env = (env_t*)arg;
413 if(PAGE_PRESENT(*pte))
416 if(upage_alloc(env,&pp,0))
418 if(page_insert(env->env_pgdir,pp,va,*pte & PTE_PERM))
423 pagecopy(page2kva(pp),ppn2kva(PTE2PPN(*pte)));
426 assert(PAGE_PAGED_OUT(*pte));
427 /* TODO: (SWAP) will need to either make a copy or CoW/refcnt the
428 * backend store. For now, this PTE will be the same as the
430 panic("Swapping not supported!");
431 pte_t* newpte = pgdir_walk(env->env_pgdir,va,1);
439 /* In general, a forked process should be a fresh process, and we copy over
440 * whatever stuff is needed between procinfo/procdata. */
441 /* Copy over the procinfo argument stuff in case they don't exec */
442 memcpy(env->procinfo->argp, e->procinfo->argp, sizeof(e->procinfo->argp));
443 memcpy(env->procinfo->argbuf, e->procinfo->argbuf,
444 sizeof(e->procinfo->argbuf));
446 /* new guy needs to know about ldt (everything else in procdata is fresh */
447 env->procdata->ldt = e->procdata->ldt;
450 /* for now, just copy the contents of every present page in the entire
452 if (env_user_mem_walk(e, 0, UMAPTOP, ©_page, env)) {
453 proc_destroy(env); /* this is prob what you want, not decref by 2 */
457 clone_files(&e->open_files, &env->open_files);
459 __proc_set_state(env, PROC_RUNNABLE_S);
462 // don't decref the new process.
463 // that will happen when the parent waits for it.
464 // TODO: if the parent doesn't wait, we need to change the child's parent
465 // when the parent dies, or at least decref it
467 printd("[PID %d] fork PID %d\n",e->pid,env->pid);
471 /* Load the binary "path" into the current process, and start executing it.
472 * argv and envp are magically bundled in procinfo for now. Keep in sync with
473 * glibc's sysdeps/ros/execve.c. Once past a certain point, this function won't
474 * return. It assumes (and checks) that it is current. Don't give it an extra
475 * refcnt'd *p (syscall won't do that).
476 * Note: if someone batched syscalls with this call, they could clobber their
477 * old memory (and will likely PF and die). Don't do it... */
478 static int sys_exec(struct proc *p, char *path, size_t path_l,
483 struct file *program;
484 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
485 struct trapframe *old_cur_tf = pcpui->cur_tf;
487 /* We probably want it to never be allowed to exec if it ever was _M */
488 if (p->state != PROC_RUNNING_S) {
492 if (p != pcpui->cur_proc) {
496 /* Can't exec if we don't have a current_tf to restart (if we fail). This
497 * isn't 100% true, but I'm okay with it. */
502 /* Copy in the path. Consider putting an upper bound on path_l. */
503 t_path = user_strdup_errno(p, path, path_l);
506 /* Clear the current_tf. We won't be returning the 'normal' way. Even if
507 * we want to return with an error, we need to go back differently in case
508 * we succeed. This needs to be done before we could possibly block, but
509 * unfortunately happens before the point of no return. */
511 /* This could block: */
512 program = do_file_open(t_path, 0, 0);
513 user_memdup_free(p, t_path);
516 /* Set the argument stuff needed by glibc */
517 if (memcpy_from_user_errno(p, p->procinfo->argp, pi->argp,
520 if (memcpy_from_user_errno(p, p->procinfo->argbuf, pi->argbuf,
523 /* This is the point of no return for the process. */
525 /* clear this, so the new program knows to get an LDT */
526 p->procdata->ldt = 0;
529 close_all_files(&p->open_files, TRUE);
530 env_user_mem_free(p, 0, UMAPTOP);
531 if (load_elf(p, program)) {
532 kref_put(&program->f_kref);
533 /* Need an edible reference for proc_destroy in case it doesn't return.
534 * sys_exec was given current's ref (counted once just for current) */
538 /* We don't want to do anything else - we just need to not accidentally
539 * return to the user (hence the all_out) */
542 printd("[PID %d] exec %s\n", p->pid, file_name(program));
543 kref_put(&program->f_kref);
545 /* These error and out paths are so we can handle the async interface, both
546 * for when we want to error/return to the proc, as well as when we succeed
547 * and want to start the newly exec'd _S */
549 /* These two error paths are for when we want to restart the process with an
550 * error value (errno is already set). */
551 kref_put(&program->f_kref);
553 p->env_tf = *old_cur_tf;
554 finish_current_sysc(-1);
556 /* Here's how we'll restart the new (or old) process: */
557 spin_lock(&p->proc_lock);
558 __proc_set_state(p, PROC_RUNNABLE_S);
560 spin_unlock(&p->proc_lock);
562 /* we can't return, since we'd write retvals to the old location of the
563 * sycall struct (which has been freed and is in the old userspace) (or has
564 * already been written to).*/
570 static ssize_t sys_trywait(env_t* e, pid_t pid, int* status)
572 struct proc* p = pid2proc(pid);
574 // TODO: this syscall is racy, so we only support for single-core procs
575 if(e->state != PROC_RUNNING_S)
578 // TODO: need to use errno properly. sadly, ROS error codes conflict..
584 if(current->pid == p->ppid)
586 if(p->state == PROC_DYING)
588 memcpy_to_user(e,status,&p->exitcode,sizeof(int));
589 printd("[PID %d] waited for PID %d (code %d)\n",
590 e->pid,p->pid,p->exitcode);
599 else // not a child of the calling process
605 // if the wait succeeded, decref twice
616 /************** Memory Management Syscalls **************/
618 static void *sys_mmap(struct proc *p, uintptr_t addr, size_t len, int prot,
619 int flags, int fd, off_t offset)
621 return mmap(p, addr, len, prot, flags, fd, offset);
624 static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
626 return mprotect(p, (uintptr_t)addr, len, prot);
629 static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
631 return munmap(p, (uintptr_t)addr, len);
634 static ssize_t sys_shared_page_alloc(env_t* p1,
635 void**DANGEROUS _addr, pid_t p2_id,
636 int p1_flags, int p2_flags
639 printk("[kernel] shared page alloc is deprecated/unimplemented.\n");
643 static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
649 static int sys_resource_req(struct proc *p, int type, unsigned int amt_wanted,
650 unsigned int amt_wanted_min, int flags)
653 finish_current_sysc(0);
654 /* this might not return (if it's a _S -> _M transition) */
656 retval = resource_req(p, type, amt_wanted, amt_wanted_min, flags);
661 /* Untested. Will notify the target on the given vcore, if the caller controls
662 * the target. Will honor the target's wanted/vcoreid. u_ne can be NULL. */
663 static int sys_notify(struct proc *p, int target_pid, unsigned int ev_type,
664 struct event_msg *u_msg)
666 struct event_msg local_msg = {0};
667 struct proc *target = pid2proc(target_pid);
672 if (!proc_controls(p, target)) {
677 /* if the user provided an ev_msg, copy it in and use that */
679 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
685 send_kernel_event(target, &local_msg, 0);
690 /* Will notify the calling process on the given vcore, independently of WANTED
691 * or advertised vcoreid. If you change the parameters, change pop_ros_tf() */
692 static int sys_self_notify(struct proc *p, uint32_t vcoreid,
693 unsigned int ev_type, struct event_msg *u_msg)
695 struct event_msg local_msg = {0};
697 printd("[kernel] received self notify for vcoreid %d, type %d, msg %08p\n",
698 vcoreid, ev_type, u_msg);
699 /* if the user provided an ev_msg, copy it in and use that */
701 if (memcpy_from_user(p, &local_msg, u_msg, sizeof(struct event_msg))) {
706 /* this will post a message and IPI, regardless of wants/needs/debutantes.*/
707 post_vcore_event(p, &local_msg, vcoreid);
708 proc_notify(p, vcoreid);
712 /* This will set a local timer for usec, then shut down the core. There's a
713 * slight race between spinner and halt. For now, the core will wake up for
714 * other interrupts and service them, but will not process routine messages or
715 * do anything other than halt until the alarm goes off. We could just unset
716 * the alarm and return early. On hardware, there are a lot of interrupts that
717 * come in. If we ever use this, we can take a closer look. */
718 static int sys_halt_core(struct proc *p, unsigned int usec)
720 struct timer_chain *tchain = &per_cpu_info[core_id()].tchain;
721 struct alarm_waiter a_waiter;
723 void unblock(struct alarm_waiter *waiter)
727 init_awaiter(&a_waiter, unblock);
728 set_awaiter_rel(&a_waiter, MAX(usec, 100));
729 set_alarm(tchain, &a_waiter);
731 /* Could wake up due to another interrupt, but we want to sleep still. */
733 cpu_halt(); /* slight race between spinner and halt */
736 printd("Returning from halting\n");
740 /************** Platform Specific Syscalls **************/
742 //Read a buffer over the serial port
743 static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
745 printk("[kernel] serial reading is deprecated.\n");
749 #ifdef __CONFIG_SERIAL_IO__
750 char *COUNT(len) buf = user_mem_assert(e, _buf, len, 1, PTE_USER_RO);
751 size_t bytes_read = 0;
753 while((c = serial_read_byte()) != -1) {
754 buf[bytes_read++] = (uint8_t)c;
755 if(bytes_read == len) break;
757 return (ssize_t)bytes_read;
763 //Write a buffer over the serial port
764 static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
766 printk("[kernel] serial writing is deprecated.\n");
769 #ifdef __CONFIG_SERIAL_IO__
770 char *COUNT(len) _buf = user_mem_assert(e, buf, len, 1, PTE_USER_RO);
771 for(int i =0; i<len; i++)
772 serial_send_byte(buf[i]);
779 #ifdef __CONFIG_NETWORKING__
780 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
781 static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf)
788 spin_lock(&packet_buffers_lock);
790 if (num_packet_buffers == 0) {
791 spin_unlock(&packet_buffers_lock);
795 ptr = packet_buffers[packet_buffers_head];
796 len = packet_buffers_sizes[packet_buffers_head];
798 num_packet_buffers--;
799 packet_buffers_head = (packet_buffers_head + 1) % MAX_PACKET_BUFFERS;
801 spin_unlock(&packet_buffers_lock);
803 char* _buf = user_mem_assert(e, buf, len, 1, PTE_U);
805 memcpy(_buf, ptr, len);
815 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
816 static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
823 // HACK TO BYPASS HACK
824 int just_sent = send_frame(buf, len);
827 printk("Packet send fail\n");
833 // END OF RECURSIVE HACK
835 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
838 int cur_packet_len = 0;
839 while (total_sent != len) {
840 cur_packet_len = ((len - total_sent) > MTU) ? MTU : (len - total_sent);
841 char dest_mac[6] = APPSERVER_MAC_ADDRESS;
842 char* wrap_buffer = eth_wrap(_buf + total_sent, cur_packet_len, device_mac, dest_mac, APPSERVER_PORT);
843 just_sent = send_frame(wrap_buffer, cur_packet_len + sizeof(struct ETH_Header));
846 return 0; // This should be an error code of its own
851 total_sent += cur_packet_len;
861 static ssize_t sys_eth_get_mac_addr(env_t* e, char *DANGEROUS buf)
864 for (int i = 0; i < 6; i++)
865 buf[i] = device_mac[i];
872 static int sys_eth_recv_check(env_t* e)
874 if (num_packet_buffers != 0)
882 static intreg_t sys_read(struct proc *p, int fd, void *buf, int len)
885 struct file *file = get_file_from_fd(&p->open_files, fd);
890 if (!file->f_op->read) {
891 kref_put(&file->f_kref);
895 /* TODO: (UMEM) currently, read() handles user memcpy issues, but we
896 * probably should user_mem_check and pin the region here, so read doesn't
898 ret = file->f_op->read(file, buf, len, &file->f_pos);
899 kref_put(&file->f_kref);
903 static intreg_t sys_write(struct proc *p, int fd, const void *buf, int len)
906 struct file *file = get_file_from_fd(&p->open_files, fd);
911 if (!file->f_op->write) {
912 kref_put(&file->f_kref);
917 ret = file->f_op->write(file, buf, len, &file->f_pos);
918 kref_put(&file->f_kref);
922 /* Checks args/reads in the path, opens the file, and inserts it into the
923 * process's open file list.
925 * TODO: take the path length */
926 static intreg_t sys_open(struct proc *p, const char *path, size_t path_l,
932 printd("File %s Open attempt\n", path);
933 char *t_path = user_strdup_errno(p, path, path_l);
936 mode &= ~p->fs_env.umask;
937 file = do_file_open(t_path, oflag, mode);
938 user_memdup_free(p, t_path);
941 fd = insert_file(&p->open_files, file, 0); /* stores the ref to file */
942 kref_put(&file->f_kref);
944 warn("File insertion failed");
947 printd("File %s Open, res=%d\n", path, fd);
951 static intreg_t sys_close(struct proc *p, int fd)
953 struct file *file = put_file_from_fd(&p->open_files, fd);
961 /* kept around til we remove the last ufe */
962 #define ufe(which,a0,a1,a2,a3) \
963 frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
964 (int)(a0),(int)(a1),(int)(a2),(int)(a3))
966 static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
969 struct file *file = get_file_from_fd(&p->open_files, fd);
974 kbuf = kmalloc(sizeof(struct kstat), 0);
976 kref_put(&file->f_kref);
980 stat_inode(file->f_dentry->d_inode, kbuf);
981 kref_put(&file->f_kref);
982 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
983 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
992 /* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
993 * treat a symlink for the final item, which (probably) will be controlled by
994 * the lookup flags */
995 static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
996 struct kstat *u_stat, int flags)
999 struct dentry *path_d;
1000 char *t_path = user_strdup_errno(p, path, path_l);
1003 path_d = lookup_dentry(t_path, flags);
1004 user_memdup_free(p, t_path);
1007 kbuf = kmalloc(sizeof(struct kstat), 0);
1010 kref_put(&path_d->d_kref);
1013 stat_inode(path_d->d_inode, kbuf);
1014 kref_put(&path_d->d_kref);
1015 /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
1016 if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
1025 /* Follow a final symlink */
1026 static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
1027 struct kstat *u_stat)
1029 return stat_helper(p, path, path_l, u_stat, LOOKUP_FOLLOW);
1032 /* Don't follow a final symlink */
1033 static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
1034 struct kstat *u_stat)
1036 return stat_helper(p, path, path_l, u_stat, 0);
1039 intreg_t sys_fcntl(struct proc *p, int fd, int cmd, int arg)
1042 struct file *file = get_file_from_fd(&p->open_files, fd);
1049 retval = insert_file(&p->open_files, file, arg);
1056 retval = p->open_files.fd[fd].fd_flags;
1059 if (arg == FD_CLOEXEC)
1060 file->f_flags |= O_CLOEXEC;
1063 retval = file->f_flags;
1066 /* only allowed to set certain flags. */
1067 arg &= O_FCNTL_FLAGS;
1068 file->f_flags = (file->f_flags & ~O_FCNTL_FLAGS) | arg;
1071 warn("Unsupported fcntl cmd %d\n", cmd);
1073 kref_put(&file->f_kref);
1077 static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
1081 char *t_path = user_strdup_errno(p, path, path_l);
1084 retval = do_access(t_path, mode);
1085 user_memdup_free(p, t_path);
1086 printd("Access for path: %s retval: %d\n", path, retval);
1094 intreg_t sys_umask(struct proc *p, int mask)
1096 int old_mask = p->fs_env.umask;
1097 p->fs_env.umask = mask & S_PMASK;
1101 intreg_t sys_chmod(struct proc *p, const char *path, size_t path_l, int mode)
1104 char *t_path = user_strdup_errno(p, path, path_l);
1107 retval = do_chmod(t_path, mode);
1108 user_memdup_free(p, t_path);
1116 static intreg_t sys_lseek(struct proc *p, int fd, off_t offset, int whence)
1119 struct file *file = get_file_from_fd(&p->open_files, fd);
1124 ret = file->f_op->llseek(file, offset, whence);
1125 kref_put(&file->f_kref);
1129 intreg_t sys_link(struct proc *p, char *old_path, size_t old_l,
1130 char *new_path, size_t new_l)
1133 char *t_oldpath = user_strdup_errno(p, old_path, old_l);
1134 if (t_oldpath == NULL)
1136 char *t_newpath = user_strdup_errno(p, new_path, new_l);
1137 if (t_newpath == NULL) {
1138 user_memdup_free(p, t_oldpath);
1141 ret = do_link(t_oldpath, t_newpath);
1142 user_memdup_free(p, t_oldpath);
1143 user_memdup_free(p, t_newpath);
1147 intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
1150 char *t_path = user_strdup_errno(p, path, path_l);
1153 retval = do_unlink(t_path);
1154 user_memdup_free(p, t_path);
1158 intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
1159 char *new_path, size_t new_l)
1162 char *t_oldpath = user_strdup_errno(p, old_path, old_l);
1163 if (t_oldpath == NULL)
1165 char *t_newpath = user_strdup_errno(p, new_path, new_l);
1166 if (t_newpath == NULL) {
1167 user_memdup_free(p, t_oldpath);
1170 ret = do_symlink(new_path, old_path, S_IRWXU | S_IRWXG | S_IRWXO);
1171 user_memdup_free(p, t_oldpath);
1172 user_memdup_free(p, t_newpath);
1176 intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
1177 char *u_buf, size_t buf_l)
1181 struct dentry *path_d;
1182 char *t_path = user_strdup_errno(p, path, path_l);
1185 path_d = lookup_dentry(t_path, 0);
1186 user_memdup_free(p, t_path);
1189 symname = path_d->d_inode->i_op->readlink(path_d);
1190 copy_amt = strnlen(symname, buf_l - 1) + 1;
1191 if (memcpy_to_user_errno(p, u_buf, symname, copy_amt)) {
1192 kref_put(&path_d->d_kref);
1196 kref_put(&path_d->d_kref);
1197 printd("READLINK returning %s\n", u_buf);
1201 intreg_t sys_chdir(struct proc *p, const char *path, size_t path_l)
1204 char *t_path = user_strdup_errno(p, path, path_l);
1207 retval = do_chdir(&p->fs_env, t_path);
1208 user_memdup_free(p, t_path);
1216 /* Note cwd_l is not a strlen, it's an absolute size */
1217 intreg_t sys_getcwd(struct proc *p, char *u_cwd, size_t cwd_l)
1221 char *k_cwd = do_getcwd(&p->fs_env, &kfree_this, cwd_l);
1223 return -1; /* errno set by do_getcwd */
1224 if (memcpy_to_user_errno(p, u_cwd, k_cwd, strnlen(k_cwd, cwd_l - 1) + 1))
1230 intreg_t sys_mkdir(struct proc *p, const char *path, size_t path_l, int mode)
1233 char *t_path = user_strdup_errno(p, path, path_l);
1236 mode &= ~p->fs_env.umask;
1237 retval = do_mkdir(t_path, mode);
1238 user_memdup_free(p, t_path);
1242 intreg_t sys_rmdir(struct proc *p, const char *path, size_t path_l)
1245 char *t_path = user_strdup_errno(p, path, path_l);
1248 retval = do_rmdir(t_path);
1249 user_memdup_free(p, t_path);
1253 intreg_t sys_gettimeofday(struct proc *p, int *buf)
1255 static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
1258 spin_lock(>od_lock);
1261 #if (defined __CONFIG_APPSERVER__)
1262 t0 = ufe(time,0,0,0,0);
1264 // Nanwan's birthday, bitches!!
1267 spin_unlock(>od_lock);
1269 long long dt = read_tsc();
1270 /* TODO: This probably wants its own function, using a struct timeval */
1271 int kbuf[2] = {t0+dt/system_timing.tsc_freq,
1272 (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
1274 return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
1277 #define SIZEOF_STRUCT_TERMIOS 60
1278 intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
1280 int* kbuf = kmalloc(SIZEOF_STRUCT_TERMIOS,0);
1281 int ret = ufe(tcgetattr,fd,PADDR(kbuf),0,0);
1282 if(ret != -1 && memcpy_to_user_errno(p,termios_p,kbuf,SIZEOF_STRUCT_TERMIOS))
1288 intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
1289 const void *termios_p)
1291 void* kbuf = user_memdup_errno(p,termios_p,SIZEOF_STRUCT_TERMIOS);
1294 int ret = ufe(tcsetattr,fd,optional_actions,PADDR(kbuf),0);
1295 user_memdup_free(p,kbuf);
1299 /* TODO: we don't have any notion of UIDs or GIDs yet, but don't let that stop a
1300 * process from thinking it can do these. The other alternative is to have
1301 * glibc return 0 right away, though someone might want to do something with
1302 * these calls. Someday. */
1303 intreg_t sys_setuid(struct proc *p, uid_t uid)
1308 intreg_t sys_setgid(struct proc *p, gid_t gid)
1313 /************** Syscall Invokation **************/
1315 const static struct sys_table_entry syscall_table[] = {
1316 [SYS_null] = {(syscall_t)sys_null, "null"},
1317 [SYS_block] = {(syscall_t)sys_block, "block"},
1318 [SYS_cache_buster] = {(syscall_t)sys_cache_buster, "buster"},
1319 [SYS_cache_invalidate] = {(syscall_t)sys_cache_invalidate, "wbinv"},
1320 [SYS_reboot] = {(syscall_t)reboot, "reboot!"},
1321 [SYS_cputs] = {(syscall_t)sys_cputs, "cputs"},
1322 [SYS_cgetc] = {(syscall_t)sys_cgetc, "cgetc"},
1323 [SYS_getcpuid] = {(syscall_t)sys_getcpuid, "getcpuid"},
1324 [SYS_getvcoreid] = {(syscall_t)sys_getvcoreid, "getvcoreid"},
1325 [SYS_getpid] = {(syscall_t)sys_getpid, "getpid"},
1326 [SYS_proc_create] = {(syscall_t)sys_proc_create, "proc_create"},
1327 [SYS_proc_run] = {(syscall_t)sys_proc_run, "proc_run"},
1328 [SYS_proc_destroy] = {(syscall_t)sys_proc_destroy, "proc_destroy"},
1329 [SYS_yield] = {(syscall_t)sys_proc_yield, "proc_yield"},
1330 [SYS_fork] = {(syscall_t)sys_fork, "fork"},
1331 [SYS_exec] = {(syscall_t)sys_exec, "exec"},
1332 [SYS_trywait] = {(syscall_t)sys_trywait, "trywait"},
1333 [SYS_mmap] = {(syscall_t)sys_mmap, "mmap"},
1334 [SYS_munmap] = {(syscall_t)sys_munmap, "munmap"},
1335 [SYS_mprotect] = {(syscall_t)sys_mprotect, "mprotect"},
1336 [SYS_shared_page_alloc] = {(syscall_t)sys_shared_page_alloc, "pa"},
1337 [SYS_shared_page_free] = {(syscall_t)sys_shared_page_free, "pf"},
1338 [SYS_resource_req] = {(syscall_t)sys_resource_req, "resource_req"},
1339 [SYS_notify] = {(syscall_t)sys_notify, "notify"},
1340 [SYS_self_notify] = {(syscall_t)sys_self_notify, "self_notify"},
1341 [SYS_halt_core] = {(syscall_t)sys_halt_core, "halt_core"},
1342 #ifdef __CONFIG_SERIAL_IO__
1343 [SYS_serial_read] = {(syscall_t)sys_serial_read, "ser_read"},
1344 [SYS_serial_write] = {(syscall_t)sys_serial_write, "ser_write"},
1346 #ifdef __CONFIG_NETWORKING__
1347 [SYS_eth_read] = {(syscall_t)sys_eth_read, "eth_read"},
1348 [SYS_eth_write] = {(syscall_t)sys_eth_write, "eth_write"},
1349 [SYS_eth_get_mac_addr] = {(syscall_t)sys_eth_get_mac_addr, "get_mac"},
1350 [SYS_eth_recv_check] = {(syscall_t)sys_eth_recv_check, "recv_check"},
1352 #ifdef __CONFIG_ARSC_SERVER__
1353 [SYS_init_arsc] = {(syscall_t)sys_init_arsc, "init_arsc"},
1355 [SYS_read] = {(syscall_t)sys_read, "read"},
1356 [SYS_write] = {(syscall_t)sys_write, "write"},
1357 [SYS_open] = {(syscall_t)sys_open, "open"},
1358 [SYS_close] = {(syscall_t)sys_close, "close"},
1359 [SYS_fstat] = {(syscall_t)sys_fstat, "fstat"},
1360 [SYS_stat] = {(syscall_t)sys_stat, "stat"},
1361 [SYS_lstat] = {(syscall_t)sys_lstat, "lstat"},
1362 [SYS_fcntl] = {(syscall_t)sys_fcntl, "fcntl"},
1363 [SYS_access] = {(syscall_t)sys_access, "access"},
1364 [SYS_umask] = {(syscall_t)sys_umask, "umask"},
1365 [SYS_chmod] = {(syscall_t)sys_chmod, "chmod"},
1366 [SYS_lseek] = {(syscall_t)sys_lseek, "lseek"},
1367 [SYS_link] = {(syscall_t)sys_link, "link"},
1368 [SYS_unlink] = {(syscall_t)sys_unlink, "unlink"},
1369 [SYS_symlink] = {(syscall_t)sys_symlink, "symlink"},
1370 [SYS_readlink] = {(syscall_t)sys_readlink, "readlink"},
1371 [SYS_chdir] = {(syscall_t)sys_chdir, "chdir"},
1372 [SYS_getcwd] = {(syscall_t)sys_getcwd, "getcwd"},
1373 [SYS_mkdir] = {(syscall_t)sys_mkdir, "mkdri"},
1374 [SYS_rmdir] = {(syscall_t)sys_rmdir, "rmdir"},
1375 [SYS_gettimeofday] = {(syscall_t)sys_gettimeofday, "gettime"},
1376 [SYS_tcgetattr] = {(syscall_t)sys_tcgetattr, "tcgetattr"},
1377 [SYS_tcsetattr] = {(syscall_t)sys_tcsetattr, "tcsetattr"},
1378 [SYS_setuid] = {(syscall_t)sys_setuid, "setuid"},
1379 [SYS_setgid] = {(syscall_t)sys_setgid, "setgid"}
1382 /* Executes the given syscall.
1384 * Note tf is passed in, which points to the tf of the context on the kernel
1385 * stack. If any syscall needs to block, it needs to save this info, as well as
1388 * This syscall function is used by both local syscall and arsc, and should
1389 * remain oblivious of the caller. */
1390 intreg_t syscall(struct proc *p, uintreg_t sc_num, uintreg_t a0, uintreg_t a1,
1391 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
1393 const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
1395 uint32_t coreid, vcoreid;
1396 if (systrace_flags & SYSTRACE_ON) {
1397 if ((systrace_flags & SYSTRACE_ALLPROC) || (proc_is_traced(p))) {
1399 vcoreid = proc_get_vcoreid(p, coreid);
1400 if (systrace_flags & SYSTRACE_LOUD) {
1401 printk("[%16llu] Syscall %3d (%12s):(%08p, %08p, %08p, %08p, "
1402 "%08p, %08p) proc: %d core: %d vcore: %d\n", read_tsc(),
1403 sc_num, syscall_table[sc_num].name, a0, a1, a2, a3,
1404 a4, a5, p->pid, coreid, vcoreid);
1406 struct systrace_record *trace;
1407 uintptr_t idx, new_idx;
1409 idx = systrace_bufidx;
1410 new_idx = (idx + 1) % systrace_bufsize;
1411 } while (!atomic_cas_u32(&systrace_bufidx, idx, new_idx));
1412 trace = &systrace_buffer[idx];
1413 trace->timestamp = read_tsc();
1414 trace->syscallno = sc_num;
1421 trace->pid = p->pid;
1422 trace->coreid = coreid;
1423 trace->vcoreid = vcoreid;
1427 if (sc_num > max_syscall || syscall_table[sc_num].call == NULL)
1428 panic("Invalid syscall number %d for proc %x!", sc_num, p);
1430 return syscall_table[sc_num].call(p, a0, a1, a2, a3, a4, a5);
1433 /* Execute the syscall on the local core */
1434 void run_local_syscall(struct syscall *sysc)
1436 struct per_cpu_info *pcpui = &per_cpu_info[core_id()];
1438 /* TODO: (UMEM) assert / pin the memory for the sysc */
1439 user_mem_assert(pcpui->cur_proc, sysc, sizeof(struct syscall),
1440 sizeof(uintptr_t), PTE_USER_RW);
1441 pcpui->cur_sysc = sysc; /* let the core know which sysc it is */
1442 sysc->retval = syscall(pcpui->cur_proc, sysc->num, sysc->arg0, sysc->arg1,
1443 sysc->arg2, sysc->arg3, sysc->arg4, sysc->arg5);
1444 /* Need to re-load pcpui, in case we migrated */
1445 pcpui = &per_cpu_info[core_id()];
1446 finish_sysc(sysc, pcpui->cur_proc);
1447 /* Can unpin (UMEM) at this point */
1448 pcpui->cur_sysc = 0; /* no longer working on sysc */
1451 /* A process can trap and call this function, which will set up the core to
1452 * handle all the syscalls. a.k.a. "sys_debutante(needs, wants)". If there is
1453 * at least one, it will run it directly. */
1454 void prep_syscalls(struct proc *p, struct syscall *sysc, unsigned int nr_syscs)
1457 /* Careful with pcpui here, we could have migrated */
1460 /* For all after the first call, send ourselves a KMSG (TODO). */
1462 warn("Only one supported (Debutante calls: %d)\n", nr_syscs);
1463 /* Call the first one directly. (we already checked to make sure there is
1465 run_local_syscall(sysc);
1468 /* Call this when something happens on the syscall where userspace might want to
1469 * get signaled. Passing p, since the caller should know who the syscall
1470 * belongs to (probably is current).
1472 * You need to have SC_K_LOCK set when you call this. */
1473 void __signal_syscall(struct syscall *sysc, struct proc *p)
1475 struct event_queue *ev_q;
1476 struct event_msg local_msg;
1477 /* User sets the ev_q then atomically sets the flag (races with SC_DONE) */
1478 if (atomic_read(&sysc->flags) & SC_UEVENT) {
1482 memset(&local_msg, 0, sizeof(struct event_msg));
1483 local_msg.ev_type = EV_SYSCALL;
1484 local_msg.ev_arg3 = sysc;
1485 send_event(p, ev_q, &local_msg, 0);
1490 /* Syscall tracing */
1491 static void __init_systrace(void)
1493 systrace_buffer = kmalloc(MAX_SYSTRACES*sizeof(struct systrace_record), 0);
1494 if (!systrace_buffer)
1495 panic("Unable to alloc a trace buffer\n");
1496 systrace_bufidx = 0;
1497 systrace_bufsize = MAX_SYSTRACES;
1498 /* Note we never free the buffer - it's around forever. Feel free to change
1499 * this if you want to change the size or something dynamically. */
1502 /* If you call this while it is running, it will change the mode */
1503 void systrace_start(bool silent)
1505 static bool init = FALSE;
1506 spin_lock_irqsave(&systrace_lock);
1511 systrace_flags = silent ? SYSTRACE_ON : SYSTRACE_ON | SYSTRACE_LOUD;
1512 spin_unlock_irqsave(&systrace_lock);
1515 int systrace_reg(bool all, struct proc *p)
1518 spin_lock_irqsave(&systrace_lock);
1520 printk("Tracing syscalls for all processes\n");
1521 systrace_flags |= SYSTRACE_ALLPROC;
1524 for (int i = 0; i < MAX_NUM_TRACED; i++) {
1525 if (!systrace_procs[i]) {
1526 printk("Tracing syscalls for process %d\n", p->pid);
1527 systrace_procs[i] = p;
1533 spin_unlock_irqsave(&systrace_lock);
1537 void systrace_stop(void)
1539 spin_lock_irqsave(&systrace_lock);
1541 for (int i = 0; i < MAX_NUM_TRACED; i++)
1542 systrace_procs[i] = 0;
1543 spin_unlock_irqsave(&systrace_lock);
1546 /* If you registered a process specifically, then you need to dereg it
1547 * specifically. Or just fully stop, which will do it for all. */
1548 int systrace_dereg(bool all, struct proc *p)
1550 spin_lock_irqsave(&systrace_lock);
1552 printk("No longer tracing syscalls for all processes.\n");
1553 systrace_flags &= ~SYSTRACE_ALLPROC;
1555 for (int i = 0; i < MAX_NUM_TRACED; i++) {
1556 if (systrace_procs[i] == p) {
1557 systrace_procs[i] = 0;
1558 printk("No longer tracing syscalls for process %d\n", p->pid);
1562 spin_unlock_irqsave(&systrace_lock);
1566 /* Regardless of locking, someone could be writing into the buffer */
1567 void systrace_print(bool all, struct proc *p)
1569 spin_lock_irqsave(&systrace_lock);
1570 /* if you want to be clever, you could make this start from the earliest
1571 * timestamp and loop around. Careful of concurrent writes. */
1572 for (int i = 0; i < systrace_bufsize; i++)
1573 if (systrace_buffer[i].timestamp)
1574 printk("[%16llu] Syscall %3d (%12s):(%08p, %08p, %08p, %08p, %08p,"
1575 "%08p) proc: %d core: %d vcore: %d\n",
1576 systrace_buffer[i].timestamp,
1577 systrace_buffer[i].syscallno,
1578 syscall_table[systrace_buffer[i].syscallno].name,
1579 systrace_buffer[i].arg0,
1580 systrace_buffer[i].arg1,
1581 systrace_buffer[i].arg2,
1582 systrace_buffer[i].arg3,
1583 systrace_buffer[i].arg4,
1584 systrace_buffer[i].arg5,
1585 systrace_buffer[i].pid,
1586 systrace_buffer[i].coreid,
1587 systrace_buffer[i].vcoreid);
1588 spin_unlock_irqsave(&systrace_lock);
1591 void systrace_clear_buffer(void)
1593 spin_lock_irqsave(&systrace_lock);
1594 memset(systrace_buffer, 0, sizeof(struct systrace_record) * MAX_SYSTRACES);
1595 spin_unlock_irqsave(&systrace_lock);