readdir() and readdir_r() (XCC)
[akaros.git] / kern / src / syscall.c
index 7019506..0eadc4f 100644 (file)
 #endif
 
 #include <ros/common.h>
+#include <ros/notification.h>
 #include <arch/types.h>
 #include <arch/arch.h>
 #include <arch/mmu.h>
 #include <arch/console.h>
 #include <ros/timer.h>
-#include <ros/error.h>
+#include <error.h>
 
+#include <elf.h>
 #include <string.h>
 #include <assert.h>
 #include <process.h>
 #include <schedule.h>
 #include <pmap.h>
+#include <umem.h>
 #include <mm.h>
 #include <trap.h>
 #include <syscall.h>
 #include <kmalloc.h>
 #include <stdio.h>
 #include <resource.h>
+#include <frontend.h>
+#include <colored_caches.h>
+#include <hashtable.h>
+#include <arch/bitmask.h>
 #include <kfs.h> // eventually replace this with vfs.h
+#include <smp.h>
+#include <arsc_server.h>
 
-#ifdef __sparc_v8__
-#include <arch/frontend.h>
-#endif 
 
-#ifdef __NETWORK__
+#ifdef __CONFIG_NETWORKING__
 #include <arch/nic_common.h>
-extern char *CT(PACKET_HEADER_SIZE + len) (*packet_wrap)(const char *CT(len) data, size_t len);
 extern int (*send_frame)(const char *CT(len) data, size_t len);
+extern unsigned char device_mac[6];
 #endif
 
-//Do absolutely nothing.  Used for profiling.
-static void sys_null(void)
-{
-       return;
-}
+/* Tracing Globals */
+int systrace_flags = 0;
+struct systrace_record *systrace_buffer = 0;
+unsigned int systrace_bufidx = 0;
+size_t systrace_bufsize = 0;
+struct proc *systrace_procs[MAX_NUM_TRACED] = {0};
+spinlock_t systrace_lock = SPINLOCK_INITIALIZER;
 
-//Write a buffer over the serial port
-static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
+/* Not enforcing the packing of systrace_procs yet, but don't rely on that */
+static bool proc_is_traced(struct proc *p)
 {
-       if (len == 0)
-               return 0;
-       #ifdef SERIAL_IO
-               char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_USER_RO);
-               for(int i =0; i<len; i++)
-                       serial_send_byte(buf[i]);
-               return (ssize_t)len;
-       #else
-               return -EINVAL;
-       #endif
-}
-
-//Read a buffer over the serial port
-static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
-{
-       if (len == 0)
-               return 0;
-
-       #ifdef SERIAL_IO
-           char *COUNT(len) buf = user_mem_assert(e, _buf, len, PTE_USER_RO);
-               size_t bytes_read = 0;
-               int c;
-               while((c = serial_read_byte()) != -1) {
-                       buf[bytes_read++] = (uint8_t)c;
-                       if(bytes_read == len) break;
-               }
-               return (ssize_t)bytes_read;
-       #else
-               return -EINVAL;
-       #endif
+       for (int i = 0; i < MAX_NUM_TRACED; i++)
+               if (systrace_procs[i] == p)
+                       return true;
+       return false;
 }
 
-//
-/* START OF REMOTE SYSTEMCALL SUPPORT SYSCALLS. THESE WILL GO AWAY AS THINGS MATURE */
-//
-
-static ssize_t sys_run_binary(env_t* e, void *DANGEROUS binary_buf,
-                              void*DANGEROUS arg, size_t len) {
-       uint8_t *CT(len) checked_binary_buf;
-       checked_binary_buf = user_mem_assert(e, binary_buf, len, PTE_USER_RO);
-       
-       uint8_t* new_binary = kmalloc(len, 0);
-       if(new_binary == NULL)
-               return -ENOMEM;
-       memcpy(new_binary, checked_binary_buf, len);
-
-       env_t* env = env_create(new_binary, len);
-       kfree(new_binary);
-       proc_set_state(env, PROC_RUNNABLE_S);
-       schedule_proc(env);
-       proc_yield(e); // changed from sys_yield.  did not test this at all.
-       return 0;
-}
+/************** Utility Syscalls **************/
 
-#ifdef __NETWORK__
-// This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
-static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
+static int sys_null(void)
 {
-       extern int eth_up;
-
-       if (eth_up) {
-
-               if (len == 0)
-                       return 0;
-
-               char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
-               int total_sent = 0;
-               int just_sent = 0;
-               int cur_packet_len = 0;
-               while (total_sent != len) {
-                       cur_packet_len = ((len - total_sent) > MAX_PACKET_DATA) ? MAX_PACKET_DATA : (len - total_sent);
-                       char* wrap_buffer = packet_wrap(_buf + total_sent, cur_packet_len);
-                       just_sent = send_frame(wrap_buffer, cur_packet_len + PACKET_HEADER_SIZE);
-
-                       if (just_sent < 0)
-                               return 0; // This should be an error code of its own
-
-                       if (wrap_buffer)
-                               kfree(wrap_buffer);
-
-                       total_sent += cur_packet_len;
-               }
-
-               return (ssize_t)len;
-
-       }
-       else
-               return -EINVAL;
-}
-
-// This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
-static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf, size_t len)
-{
-       extern int eth_up;
-
-       if (eth_up) {
-               extern int packet_waiting;
-               extern int packet_buffer_size;
-               extern char*CT(packet_buffer_size) packet_buffer;
-               extern char*CT(MAX_FRAME_SIZE) packet_buffer_orig;
-               extern int packet_buffer_pos;
-
-               if (len == 0)
-                       return 0;
-
-               char *CT(len) _buf = user_mem_assert(e, buf,len, PTE_U);
-
-               if (packet_waiting == 0)
-                       return 0;
-
-               int read_len = ((packet_buffer_pos + len) > packet_buffer_size) ? packet_buffer_size - packet_buffer_pos : len;
-
-               memcpy(_buf, packet_buffer + packet_buffer_pos, read_len);
-
-               packet_buffer_pos = packet_buffer_pos + read_len;
-
-               if (packet_buffer_pos == packet_buffer_size) {
-                       kfree(packet_buffer_orig);
-                       packet_waiting = 0;
-               }
-
-               return read_len;
-       }
-       else
-               return -EINVAL;
-}
-#endif // Network
-
-//
-/* END OF REMOTE SYSTEMCALL SUPPORT SYSCALLS. */
-//
-
-static ssize_t sys_shared_page_alloc(env_t* p1,
-                                     void**DANGEROUS _addr, envid_t p2_id,
-                                     int p1_flags, int p2_flags
-                                    )
-{
-       //if (!VALID_USER_PERMS(p1_flags)) return -EPERM;
-       //if (!VALID_USER_PERMS(p2_flags)) return -EPERM;
-
-       void * COUNT(1) * COUNT(1) addr = user_mem_assert(p1, _addr, sizeof(void *),
-                                                      PTE_USER_RW);
-       page_t* page;
-       env_t* p2 = &(envs[ENVX(p2_id)]);
-       error_t e = page_alloc(&page);
-
-       if(e < 0) return e;
-
-       void* p2_addr = page_insert_in_range(p2->env_pgdir, page,
-                                            (void*SNT)UTEXT, (void*SNT)UTOP, p2_flags);
-       if(p2_addr == NULL)
-               return -EFAIL;
-
-       void* p1_addr = page_insert_in_range(p1->env_pgdir, page,
-                                           (void*SNT)UTEXT, (void*SNT)UTOP, p1_flags);
-       if(p1_addr == NULL) {
-               page_remove(p2->env_pgdir, p2_addr);
-               return -EFAIL;
-       }
-       *addr = p1_addr;
-       return ESUCCESS;
-}
-
-static void sys_shared_page_free(env_t* p1, void*DANGEROUS addr, envid_t p2)
-{
-}
-
-// Invalidate the cache of this core.  Only useful if you want a cold cache for
-// performance testing reasons.
-static void sys_cache_invalidate(void)
-{
-       #ifdef __i386__
-               wbinvd();
-       #endif
-       return;
+       return 0;
 }
 
 // Writes 'val' to 'num_writes' entries of the well-known array in the kernel
 // address space.  It's just #defined to be some random 4MB chunk (which ought
 // to be boot_alloced or something).  Meant to grab exclusive access to cache
 // lines, to simulate doing something useful.
