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