xv6, line by line
kernel/sysproc.c

kernel/sysproc.c

C · 112 lines · annotated 100% · kernel · upstream

About this file

The handlers for the system calls about processes, memory and time: exit, getpid, fork, wait, sbrk, pause, kill and uptime. (The file system calls are in kernel/sysfile.c.)

Each sys_* function is reached through the table in kernel/syscall.c and has the same shape: no C parameters, a uint64 result. It fetches its arguments from the saved user registers with argint or argaddr, does the work, usually by calling a function in kernel/proc.c, and returns a value that syscall puts in the user’s a0. By convention -1 means failure.

Most handlers are thin wrappers. The two with real logic are sys_sbrk, which grows memory either eagerly or lazily, and sys_pause, which sleeps on the clock.

Read before: kernel/syscall.c. Read next: kernel/proc.c for kfork, kexit, kwait and kkill.

1#include "types.h"
2#include "riscv.h"
3#include "defs.h"
4#include "param.h"
6#include "spinlock.h"
7#include "proc.h"
8#include "vm.h"
13 int n;
14 argint(0, &n);
16 return 0; // not reached
22 return myproc()->pid;
28 return kfork();
35 argaddr(0, &p);
36 return kwait(p);
43 int t;
44 int n;
46 argint(0, &n);
47 argint(1, &t);
50 if (t == SBRK_EAGER || n < 0) {
51 if (growproc(n) < 0) {
52 return -1;
53 }
54 } else {
55 // Lazily allocate memory for this process: increase its memory
56 // size but don't allocate memory. If the processes uses the
57 // memory, vmfault() will allocate it.
58 if (addr + n < addr)
59 return -1;
60 if (addr + n > TRAPFRAME)
61 return -1;
62 myproc()->sz += n;
63 }
64 return addr;
70 int n;
73 argint(0, &n);
74 if (n < 0)
75 n = 0;
78 while (ticks - ticks0 < n) {
79 if (killed(myproc())) {
81 return -1;
82 }
87 }
89 return 0;
95 int pid;
97 argint(0, &pid);
98 return kkill(pid);
101// return how many clock tick interrupts have occurred
102// since start.
111 return xticks;