Made pmap.c more consistent with demand paging
[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 <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 __NETWORK__
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                 return -EBADPROC;
256         if (!proc_controls(p, p_to_die)) {
257                 proc_decref(p_to_die, 1);
258                 return -EPERM;
259         }
260         if (p_to_die == p) {
261                 // syscall code and pid2proc both have edible references, only need 1.
262                 p->exitcode = exitcode;
263                 proc_decref(p, 1);
264                 printd("[PID %d] proc exiting gracefully (code %d)\n", p->pid,exitcode);
265         } else {
266                 panic("Destroying other processes is not supported yet.");
267                 //printk("[%d] destroying proc %d\n", p->pid, p_to_die->pid);
268         }
269         proc_destroy(p_to_die);
270         return ESUCCESS;
271 }
272
273 static int sys_proc_yield(struct proc *p)
274 {
275         proc_yield(p);
276         return 0;
277 }
278
279 static ssize_t sys_run_binary(env_t* e, void *DANGEROUS binary_buf, size_t len,
280                               procinfo_t*DANGEROUS procinfo, size_t num_colors)
281 {
282         env_t* env = proc_create(NULL,0);
283         assert(env != NULL);
284
285         if(memcpy_from_user(e,e->env_procinfo,procinfo,sizeof(*procinfo)))
286                 return -1;
287         proc_init_procinfo(e);
288
289         env_load_icode(env,e,binary_buf,len);
290         __proc_set_state(env, PROC_RUNNABLE_S);
291         schedule_proc(env);
292         if(num_colors > 0) {
293                 env->cache_colors_map = cache_colors_map_alloc();
294                 for(int i=0; i<num_colors; i++)
295                         cache_color_alloc(llc_cache, env->cache_colors_map);
296         }
297         proc_decref(env, 1);
298         proc_yield(e);
299         return 0;
300 }
301
302 static ssize_t sys_fork(env_t* e)
303 {
304         // TODO: right now we only support fork for single-core processes
305         if(e->state != PROC_RUNNING_S)
306         {
307                 set_errno(current_tf,EINVAL);
308                 return -1;
309         }
310
311         env_t* env = proc_create(NULL,0);
312         assert(env != NULL);
313
314         env->heap_bottom = e->heap_bottom;
315         env->heap_top = e->heap_top;
316         env->ppid = e->pid;
317         env->env_tf = *current_tf;
318
319         env->cache_colors_map = cache_colors_map_alloc();
320         for(int i=0; i < llc_cache->num_colors; i++)
321                 if(GET_BITMASK_BIT(e->cache_colors_map,i))
322                         cache_color_alloc(llc_cache, env->cache_colors_map);
323
324         int copy_page(env_t* e, pte_t* pte, void* va, void* arg)
325         {
326                 env_t* env = (env_t*)arg;
327
328                 if(PAGE_PRESENT(*pte))
329                 {
330                         page_t* pp;
331                         if(upage_alloc(env,&pp,0))
332                                 return -1;
333                         if(page_insert(env->env_pgdir,pp,va,*pte & PTE_PERM))
334                         {
335                                 page_decref(pp);
336                                 return -1;
337                         }
338
339                         pagecopy(page2kva(pp),ppn2kva(PTE2PPN(*pte)));
340                 }
341                 else // PAGE_PAGED_OUT(*pte)
342                 {
343                         pte_t* newpte = pgdir_walk(env->env_pgdir,va,1);
344                         if(!newpte)
345                                 return -1;
346
347                         struct file* file = PTE2PFAULT_INFO(*pte)->file;
348                         pfault_info_t* newpfi = pfault_info_alloc(file);
349                         if(!newpfi)
350                                 return -1;
351
352                         *newpfi = *PTE2PFAULT_INFO(*pte);
353                         *newpte = PFAULT_INFO2PTE(newpfi);
354                 }
355
356                 return 0;
357         }
358
359         // copy procdata and procinfo
360         memcpy(env->env_procdata,e->env_procdata,sizeof(struct procdata));
361         memcpy(env->env_procinfo,e->env_procinfo,sizeof(struct procinfo));
362         env->env_procinfo->pid = env->pid;
363         env->env_procinfo->ppid = env->ppid;
364
365         // copy all memory below procdata
366         if(env_user_mem_walk(e,0,UDATA,&copy_page,env))
367         {
368                 proc_decref(env,2);
369                 set_errno(current_tf,ENOMEM);
370                 return -1;
371         }
372
373         __proc_set_state(env, PROC_RUNNABLE_S);
374         schedule_proc(env);
375
376         // don't decref the new process.
377         // that will happen when the parent waits for it.
378
379         printd("[PID %d] fork PID %d\n",e->pid,env->pid);
380
381         return env->pid;
382 }
383
384 intreg_t sys_exec(struct proc* p, int fd, procinfo_t* pi)
385 {
386         if(p->state != PROC_RUNNING_S)
387                 return -1;
388
389         int ret = -1;
390         struct file* f = file_open_from_fd(p,fd);
391         if(f == NULL)
392                 goto out;
393
394
395         if(memcpy_from_user(p,p->env_procinfo,pi,sizeof(procinfo_t)))
396         {
397                 proc_destroy(p);
398                 goto out;
399         }
400         proc_init_procinfo(p);
401
402         env_user_mem_free(p,0,USTACKTOP);
403
404         if(load_elf(p,f))
405         {
406                 proc_destroy(p);
407                 goto out;
408         }
409         file_decref(f);
410         *current_tf = p->env_tf;
411         ret = 0;
412
413         printd("[PID %d] exec fd %d\n",p->pid,fd);
414
415 out:
416         return ret;
417 }
418
419 static ssize_t sys_trywait(env_t* e, pid_t pid, int* status)
420 {
421         struct proc* p = pid2proc(pid);
422
423         // TODO: this syscall is racy, so we only support for single-core procs
424         if(e->state != PROC_RUNNING_S)
425                 return -1;
426
427         // TODO: need to use errno properly.  sadly, ROS error codes conflict..
428
429         if(p)
430         {
431                 ssize_t ret;
432
433                 if(current->pid == p->ppid)
434                 {
435                         if(p->state == PROC_DYING)
436                         {
437                                 memcpy_to_user(e,status,&p->exitcode,sizeof(int));
438                                 printd("[PID %d] waited for PID %d (code %d)\n",
439                                        e->pid,p->pid,p->exitcode);
440                                 ret = 0;
441                         }
442                         else // not dead yet
443                         {
444                                 set_errno(current_tf,0);
445                                 ret = -1;
446                         }
447                 }
448                 else // not a child of the calling process
449                 {
450                         set_errno(current_tf,1);
451                         ret = -1;
452                 }
453
454                 // if the wait succeeded, decref twice
455                 proc_decref(p,1 + (ret == 0));
456                 return ret;
457         }
458
459         set_errno(current_tf,1);
460         return -1;
461 }
462
463 /************** Memory Management Syscalls **************/
464
465 static void *sys_mmap(struct proc* p, uintreg_t a1, uintreg_t a2, uintreg_t a3,
466                       uintreg_t* a456)
467 {
468         uintreg_t _a456[3];
469         if(memcpy_from_user(p,_a456,a456,3*sizeof(uintreg_t)))
470                 sys_proc_destroy(p,p->pid,-1);
471         return mmap(p,a1,a2,a3,_a456[0],_a456[1],_a456[2]);
472 }
473
474 static intreg_t sys_mprotect(struct proc* p, void* addr, size_t len, int prot)
475 {
476         return mprotect(p, addr, len, prot);
477 }
478
479 static intreg_t sys_munmap(struct proc* p, void* addr, size_t len)
480 {
481         return munmap(p, addr, len);
482 }
483
484 static void* sys_brk(struct proc *p, void* addr) {
485         ssize_t range;
486
487         spin_lock_irqsave(&p->proc_lock);
488
489         if((addr < p->heap_bottom) || (addr >= (void*)USTACKBOT))
490                 goto out;
491
492         uintptr_t real_heap_top = ROUNDUP((uintptr_t)p->heap_top,PGSIZE);
493         uintptr_t real_new_heap_top = ROUNDUP((uintptr_t)addr,PGSIZE);
494         range = real_new_heap_top - real_heap_top;
495
496         if (range > 0) {
497                 if(__do_mmap(p, real_heap_top, range, PROT_READ | PROT_WRITE,
498                              MAP_FIXED | MAP_ANONYMOUS, NULL, 0))
499                         goto out;
500         }
501         else if (range < 0) {
502                 if(__munmap(p, (void*)real_new_heap_top, -range))
503                         goto out;
504         }
505         p->heap_top = addr;
506
507 out:
508         spin_unlock_irqsave(&p->proc_lock);
509         return p->heap_top;
510 }
511
512 static ssize_t sys_shared_page_alloc(env_t* p1,
513                                      void**DANGEROUS _addr, pid_t p2_id,
514                                      int p1_flags, int p2_flags
515                                     )
516 {
517         //if (!VALID_USER_PERMS(p1_flags)) return -EPERM;
518         //if (!VALID_USER_PERMS(p2_flags)) return -EPERM;
519
520         void * COUNT(1) * COUNT(1) addr = user_mem_assert(p1, _addr, sizeof(void *),
521                                                       PTE_USER_RW);
522         struct proc *p2 = pid2proc(p2_id);
523         if (!p2)
524                 return -EBADPROC;
525
526         page_t* page;
527         error_t e = upage_alloc(p1, &page,1);
528         if (e < 0) {
529                 proc_decref(p2, 1);
530                 return e;
531         }
532
533         void* p2_addr = page_insert_in_range(p2->env_pgdir, page,
534                         (void*SNT)UTEXT, (void*SNT)UTOP, p2_flags);
535         if (p2_addr == NULL) {
536                 page_free(page);
537                 proc_decref(p2, 1);
538                 return -EFAIL;
539         }
540
541         void* p1_addr = page_insert_in_range(p1->env_pgdir, page,
542                         (void*SNT)UTEXT, (void*SNT)UTOP, p1_flags);
543         if(p1_addr == NULL) {
544                 page_remove(p2->env_pgdir, p2_addr);
545                 page_free(page);
546                 proc_decref(p2, 1);
547                 return -EFAIL;
548         }
549         *addr = p1_addr;
550         proc_decref(p2, 1);
551         return ESUCCESS;
552 }
553
554 static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
555 {
556         return -1;
557 }
558
559
560 /************** Resource Request Syscalls **************/
561
562 /* sys_resource_req(): called directly from dispatch table. */
563
564 /************** Platform Specific Syscalls **************/
565
566 //Read a buffer over the serial port
567 static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
568 {
569         if (len == 0)
570                 return 0;
571
572         #ifdef SERIAL_IO
573             char *COUNT(len) buf = user_mem_assert(e, _buf, len, PTE_USER_RO);
574                 size_t bytes_read = 0;
575                 int c;
576                 while((c = serial_read_byte()) != -1) {
577                         buf[bytes_read++] = (uint8_t)c;
578                         if(bytes_read == len) break;
579                 }
580                 return (ssize_t)bytes_read;
581         #else
582                 return -EINVAL;
583         #endif
584 }
585
586 //Write a buffer over the serial port
587 static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
588 {
589         if (len == 0)
590                 return 0;
591         #ifdef SERIAL_IO
592                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_USER_RO);
593                 for(int i =0; i<len; i++)
594                         serial_send_byte(buf[i]);
595                 return (ssize_t)len;
596         #else
597                 return -EINVAL;
598         #endif
599 }
600
601 #ifdef __NETWORK__
602 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
603 static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf)
604 {
605         if (eth_up) {
606
607                 uint32_t len;
608                 char *ptr;
609
610                 spin_lock(&packet_buffers_lock);
611
612                 if (num_packet_buffers == 0) {
613                         spin_unlock(&packet_buffers_lock);
614                         return 0;
615                 }
616
617                 ptr = packet_buffers[packet_buffers_head];
618                 len = packet_buffers_sizes[packet_buffers_head];
619
620                 num_packet_buffers--;
621                 packet_buffers_head = (packet_buffers_head + 1) % MAX_PACKET_BUFFERS;
622
623                 spin_unlock(&packet_buffers_lock);
624
625                 char* _buf = user_mem_assert(e, buf, len, PTE_U);
626
627                 memcpy(_buf, ptr, len);
628
629                 kfree(ptr);
630
631                 return len;
632         }
633         else
634                 return -EINVAL;
635 }
636
637 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
638 static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
639 {
640         if (eth_up) {
641
642                 if (len == 0)
643                         return 0;
644
645                 // HACK TO BYPASS HACK
646                 int just_sent = send_frame(buf, len);
647
648                 if (just_sent < 0) {
649                         printk("Packet send fail\n");
650                         return 0;
651                 }
652
653                 return just_sent;
654
655                 // END OF RECURSIVE HACK
656 /*
657                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
658                 int total_sent = 0;
659                 int just_sent = 0;
660                 int cur_packet_len = 0;
661                 while (total_sent != len) {
662                         cur_packet_len = ((len - total_sent) > MTU) ? MTU : (len - total_sent);
663                         char dest_mac[6] = APPSERVER_MAC_ADDRESS;
664                         char* wrap_buffer = eth_wrap(_buf + total_sent, cur_packet_len, device_mac, dest_mac, APPSERVER_PORT);
665                         just_sent = send_frame(wrap_buffer, cur_packet_len + sizeof(struct ETH_Header));
666
667                         if (just_sent < 0)
668                                 return 0; // This should be an error code of its own
669
670                         if (wrap_buffer)
671                                 kfree(wrap_buffer);
672
673                         total_sent += cur_packet_len;
674                 }
675
676                 return (ssize_t)len;
677 */
678         }
679         else
680                 return -EINVAL;
681 }
682
683 static ssize_t sys_eth_get_mac_addr(env_t* e, char *DANGEROUS buf) 
684 {
685         if (eth_up) {
686                 for (int i = 0; i < 6; i++)
687                         buf[i] = device_mac[i];
688                 return 0;
689         }
690         else
691                 return -EINVAL;
692 }
693
694 static int sys_eth_recv_check(env_t* e) 
695 {
696         if (num_packet_buffers != 0) 
697                 return 1;
698         else
699                 return 0;
700 }
701
702 #endif // Network
703
704 // Syscalls below here are serviced by the appserver for now.
705 #define ufe(which,a0,a1,a2,a3) \
706         frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
707                            (int)(a0),(int)(a1),(int)(a2),(int)(a3))
708
709 intreg_t sys_write(struct proc* p, int fd, const void* buf, int len)
710 {
711         void* kbuf = user_memdup_errno(p,buf,len);
712         if(kbuf == NULL)
713                 return -1;
714         int ret = ufe(write,fd,PADDR(kbuf),len,0);
715         user_memdup_free(p,kbuf);
716         return ret;
717 }
718
719 intreg_t sys_read(struct proc* p, int fd, void* buf, int len)
720 {
721         void* kbuf = kmalloc_errno(len);
722         if(kbuf == NULL)
723                 return -1;
724         int ret = ufe(read,fd,PADDR(kbuf),len,0);
725         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
726                 ret = -1;
727         user_memdup_free(p,kbuf);
728         return ret;
729 }
730
731 intreg_t sys_pwrite(struct proc* p, int fd, const void* buf, int len, int offset)
732 {
733         void* kbuf = user_memdup_errno(p,buf,len);
734         if(kbuf == NULL)
735                 return -1;
736         int ret = ufe(pwrite,fd,PADDR(kbuf),len,offset);
737         user_memdup_free(p,kbuf);
738         return ret;
739 }
740
741 intreg_t sys_pread(struct proc* p, int fd, void* buf, int len, int offset)
742 {
743         void* kbuf = kmalloc_errno(len);
744         if(kbuf == NULL)
745                 return -1;
746         int ret = ufe(pread,fd,PADDR(kbuf),len,offset);
747         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
748                 ret = -1;
749         user_memdup_free(p,kbuf);
750         return ret;
751 }
752
753 intreg_t sys_open(struct proc* p, const char* path, int oflag, int mode)
754 {
755         char* fn = user_strdup_errno(p,path,PGSIZE);
756         if(fn == NULL)
757                 return -1;
758         int ret = ufe(open,PADDR(fn),oflag,mode,0);
759         user_memdup_free(p,fn);
760         return ret;
761 }
762 intreg_t sys_close(struct proc* p, int fd)
763 {
764         return ufe(close,fd,0,0,0);
765 }
766
767 #define NEWLIB_STAT_SIZE 64
768 intreg_t sys_fstat(struct proc* p, int fd, void* buf)
769 {
770         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
771         int ret = ufe(fstat,fd,PADDR(kbuf),0,0);
772         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
773                 ret = -1;
774         kfree(kbuf);
775         return ret;
776 }
777
778 intreg_t sys_stat(struct proc* p, const char* path, void* buf)
779 {
780         char* fn = user_strdup_errno(p,path,PGSIZE);
781         if(fn == NULL)
782                 return -1;
783
784         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
785         int ret = ufe(stat,PADDR(fn),PADDR(kbuf),0,0);
786         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
787                 ret = -1;
788
789         user_memdup_free(p,fn);
790         kfree(kbuf);
791         return ret;
792 }
793
794 intreg_t sys_lstat(struct proc* p, const char* path, void* buf)
795 {
796         char* fn = user_strdup_errno(p,path,PGSIZE);
797         if(fn == NULL)
798                 return -1;
799
800         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
801         int ret = ufe(lstat,PADDR(fn),PADDR(kbuf),0,0);
802         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
803                 ret = -1;
804
805         user_memdup_free(p,fn);
806         kfree(kbuf);
807         return ret;
808 }
809
810 intreg_t sys_fcntl(struct proc* p, int fd, int cmd, int arg)
811 {
812         return ufe(fcntl,fd,cmd,arg,0);
813 }
814
815 intreg_t sys_access(struct proc* p, const char* path, int type)
816 {
817         char* fn = user_strdup_errno(p,path,PGSIZE);
818         if(fn == NULL)
819                 return -1;
820         int ret = ufe(access,PADDR(fn),type,0,0);
821         user_memdup_free(p,fn);
822         return ret;
823 }
824
825 intreg_t sys_umask(struct proc* p, int mask)
826 {
827         return ufe(umask,mask,0,0,0);
828 }
829
830 intreg_t sys_chmod(struct proc* p, const char* path, int mode)
831 {
832         char* fn = user_strdup_errno(p,path,PGSIZE);
833         if(fn == NULL)
834                 return -1;
835         int ret = ufe(chmod,PADDR(fn),mode,0,0);
836         user_memdup_free(p,fn);
837         return ret;
838 }
839
840 intreg_t sys_lseek(struct proc* p, int fd, int offset, int whence)
841 {
842         return ufe(lseek,fd,offset,whence,0);
843 }
844
845 intreg_t sys_link(struct proc* p, const char* _old, const char* _new)
846 {
847         char* oldpath = user_strdup_errno(p,_old,PGSIZE);
848         if(oldpath == NULL)
849                 return -1;
850
851         char* newpath = user_strdup_errno(p,_new,PGSIZE);
852         if(newpath == NULL)
853         {
854                 user_memdup_free(p,oldpath);
855                 return -1;
856         }
857
858         int ret = ufe(link,PADDR(oldpath),PADDR(newpath),0,0);
859         user_memdup_free(p,oldpath);
860         user_memdup_free(p,newpath);
861         return ret;
862 }
863
864 intreg_t sys_unlink(struct proc* p, const char* path)
865 {
866         char* fn = user_strdup_errno(p,path,PGSIZE);
867         if(fn == NULL)
868                 return -1;
869         int ret = ufe(unlink,PADDR(fn),0,0,0);
870         user_memdup_free(p,fn);
871         return ret;
872 }
873
874 intreg_t sys_chdir(struct proc* p, const char* path)
875 {
876         char* fn = user_strdup_errno(p,path,PGSIZE);
877         if(fn == NULL)
878                 return -1;
879         int ret = ufe(chdir,PADDR(fn),0,0,0);
880         user_memdup_free(p,fn);
881         return ret;
882 }
883
884 intreg_t sys_getcwd(struct proc* p, char* pwd, int size)
885 {
886         void* kbuf = kmalloc_errno(size);
887         if(kbuf == NULL)
888                 return -1;
889         int ret = ufe(read,PADDR(kbuf),size,0,0);
890         if(ret != -1 && memcpy_to_user_errno(p,pwd,kbuf,strnlen(kbuf,size)))
891                 ret = -1;
892         user_memdup_free(p,kbuf);
893         return ret;
894 }
895
896 intreg_t sys_gettimeofday(struct proc* p, int* buf)
897 {
898         static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
899         static int t0 = 0;
900
901         spin_lock(&gtod_lock);
902         if(t0 == 0)
903                 t0 = ufe(time,0,0,0,0);
904         spin_unlock(&gtod_lock);
905
906         long long dt = read_tsc();
907         int kbuf[2] = {t0+dt/system_timing.tsc_freq,
908             (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
909
910         return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
911 }
912
913 #define SIZEOF_STRUCT_TERMIOS 60
914 intreg_t sys_tcgetattr(struct proc* p, int fd, void* termios_p)
915 {
916         int* kbuf = kmalloc(SIZEOF_STRUCT_TERMIOS,0);
917         int ret = ufe(tcgetattr,fd,PADDR(kbuf),0,0);
918         if(ret != -1 && memcpy_to_user_errno(p,termios_p,kbuf,SIZEOF_STRUCT_TERMIOS))
919                 ret = -1;
920         kfree(kbuf);
921         return ret;
922 }
923
924 intreg_t sys_tcsetattr(struct proc* p, int fd, int optional_actions, const void* termios_p)
925 {
926         void* kbuf = user_memdup_errno(p,termios_p,SIZEOF_STRUCT_TERMIOS);
927         if(kbuf == NULL)
928                 return -1;
929         int ret = ufe(tcsetattr,fd,optional_actions,PADDR(kbuf),0);
930         user_memdup_free(p,kbuf);
931         return ret;
932 }
933 /************** Syscall Invokation **************/
934
935 /* Executes the given syscall.
936  *
937  * Note tf is passed in, which points to the tf of the context on the kernel
938  * stack.  If any syscall needs to block, it needs to save this info, as well as
939  * any silly state.
940  *
941  * TODO: Build a dispatch table instead of switching on the syscallno
942  * Dispatches to the correct kernel function, passing the arguments.
943  */
944 intreg_t syscall(struct proc *p, uintreg_t syscallno, uintreg_t a1,
945                  uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
946 {
947         // Initialize the return value and error code returned to 0
948         proc_set_syscall_retval(current_tf, 0);
949         set_errno(current_tf,0);
950
951         typedef intreg_t (*syscall_t)(struct proc*,uintreg_t,uintreg_t,
952                                       uintreg_t,uintreg_t,uintreg_t);
953
954         const static syscall_t syscall_table[] = {
955                 [SYS_null] = (syscall_t)sys_null,
956                 [SYS_cache_buster] = (syscall_t)sys_cache_buster,
957                 [SYS_cache_invalidate] = (syscall_t)sys_cache_invalidate,
958                 [SYS_reboot] = (syscall_t)reboot,
959                 [SYS_cputs] = (syscall_t)sys_cputs,
960                 [SYS_cgetc] = (syscall_t)sys_cgetc,
961                 [SYS_getcpuid] = (syscall_t)sys_getcpuid,
962                 [SYS_getvcoreid] = (syscall_t)sys_getvcoreid,
963                 [SYS_getpid] = (syscall_t)sys_getpid,
964                 [SYS_proc_create] = (syscall_t)sys_proc_create,
965                 [SYS_proc_run] = (syscall_t)sys_proc_run,
966                 [SYS_proc_destroy] = (syscall_t)sys_proc_destroy,
967                 [SYS_yield] = (syscall_t)sys_proc_yield,
968                 [SYS_run_binary] = (syscall_t)sys_run_binary,
969                 [SYS_fork] = (syscall_t)sys_fork,
970                 [SYS_exec] = (syscall_t)sys_exec,
971                 [SYS_trywait] = (syscall_t)sys_trywait,
972                 [SYS_mmap] = (syscall_t)sys_mmap,
973                 [SYS_munmap] = (syscall_t)sys_munmap,
974                 [SYS_mprotect] = (syscall_t)sys_mprotect,
975                 [SYS_brk] = (syscall_t)sys_brk,
976                 [SYS_shared_page_alloc] = (syscall_t)sys_shared_page_alloc,
977                 [SYS_shared_page_free] = (syscall_t)sys_shared_page_free,
978                 [SYS_resource_req] = (syscall_t)resource_req,
979         #ifdef __i386__
980                 [SYS_serial_read] = (syscall_t)sys_serial_read,
981                 [SYS_serial_write] = (syscall_t)sys_serial_write,
982         #endif
983         #ifdef __NETWORK__
984                 [SYS_eth_read] = (syscall_t)sys_eth_read,
985                 [SYS_eth_write] = (syscall_t)sys_eth_write,
986                 [SYS_eth_get_mac_addr] = (syscall_t)sys_eth_get_mac_addr,
987                 [SYS_eth_recv_check] = (syscall_t)sys_eth_recv_check,
988         #endif
989                 // Syscalls serviced by the appserver for now.
990                 [SYS_read] = (syscall_t)sys_read,
991                 [SYS_write] = (syscall_t)sys_write,
992                 [SYS_open] = (syscall_t)sys_open,
993                 [SYS_close] = (syscall_t)sys_close,
994                 [SYS_fstat] = (syscall_t)sys_fstat,
995                 [SYS_stat] = (syscall_t)sys_stat,
996                 [SYS_lstat] = (syscall_t)sys_lstat,
997                 [SYS_fcntl] = (syscall_t)sys_fcntl,
998                 [SYS_access] = (syscall_t)sys_access,
999                 [SYS_umask] = (syscall_t)sys_umask,
1000                 [SYS_chmod] = (syscall_t)sys_chmod,
1001                 [SYS_lseek] = (syscall_t)sys_lseek,
1002                 [SYS_link] = (syscall_t)sys_link,
1003                 [SYS_unlink] = (syscall_t)sys_unlink,
1004                 [SYS_chdir] = (syscall_t)sys_chdir,
1005                 [SYS_getcwd] = (syscall_t)sys_getcwd,
1006                 [SYS_gettimeofday] = (syscall_t)sys_gettimeofday,
1007                 [SYS_tcgetattr] = (syscall_t)sys_tcgetattr,
1008                 [SYS_tcsetattr] = (syscall_t)sys_tcsetattr
1009         };
1010
1011         const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
1012
1013         //printk("Incoming syscall on core: %d number: %d\n    a1: %x\n   "
1014         //       " a2: %x\n    a3: %x\n    a4: %x\n    a5: %x\n", core_id(),
1015         //       syscallno, a1, a2, a3, a4, a5);
1016
1017         if(syscallno > max_syscall || syscall_table[syscallno] == NULL)
1018                 panic("Invalid syscall number %d for proc %x!", syscallno, *p);
1019
1020         return syscall_table[syscallno](p,a1,a2,a3,a4,a5);
1021 }
1022
1023 intreg_t syscall_async(struct proc *p, syscall_req_t *call)
1024 {
1025         return syscall(p, call->num, call->args[0], call->args[1],
1026                        call->args[2], call->args[3], call->args[4]);
1027 }
1028
1029 /* You should already have a refcnt'd ref to p before calling this */
1030 intreg_t process_generic_syscalls(struct proc *p, size_t max)
1031 {
1032         size_t count = 0;
1033         syscall_back_ring_t* sysbr = &p->syscallbackring;
1034
1035         /* make sure the proc is still alive, and keep it from dying from under us
1036          * incref will return ESUCCESS on success.  This might need some thought
1037          * regarding when the incref should have happened (like by whoever passed us
1038          * the *p). */
1039         // TODO: ought to be unnecessary, if you called this right, kept here for
1040         // now in case anyone actually uses the ARSCs.
1041         proc_incref(p, 1);
1042
1043         // max is the most we'll process.  max = 0 means do as many as possible
1044         while (RING_HAS_UNCONSUMED_REQUESTS(sysbr) && ((!max)||(count < max)) ) {
1045                 if (!count) {
1046                         // ASSUME: one queue per process
1047                         // only switch cr3 for the very first request for this queue
1048                         // need to switch to the right context, so we can handle the user pointer
1049                         // that points to a data payload of the syscall
1050                         lcr3(p->env_cr3);
1051                 }
1052                 count++;
1053                 //printk("DEBUG PRE: sring->req_prod: %d, sring->rsp_prod: %d\n",
1054                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1055                 // might want to think about 0-ing this out, if we aren't
1056                 // going to explicitly fill in all fields
1057                 syscall_rsp_t rsp;
1058                 // this assumes we get our answer immediately for the syscall.
1059                 syscall_req_t* req = RING_GET_REQUEST(sysbr, ++(sysbr->req_cons));
1060                 rsp.retval = syscall_async(p, req);
1061                 // write response into the slot it came from
1062                 memcpy(req, &rsp, sizeof(syscall_rsp_t));
1063                 // update our counter for what we've produced (assumes we went in order!)
1064                 (sysbr->rsp_prod_pvt)++;
1065                 RING_PUSH_RESPONSES(sysbr);
1066                 //printk("DEBUG POST: sring->req_prod: %d, sring->rsp_prod: %d\n",
1067                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1068         }
1069         // load sane page tables (and don't rely on decref to do it for you).
1070         lcr3(boot_cr3);
1071         proc_decref(p, 1);
1072         return (intreg_t)count;
1073 }
1074