Add your first system call to xv6
Easy
xv6 book Sect 2.3 Kernel organization
The first system call we are going to add is getnumsyscalls. When a user-space program executes this system call, it returns the total number of system calls executed in the current process.
The following exercise will guide you through implementing your first system call. Many of these steps will be useful for implementing other system calls later in the semester, so make sure you understand well and don’t hesitate to come back to this tutorial when in doubt!
Add a counter per process
To implement getnumsyscalls, we will need to keep track of the number of system calls called by each process.
-
Add a field
uint64 numsyscallsto thestruct procinkernel/proc.h. Do this in the “private” section. -
When we add a field to the struct, we must also make sure that this field is assigned an initial value when creating a process (i.e., during
fork). Initialize the fieldnumsyscallsin the functionallocprocinkernel/proc.c. -
To ensure that the counter correctly counts the number of system calls, increase this value each time the system call handler is called (cf.
syscallinkernel/syscall.c). You can increase the counter regardless of whether the system call number was valid.
Implement the system call
Now that our counter is working correctly, all that remains is the actual implementation of the system call.
- Add
SYS_getnumsyscallstokernel/syscall.h. - Implement
sys_getnumsyscallsinkernel/sysproc.c. You can get a pointer to the current process via themyprocfunction. - Make sure the system call handler
syscallforwards our new system call correctly.
To be able to call
sys_getnumsyscallsfromsyscall, you will have to tell the C compiler that this function exists, and thus declare it. Follow the example of the declarations of the other system calls.
Expose the system call to user-space
Our system call is now working. We just can’t easily call it from user-space yet. System calls are called via a C-wrapper, so let’s declare our C wrapper.
- Add
int getnumsyscalls()touser/user.h
The implementation of the wrapper function is done in assembly. In principle, you have enough knowledge to implement this wrapper yourself. However, xv6 offers a script to automate this task. The script user/usys.pl, which is called automatically by the Makefile, generates an assembly file (user/usys.S) containing the implementation of the wrappers. Look at the generated file and make sure you understand the wrappers.
- Add
entry("getnumsyscalls")touser/usys.pl
Invoke your system call
The system call is ready, time to test it out.
-
Edit
user/hello.cso thatgetnumsyscallsis called before returning frommainand print out the result. -
Now run the program
hello. What result do you get? Is this the result you expected? Can you find out which system calls were executed in the process that you did not explicitly call yourself? Hint: use the debugger to monitor calls to thesyscallfunction.