-static void sys_cache_buster(env_t* e, uint32_t num_writes, uint32_t num_pages,
-                             uint32_t flags)
+static int sys_cache_buster(struct proc *p, uint32_t num_writes,
+                             uint32_t num_pages, uint32_t flags)
 { TRUSTEDBLOCK /* zra: this is not really part of the kernel */
        #define BUSTER_ADDR             0xd0000000  // around 512 MB deep
        #define MAX_WRITES              1048576*8
        #define MAX_PAGES               32
        #define INSERT_ADDR     (UINFO + 2*PGSIZE) // should be free for these tests
        uint32_t* buster = (uint32_t*)BUSTER_ADDR;
-       static uint32_t buster_lock = 0;
+       static spinlock_t buster_lock = SPINLOCK_INITIALIZER;
        uint64_t ticks = -1;
        page_t* a_page[MAX_PAGES];
 
@@ -263,8 +107,8 @@ static void sys_cache_buster(env_t* e, uint32_t num_writes, uint32_t num_pages,
        if (num_pages) {
                spin_lock(&buster_lock);
                for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
-                       page_alloc(&a_page[i]);
-                       page_insert(e->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
+                       upage_alloc(p, &a_page[i],1);
+                       page_insert(p->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
                                    PTE_USER_RW);
                }
                spin_unlock(&buster_lock);
@@ -280,7 +124,7 @@ static void sys_cache_buster(env_t* e, uint32_t num_writes, uint32_t num_pages,
        if (num_pages) {
                spin_lock(&buster_lock);
                for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
-                       page_remove(e->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
+                       page_remove(p->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
                        page_decref(a_page[i]);
                }
                spin_unlock(&buster_lock);
@@ -291,27 +135,35 @@ static void sys_cache_buster(env_t* e, uint32_t num_writes, uint32_t num_pages,
                ticks = stop_timing(ticks);
                printk("%llu,", ticks);
        }
-       return;
+       return 0;
 }
 
-// Print a string to the system console.
-// The string is exactly 'len' characters long.
-// Destroys the environment on memory errors.
-static ssize_t sys_cputs(env_t* e, const char *DANGEROUS s, size_t len)
+static int sys_cache_invalidate(void)
 {
-       // Check that the user has permission to read memory [s, s+len).
-       // Destroy the environment if not.
-       pte_t* p = pgdir_walk(e->env_pgdir,s,0);
-       char *COUNT(len) _s = user_mem_assert(e, s, len, PTE_USER_RO);
+       #ifdef __i386__
+               wbinvd();
+       #endif
+       return 0;
+}
 
-       // Print the string supplied by the user.
-       printk("%.*s", len, _s);
-       return (ssize_t)len;
+/* sys_reboot(): called directly from dispatch table. */
+
+/* Print a string to the system console. */
+static ssize_t sys_cputs(struct proc *p, const char *DANGEROUS string,
+                         size_t strlen)
+{
+       char *t_string;
+       t_string = user_strdup_errno(p, string, strlen);
+       if (!t_string)
+               return -1;
+       printk("%.*s", strlen, t_string);
+       user_memdup_free(p, t_string);
+       return (ssize_t)strlen;
 }
 
 // Read a character from the system console.
 // Returns the character.
-static uint16_t sys_cgetc(env_t* e)
+static uint16_t sys_cgetc(struct proc *p)
 {
        uint16_t c;
 
@@ -323,279 +175,1216 @@ static uint16_t sys_cgetc(env_t* e)
        return c;
 }
 
-// Returns the current environment's envid.
-static envid_t sys_getenvid(env_t* e)
-{
-       return e->env_id;
-}
-
-// Returns the id of the cpu this syscall is executed on.
-static envid_t sys_getcpuid(void)
+/* Returns the id of the cpu this syscall is executed on. */
+static uint32_t sys_getcpuid(void)
 {
        return core_id();
 }
 
-// TODO: Temporary hack until thread-local storage is implemented on i386
-static size_t sys_getvcoreid(env_t* e)
+// TODO: Temporary hack until thread-local storage is implemented on i386 and
+// this is removed from the user interface
+static size_t sys_getvcoreid(struct proc *p)
 {
-       if(e->state == PROC_RUNNING_S)
-               return 0;
-
-       size_t i;
-       for(i = 0; i < e->num_vcores; i++)
-               if(core_id() == e->vcoremap[i])
-                       return i;
-
-       panic("virtual core id not found in sys_getvcoreid()!");
+       return proc_get_vcoreid(p, core_id());
 }
 
-// TODO FIX Me!!!! for processes
-// Destroy a given environment (possibly the currently running environment).
-//
-// Returns 0 on success, < 0 on error.  Errors are:
-//     -EBADENV if environment envid doesn't currently exist,
-//             or the caller doesn't have permission to change envid.
-static error_t sys_env_destroy(env_t* e, envid_t envid)
-{
-       int r;
-       env_t *env_to_die;
+/************** Process management syscalls **************/
 
-       if ((r = envid2env(envid, &env_to_die, 1)) < 0)
-               return r;
-       if (env_to_die == e)
-               printk("[%08x] exiting gracefully\n", e->env_id);
-       else
-               panic("Destroying other processes is not supported yet.");
-               //printk("[%08x] destroying %08x\n", e->env_id, env_to_die->env_id);
-       proc_destroy(env_to_die);
-       return ESUCCESS;
+/* Returns the calling process's pid */
+static pid_t sys_getpid(struct proc *p)
+{
+       return p->pid;
 }
 
-/*
- * Creates a process found at the user string 'path'.  Currently uses KFS.
- * Not runnable by default, so it needs it's status to be changed so that the
- * next call to schedule() will try to run it.
- * TODO: once we have a decent VFS, consider splitting this up
- * and once there's an mmap, can have most of this in process.c
- */
-static int sys_proc_create(struct proc *p, const char *DANGEROUS path)
-{
-       #define MAX_PATH_LEN 256 // totally arbitrary
+/* Creates a process from the file 'path'.  The process is not runnable by
+ * default, so it needs it's status to be changed so that the next call to
+ * schedule() will try to run it.  TODO: take args/envs from userspace. */
+static int sys_proc_create(struct proc *p, char *path, size_t path_l,
+                           struct procinfo *pi)
+{
        int pid = 0;
-       char tpath[MAX_PATH_LEN];
-       /*
-        * There's a bunch of issues with reading in the path, which we'll
-        * need to sort properly in the VFS.  Main concerns are TOCTOU (copy-in),
-        * whether or not it's a big deal that the pointer could be into kernel
-        * space, and resolving both of these without knowing the length of the
-        * string. (TODO)
-        * Change this so that all syscalls with a pointer take a length.
-        *
-        * zra: I've added this user_mem_strlcpy, which I think eliminates the
-     * the TOCTOU issue. Adding a length arg to this call would allow a more
-        * efficient implementation, though, since only one call to user_mem_check
-        * would be required.
-        */
-       int ret = user_mem_strlcpy(p,tpath, path, MAX_PATH_LEN, PTE_USER_RO);
-       int kfs_inode = kfs_lookup_path(tpath);
-       if (kfs_inode < 0)
-               return -EINVAL;
-       struct proc *new_p = kfs_proc_create(kfs_inode);
-       return new_p->env_id; // TODO replace this with a real proc_id
+       char *t_path;
+       struct file *program;
+       struct proc *new_p;
+
+       /* Copy in the path.  Consider putting an upper bound on path_l. */
+       t_path = user_strdup_errno(p, path, path_l);
+       if (!t_path)
+               return -1;
+       program = do_file_open(t_path, 0, 0);
+       user_memdup_free(p, t_path);
+       if (!program)
+               return -1;                      /* presumably, errno is already set */
+       /* TODO: need to split the proc creation, since you must load after setting
+        * args/env, since auxp gets set up there. */
+       //new_p = proc_create(program, 0, 0);
+       if (proc_alloc(&new_p, current))
+               goto mid_error;
+       /* Set the argument stuff needed by glibc */
+       if (memcpy_from_user_errno(p, new_p->procinfo->argp, pi->argp,
+                                  sizeof(pi->argp)))
+               goto late_error;
+       if (memcpy_from_user_errno(p, new_p->procinfo->argbuf, pi->argbuf,
+                                  sizeof(pi->argbuf)))
+               goto late_error;
+       if (load_elf(new_p, program))
+               goto late_error;
+       kref_put(&program->f_kref);
+       __proc_ready(new_p);
+       pid = new_p->pid;
+       kref_put(&new_p->kref); /* give up the reference created in proc_create() */
+       return pid;
+late_error:
+       proc_destroy(new_p);
+mid_error:
+       kref_put(&program->f_kref);
+       return -1;
 }
 
-/* Makes process PID runnable.  Consider moving the functionality to env.c */
+/* Makes process PID runnable.  Consider moving the functionality to process.c */
 static error_t sys_proc_run(struct proc *p, unsigned pid)
 {
-       struct proc *target = get_proc(pid);
+       struct proc *target = pid2proc(pid);
        error_t retval = 0;
-       spin_lock_irqsave(&p->proc_lock); // note we can get interrupted here. it's not bad.
+
+       if (!target)
+               return -EBADPROC;
+       // note we can get interrupted here. it's not bad.
+       spin_lock(&p->proc_lock);
        // make sure we have access and it's in the right state to be activated
        if (!proc_controls(p, target)) {
+               kref_put(&target->kref);
                retval = -EPERM;
        } else if (target->state != PROC_CREATED) {
+               kref_put(&target->kref);
                retval = -EINVAL;
        } else {
-               proc_set_state(target, PROC_RUNNABLE_S);
+               __proc_set_state(target, PROC_RUNNABLE_S);
                schedule_proc(target);
        }
-       spin_unlock_irqsave(&p->proc_lock);
+       spin_unlock(&p->proc_lock);
+       kref_put(&target->kref);
        return retval;
 }
 
-static error_t sys_brk(struct proc *p, void* addr) {
-       size_t range;
+/* Destroy proc pid.  If this is called by the dying process, it will never
+ * return.  o/w it will return 0 on success, or an error.  Errors include:
+ * - EBADPROC: if there is no such process with pid
+ * - EPERM: if caller does not control pid */
+static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
+{
+       error_t r;
+       struct proc *p_to_die = pid2proc(pid);
 
-       if((addr < p->end_text_segment) || (addr >= (void*)USTACKBOT))
-               return -EINVAL;
-       if(addr == p->end_data_segment)
-               return ESUCCESS;
+       if (!p_to_die) {
+               set_errno(ESRCH);
+               return -1;
+       }
+       if (!proc_controls(p, p_to_die)) {
+               kref_put(&p_to_die->kref);
+               set_errno(EPERM);
+               return -1;
+       }
+       if (p_to_die == p) {
+               // syscall code and pid2proc both have edible references, only need 1.
+               p->exitcode = exitcode;
+               kref_put(&p_to_die->kref);
+               printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
+       } else {
+               printd("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
+       }
+       proc_destroy(p_to_die);
+       kref_put(&p_to_die->kref);
+       return ESUCCESS;
+}
+
+static int sys_proc_yield(struct proc *p, bool being_nice)
+{
+       proc_yield(p, being_nice);
+       return 0;
+}
+
+static ssize_t sys_fork(env_t* e)
+{
+       // TODO: right now we only support fork for single-core processes
+       if (e->state != PROC_RUNNING_S) {
+               set_errno(EINVAL);
+               return -1;
+       }
+       /* Can't really fork if we don't have a current_tf to fork */
+       if (!current_tf) {
+               set_errno(EINVAL);
+               return -1;
+       }
+       env_t* env;
+       assert(!proc_alloc(&env, current));
+       assert(env != NULL);
+
+       env->heap_top = e->heap_top;
+       env->ppid = e->pid;
+       env->env_tf = *current_tf;
+
+       env->cache_colors_map = cache_colors_map_alloc();
+       for(int i=0; i < llc_cache->num_colors; i++)
+               if(GET_BITMASK_BIT(e->cache_colors_map,i))
+                       cache_color_alloc(llc_cache, env->cache_colors_map);
+
+       duplicate_vmrs(e, env);
+
+       int copy_page(env_t* e, pte_t* pte, void* va, void* arg)
+       {
+               env_t* env = (env_t*)arg;
+
+               if(PAGE_PRESENT(*pte))
+               {
+                       page_t* pp;
+                       if(upage_alloc(env,&pp,0))
+                               return -1;
+                       if(page_insert(env->env_pgdir,pp,va,*pte & PTE_PERM))
+                       {
+                               page_decref(pp);
+                               return -1;
+                       }
+
+                       pagecopy(page2kva(pp),ppn2kva(PTE2PPN(*pte)));
+               } else {
+                       assert(PAGE_PAGED_OUT(*pte));
+                       /* TODO: (SWAP) will need to either make a copy or CoW/refcnt the
+                        * backend store.  For now, this PTE will be the same as the
+                        * original PTE */
+                       panic("Swapping not supported!");
+                       pte_t* newpte = pgdir_walk(env->env_pgdir,va,1);
+                       if(!newpte)
+                               return -1;
+                       *newpte = *pte;
+               }
+               return 0;
+       }
+
+       // TODO: (PC) this won't work.  Needs revisiting.
+       // copy procdata and procinfo
+       memcpy(env->procdata,e->procdata,sizeof(struct procdata));
+       memcpy(env->procinfo,e->procinfo,sizeof(struct procinfo));
+       env->procinfo->pid = env->pid;
+       env->procinfo->ppid = env->ppid;
+
+       /* for now, just copy the contents of every present page in the entire
+        * address space. */
+       if (env_user_mem_walk(e, 0, UMAPTOP, &copy_page, env)) {
+               proc_destroy(env);      /* this is prob what you want, not decref by 2 */
+               set_errno(ENOMEM);
+               return -1;
+       }
+       clone_files(&e->open_files, &env->open_files);
+       __proc_ready(env);
+       __proc_set_state(env, PROC_RUNNABLE_S);
+       schedule_proc(env);
+
+       // don't decref the new process.
+       // that will happen when the parent waits for it.
+       // TODO: if the parent doesn't wait, we need to change the child's parent
+       // when the parent dies, or at least decref it
+
+       printd("[PID %d] fork PID %d\n",e->pid,env->pid);
+
+       return env->pid;
+}
+
+/* Load the binary "path" into the current process, and start executing it.
+ * argv and envp are magically bundled in procinfo for now.  Keep in sync with
+ * glibc's sysdeps/ros/execve.c */
+static int sys_exec(struct proc *p, char *path, size_t path_l,
+                    struct procinfo *pi)
+{
+       int ret = -1;
+       char *t_path;
+       struct file *program;
+
+       /* We probably want it to never be allowed to exec if it ever was _M */
+       if (p->state != PROC_RUNNING_S) {
+               set_errno(EINVAL);
+               return -1;
+       }
+       /* Can't really exec if we don't have a current_tf to reset */
+       if (!current_tf) {
+               set_errno(EINVAL);
+               return -1;
+       }
+       /* Copy in the path.  Consider putting an upper bound on path_l. */
+       t_path = user_strdup_errno(p, path, path_l);
+       if (!t_path)
+               return -1;
+       program = do_file_open(t_path, 0, 0);
+       user_memdup_free(p, t_path);
+       if (!program)
+               return -1;                      /* presumably, errno is already set */
+       /* Set the argument stuff needed by glibc */
+       if (memcpy_from_user_errno(p, p->procinfo->argp, pi->argp,
+                                  sizeof(pi->argp)))
+               goto mid_error;
+       if (memcpy_from_user_errno(p, p->procinfo->argbuf, pi->argbuf,
+                                  sizeof(pi->argbuf)))
+               goto mid_error;
+       /* This is the point of no return for the process. */
+       /* TODO: issues with this: Need to also assert there are no outstanding
+        * users of the sysrings.  the ldt page will get freed shortly, so that's
+        * okay.  Potentially issues with the nm and vcpd if we were in _M before
+        * and someone is trying to notify. */
+       memset(p->procdata, 0, sizeof(procdata_t));
+       destroy_vmrs(p);
+       close_all_files(&p->open_files, TRUE);
+       env_user_mem_free(p, 0, UMAPTOP);
+       if (load_elf(p, program)) {
+               kref_put(&program->f_kref);
+               proc_destroy(p);
+               smp_idle();             /* syscall can't return on failure now */
+       }
+       printd("[PID %d] exec %s\n", p->pid, file_name(program));
+       kref_put(&program->f_kref);
+       *current_tf = p->env_tf;
+       return 0;
+mid_error:
+       kref_put(&program->f_kref);
+       return -1;
+}
+
+static ssize_t sys_trywait(env_t* e, pid_t pid, int* status)
+{
+       struct proc* p = pid2proc(pid);
+
+       // TODO: this syscall is racy, so we only support for single-core procs
+       if(e->state != PROC_RUNNING_S)
+               return -1;
+
+       // TODO: need to use errno properly.  sadly, ROS error codes conflict..
+
+       if(p)
+       {
+               ssize_t ret;
+
+               if(current->pid == p->ppid)
+               {
+                       if(p->state == PROC_DYING)
+                       {
+                               memcpy_to_user(e,status,&p->exitcode,sizeof(int));
+                               printd("[PID %d] waited for PID %d (code %d)\n",
+                                      e->pid,p->pid,p->exitcode);
+                               ret = 0;
+                       }
+                       else // not dead yet
+                       {
+                               set_errno(ESUCCESS);
+                               ret = -1;
+                       }
+               }
+               else // not a child of the calling process
+               {
+                       set_errno(EPERM);
+                       ret = -1;
+               }
+
+               // if the wait succeeded, decref twice
+               if (ret == 0)
+                       kref_put(&p->kref);
+               kref_put(&p->kref);
+               return ret;
+       }
+
+       set_errno(EPERM);
+       return -1;
+}
+
+/************** Memory Management Syscalls **************/
+
+static void *sys_mmap(struct proc *p, uintreg_t a1, uintreg_t a2, uintreg_t a3,
+                      uintreg_t *a456)
+{
+       uintreg_t _a456[3];
+       if (memcpy_from_user(p, _a456, a456, 3 * sizeof(uintreg_t)))
+               sys_proc_destroy(p, p->pid, -1);
+       return mmap(p, a1, a2, a3, _a456[0], _a456[1], _a456[2]);
+}
+
+static intreg_t sys_mprotect(struct proc *p, void *addr, size_t len, int prot)
+{
+       return mprotect(p, (uintptr_t)addr, len, prot);
+}
+
+static intreg_t sys_munmap(struct proc *p, void *addr, size_t len)
+{
+       return munmap(p, (uintptr_t)addr, len);
+}
 
-       if (addr > p->end_data_segment) {
-               range = addr - p->end_data_segment;
-               env_segment_alloc(p, p->end_data_segment, range);
+static ssize_t sys_shared_page_alloc(env_t* p1,
+                                     void**DANGEROUS _addr, pid_t p2_id,
+                                     int p1_flags, int p2_flags
+                                    )
+{
+       /* When we remove/change this, also get rid of page_insert_in_range() */
+       printk("[kernel] the current shared page alloc is deprecated.\n");
+       //if (!VALID_USER_PERMS(p1_flags)) return -EPERM;
+       //if (!VALID_USER_PERMS(p2_flags)) return -EPERM;
+
+       void * COUNT(1) * COUNT(1) addr = user_mem_assert(p1, _addr, sizeof(void *),
+                                                      PTE_USER_RW);
+       struct proc *p2 = pid2proc(p2_id);
+       if (!p2)
+               return -EBADPROC;
+
+       page_t* page;
+       error_t e = upage_alloc(p1, &page,1);
+       if (e < 0) {
+               kref_put(&p2->kref);
+               return e;
        }
-       else if (addr < p->end_data_segment) {
-               range = p->end_data_segment - addr;
-               env_segment_free(p, addr, range);
+
+       void* p2_addr = page_insert_in_range(p2->env_pgdir, page,
+                       (void*SNT)UTEXT, (void*SNT)UTOP, p2_flags);
+       if (p2_addr == NULL) {
+               page_free(page);
+               kref_put(&p2->kref);
+               return -EFAIL;
        }
-       p->end_data_segment = addr;
+
+       void* p1_addr = page_insert_in_range(p1->env_pgdir, page,
+                       (void*SNT)UTEXT, (void*SNT)UTOP, p1_flags);
+       if(p1_addr == NULL) {
+               page_remove(p2->env_pgdir, p2_addr);
+               page_free(page);
+               kref_put(&p2->kref);
+               return -EFAIL;
+       }
+       *addr = p1_addr;
+       kref_put(&p2->kref);
        return ESUCCESS;
 }
 
-/* Executes the given syscall.
- *
- * Note tf is passed in, which points to the tf of the context on the kernel
- * stack.  If any syscall needs to block, it needs to save this info, as well as
- * any silly state.
- *
- * TODO: Build a dispatch table instead of switching on the syscallno
- * Dispatches to the correct kernel function, passing the arguments.
- */
-intreg_t syscall(struct proc *p, trapframe_t *tf, uintreg_t syscallno,
-                 uintreg_t a1, uintreg_t a2, uintreg_t a3, uintreg_t a4,
-                                uintreg_t a5)
-{
-       // Call the function corresponding to the 'syscallno' parameter.
-       // Return any appropriate return value.
-
-       //cprintf("Incoming syscall on core: %d number: %d\n    a1: %x\n   "
-       //        " a2: %x\n    a3: %x\n    a4: %x\n    a5: %x\n", core_id(),
-       //        syscallno, a1, a2, a3, a4, a5);
-
-       // used if we need more args, like in mmap
-       int32_t _a4, _a5, _a6, *COUNT(3) args;
-
-       assert(p); // should always have an env for every syscall
-       //printk("Running syscall: %d\n", syscallno);
-       if (INVALID_SYSCALL(syscallno))
+static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
+{
+       return -1;
+}
+
+
+/* sys_resource_req(): called directly from dispatch table. */
+
+/* Will notify the target on the given vcore, if the caller controls the target.
+ * Will honor the target's wanted/vcoreid.  u_ne can be NULL. */
+static int sys_notify(struct proc *p, int target_pid, unsigned int notif,
+                      struct notif_event *u_ne)
+{
+       struct notif_event local_ne;
+       struct proc *target = pid2proc(target_pid);
+
+       if (!target) {
+               set_errno(EBADPROC);
+               return -1;
+       }
+       if (!proc_controls(p, target)) {
+               kref_put(&target->kref);
+               set_errno(EPERM);
+               return -1;
+       }
+       /* if the user provided a notif_event, copy it in and use that */
+       if (u_ne) {
+               if (memcpy_from_user(p, &local_ne, u_ne, sizeof(struct notif_event))) {
+                       kref_put(&target->kref);
+                       set_errno(EINVAL);
+                       return -1;
+               }
+               proc_notify(target, local_ne.ne_type, &local_ne);
+       } else {
+               proc_notify(target, notif, 0);
+       }
+       kref_put(&target->kref);
+       return 0;
+}
+
+/* Will notify the calling process on the given vcore, independently of WANTED
+ * or advertised vcoreid.  If you change the parameters, change pop_ros_tf() */
+static int sys_self_notify(struct proc *p, uint32_t vcoreid, unsigned int notif,
+                           struct notif_event *u_ne)
+{
+       struct notif_event local_ne;
+
+       printd("[kernel] received self notify for vcoreid %d, notif %d, ne %08p\n",
+              vcoreid, notif, u_ne);
+       /* if the user provided a notif_event, copy it in and use that */
+       if (u_ne) {
+               if (memcpy_from_user(p, &local_ne, u_ne, sizeof(struct notif_event))) {
+                       set_errno(EINVAL);
+                       return -1;
+               }
+               do_notify(p, vcoreid, local_ne.ne_type, &local_ne);
+       } else {
+               do_notify(p, vcoreid, notif, 0);
+       }
+       return 0;
+}
+
+/* This will set a local timer for usec, then shut down the core */
+static int sys_halt_core(struct proc *p, unsigned int usec)
+{
+       /* TODO: ought to check and see if a timer was already active, etc, esp so
+        * userspace can't turn off timers.  also note we will also call whatever
+        * timer_interrupt() will do, though all we care about is just
+        * self_ipi/interrupting. */
+       set_core_timer(usec);
+       cpu_halt();
+
+       return 0;
+}
+
+/************** Platform Specific Syscalls **************/
+
+//Read a buffer over the serial port
+static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
+{
+       printk("[kernel] serial reading is deprecated.\n");
+       if (len == 0)
+               return 0;
+
+       #ifdef __CONFIG_SERIAL_IO__
+           char *COUNT(len) buf = user_mem_assert(e, _buf, len, PTE_USER_RO);
+               size_t bytes_read = 0;
+               int c;
+               while((c = serial_read_byte()) != -1) {
+                       buf[bytes_read++] = (uint8_t)c;
+                       if(bytes_read == len) break;
+               }
+               return (ssize_t)bytes_read;
+       #else
                return -EINVAL;
+       #endif
+}
+
+//Write a buffer over the serial port
+static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
+{
+       printk("[kernel] serial writing is deprecated.\n");
+       if (len == 0)
+               return 0;
+       #ifdef __CONFIG_SERIAL_IO__
+               char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_USER_RO);
+               for(int i =0; i<len; i++)
+                       serial_send_byte(buf[i]);
+               return (ssize_t)len;
+       #else
+               return -EINVAL;
+       #endif
+}
+
+#ifdef __CONFIG_NETWORKING__
+// This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
+static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf)
+{
+       if (eth_up) {
+
+               uint32_t len;
+               char *ptr;
+
+               spin_lock(&packet_buffers_lock);
+
+               if (num_packet_buffers == 0) {
+                       spin_unlock(&packet_buffers_lock);
+                       return 0;
+               }
+
+               ptr = packet_buffers[packet_buffers_head];
+               len = packet_buffers_sizes[packet_buffers_head];
+
+               num_packet_buffers--;
+               packet_buffers_head = (packet_buffers_head + 1) % MAX_PACKET_BUFFERS;
+
+               spin_unlock(&packet_buffers_lock);
+
+               char* _buf = user_mem_assert(e, buf, len, PTE_U);
+
+               memcpy(_buf, ptr, len);
+
+               kfree(ptr);
+
+               return len;
+       }
+       else
+               return -EINVAL;
+}
+
+// This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
+static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
+{
+       if (eth_up) {
 
-       switch (syscallno) {
-               case SYS_null:
-                       sys_null();
-                       return ESUCCESS;
-               case SYS_cache_buster:
-                       sys_cache_buster(p, a1, a2, a3);
+               if (len == 0)
                        return 0;
-               case SYS_cache_invalidate:
-                       sys_cache_invalidate();
+
+               // HACK TO BYPASS HACK
+               int just_sent = send_frame(buf, len);
+
+               if (just_sent < 0) {
+                       printk("Packet send fail\n");
                        return 0;
-               case SYS_shared_page_alloc:
-                       return sys_shared_page_alloc(p, (void** DANGEROUS) a1,
-                                                a2, (int) a3, (int) a4);
-               case SYS_shared_page_free:
-                       sys_shared_page_free(p, (void* DANGEROUS) a1, a2);
-                   return ESUCCESS;
-               case SYS_cputs:
-                       return sys_cputs(p, (char *DANGEROUS)a1, (size_t)a2);
-               case SYS_cgetc:
-                       return sys_cgetc(p); // this will need to block
-               case SYS_getcpuid:
-                       return sys_getcpuid();
-               case SYS_getvcoreid:
-                       return sys_getvcoreid(p);
-               case SYS_getpid:
-                       return sys_getenvid(p);
-               case SYS_proc_destroy:
-                       return sys_env_destroy(p, (envid_t)a1);
-               case SYS_yield:
-                       proc_yield(p);
-                       return ESUCCESS;
-               case SYS_proc_create:
-                       return sys_proc_create(p, (char *DANGEROUS)a1);
-               case SYS_proc_run:
-                       return sys_proc_run(p, (size_t)a1);
-               case SYS_mmap:
-                       // we only have 4 parameters from sysenter currently, need to copy
-                       // in the others.  if we stick with this, we can make a func for it.
-                       args = user_mem_assert(p, (void*DANGEROUS)a4,
-                                              3*sizeof(_a4), PTE_USER_RW);
-                       _a4 = args[0];
-                       _a5 = args[1];
-                       _a6 = args[2];
-                       return (intreg_t) mmap(p, a1, a2, a3, _a4, _a5, _a6);
-               case SYS_brk:
-                       return sys_brk(p, (void*)a1);
-               case SYS_resource_req:
-                       /* preemptively set the return code to 0.  if it's not, it will get
-                        * overwriten on a proper return path.  if it ends up being a core
-                        * request from a RUNNING_S, it will never return out this way
-                        */
-                       proc_set_syscall_retval(tf, ESUCCESS);
-                       return resource_req(p, a1, a2, a3);
+               }
 
-       #ifdef __i386__
-               case SYS_serial_write:
-                       return sys_serial_write(p, (char *DANGEROUS)a1, (size_t)a2);
-               case SYS_serial_read:
-                       return sys_serial_read(p, (char *DANGEROUS)a1, (size_t)a2);
+               return just_sent;
+
+               // END OF RECURSIVE HACK
+/*
+               char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
+               int total_sent = 0;
+               int just_sent = 0;
+               int cur_packet_len = 0;
+               while (total_sent != len) {
+                       cur_packet_len = ((len - total_sent) > MTU) ? MTU : (len - total_sent);
+                       char dest_mac[6] = APPSERVER_MAC_ADDRESS;
+                       char* wrap_buffer = eth_wrap(_buf + total_sent, cur_packet_len, device_mac, dest_mac, APPSERVER_PORT);
+                       just_sent = send_frame(wrap_buffer, cur_packet_len + sizeof(struct ETH_Header));
+
+                       if (just_sent < 0)
+                               return 0; // This should be an error code of its own
+
+                       if (wrap_buffer)
+                               kfree(wrap_buffer);
+
+                       total_sent += cur_packet_len;
+               }
+
+               return (ssize_t)len;
+*/
+       }
+       else
+               return -EINVAL;
+}
+
+static ssize_t sys_eth_get_mac_addr(env_t* e, char *DANGEROUS buf) 
+{
+       if (eth_up) {
+               for (int i = 0; i < 6; i++)
+                       buf[i] = device_mac[i];
+               return 0;
+       }
+       else
+               return -EINVAL;
+}
+
+static int sys_eth_recv_check(env_t* e) 
+{
+       if (num_packet_buffers != 0) 
+               return 1;
+       else
+               return 0;
+}
+
+#endif // Network
+
+static intreg_t sys_read(struct proc *p, int fd, void *buf, int len)
+{
+       ssize_t ret;
+       struct file *file = get_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       assert(file->f_op->read);
+       /* TODO: (UMEM) currently, read() handles user memcpy issues, but we
+        * probably should user_mem_check and pin the region here, so read doesn't
+        * worry about it */
+       ret = file->f_op->read(file, buf, len, &file->f_pos);
+       kref_put(&file->f_kref);
+       return ret;
+}
+
+static intreg_t sys_write(struct proc *p, int fd, const void *buf, int len)
+{
+       /* Catch common usage of stdout and stderr.  No protections or anything. */
+       if (fd == 1) {
+               printk("[stdout]: %s\n", buf);
+               return len;
+       } else if (fd == 2) {
+               printk("[stderr]: %s\n", buf);
+               return len;
+       }
+       /* the real sys_write: */
+       ssize_t ret;
+       struct file *file = get_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       if (!file->f_op->write) {
+               kref_put(&file->f_kref);
+               set_errno(EINVAL);
+               return -1;
+       }
+       /* TODO: (UMEM) */
+       ret = file->f_op->write(file, buf, len, &file->f_pos);
+       kref_put(&file->f_kref);
+       return ret;
+}
+
+/* Checks args/reads in the path, opens the file, and inserts it into the
+ * process's open file list. 
+ *
+ * TODO: take the path length */
+static intreg_t sys_open(struct proc *p, const char *path, size_t path_l,
+                         int oflag, int mode)
+{
+       int fd = 0;
+       struct file *file;
+
+       char *t_path = user_strdup_errno(p, path, path_l);
+       if (!t_path)
+               return -1;
+       file = do_file_open(t_path, oflag, mode);
+       user_memdup_free(p, t_path);
+       if (!file)
+               return -1;
+       fd = insert_file(&p->open_files, file); /* stores the ref to file */
+       kref_put(&file->f_kref);
+       if (fd < 0) {
+               warn("File insertion failed");
+               return -1;
+       }
+       printd("File %s Open, res=%d\n", path, fd);
+       return fd;
+}
+
+static intreg_t sys_close(struct proc *p, int fd)
+{
+       struct file *file = put_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       return 0;
+}
+
+/* kept around til we remove the last ufe */
+#define ufe(which,a0,a1,a2,a3) \
+       frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
+                          (int)(a0),(int)(a1),(int)(a2),(int)(a3))
+
+static intreg_t sys_fstat(struct proc *p, int fd, struct kstat *u_stat)
+{
+       struct kstat *kbuf;
+       struct file *file = get_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       kbuf = kmalloc(sizeof(struct kstat), 0);
+       if (!kbuf) {
+               kref_put(&file->f_kref);
+               set_errno(ENOMEM);
+               return -1;
+       }
+       stat_inode(file->f_dentry->d_inode, kbuf);
+       kref_put(&file->f_kref);
+       /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
+       if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
+               kfree(kbuf);
+               set_errno(EINVAL);
+               return -1;
+       }
+       kfree(kbuf);
+       return 0;
+}
+
+/* sys_stat() and sys_lstat() do nearly the same thing, differing in how they
+ * treat a symlink for the final item, which (probably) will be controlled by
+ * the lookup flags */
+static intreg_t stat_helper(struct proc *p, const char *path, size_t path_l,
+                            struct kstat *u_stat, int flags)
+{
+       struct kstat *kbuf;
+       struct dentry *path_d;
+       char *t_path = user_strdup_errno(p, path, path_l);
+       if (!t_path)
+               return -1;
+       path_d = lookup_dentry(t_path, flags);
+       user_memdup_free(p, t_path);
+       if (!path_d)
+               return -1;
+       kbuf = kmalloc(sizeof(struct kstat), 0);
+       if (!kbuf) {
+               set_errno(ENOMEM);
+               kref_put(&path_d->d_kref);
+               return -1;
+       }
+       stat_inode(path_d->d_inode, kbuf);
+       kref_put(&path_d->d_kref);
+       /* TODO: UMEM: pin the memory, copy directly, and skip the kernel buffer */
+       if (memcpy_to_user_errno(p, u_stat, kbuf, sizeof(struct kstat))) {
+               kfree(kbuf);
+               set_errno(EINVAL);
+               return -1;
+       }
+       kfree(kbuf);
+       return 0;
+}
+
+/* Follow a final symlink */
+static intreg_t sys_stat(struct proc *p, const char *path, size_t path_l,
+                         struct kstat *u_stat)
+{
+       return stat_helper(p, path, path_l, u_stat, LOOKUP_FOLLOW);
+}
+
+/* Don't follow a final symlink */
+static intreg_t sys_lstat(struct proc *p, const char *path, size_t path_l,
+                          struct kstat *u_stat)
+{
+       return stat_helper(p, path, path_l, u_stat, 0);
+}
+
+intreg_t sys_fcntl(struct proc *p, int fd, int cmd, int arg)
+{
+       int retval = 0;
+       struct file *file = get_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       switch (cmd) {
+               case (F_DUPFD):
+                       printk("[kernel] dup not supported yet\n");
+                       break;
+               case (F_GETFD):
+                       /* GET and SETFD just care about CLOEXEC.  We don't have a separate
+                        * flag variable for the FD (we might need to, technically). */
+                       if (file->f_flags & O_CLOEXEC)
+                               retval = FD_CLOEXEC;
+                       break;
+               case (F_SETFD):
+                       if (arg == FD_CLOEXEC)
+                               file->f_flags |= O_CLOEXEC;
+                       break;
+               case (F_GETFL):
+                       retval = file->f_flags;
+                       break;
+               case (F_SETFL):
+                       /* only allowed to set certain flags. */
+                       arg &= O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NONBLOCK;
+                       break;
+               default:
+                       warn("Unsupported fcntl cmd %d\n", cmd);
+       }
+       kref_put(&file->f_kref);
+       return 0;
+}
+
+static intreg_t sys_access(struct proc *p, const char *path, size_t path_l,
+                           int mode)
+{
+       int retval;
+
+       char *t_path = user_strdup_errno(p, path, path_l);
+       if (!t_path)
+               return -1;
+       retval = do_file_access(t_path, mode);
+       user_memdup_free(p, t_path);
+       printd("Access for path: %s retval: %d\n", path, retval);
+       if (retval < 0) {
+               set_errno(-retval);
+               return -1;
+       }
+       return retval;
+}
+
+intreg_t sys_umask(struct proc *p, int mask)
+{
+       return ufe(umask,mask,0,0,0);
+}
+
+intreg_t sys_chmod(struct proc *p, const char *path, size_t path_l, int mode)
+{
+       char* fn = user_strdup_errno(p,path,PGSIZE);
+       if(fn == NULL)
+               return -1;
+       int ret = ufe(chmod,PADDR(fn),mode,0,0);
+       user_memdup_free(p,fn);
+       return ret;
+}
+
+static intreg_t sys_lseek(struct proc *p, int fd, off_t offset, int whence)
+{
+       off_t ret;
+       struct file *file = get_file_from_fd(&p->open_files, fd);
+       if (!file) {
+               set_errno(EBADF);
+               return -1;
+       }
+       ret = file->f_op->llseek(file, offset, whence);
+       kref_put(&file->f_kref);
+       return ret;
+}
+
+intreg_t sys_link(struct proc *p, const char *_old, size_t old_l,
+                  const char *_new, size_t new_l)
+{
+       char* oldpath = user_strdup_errno(p,_old,PGSIZE);
+       if(oldpath == NULL)
+               return -1;
+
+       char* newpath = user_strdup_errno(p,_new,PGSIZE);
+       if(newpath == NULL)
+       {
+               user_memdup_free(p,oldpath);
+               return -1;
+       }
+
+       int ret = ufe(link,PADDR(oldpath),PADDR(newpath),0,0);
+       user_memdup_free(p,oldpath);
+       user_memdup_free(p,newpath);
+       return ret;
+}
+
+intreg_t sys_unlink(struct proc *p, const char *path, size_t path_l)
+{
+       char* fn = user_strdup_errno(p,path,PGSIZE);
+       if(fn == NULL)
+               return -1;
+       int ret = ufe(unlink,PADDR(fn),0,0,0);
+       user_memdup_free(p,fn);
+       return ret;
+}
+
+intreg_t sys_symlink(struct proc *p, char *old_path, size_t old_l,
+                     char *new_path, size_t new_l)
+{
+       int ret;
+       char *t_oldpath = user_strdup_errno(p, old_path, old_l);
+       if (t_oldpath == NULL)
+               return -1;
+       char *t_newpath = user_strdup_errno(p, new_path, new_l);
+       if (t_newpath == NULL) {
+               user_memdup_free(p, t_oldpath);
+               return -1;
+       }
+       ret = do_symlink(new_path, old_path, S_IRWXU | S_IRWXG | S_IRWXO);
+       user_memdup_free(p, t_oldpath);
+       user_memdup_free(p, t_newpath);
+       return ret;
+}
+
+intreg_t sys_readlink(struct proc *p, char *path, size_t path_l,
+                      char *u_buf, size_t buf_l)
+{
+       char *symname;
+       ssize_t copy_amt;
+       struct dentry *path_d;
+       char *t_path = user_strdup_errno(p, path, path_l);
+       if (t_path == NULL)
+               return -1;
+       path_d = lookup_dentry(t_path, 0);
+       user_memdup_free(p, t_path);
+       if (!path_d)
+               return -1;
+       symname = path_d->d_inode->i_op->readlink(path_d);
+       copy_amt = strnlen(symname, buf_l - 1) + 1;
+       if (memcpy_to_user_errno(p, u_buf, symname, copy_amt)) {
+               kref_put(&path_d->d_kref);
+               set_errno(EINVAL);
+               return -1;
+       }
+       kref_put(&path_d->d_kref);
+       printd("READLINK returning %s\n", u_buf);
+       return copy_amt;
+}
+
+intreg_t sys_chdir(struct proc *p, const char *path, size_t path_l)
+{
+       char* fn = user_strdup_errno(p,path,PGSIZE);
+       if(fn == NULL)
+               return -1;
+       int ret = ufe(chdir,PADDR(fn),0,0,0);
+       user_memdup_free(p,fn);
+       return ret;
+}
+
+intreg_t sys_getcwd(struct proc *p, char *pwd, int size)
+{
+       void* kbuf = kmalloc_errno(size);
+       if(kbuf == NULL)
+               return -1;
+       int ret = ufe(read,PADDR(kbuf),size,0,0);
+       if(ret != -1 && memcpy_to_user_errno(p,pwd,kbuf,strnlen(kbuf,size)))
+               ret = -1;
+       user_memdup_free(p,kbuf);
+       return ret;
+}
+
+intreg_t sys_gettimeofday(struct proc *p, int *buf)
+{
+       static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
+       static int t0 = 0;
+
+       spin_lock(&gtod_lock);
+       if(t0 == 0)
+
+#if (defined __CONFIG_APPSERVER__)
+       t0 = ufe(time,0,0,0,0);
+#else
+       // Nanwan's birthday, bitches!!
+       t0 = 1242129600;
+#endif 
+       spin_unlock(&gtod_lock);
+
+       long long dt = read_tsc();
+       int kbuf[2] = {t0+dt/system_timing.tsc_freq,
+           (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
+
+       return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
+}
+
+#define SIZEOF_STRUCT_TERMIOS 60
+intreg_t sys_tcgetattr(struct proc *p, int fd, void *termios_p)
+{
+       int* kbuf = kmalloc(SIZEOF_STRUCT_TERMIOS,0);
+       int ret = ufe(tcgetattr,fd,PADDR(kbuf),0,0);
+       if(ret != -1 && memcpy_to_user_errno(p,termios_p,kbuf,SIZEOF_STRUCT_TERMIOS))
+               ret = -1;
+       kfree(kbuf);
+       return ret;
+}
+
+intreg_t sys_tcsetattr(struct proc *p, int fd, int optional_actions,
+                       const void *termios_p)
+{
+       void* kbuf = user_memdup_errno(p,termios_p,SIZEOF_STRUCT_TERMIOS);
+       if(kbuf == NULL)
+               return -1;
+       int ret = ufe(tcsetattr,fd,optional_actions,PADDR(kbuf),0);
+       user_memdup_free(p,kbuf);
+       return ret;
+}
+
+/************** Syscall Invokation **************/
+
+/* Executes the given syscall.
+ *
+ * Note tf is passed in, which points to the tf of the context on the kernel
+ * stack.  If any syscall needs to block, it needs to save this info, as well as
+ * any silly state.
+ * 
+ * This syscall function is used by both local syscall and arsc, and should
+ * remain oblivious of the caller. */
+intreg_t syscall(struct proc *p, uintreg_t syscallno, uintreg_t a1,
+                 uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
+{
+       /* Initialize the return value and error code returned to 0 */
+       set_retval(ESUCCESS);
+       set_errno(ESUCCESS);
+
+       typedef intreg_t (*syscall_t)(struct proc*,uintreg_t,uintreg_t,
+                                     uintreg_t,uintreg_t,uintreg_t);
+
+       const static syscall_t syscall_table[] = {
+               [SYS_null] = (syscall_t)sys_null,
+               [SYS_cache_buster] = (syscall_t)sys_cache_buster,
+               [SYS_cache_invalidate] = (syscall_t)sys_cache_invalidate,
+               [SYS_reboot] = (syscall_t)reboot,
+               [SYS_cputs] = (syscall_t)sys_cputs,
+               [SYS_cgetc] = (syscall_t)sys_cgetc,
+               [SYS_getcpuid] = (syscall_t)sys_getcpuid,
+               [SYS_getvcoreid] = (syscall_t)sys_getvcoreid,
+               [SYS_getpid] = (syscall_t)sys_getpid,
+               [SYS_proc_create] = (syscall_t)sys_proc_create,
+               [SYS_proc_run] = (syscall_t)sys_proc_run,
+               [SYS_proc_destroy] = (syscall_t)sys_proc_destroy,
+               [SYS_yield] = (syscall_t)sys_proc_yield,
+               [SYS_fork] = (syscall_t)sys_fork,
+               [SYS_exec] = (syscall_t)sys_exec,
+               [SYS_trywait] = (syscall_t)sys_trywait,
+               [SYS_mmap] = (syscall_t)sys_mmap,
+               [SYS_munmap] = (syscall_t)sys_munmap,
+               [SYS_mprotect] = (syscall_t)sys_mprotect,
+               [SYS_shared_page_alloc] = (syscall_t)sys_shared_page_alloc,
+               [SYS_shared_page_free] = (syscall_t)sys_shared_page_free,
+               [SYS_resource_req] = (syscall_t)resource_req,
+               [SYS_notify] = (syscall_t)sys_notify,
+               [SYS_self_notify] = (syscall_t)sys_self_notify,
+               [SYS_halt_core] = (syscall_t)sys_halt_core,
+       #ifdef __CONFIG_SERIAL_IO__
+               [SYS_serial_read] = (syscall_t)sys_serial_read,
+               [SYS_serial_write] = (syscall_t)sys_serial_write,
        #endif
-               case SYS_run_binary:
-                       return sys_run_binary(p, (char *DANGEROUS)a1,
-                                             (char* DANGEROUS)a2, (size_t)a3);
-       #ifdef __NETWORK__
-               case SYS_eth_write:
-                       return sys_eth_write(p, (char *DANGEROUS)a1, (size_t)a2);
-               case SYS_eth_read:
-                       return sys_eth_read(p, (char *DANGEROUS)a1, (size_t)a2);
+       #ifdef __CONFIG_NETWORKING__
+               [SYS_eth_read] = (syscall_t)sys_eth_read,
+               [SYS_eth_write] = (syscall_t)sys_eth_write,
+               [SYS_eth_get_mac_addr] = (syscall_t)sys_eth_get_mac_addr,
+               [SYS_eth_recv_check] = (syscall_t)sys_eth_recv_check,
        #endif
-       #ifdef __sparc_v8__
-               case SYS_frontend:
-                       return frontend_syscall_from_user(p,a1,a2,a3,a4);
+       #ifdef __CONFIG_ARSC_SERVER__
+               [SYS_init_arsc] = (syscall_t)sys_init_arsc,
        #endif
-
-               default:
-                       // or just return -EINVAL
-                       panic("Invalid syscall number %d for env %x!", syscallno, *p);
+               // Syscalls serviced by the appserver for now.
+               [SYS_read] = (syscall_t)sys_read,
+               [SYS_write] = (syscall_t)sys_write,
+               [SYS_open] = (syscall_t)sys_open,
+               [SYS_close] = (syscall_t)sys_close,
+               [SYS_fstat] = (syscall_t)sys_fstat,
+               [SYS_stat] = (syscall_t)sys_stat,
+               [SYS_lstat] = (syscall_t)sys_lstat,
+               [SYS_fcntl] = (syscall_t)sys_fcntl,
+               [SYS_access] = (syscall_t)sys_access,
+               [SYS_umask] = (syscall_t)sys_umask,
+               [SYS_chmod] = (syscall_t)sys_chmod,
+               [SYS_lseek] = (syscall_t)sys_lseek,
+               [SYS_link] = (syscall_t)sys_link,
+               [SYS_unlink] = (syscall_t)sys_unlink,
+               [SYS_symlink] = (syscall_t)sys_symlink,
+               [SYS_readlink] = (syscall_t)sys_readlink,
+               [SYS_chdir] = (syscall_t)sys_chdir,
+               [SYS_getcwd] = (syscall_t)sys_getcwd,
+               [SYS_gettimeofday] = (syscall_t)sys_gettimeofday,
+               [SYS_tcgetattr] = (syscall_t)sys_tcgetattr,
+               [SYS_tcsetattr] = (syscall_t)sys_tcsetattr
+       };
+
+       const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
+
+       uint32_t coreid, vcoreid;
+       if (systrace_flags & SYSTRACE_ON) {
+               if ((systrace_flags & SYSTRACE_ALLPROC) || (proc_is_traced(p))) {
+                       coreid = core_id();
+                       vcoreid = proc_get_vcoreid(p, core_id());
+                       if (systrace_flags & SYSTRACE_LOUD) {
+                               printk("[%16llu] Syscall %d for proc %d on core %d, vcore %d\n",
+                                      read_tsc(), syscallno, p->pid, coreid, vcoreid);
+                       } else {
+                               struct systrace_record *trace;
+                               unsigned int idx, new_idx;
+                               do {
+                                       idx = systrace_bufidx;
+                                       new_idx = (idx + 1) % systrace_bufsize;
+                               } while (!atomic_comp_swap(&systrace_bufidx, idx, new_idx));
+                               trace = &systrace_buffer[idx];
+                               trace->timestamp = read_tsc();
+                               trace->syscallno = syscallno;
+                               trace->pid = p->pid;
+                               trace->coreid = coreid;
+                               trace->vcoreid = vcoreid;
+                       }
+               }
        }
-       return 0xdeadbeef;
+       //printk("Incoming syscall on core: %d number: %d\n    a1: %x\n   "
+       //       " a2: %x\n    a3: %x\n    a4: %x\n    a5: %x\n", core_id(),
+       //       syscallno, a1, a2, a3, a4, a5);
+
+       if(syscallno > max_syscall || syscall_table[syscallno] == NULL)
+               panic("Invalid syscall number %d for proc %x!", syscallno, *p);
+
+       return syscall_table[syscallno](p,a1,a2,a3,a4,a5);
 }
 
-intreg_t syscall_async(env_t* e, syscall_req_t *call)
+/* Syscall tracing */
+static void __init_systrace(void)
 {
-       return syscall(e, NULL, call->num, call->args[0], call->args[1],
-                      call->args[2], call->args[3], call->args[4]);
+       systrace_buffer = kmalloc(MAX_SYSTRACES*sizeof(struct systrace_record), 0);
+       if (!systrace_buffer)
+               panic("Unable to alloc a trace buffer\n");
+       systrace_bufidx = 0;
+       systrace_bufsize = MAX_SYSTRACES;
+       /* Note we never free the buffer - it's around forever.  Feel free to change
+        * this if you want to change the size or something dynamically. */
 }
 
-intreg_t process_generic_syscalls(env_t* e, size_t max)
+/* If you call this while it is running, it will change the mode */
+void systrace_start(bool silent)
 {
-       size_t count = 0;
-       syscall_back_ring_t* sysbr = &e->syscallbackring;
+       static bool init = FALSE;
+       spin_lock_irqsave(&systrace_lock);
+       if (!init) {
+               __init_systrace();
+               init = TRUE;
+       }
+       systrace_flags = silent ? SYSTRACE_ON : SYSTRACE_ON | SYSTRACE_LOUD; 
+       spin_unlock_irqsave(&systrace_lock);
+}
 
-       // make sure the env is still alive.
-       // incref will return ESUCCESS on success.
-       if (proc_incref(e))
-               return -EFAIL;
+int systrace_reg(bool all, struct proc *p)
+{
+       int retval = 0;
+       spin_lock_irqsave(&systrace_lock);
+       if (all) {
+               printk("Tracing syscalls for all processes\n");
+               systrace_flags |= SYSTRACE_ALLPROC;
+               retval = 0;
+       } else {
+               for (int i = 0; i < MAX_NUM_TRACED; i++) {
+                       if (!systrace_procs[i]) {
+                               printk("Tracing syscalls for process %d\n", p->pid);
+                               systrace_procs[i] = p;
+                               retval = 0;
+                               break;
+                       }
+               }
+       }
+       spin_unlock_irqsave(&systrace_lock);
+       return retval;
+}
+
+void systrace_stop(void)
+{
+       spin_lock_irqsave(&systrace_lock);
+       systrace_flags = 0;
+       for (int i = 0; i < MAX_NUM_TRACED; i++)
+               systrace_procs[i] = 0;
+       spin_unlock_irqsave(&systrace_lock);
+}
 
-       // max is the most we'll process.  max = 0 means do as many as possible
-       while (RING_HAS_UNCONSUMED_REQUESTS(sysbr) && ((!max)||(count < max)) ) {
-               if (!count) {
-                       // ASSUME: one queue per process
-                       // only switch cr3 for the very first request for this queue
-                       // need to switch to the right context, so we can handle the user pointer
-                       // that points to a data payload of the syscall
-                       lcr3(e->env_cr3);
+/* If you registered a process specifically, then you need to dereg it
+ * specifically.  Or just fully stop, which will do it for all. */
+int systrace_dereg(bool all, struct proc *p)
+{
+       spin_lock_irqsave(&systrace_lock);
+       if (all) {
+               printk("No longer tracing syscalls for all processes.\n");
+               systrace_flags &= ~SYSTRACE_ALLPROC;
+       } else {
+               for (int i = 0; i < MAX_NUM_TRACED; i++) {
+                       if (systrace_procs[i] == p) {
+                               systrace_procs[i] = 0;
+                               printk("No longer tracing syscalls for process %d\n", p->pid);
+                       }
                }
-               count++;
-               //printk("DEBUG PRE: sring->req_prod: %d, sring->rsp_prod: %d\n",
-               //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
-               // might want to think about 0-ing this out, if we aren't
-               // going to explicitly fill in all fields
-               syscall_rsp_t rsp;
-               // this assumes we get our answer immediately for the syscall.
-               syscall_req_t* req = RING_GET_REQUEST(sysbr, ++(sysbr->req_cons));
-               rsp.retval = syscall_async(e, req);
-               // write response into the slot it came from
-               memcpy(req, &rsp, sizeof(syscall_rsp_t));
-               // update our counter for what we've produced (assumes we went in order!)
-               (sysbr->rsp_prod_pvt)++;
-               RING_PUSH_RESPONSES(sysbr);
-               //printk("DEBUG POST: sring->req_prod: %d, sring->rsp_prod: %d\n",
-               //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
-       }
-       // load sane page tables (and don't rely on decref to do it for you).
-       lcr3(boot_cr3);
-       proc_decref(e);
-       return (intreg_t)count;
+       }
+       spin_unlock_irqsave(&systrace_lock);
+       return 0;
+}
+
+/* Regardless of locking, someone could be writing into the buffer */
+void systrace_print(bool all, struct proc *p)
+{
+       spin_lock_irqsave(&systrace_lock);
+       /* if you want to be clever, you could make this start from the earliest
+        * timestamp and loop around.  Careful of concurrent writes. */
+       for (int i = 0; i < systrace_bufsize; i++)
+               if (systrace_buffer[i].timestamp)
+                       printk("[%16llu] Syscall %d for proc %d on core %d, vcore %d\n",
+                              systrace_buffer[i].timestamp,
+                              systrace_buffer[i].syscallno,
+                              systrace_buffer[i].pid,
+                              systrace_buffer[i].coreid,
+                              systrace_buffer[i].vcoreid);
+       spin_unlock_irqsave(&systrace_lock);
+}
+
+void systrace_clear_buffer(void)
+{
+       spin_lock_irqsave(&systrace_lock);
+       memset(systrace_buffer, 0, sizeof(struct systrace_record)*MAX_NUM_TRACED);
+       spin_unlock_irqsave(&systrace_lock);
+}
+
+void set_retval(uint32_t retval)
+{
+       struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
+       *(coreinfo->cur_ret.returnloc) = retval;
+}
+void set_errno(uint32_t errno)
+{
+       struct per_cpu_info* coreinfo = &per_cpu_info[core_id()];
+       if (coreinfo && coreinfo->cur_ret.errno_loc)
+               *(coreinfo->cur_ret.errno_loc) = errno;
 }