Added demand paging support
[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_segment_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         size_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         if (addr > p->heap_top) {
493                 range = addr - p->heap_top;
494                 env_segment_alloc(p, p->heap_top, range);
495         }
496         else if (addr < p->heap_top) {
497                 range = p->heap_top - addr;
498                 env_segment_free(p, addr, range);
499         }
500         p->heap_top = addr;
501
502 out:
503         spin_unlock_irqsave(&p->proc_lock);
504         return p->heap_top;
505 }
506
507 static ssize_t sys_shared_page_alloc(env_t* p1,
508                                      void**DANGEROUS _addr, pid_t p2_id,
509                                      int p1_flags, int p2_flags
510                                     )
511 {
512         //if (!VALID_USER_PERMS(p1_flags)) return -EPERM;
513         //if (!VALID_USER_PERMS(p2_flags)) return -EPERM;
514
515         void * COUNT(1) * COUNT(1) addr = user_mem_assert(p1, _addr, sizeof(void *),
516                                                       PTE_USER_RW);
517         struct proc *p2 = pid2proc(p2_id);
518         if (!p2)
519                 return -EBADPROC;
520
521         page_t* page;
522         error_t e = upage_alloc(p1, &page,1);
523         if (e < 0) {
524                 proc_decref(p2, 1);
525                 return e;
526         }
527
528         void* p2_addr = page_insert_in_range(p2->env_pgdir, page,
529                         (void*SNT)UTEXT, (void*SNT)UTOP, p2_flags);
530         if (p2_addr == NULL) {
531                 page_free(page);
532                 proc_decref(p2, 1);
533                 return -EFAIL;
534         }
535
536         void* p1_addr = page_insert_in_range(p1->env_pgdir, page,
537                         (void*SNT)UTEXT, (void*SNT)UTOP, p1_flags);
538         if(p1_addr == NULL) {
539                 page_remove(p2->env_pgdir, p2_addr);
540                 page_free(page);
541                 proc_decref(p2, 1);
542                 return -EFAIL;
543         }
544         *addr = p1_addr;
545         proc_decref(p2, 1);
546         return ESUCCESS;
547 }
548
549 static int sys_shared_page_free(env_t* p1, void*DANGEROUS addr, pid_t p2)
550 {
551         return -1;
552 }
553
554
555 /************** Resource Request Syscalls **************/
556
557 /* sys_resource_req(): called directly from dispatch table. */
558
559 /************** Platform Specific Syscalls **************/
560
561 //Read a buffer over the serial port
562 static ssize_t sys_serial_read(env_t* e, char *DANGEROUS _buf, size_t len)
563 {
564         if (len == 0)
565                 return 0;
566
567         #ifdef SERIAL_IO
568             char *COUNT(len) buf = user_mem_assert(e, _buf, len, PTE_USER_RO);
569                 size_t bytes_read = 0;
570                 int c;
571                 while((c = serial_read_byte()) != -1) {
572                         buf[bytes_read++] = (uint8_t)c;
573                         if(bytes_read == len) break;
574                 }
575                 return (ssize_t)bytes_read;
576         #else
577                 return -EINVAL;
578         #endif
579 }
580
581 //Write a buffer over the serial port
582 static ssize_t sys_serial_write(env_t* e, const char *DANGEROUS buf, size_t len)
583 {
584         if (len == 0)
585                 return 0;
586         #ifdef SERIAL_IO
587                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_USER_RO);
588                 for(int i =0; i<len; i++)
589                         serial_send_byte(buf[i]);
590                 return (ssize_t)len;
591         #else
592                 return -EINVAL;
593         #endif
594 }
595
596 #ifdef __NETWORK__
597 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
598 static ssize_t sys_eth_read(env_t* e, char *DANGEROUS buf)
599 {
600         if (eth_up) {
601
602                 uint32_t len;
603                 char *ptr;
604
605                 spin_lock(&packet_buffers_lock);
606
607                 if (num_packet_buffers == 0) {
608                         spin_unlock(&packet_buffers_lock);
609                         return 0;
610                 }
611
612                 ptr = packet_buffers[packet_buffers_head];
613                 len = packet_buffers_sizes[packet_buffers_head];
614
615                 num_packet_buffers--;
616                 packet_buffers_head = (packet_buffers_head + 1) % MAX_PACKET_BUFFERS;
617
618                 spin_unlock(&packet_buffers_lock);
619
620                 char* _buf = user_mem_assert(e, buf, len, PTE_U);
621
622                 memcpy(_buf, ptr, len);
623
624                 kfree(ptr);
625
626                 return len;
627         }
628         else
629                 return -EINVAL;
630 }
631
632 // This is not a syscall we want. Its hacky. Here just for syscall stuff until get a stack.
633 static ssize_t sys_eth_write(env_t* e, const char *DANGEROUS buf, size_t len)
634 {
635         if (eth_up) {
636
637                 if (len == 0)
638                         return 0;
639
640                 // HACK TO BYPASS HACK
641                 int just_sent = send_frame(buf, len);
642
643                 if (just_sent < 0) {
644                         printk("Packet send fail\n");
645                         return 0;
646                 }
647
648                 return just_sent;
649
650                 // END OF RECURSIVE HACK
651 /*
652                 char *COUNT(len) _buf = user_mem_assert(e, buf, len, PTE_U);
653                 int total_sent = 0;
654                 int just_sent = 0;
655                 int cur_packet_len = 0;
656                 while (total_sent != len) {
657                         cur_packet_len = ((len - total_sent) > MTU) ? MTU : (len - total_sent);
658                         char dest_mac[6] = APPSERVER_MAC_ADDRESS;
659                         char* wrap_buffer = eth_wrap(_buf + total_sent, cur_packet_len, device_mac, dest_mac, APPSERVER_PORT);
660                         just_sent = send_frame(wrap_buffer, cur_packet_len + sizeof(struct ETH_Header));
661
662                         if (just_sent < 0)
663                                 return 0; // This should be an error code of its own
664
665                         if (wrap_buffer)
666                                 kfree(wrap_buffer);
667
668                         total_sent += cur_packet_len;
669                 }
670
671                 return (ssize_t)len;
672 */
673         }
674         else
675                 return -EINVAL;
676 }
677
678 static ssize_t sys_eth_get_mac_addr(env_t* e, char *DANGEROUS buf) 
679 {
680         if (eth_up) {
681                 for (int i = 0; i < 6; i++)
682                         buf[i] = device_mac[i];
683                 return 0;
684         }
685         else
686                 return -EINVAL;
687 }
688
689 static int sys_eth_recv_check(env_t* e) 
690 {
691         if (num_packet_buffers != 0) 
692                 return 1;
693         else
694                 return 0;
695 }
696
697 #endif // Network
698
699 // Syscalls below here are serviced by the appserver for now.
700 #define ufe(which,a0,a1,a2,a3) \
701         frontend_syscall_errno(p,APPSERVER_SYSCALL_##which,\
702                            (int)(a0),(int)(a1),(int)(a2),(int)(a3))
703
704 intreg_t sys_write(struct proc* p, int fd, const void* buf, int len)
705 {
706         void* kbuf = user_memdup_errno(p,buf,len);
707         if(kbuf == NULL)
708                 return -1;
709         int ret = ufe(write,fd,PADDR(kbuf),len,0);
710         user_memdup_free(p,kbuf);
711         return ret;
712 }
713
714 intreg_t sys_read(struct proc* p, int fd, void* buf, int len)
715 {
716         void* kbuf = kmalloc_errno(len);
717         if(kbuf == NULL)
718                 return -1;
719         int ret = ufe(read,fd,PADDR(kbuf),len,0);
720         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
721                 ret = -1;
722         user_memdup_free(p,kbuf);
723         return ret;
724 }
725
726 intreg_t sys_pwrite(struct proc* p, int fd, const void* buf, int len, int offset)
727 {
728         void* kbuf = user_memdup_errno(p,buf,len);
729         if(kbuf == NULL)
730                 return -1;
731         int ret = ufe(pwrite,fd,PADDR(kbuf),len,offset);
732         user_memdup_free(p,kbuf);
733         return ret;
734 }
735
736 intreg_t sys_pread(struct proc* p, int fd, void* buf, int len, int offset)
737 {
738         void* kbuf = kmalloc_errno(len);
739         if(kbuf == NULL)
740                 return -1;
741         int ret = ufe(pread,fd,PADDR(kbuf),len,offset);
742         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,len))
743                 ret = -1;
744         user_memdup_free(p,kbuf);
745         return ret;
746 }
747
748 intreg_t sys_open(struct proc* p, const char* path, int oflag, int mode)
749 {
750         char* fn = user_strdup_errno(p,path,PGSIZE);
751         if(fn == NULL)
752                 return -1;
753         int ret = ufe(open,PADDR(fn),oflag,mode,0);
754         user_memdup_free(p,fn);
755         return ret;
756 }
757 intreg_t sys_close(struct proc* p, int fd)
758 {
759         return ufe(close,fd,0,0,0);
760 }
761
762 #define NEWLIB_STAT_SIZE 64
763 intreg_t sys_fstat(struct proc* p, int fd, void* buf)
764 {
765         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
766         int ret = ufe(fstat,fd,PADDR(kbuf),0,0);
767         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
768                 ret = -1;
769         kfree(kbuf);
770         return ret;
771 }
772
773 intreg_t sys_stat(struct proc* p, const char* path, void* buf)
774 {
775         char* fn = user_strdup_errno(p,path,PGSIZE);
776         if(fn == NULL)
777                 return -1;
778
779         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
780         int ret = ufe(stat,PADDR(fn),PADDR(kbuf),0,0);
781         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
782                 ret = -1;
783
784         user_memdup_free(p,fn);
785         kfree(kbuf);
786         return ret;
787 }
788
789 intreg_t sys_lstat(struct proc* p, const char* path, void* buf)
790 {
791         char* fn = user_strdup_errno(p,path,PGSIZE);
792         if(fn == NULL)
793                 return -1;
794
795         int *kbuf = kmalloc(NEWLIB_STAT_SIZE, 0);
796         int ret = ufe(lstat,PADDR(fn),PADDR(kbuf),0,0);
797         if(ret != -1 && memcpy_to_user_errno(p,buf,kbuf,NEWLIB_STAT_SIZE))
798                 ret = -1;
799
800         user_memdup_free(p,fn);
801         kfree(kbuf);
802         return ret;
803 }
804
805 intreg_t sys_fcntl(struct proc* p, int fd, int cmd, int arg)
806 {
807         return ufe(fcntl,fd,cmd,arg,0);
808 }
809
810 intreg_t sys_access(struct proc* p, const char* path, int type)
811 {
812         char* fn = user_strdup_errno(p,path,PGSIZE);
813         if(fn == NULL)
814                 return -1;
815         int ret = ufe(access,PADDR(fn),type,0,0);
816         user_memdup_free(p,fn);
817         return ret;
818 }
819
820 intreg_t sys_umask(struct proc* p, int mask)
821 {
822         return ufe(umask,mask,0,0,0);
823 }
824
825 intreg_t sys_chmod(struct proc* p, const char* path, int mode)
826 {
827         char* fn = user_strdup_errno(p,path,PGSIZE);
828         if(fn == NULL)
829                 return -1;
830         int ret = ufe(chmod,PADDR(fn),mode,0,0);
831         user_memdup_free(p,fn);
832         return ret;
833 }
834
835 intreg_t sys_lseek(struct proc* p, int fd, int offset, int whence)
836 {
837         return ufe(lseek,fd,offset,whence,0);
838 }
839
840 intreg_t sys_link(struct proc* p, const char* _old, const char* _new)
841 {
842         char* oldpath = user_strdup_errno(p,_old,PGSIZE);
843         if(oldpath == NULL)
844                 return -1;
845
846         char* newpath = user_strdup_errno(p,_new,PGSIZE);
847         if(newpath == NULL)
848         {
849                 user_memdup_free(p,oldpath);
850                 return -1;
851         }
852
853         int ret = ufe(link,PADDR(oldpath),PADDR(newpath),0,0);
854         user_memdup_free(p,oldpath);
855         user_memdup_free(p,newpath);
856         return ret;
857 }
858
859 intreg_t sys_unlink(struct proc* p, const char* path)
860 {
861         char* fn = user_strdup_errno(p,path,PGSIZE);
862         if(fn == NULL)
863                 return -1;
864         int ret = ufe(unlink,PADDR(fn),0,0,0);
865         user_memdup_free(p,fn);
866         return ret;
867 }
868
869 intreg_t sys_chdir(struct proc* p, const char* path)
870 {
871         char* fn = user_strdup_errno(p,path,PGSIZE);
872         if(fn == NULL)
873                 return -1;
874         int ret = ufe(chdir,PADDR(fn),0,0,0);
875         user_memdup_free(p,fn);
876         return ret;
877 }
878
879 intreg_t sys_getcwd(struct proc* p, char* pwd, int size)
880 {
881         void* kbuf = kmalloc_errno(size);
882         if(kbuf == NULL)
883                 return -1;
884         int ret = ufe(read,PADDR(kbuf),size,0,0);
885         if(ret != -1 && memcpy_to_user_errno(p,pwd,kbuf,strnlen(kbuf,size)))
886                 ret = -1;
887         user_memdup_free(p,kbuf);
888         return ret;
889 }
890
891 intreg_t sys_gettimeofday(struct proc* p, int* buf)
892 {
893         static spinlock_t gtod_lock = SPINLOCK_INITIALIZER;
894         static int t0 = 0;
895
896         spin_lock(&gtod_lock);
897         if(t0 == 0)
898                 t0 = ufe(time,0,0,0,0);
899         spin_unlock(&gtod_lock);
900
901         long long dt = read_tsc();
902         int kbuf[2] = {t0+dt/system_timing.tsc_freq,
903             (dt%system_timing.tsc_freq)*1000000/system_timing.tsc_freq};
904
905         return memcpy_to_user_errno(p,buf,kbuf,sizeof(kbuf));
906 }
907
908 #define SIZEOF_STRUCT_TERMIOS 60
909 intreg_t sys_tcgetattr(struct proc* p, int fd, void* termios_p)
910 {
911         int* kbuf = kmalloc(SIZEOF_STRUCT_TERMIOS,0);
912         int ret = ufe(tcgetattr,fd,PADDR(kbuf),0,0);
913         if(ret != -1 && memcpy_to_user_errno(p,termios_p,kbuf,SIZEOF_STRUCT_TERMIOS))
914                 ret = -1;
915         kfree(kbuf);
916         return ret;
917 }
918
919 intreg_t sys_tcsetattr(struct proc* p, int fd, int optional_actions, const void* termios_p)
920 {
921         void* kbuf = user_memdup_errno(p,termios_p,SIZEOF_STRUCT_TERMIOS);
922         if(kbuf == NULL)
923                 return -1;
924         int ret = ufe(tcsetattr,fd,optional_actions,PADDR(kbuf),0);
925         user_memdup_free(p,kbuf);
926         return ret;
927 }
928 /************** Syscall Invokation **************/
929
930 /* Executes the given syscall.
931  *
932  * Note tf is passed in, which points to the tf of the context on the kernel
933  * stack.  If any syscall needs to block, it needs to save this info, as well as
934  * any silly state.
935  *
936  * TODO: Build a dispatch table instead of switching on the syscallno
937  * Dispatches to the correct kernel function, passing the arguments.
938  */
939 intreg_t syscall(struct proc *p, uintreg_t syscallno, uintreg_t a1,
940                  uintreg_t a2, uintreg_t a3, uintreg_t a4, uintreg_t a5)
941 {
942         // Initialize the return value and error code returned to 0
943         proc_set_syscall_retval(current_tf, 0);
944         set_errno(current_tf,0);
945
946         typedef intreg_t (*syscall_t)(struct proc*,uintreg_t,uintreg_t,
947                                       uintreg_t,uintreg_t,uintreg_t);
948
949         const static syscall_t syscall_table[] = {
950                 [SYS_null] = (syscall_t)sys_null,
951                 [SYS_cache_buster] = (syscall_t)sys_cache_buster,
952                 [SYS_cache_invalidate] = (syscall_t)sys_cache_invalidate,
953                 [SYS_reboot] = (syscall_t)reboot,
954                 [SYS_cputs] = (syscall_t)sys_cputs,
955                 [SYS_cgetc] = (syscall_t)sys_cgetc,
956                 [SYS_getcpuid] = (syscall_t)sys_getcpuid,
957                 [SYS_getvcoreid] = (syscall_t)sys_getvcoreid,
958                 [SYS_getpid] = (syscall_t)sys_getpid,
959                 [SYS_proc_create] = (syscall_t)sys_proc_create,
960                 [SYS_proc_run] = (syscall_t)sys_proc_run,
961                 [SYS_proc_destroy] = (syscall_t)sys_proc_destroy,
962                 [SYS_yield] = (syscall_t)sys_proc_yield,
963                 [SYS_run_binary] = (syscall_t)sys_run_binary,
964                 [SYS_fork] = (syscall_t)sys_fork,
965                 [SYS_exec] = (syscall_t)sys_exec,
966                 [SYS_trywait] = (syscall_t)sys_trywait,
967                 [SYS_mmap] = (syscall_t)sys_mmap,
968                 [SYS_munmap] = (syscall_t)sys_munmap,
969                 [SYS_mprotect] = (syscall_t)sys_mprotect,
970                 [SYS_brk] = (syscall_t)sys_brk,
971                 [SYS_shared_page_alloc] = (syscall_t)sys_shared_page_alloc,
972                 [SYS_shared_page_free] = (syscall_t)sys_shared_page_free,
973                 [SYS_resource_req] = (syscall_t)resource_req,
974         #ifdef __i386__
975                 [SYS_serial_read] = (syscall_t)sys_serial_read,
976                 [SYS_serial_write] = (syscall_t)sys_serial_write,
977         #endif
978         #ifdef __NETWORK__
979                 [SYS_eth_read] = (syscall_t)sys_eth_read,
980                 [SYS_eth_write] = (syscall_t)sys_eth_write,
981                 [SYS_eth_get_mac_addr] = (syscall_t)sys_eth_get_mac_addr,
982                 [SYS_eth_recv_check] = (syscall_t)sys_eth_recv_check,
983         #endif
984                 // Syscalls serviced by the appserver for now.
985                 [SYS_read] = (syscall_t)sys_read,
986                 [SYS_write] = (syscall_t)sys_write,
987                 [SYS_open] = (syscall_t)sys_open,
988                 [SYS_close] = (syscall_t)sys_close,
989                 [SYS_fstat] = (syscall_t)sys_fstat,
990                 [SYS_stat] = (syscall_t)sys_stat,
991                 [SYS_lstat] = (syscall_t)sys_lstat,
992                 [SYS_fcntl] = (syscall_t)sys_fcntl,
993                 [SYS_access] = (syscall_t)sys_access,
994                 [SYS_umask] = (syscall_t)sys_umask,
995                 [SYS_chmod] = (syscall_t)sys_chmod,
996                 [SYS_lseek] = (syscall_t)sys_lseek,
997                 [SYS_link] = (syscall_t)sys_link,
998                 [SYS_unlink] = (syscall_t)sys_unlink,
999                 [SYS_chdir] = (syscall_t)sys_chdir,
1000                 [SYS_getcwd] = (syscall_t)sys_getcwd,
1001                 [SYS_gettimeofday] = (syscall_t)sys_gettimeofday,
1002                 [SYS_tcgetattr] = (syscall_t)sys_tcgetattr,
1003                 [SYS_tcsetattr] = (syscall_t)sys_tcsetattr
1004         };
1005
1006         const int max_syscall = sizeof(syscall_table)/sizeof(syscall_table[0]);
1007
1008         //printk("Incoming syscall on core: %d number: %d\n    a1: %x\n   "
1009         //       " a2: %x\n    a3: %x\n    a4: %x\n    a5: %x\n", core_id(),
1010         //       syscallno, a1, a2, a3, a4, a5);
1011
1012         if(syscallno > max_syscall || syscall_table[syscallno] == NULL)
1013                 panic("Invalid syscall number %d for proc %x!", syscallno, *p);
1014
1015         return syscall_table[syscallno](p,a1,a2,a3,a4,a5);
1016 }
1017
1018 intreg_t syscall_async(struct proc *p, syscall_req_t *call)
1019 {
1020         return syscall(p, call->num, call->args[0], call->args[1],
1021                        call->args[2], call->args[3], call->args[4]);
1022 }
1023
1024 /* You should already have a refcnt'd ref to p before calling this */
1025 intreg_t process_generic_syscalls(struct proc *p, size_t max)
1026 {
1027         size_t count = 0;
1028         syscall_back_ring_t* sysbr = &p->syscallbackring;
1029
1030         /* make sure the proc is still alive, and keep it from dying from under us
1031          * incref will return ESUCCESS on success.  This might need some thought
1032          * regarding when the incref should have happened (like by whoever passed us
1033          * the *p). */
1034         // TODO: ought to be unnecessary, if you called this right, kept here for
1035         // now in case anyone actually uses the ARSCs.
1036         proc_incref(p, 1);
1037
1038         // max is the most we'll process.  max = 0 means do as many as possible
1039         while (RING_HAS_UNCONSUMED_REQUESTS(sysbr) && ((!max)||(count < max)) ) {
1040                 if (!count) {
1041                         // ASSUME: one queue per process
1042                         // only switch cr3 for the very first request for this queue
1043                         // need to switch to the right context, so we can handle the user pointer
1044                         // that points to a data payload of the syscall
1045                         lcr3(p->env_cr3);
1046                 }
1047                 count++;
1048                 //printk("DEBUG PRE: sring->req_prod: %d, sring->rsp_prod: %d\n",
1049                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1050                 // might want to think about 0-ing this out, if we aren't
1051                 // going to explicitly fill in all fields
1052                 syscall_rsp_t rsp;
1053                 // this assumes we get our answer immediately for the syscall.
1054                 syscall_req_t* req = RING_GET_REQUEST(sysbr, ++(sysbr->req_cons));
1055                 rsp.retval = syscall_async(p, req);
1056                 // write response into the slot it came from
1057                 memcpy(req, &rsp, sizeof(syscall_rsp_t));
1058                 // update our counter for what we've produced (assumes we went in order!)
1059                 (sysbr->rsp_prod_pvt)++;
1060                 RING_PUSH_RESPONSES(sysbr);
1061                 //printk("DEBUG POST: sring->req_prod: %d, sring->rsp_prod: %d\n",
1062                 //         sysbr->sring->req_prod, sysbr->sring->rsp_prod);
1063         }
1064         // load sane page tables (and don't rely on decref to do it for you).
1065         lcr3(boot_cr3);
1066         proc_decref(p, 1);
1067         return (intreg_t)count;
1068 }
1069