Finally got KFS stuff sorted out on the new setup
[akaros.git] / kern / src / syscall.c
1 /* See COPYRIGHT for copyright information. */
2
3 #ifdef __SHARC__
4 #pragma nosharc
5 #endif
6
7 #include <ros/common.h>
8 #include <arch/types.h>
9 #include <arch/arch.h>
10 #include <arch/mmu.h>
11 #include <arch/console.h>
12 #include <ros/timer.h>
13 #include <error.h>
14
15 #include <elf.h>
16 #include <string.h>
17 #include <assert.h>
18 #include <process.h>
19 #include <schedule.h>
20 #include <pmap.h>
21 #include <mm.h>
22 #include <trap.h>
23 #include <syscall.h>
24 #include <kmalloc.h>
25 #include <stdio.h>
26 #include <resource.h>
27 #include <frontend.h>
28 #include <colored_caches.h>
29 #include <arch/bitmask.h>
30 #include <kfs.h> // eventually replace this with vfs.h
31
32
33 #ifdef __CONFIG_NETWORKING__
34 #include <arch/nic_common.h>
35 extern int (*send_frame)(const char *CT(len) data, size_t len);
36 extern char device_mac[6];
37 #endif
38
39 /************** Utility Syscalls **************/
40
41 static int sys_null(void)
42 {
43         return 0;
44 }
45
46 // Writes 'val' to 'num_writes' entries of the well-known array in the kernel
47 // address space.  It's just #defined to be some random 4MB chunk (which ought
48 // to be boot_alloced or something).  Meant to grab exclusive access to cache
49 // lines, to simulate doing something useful.
50 static int sys_cache_buster(struct proc *p, uint32_t num_writes,
51                              uint32_t num_pages, uint32_t flags)
52 { TRUSTEDBLOCK /* zra: this is not really part of the kernel */
53         #define BUSTER_ADDR             0xd0000000  // around 512 MB deep
54         #define MAX_WRITES              1048576*8
55         #define MAX_PAGES               32
56         #define INSERT_ADDR     (UINFO + 2*PGSIZE) // should be free for these tests
57         uint32_t* buster = (uint32_t*)BUSTER_ADDR;
58         static spinlock_t buster_lock = SPINLOCK_INITIALIZER;
59         uint64_t ticks = -1;
60         page_t* a_page[MAX_PAGES];
61
62         /* Strided Accesses or Not (adjust to step by cachelines) */
63         uint32_t stride = 1;
64         if (flags & BUSTER_STRIDED) {
65                 stride = 16;
66                 num_writes *= 16;
67         }
68
69         /* Shared Accesses or Not (adjust to use per-core regions)
70          * Careful, since this gives 8MB to each core, starting around 512MB.
71          * Also, doesn't separate memory for core 0 if it's an async call.
72          */
73         if (!(flags & BUSTER_SHARED))
74                 buster = (uint32_t*)(BUSTER_ADDR + core_id() * 0x00800000);
75
76         /* Start the timer, if we're asked to print this info*/
77         if (flags & BUSTER_PRINT_TICKS)
78                 ticks = start_timing();
79
80         /* Allocate num_pages (up to MAX_PAGES), to simulate doing some more
81          * realistic work.  Note we don't write to these pages, even if we pick
82          * unshared.  Mostly due to the inconvenience of having to match up the
83          * number of pages with the number of writes.  And it's unnecessary.
84          */
85         if (num_pages) {
86                 spin_lock(&buster_lock);
87                 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
88                         upage_alloc(p, &a_page[i],1);
89                         page_insert(p->env_pgdir, a_page[i], (void*)INSERT_ADDR + PGSIZE*i,
90                                     PTE_USER_RW);
91                 }
92                 spin_unlock(&buster_lock);
93         }
94
95         if (flags & BUSTER_LOCKED)
96                 spin_lock(&buster_lock);
97         for (int i = 0; i < MIN(num_writes, MAX_WRITES); i=i+stride)
98                 buster[i] = 0xdeadbeef;
99         if (flags & BUSTER_LOCKED)
100                 spin_unlock(&buster_lock);
101
102         if (num_pages) {
103                 spin_lock(&buster_lock);
104                 for (int i = 0; i < MIN(num_pages, MAX_PAGES); i++) {
105                         page_remove(p->env_pgdir, (void*)(INSERT_ADDR + PGSIZE * i));
106                         page_decref(a_page[i]);
107                 }
108                 spin_unlock(&buster_lock);
109         }
110
111         /* Print info */
112         if (flags & BUSTER_PRINT_TICKS) {
113                 ticks = stop_timing(ticks);
114                 printk("%llu,", ticks);
115         }
116         return 0;
117 }
118
119 static int sys_cache_invalidate(void)
120 {
121         #ifdef __i386__
122                 wbinvd();
123         #endif
124         return 0;
125 }
126
127 /* sys_reboot(): called directly from dispatch table. */
128
129 // Print a string to the system console.
130 // The string is exactly 'len' characters long.
131 // Destroys the environment on memory errors.
132 static ssize_t sys_cputs(env_t* e, const char *DANGEROUS s, size_t len)
133 {
134         // Check that the user has permission to read memory [s, s+len).
135         // Destroy the environment if not.
136         char *COUNT(len) _s = user_mem_assert(e, s, len, PTE_USER_RO);
137
138         // Print the string supplied by the user.
139         printk("%.*s", len, _s);
140         return (ssize_t)len;
141 }
142
143 // Read a character from the system console.
144 // Returns the character.
145 static uint16_t sys_cgetc(env_t* e)
146 {
147         uint16_t c;
148
149         // The cons_getc() primitive doesn't wait for a character,
150         // but the sys_cgetc() system call does.
151         while ((c = cons_getc()) == 0)
152                 cpu_relax();
153
154         return c;
155 }
156
157 /* Returns the id of the cpu this syscall is executed on. */
158 static uint32_t sys_getcpuid(void)
159 {
160         return core_id();
161 }
162
163 // TODO: Temporary hack until thread-local storage is implemented on i386
164 static size_t sys_getvcoreid(env_t* e)
165 {
166         if(e->state == PROC_RUNNING_S)
167                 return 0;
168
169         size_t i;
170         for(i = 0; i < e->num_vcores; i++)
171                 if(core_id() == e->vcoremap[i])
172                         return i;
173
174         panic("virtual core id not found in sys_getvcoreid()!");
175 }
176
177 /************** Process management syscalls **************/
178
179 /* Returns the calling process's pid */
180 static pid_t sys_getpid(struct proc *p)
181 {
182         return p->pid;
183 }
184
185 /*
186  * Creates a process found at the user string 'path'.  Currently uses KFS.
187  * Not runnable by default, so it needs it's status to be changed so that the
188  * next call to schedule() will try to run it.
189  * TODO: once we have a decent VFS, consider splitting this up
190  * and once there's an mmap, can have most of this in process.c
191  */
192 static int sys_proc_create(struct proc *p, const char *DANGEROUS path)
193 {
194         int pid = 0;
195         char tpath[MAX_PATH_LEN];
196         /*
197          * There's a bunch of issues with reading in the path, which we'll
198          * need to sort properly in the VFS.  Main concerns are TOCTOU (copy-in),
199          * whether or not it's a big deal that the pointer could be into kernel
200          * space, and resolving both of these without knowing the length of the
201          * string. (TODO)
202          * Change this so that all syscalls with a pointer take a length.
203          *
204          * zra: I've added this user_mem_strlcpy, which I think eliminates the
205      * the TOCTOU issue. Adding a length arg to this call would allow a more
206          * efficient implementation, though, since only one call to user_mem_check
207          * would be required.
208          */
209         int ret = user_mem_strlcpy(p,tpath, path, MAX_PATH_LEN, PTE_USER_RO);
210         int kfs_inode = kfs_lookup_path(tpath);
211         if (kfs_inode < 0)
212                 return -EINVAL;
213         struct proc *new_p = kfs_proc_create(kfs_inode);
214         pid = new_p->pid;
215         proc_decref(new_p, 1); // let go of the reference created in proc_create()
216         return pid;
217 }
218
219 /* Makes process PID runnable.  Consider moving the functionality to process.c */
220 static error_t sys_proc_run(struct proc *p, unsigned pid)
221 {
222         struct proc *target = pid2proc(pid);
223         error_t retval = 0;
224
225         if (!target)
226                 return -EBADPROC;
227         // note we can get interrupted here. it's not bad.
228         spin_lock_irqsave(&p->proc_lock);
229         // make sure we have access and it's in the right state to be activated
230         if (!proc_controls(p, target)) {
231                 proc_decref(target, 1);
232                 retval = -EPERM;
233         } else if (target->state != PROC_CREATED) {
234                 proc_decref(target, 1);
235                 retval = -EINVAL;
236         } else {
237                 __proc_set_state(target, PROC_RUNNABLE_S);
238                 schedule_proc(target);
239         }
240         spin_unlock_irqsave(&p->proc_lock);
241         proc_decref(target, 1);
242         return retval;
243 }
244
245 /* Destroy proc pid.  If this is called by the dying process, it will never
246  * return.  o/w it will return 0 on success, or an error.  Errors include:
247  * - EBADPROC: if there is no such process with pid
248  * - EPERM: if caller does not control pid */
249 static error_t sys_proc_destroy(struct proc *p, pid_t pid, int exitcode)
250 {
251         error_t r;
252         struct proc *p_to_die = pid2proc(pid);
253
254         if (!p_to_die) {
255                 set_errno(current_tf, ESRCH);
256                 return -1;
257         }
258         if (!proc_controls(p, p_to_die)) {
259                 proc_decref(p_to_die, 1);
260                 set_errno(current_tf, EPERM);
261                 return -1;
262         }
263         if (p_to_die == p) {
264                 // syscall code and pid2proc both have edible references, only need 1.
265                 p->exitcode = exitcode;
266                 proc_decref(p, 1);
267                 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
268         } else {
269                 panic("Destroying other processes is not supported yet.");
270                 //printk("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
271         }
272         proc_destroy(p_to_die);
273         return ESUCCESS;
274 }
275
276 static int sys_proc_yield(struct proc *p)
277 {
278         proc_yield(p);
279         return 0;
280 }
281
282 static ssize_t sys_run_binary(env_t* e, void *DANGEROUS binary_buf, size_t len,
283                               procinfo_t*DANGEROUS procinfo, size_t num_colors)
284 {
285         env_t* env = proc_create(NULL,0);
286         assert(env != NULL);
287
288         if(memcpy_from_user(e,e->env_procinfo,procinfo,sizeof(*procinfo)))
289                 return -1;
290         proc_init_procinfo(e);
291
292         env_load_icode(env,e,binary_buf,len);
293         __proc_set_state(env, PROC_RUNNABLE_S);
294         schedule_proc(env);
295         if(num_colors > 0) {
296                 env->cache_colors_map = cache_colors_map_alloc();
297                 for(int i=0; i<num_colors; i++)
298                         cache_color_alloc(llc_cache, env->cache_colors_map);
299         }
300         proc_decref(env, 1);
301         proc_yield(e);
302         return 0;
303 }
304
305 static ssize_t sys_fork(env_t* e)
306 {
307         // TODO: right now we only support fork for single-core processes
308         if(e->state != PROC_RUNNING_S)
309         {
310                 set_errno(current_tf,EINVAL);
311                 return -1;
312         }
313
314         env_t* env = proc_create(NULL,0);
315         assert(env != NULL);
316
317         env->heap_bottom = e->heap_bottom;
318         env->heap_top = e->heap_top;
319         env->ppid = e->pid;
320         env->env_tf = *current_tf;
321
322         env->cache_colors_map = cache_colors_map_alloc();
323         for(int i=0; i < llc_cache->num_colors; i++)
324                 if(GET_BITMASK_BIT(e->cache_colors_map,i))
325                         cache_color_alloc(llc_cache, env->cache_colors_map);
326
327         int copy_page(env_t* e, pte_t* pte, void* va, void* arg)
328         {
329                 env_t* env = (env_t*)arg;
330
331                 if(PAGE_PRESENT(*pte))
332                 {
333                         page_t* pp;
334                         if(upage_alloc(env,&pp,0))
335                                 return -1;
336                         if(page_insert(env->env_pgdir,pp,va,*pte & PTE_PERM))
337                         {
338                                 page_decref(pp);
339                                 return -1;
340                         }
341
342                         pagecopy(page2kva(pp),ppn2kva(PTE2PPN(*pte)));
343                 }
344                 else // PAGE_PAGED_OUT(*pte)
345                 {
346                         pte_t* newpte = pgdir_walk(env->env_pgdir,va,1);
347                         if(!newpte)
348                                 return -1;
349
350                         struct file* file = PTE2PFAULT_INFO(*pte)->file;
351                         pfault_info_t* newpfi = pfault_info_alloc(file);
352                         if(!newpfi)
353                                 return -1;
354
355                         *newpfi = *PTE2PFAULT_INFO(*pte);
356                         *newpte = PFAULT_INFO2PTE(newpfi);
357                 }
358
359                 return 0;
360         }
361
362         // copy procdata and procinfo
363         memcpy(env->env_procdata,e->env_procdata,sizeof(struct procdata));
364         memcpy(env->env_procinfo,e->env_procinfo,sizeof(struct procinfo));
365         env->env_procinfo->pid = env->pid;
366         env->env_procinfo->ppid = env->ppid;
367
368         // copy all memory below procdata
369         if(env_user_mem_walk(e,0,UDATA,&copy_page,env))
370         {
371                 proc_decref(env,2);
372                 set_errno(current_tf,ENOMEM);
373                 return -1;
374         }
375
376         __proc_set_state(env, PROC_RUNNABLE_S);
377         schedule_proc(env);
378
379         // don't decref the new process.
380         // that will happen when the parent waits for it.
381
382         printd("[PID %d] fork PID %d\n",e->pid,env->pid);
383
384         return env->pid;
385 }
386
387 intreg_t sys_exec(struct proc* p, int fd, procinfo_t* pi)
388 {
389         if(p->state != PROC_RUNNING_S)
390                 return -1;
391
392         int ret = -1;
393         struct file* f = file_open_from_fd(p,fd);
394         if(f == NULL) {
395                 set_errno(current_tf, EBADF);
396                 goto out;
397         }
398
399         if(memcpy_from_user(p,p->env_procinfo,pi,sizeof(procinfo_t))) {
400                 proc_destroy(p);
401                 goto out;
402         }
403         proc_init_procinfo(p);
404         memset(p->env_procdata, 0, sizeof(procdata_t));
405
406         env_user_mem_free(p,0,USTACKTOP);
407
408         if(load_elf(p,f))
409         {
410                 proc_destroy(p);
411                 goto out;
412         }
413         file_decref(f);
414         *current_tf = p->env_tf;
415         ret = 0;
416
417         printd("[PID %d] exec fd %d\n",p->pid,fd);
418
419 out:
420         return ret;
421 }
422
423 static ssize_t sys_trywait(env_t* e, pid_t pid, int* status)
424 {
425         struct proc* p = pid2proc(pid);
426
427         // TODO: this syscall is racy, so we only support for single-core procs
428         if(e->state != PROC_RUNNING_S)
429                 return -1;
430
431         // TODO: need to use errno properly.  sadly, ROS error codes conflict..
432
433         if(p)
434         {
435                 ssize_t ret;
436
437                 if(current->pid == p->ppid)
438                 {
439                         if(p->state == PROC_DYING)
440                         {
441                                 memcpy_to_user(e,status,&p->exitcode,sizeof(int));
442                                 printd("[PID %d] waited for PID %d (code %d)\n",
443                                        e->pid,p->pid,p->exitcode);
444                                 ret = 0;
445                         }
446                         else // not dead yet
447                         {
448                                 set_errno(current_tf,0);
449                                 ret = -1;
450                         }
451                 }
452                 else // not a child of the calling process
453                 {
454                         set_errno(current_tf,1);
455                         ret = -1;
456                 }
457
458                 // if the wait succeeded, decref twice
459                 proc_decref(p,1 + (ret == 0));
460                 return ret;
461         }
462
463         set_errno(current_tf,1);
464         return -1;
465 }
466
467 /************** Memory Management Syscalls **************/
468
469 static void *sys_mmap(struct proc* p, uintreg_t a1, uintreg_t a2, uintreg_t a3,
470                       uintreg_t* a456)
471 {
472         uintreg_t _a456[3];
473         if(memcpy_from_user(p,_a456,a456,3*sizeof(uintreg_t)))
474                 sys_proc_destroy(p,p->pid,-1);
475         return mmap(p,a1,a2,a3,_a456[0],_a456[1],_a456[2]);
476 }
477
478 static intreg_t sys_mprotect(struct proc* p, void* addr, size_t len, int prot)
479 {
480         return mprotect(p, addr, len, prot);
481 }
482
483 static intreg_t sys_munmap(struct proc* p, void* addr, size_t len)
484 {
485         return munmap(p, addr, len);
486 }
487
488 static void* sys_brk(struct proc *p, void* addr) {
489         ssize_t range;
490
491         spin_lock_irqsave(&p->proc_lock);
492
493         if((addr < p->heap_bottom) || (addr >= (void*)USTACKBOT))
494                 goto out;
495
496         uintptr_t real_heap_top = ROUNDUP((uintptr_t)p->heap_top,PGSIZE);
497         uintptr_t real_new_heap_top = ROUNDUP((uintptr_t)addr,PGSIZE);
498         range = real_new_heap_top - real_heap_top;
499
500         if (range > 0) {
501                 if(__do_mmap(p, real_heap_top, range, PROT_READ | PROT_WRITE,
502                              MAP_FIXED | MAP_ANONYMOUS, NULL, 0) == MAP_FAILED)
503                         goto out;
504         }
505         else if (range < 0) {
506                 if(__munmap(p, (void*)real_new_heap_top, -range))
507                         goto out;
508         }
509         p->heap_top = addr;
510
511 out:
512         spin_unlock_irqsave(&p->proc_lock);
513         return p->heap_top;
514 }
515
516 static ssize_t sys_shared_page_alloc(env_t* p1,
517                                      void**DANGEROUS _addr, pid_t p2_id,
518                                      int p1_flags, int p2_flags
519                                     )
520 {
521         //if (!VALID_USER_PERMS(p1_flags)) return -EPERM;
522         //if (!VALID_USER_PERMS(p2_flags)) return -EPERM;
523
524         void * COUNT(1) * COUNT(1) addr = user_mem_assert(p1, _addr, sizeof(void *),
525                                                       PTE_USER_RW);
526         struct proc *p2 = pid2proc(p2_id);
527         if (!p2)
528                 return -EBADPROC;
529
530         page_t* page;
531         error_t e = upage_alloc(p1, &page,1);
532         if (e < 0) {
533                 proc_decref(p2, 1);
534                 return e;
535         }
536
537         void* p2_addr = page_insert_in_range(p2->env_pgdir, page,
538                         (void*SNT)UTEXT, (void*SNT)UTOP, p2_flags);
539         if (p2_addr == NULL) {
540                 page_free(page);
541                 proc_decref(p2, 1);
542                 return -EFAIL;
543         }
544
545         void* p1_addr = page_insert_in_range(p1->env_pgdir, page,
546                         (void*SNT)UTEXT, (void*SNT)UTOP, p1_flags);
547         if(p1_addr == NULL) {
548                 page_remove(p2->env_pgdir, p2_addr);
549                 page_free(page);
550                 proc_decref(p2, 1);
551                 return -EFAIL;
552         }
553         *addr = p1_addr;
554         proc_decref(p2, 1);
555         return ESUCCESS;
556 }
557
558 static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
559 {
560         return -1;
561 }
562
563
564 /************** Resource Request Syscalls **************/
565
566 /* sys_resource_req(): called directly from dispatch table. */
567
568 /************** Platform Specific Syscalls **************/
569
570 //Read a buffer over the serial port
571 static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
572 {
573         if (len == 0)
574                 return 0;
575
576         #ifdef __CONFIG_SERIAL_IO__
577             char *COUNT(len) buf = user_mem_assert(e, _buf, len, PTE_USER_RO);
578                 size_t bytes_read = 0;
579                 int c;
580                 while((c = serial_read_byte()) != -1) {
581                         buf[bytes_read++] = (uint8_t)c;
582                         if(bytes_read == len) break;
583                 }
584                 return (ssize_t)bytes_read;
585         #else
586                 return -EINVAL;
587         #endif
588 }
589
590 //Write a buffer over the serial port
591 static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
592 {
593         if (len == 0)
594                 return 0;
595         #ifdef __CONFIG_SERIAL_IO__
596                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_USER_RO);
597                 for(int i =0; i<len; i++)
598                         serial_send_byte(buf[i]);
599                 return (ssize_t)len;
600         #else
601                 return -EINVAL;
602         #endif
603 }
604
605 #ifdef __CONFIG_NETWORKING__
606 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
607 static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf)
608 {
609         if (eth_up) {
610
611                 uint32_t len;
612                 char *ptr;
613
614                 spin_lock(&packet_buffers_lock);
615
616                 if (num_packet_buffers == 0) {
617                         spin_unlock(&packet_buffers_lock);
618                         return 0;
619                 }
620
621                 ptr = packet_buffers[packet_buffers_head];
622                 len = packet_buffers_sizes[packet_buffers_head];
623
624                 num_packet_buffers--;
625                 packet_buffers_head = (packet_buffers_head + 1) % MAX_PACKET_BUFFERS;
626
627                 spin_unlock(&packet_buffers_lock);
628
629                 char* _buf = user_mem_assert(e, buf, len, PTE_U);
630
631                 memcpy(_buf, ptr, len);
632
633                 kfree(ptr);
634
635                 return len;
636         }
637         else
638                 return -EINVAL;
639 }
640
641 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
642 static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
643 {
644         if (eth_up) {
645
646                 if (len == 0)
647                         return 0;
648
649                 // HACK TO BYPASS HACK
650                 int just_sent = send_frame(buf, len);
651
652                 if (just_sent < 0) {
653                         printk("Packet send fail\n");
654                         return 0;
655                 }
656
657                 return just_sent;
658
659                 // END OF RECURSIVE HACK
660 /*
661                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
662                 int total_sent = 0;
663                 int just_sent = 0;
664                 int cur_packet_len = 0;
665                 while (total_sent != len) {
666                         cur_packet_len = ((len - total_sent) > MTU) ? MTU : (len - total_sent);
667                         char dest_mac[6] = APPSERVER_MAC_ADDRESS;
668                         char* wrap_buffer = eth_wrap(_buf + total_sent, cur_packet_len, device_mac, dest_mac, APPSERVER_PORT);
669                         just_sent = send_frame(wrap_buffer, cur_packet_len + sizeof(struct ETH_Header));
670
671                         if (just_sent < 0)
672                                 return 0; // This should be an error code of its own
673
674                         if (wrap_buffer)
675                                 kfree(wrap_buffer);
676
677                         total_sent += cur_packet_len;
678                 }
679
680                 return (ssize_t)len;
681 */
682         }
683         else
684                 return -EINVAL;
685 }
686
687 static ssize_t sys_eth_get_mac_addr(env_t* e, char *DANGEROUS buf) 
688 {
689         if (eth_up) {
690                 for (int i = 0; i < 6; i++)
691                         buf[i] = device_mac[i];
692                 return 0;
693         }
694         else
695                 return -EINVAL;
696 }
697
698 static int sys_eth_recv_check(env_t* e) 
699 {
700         if (num_packet_buffers != 0) 
701                 return 1;
702         else
703                 return 0;
704 }
705
706 #endif // Network
707
708 // Syscalls below here are serviced by the appserver for now.
709 #define ufe(which,a0,a1,a2,a3) \
710         frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
711                            (int)(a0),(int)(a1),(int)(a2),(int)(a3))
712
713 intreg_t sys_write(struct proc* p, int fd, const void* buf, int len)
714 {
715         void* kbuf = user_memdup_errno(p,buf,len);
716         if(kbuf == NULL)
717                 return -1;
718         int ret = ufe(write,fd,PADDR(kbuf),len,0);
719         user_memdup_free(p,kbuf);
720         return ret;
721 }
722
723 intreg_t sys_read(struct proc* p, int fd, void* buf, int len)
724 {
725         void* kbuf = kmalloc_errno(len);
726         if(kbuf == NULL)
727                 return -1;
728         int ret = ufe(read,fd,PADDR(kbuf),len,0);
729         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
730                 ret = -1;
731         user_memdup_free(p,kbuf);
732         return ret;
733 }
734
735 intreg_t sys_pwrite(struct proc* p, int fd, const void* buf, int len, int offset)
736 {
737         void* kbuf = user_memdup_errno(p,buf,len);
738         if(kbuf == NULL)
739                 return -1;
740         int ret = ufe(pwrite,fd,PADDR(kbuf),len,offset);
741         user_memdup_free(p,kbuf);
742         return ret;
743 }
744
745 intreg_t sys_pread(struct proc* p, int fd, void* buf, int len, int offset)
746 {
747         void* kbuf = kmalloc_errno(len);
748         if(kbuf == NULL)
749                 return -1;
750         int ret = ufe(pread,fd,PADDR(kbuf),len,offset);
751         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
752                 ret = -1;
753         user_memdup_free(p,kbuf);
754         return ret;
755 }
756
757 intreg_t sys_open(struct proc* p, const char* path, int oflag, int mode)
758 {
759         char* fn = user_strdup_errno(p,path,PGSIZE);
760         if(fn == NULL)
761                 return -1;
762         int ret = ufe(open,PADDR(fn),oflag,mode,0);
763         user_memdup_free(p,fn);
764         return ret;
765 }
766 intreg_t sys_close(struct proc* p, int fd)
767 {
768         return ufe(close,fd,0,0,0);
769 }
770
771 #define NEWLIB_STAT_SIZE 64
772 intreg_t sys_fstat(struct proc* p, int fd, void* buf)
773 {
774         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
775         int ret = ufe(fstat,fd,PADDR(kbuf),0,0);
776         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
777                 ret = -1;
778         kfree(kbuf);
779         return ret;
780 }
781
782 intreg_t sys_stat(struct proc* p, const char* path, void* buf)
783 {
784         char* fn = user_strdup_errno(p,path,PGSIZE);
785         if(fn == NULL)
786                 return -1;
787
788         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
789         int ret = ufe(stat,PADDR(fn),PADDR(kbuf),0,0);
790         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
791                 ret = -1;
792
793         user_memdup_free(p,fn);
794         kfree(kbuf);
795         return ret;
796 }
797
798 intreg_t sys_lstat(struct proc* p, const char* path, void* buf)
799 {
800         char* fn = user_strdup_errno(p,path,PGSIZE);
801         if(fn == NULL)
802                 return -1;
803
804         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
805         int ret = ufe(lstat,PADDR(fn),PADDR(kbuf),0,0);
806         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
807                 ret = -1;
808
809         user_memdup_free(p,fn);
810         kfree(kbuf);
811         return ret;
812 }
813
814 intreg_t sys_fcntl(struct proc* p, int fd, int cmd, int arg)
815 {
816         return ufe(fcntl,fd,cmd,arg,0);
817 }
818
819 intreg_t sys_access(struct proc* p, const char* path, int type)
820 {
821         char* fn = user_strdup_errno(p,path,PGSIZE);
822         if(fn == NULL)
823                 return -1;
824         int ret = ufe(access,PADDR(fn),type,0,0);
825         user_memdup_free(p,fn);
826         return ret;
827 }
828
829 intreg_t sys_umask(struct proc* p, int mask)
830 {
831         return ufe(umask,mask,0,0,0);
832 }
833
834 intreg_t sys_chmod(struct proc* p, const char* path, int mode)
835 {
836         char* fn = user_strdup_errno(p,path,PGSIZE);
837         if(fn == NULL)
838                 return -1;
839         int ret = ufe(chmod,PADDR(fn),mode,0,0);
840         user_memdup_free(p,fn);
841         return ret;
842 }
843
844 intreg_t sys_lseek(struct proc* p, int fd, int offset, int whence)
845 {
846         return ufe(lseek,fd,offset,whence,0);
847 }
848
849 intreg_t sys_link(struct proc* p, const char* _old, const char* _new)
850 {
851         char* oldpath = user_strdup_errno(p,_old,PGSIZE);
852         if(oldpath == NULL)
853                 return -1;
854
855         char* newpath = user_strdup_errno(p,_new,PGSIZE);
856         if(newpath == NULL)
857         {
858                 user_memdup_free(p,oldpath);
859                 return -1;
860         }
861
862         int ret = ufe(link,PADDR(oldpath),PADDR(newpath),0,0);
863         user_memdup_free(p,oldpath);
864         user_memdup_free(p,newpath);
865         return ret;
866 }
867
868 intreg_t sys_unlink(struct proc* p, const char* path)
869 {
870         char* fn = user_strdup_errno(p,path,PGSIZE);
871         if(fn == NULL)
872                 return -1;
873         int ret = ufe(unlink,PADDR(fn),0,0,0);
874         user_memdup_free(p,fn);
875         return ret;
876 }
877
878 intreg_t sys_chdir(struct proc* p, const char* path)
879 {
880         char* fn = user_strdup_errno(p,path,PGSIZE);
881         if(fn == NULL)
882                 return -1;
883         int ret = ufe(chdir,PADDR(fn),0,0,0);
884         user_memdup_free(p,fn);
885         return ret;
886 }
887
888 intreg_t sys_getcwd(struct proc* p, char* pwd, int size)
889 {
890         void* kbuf = kmalloc_errno(size);
891         if(kbuf == NULL)
892                 return -1;
893         int ret = ufe(read,PADDR(kbuf),size,0,0);
894         if(ret != -1 && memcpy_to_user_errno(p,pwd,kbuf,strnlen(kbuf,size)))
895                 ret = -1;
896         user_memdup_free(p,kbuf);
897         return ret;
898 }
899
900 intreg_t sys_gettimeofday(struct proc* p, int* buf)
901 {
902         static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
903         static int t0 = 0;
904
905         spin_lock(&gtod_lock);
906         if(t0 == 0)
907 #ifdef __CONFIG_APPSERVER__
908                 t0 = ufe(time,0,0,0,0);
909 #else
910                 // Nanwan's birthday, bitches!!
911                 t0 = 1242129600;
912 #endif 
913         spin_unlock(&gtod_lock);
914
915         long long dt = read_tsc();
916         int kbuf[2] = {t0+dt/system_timing.tsc_freq,
917             (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
918
919         return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
920 }
921
922 #define SIZEOF_STRUCT_TERMIOS 60
923 intreg_t sys_tcgetattr(struct proc* p, int fd, void* termios_p)
924 {
925         int* kbuf = kmalloc(SIZEOF_STRUCT_TERMIOS,0);
926         int ret = ufe(tcgetattr,fd,PADDR(kbuf),0,0);
927         if(ret != -1 && memcpy_to_user_errno(p,termios_p,kbuf,SIZEOF_STRUCT_TERMIOS))
928                 ret = -1;
929         kfree(kbuf);
930         return ret;
931 }
932
933 intreg_t sys_tcsetattr(struct proc* p, int fd, int optional_actions, const void* termios_p)
934 {
935         void* kbuf = user_memdup_errno(p,termios_p,SIZEOF_STRUCT_TERMIOS);
936         if(kbuf == NULL)
937                 return -1;
938         int ret = ufe(tcsetattr,fd,optional_actions,PADDR(kbuf),0);
939         user_memdup_free(p,kbuf);
940         return ret;
941 }
942 /************** Syscall Invokation **************/
943
944 /* Executes the given syscall.
945  *
946  * Note tf is passed in, which points to the tf of the context on the kernel
947  * stack.  If any syscall needs to block, it needs to save this info, as well as
948  * any silly state.
949  *
950  * TODO: Build a dispatch table instead of switching on the syscallno
951  * Dispatches to the correct kernel function, passing the arguments.
952  */
953 intreg_t syscall(struct proc *p, uintreg_t syscallno, uintreg_t a1,
954                  uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
955 {
956         // Initialize the return value and error code returned to 0
957         proc_set_syscall_retval(current_tf, 0);
958         set_errno(current_tf,0);
959
960         typedef intreg_t (*syscall_t)(struct proc*,uintreg_t,uintreg_t,
961                                       uintreg_t,uintreg_t,uintreg_t);
962
963         const static syscall_t syscall_table[] = {
964                 [SYS_null] = (syscall_t)sys_null,
965                 [SYS_cache_buster] = (syscall_t)sys_cache_buster,
966                 [SYS_cache_invalidate] = (syscall_t)sys_cache_invalidate,
967                 [SYS_reboot] = (syscall_t)reboot,
968                 [SYS_cputs] = (syscall_t)sys_cputs,
969                 [SYS_cgetc] = (syscall_t)sys_cgetc,
970                 [SYS_getcpuid] = (syscall_t)sys_getcpuid,
971                 [SYS_getvcoreid] = (syscall_t)sys_getvcoreid,
972                 [SYS_getpid] = (syscall_t)sys_getpid,
973                 [SYS_proc_create] = (syscall_t)sys_proc_create,
974                 [SYS_proc_run] = (syscall_t)sys_proc_run,
975                 [SYS_proc_destroy] = (syscall_t)sys_proc_destroy,
976                 [SYS_yield] = (syscall_t)sys_proc_yield,
977                 [SYS_run_binary] = (syscall_t)sys_run_binary,
978                 [SYS_fork] = (syscall_t)sys_fork,
979                 [SYS_exec] = (syscall_t)sys_exec,
980                 [SYS_trywait] = (syscall_t)sys_trywait,
981                 [SYS_mmap] = (syscall_t)sys_mmap,
982                 [SYS_munmap] = (syscall_t)sys_munmap,
983                 [SYS_mprotect] = (syscall_t)sys_mprotect,
984                 [SYS_brk] = (syscall_t)sys_brk,
985                 [SYS_shared_page_alloc] = (syscall_t)sys_shared_page_alloc,
986                 [SYS_shared_page_free] = (syscall_t)sys_shared_page_free,
987                 [SYS_resource_req] = (syscall_t)resource_req,
988         #ifdef __CONFIG_SERIAL_IO__
989                 [SYS_serial_read] = (syscall_t)sys_serial_read,
990                 [SYS_serial_write] = (syscall_t)sys_serial_write,
991         #endif
992         #ifdef __CONFIG_NETWORKING__
993                 [SYS_eth_read] = (syscall_t)sys_eth_read,
994                 [SYS_eth_write] = (syscall_t)sys_eth_write,
995                 [SYS_eth_get_mac_addr] = (syscall_t)sys_eth_get_mac_addr,
996                 [SYS_eth_recv_check] = (syscall_t)sys_eth_recv_check,
997         #endif
998                 // Syscalls serviced by the appserver for now.
999                 [SYS_read] = (syscall_t)sys_read,
1000                 [SYS_write] = (syscall_t)sys_write,
1001                 [SYS_open] = (syscall_t)sys_open,
1002                 [SYS_close] = (syscall_t)sys_close,
1003                 [SYS_fstat] = (syscall_t)sys_fstat,
1004                 [SYS_stat] = (syscall_t)sys_stat,
1005                 [SYS_lstat] = (syscall_t)sys_lstat,
1006                 [SYS_fcntl] = (syscall_t)sys_fcntl,
1007                 [SYS_access] = (syscall_t)sys_access,
1008                 [SYS_umask] = (syscall_t)sys_umask,
1009                 [SYS_chmod] = (syscall_t)sys_chmod,
1010                 [SYS_lseek] = (syscall_t)sys_lseek,
1011                 [SYS_link] = (syscall_t)sys_link,
1012                 [SYS_unlink] = (syscall_t)sys_unlink,
1013                 [SYS_chdir] = (syscall_t)sys_chdir,
1014                 [SYS_getcwd] = (syscall_t)sys_getcwd,
1015                 [SYS_gettimeofday] = (syscall_t)sys_gettimeofday,
1016                 [SYS_tcgetattr] = (syscall_t)sys_tcgetattr,
1017                 [SYS_tcsetattr] = (syscall_t)sys_tcsetattr
1018         };
1019
1020         const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
1021
1022         //printk("Incoming syscall on core: %d number: %d\n    a1: %x\n   "
1023         //       " a2: %x\n    a3: %x\n    a4: %x\n    a5: %x\n", core_id(),
1024         //       syscallno, a1, a2, a3, a4, a5);
1025
1026         if(syscallno > max_syscall || syscall_table[syscallno] == NULL)
1027                 panic("Invalid syscall number %d for proc %x!", syscallno, *p);
1028
1029         return syscall_table[syscallno](p,a1,a2,a3,a4,a5);
1030 }
1031
1032 intreg_t syscall_async(struct proc *p, syscall_req_t *call)
1033 {
1034         return syscall(p, call->num, call->args[0], call->args[1],
1035                        call->args[2], call->args[3], call->args[4]);
1036 }
1037
1038 /* You should already have a refcnt'd ref to p before calling this */
1039 intreg_t process_generic_syscalls(struct proc *p, size_t max)
1040 {
1041         size_t count = 0;
1042         syscall_back_ring_t* sysbr = &p->syscallbackring;
1043
1044         /* make sure the proc is still alive, and keep it from dying from under us
1045          * incref will return ESUCCESS on success.  This might need some thought
1046          * regarding when the incref should have happened (like by whoever passed us
1047          * the *p). */
1048         // TODO: ought to be unnecessary, if you called this right, kept here for
1049         // now in case anyone actually uses the ARSCs.
1050         proc_incref(p, 1);
1051
1052         // max is the most we'll process.  max = 0 means do as many as possible
1053         while (RING_HAS_UNCONSUMED_REQUESTS(sysbr) && ((!max)||(count < max)) ) {
1054                 if (!count) {
1055                         // ASSUME: one queue per process
1056                         // only switch cr3 for the very first request for this queue
1057                         // need to switch to the right context, so we can handle the user pointer
1058                         // that points to a data payload of the syscall
1059                         lcr3(p->env_cr3);
1060                 }
1061                 count++;
1062                 //printk("DEBUG PRE: sring->req_prod: %d, sring->rsp_prod: %d\n",
1063                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1064                 // might want to think about 0-ing this out, if we aren't
1065                 // going to explicitly fill in all fields
1066                 syscall_rsp_t rsp;
1067                 // this assumes we get our answer immediately for the syscall.
1068                 syscall_req_t* req = RING_GET_REQUEST(sysbr, ++(sysbr->req_cons));
1069                 rsp.retval = syscall_async(p, req);
1070                 // write response into the slot it came from
1071                 memcpy(req, &rsp, sizeof(syscall_rsp_t));
1072                 // update our counter for what we've produced (assumes we went in order!)
1073                 (sysbr->rsp_prod_pvt)++;
1074                 RING_PUSH_RESPONSES(sysbr);
1075                 //printk("DEBUG POST: sring->req_prod: %d, sring->rsp_prod: %d\n",
1076                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1077         }
1078         // load sane page tables (and don't rely on decref to do it for you).
1079         lcr3(boot_cr3);
1080         proc_decref(p, 1);
1081         return (intreg_t)count;
1082 }
1083