KL-OS: System Call

2026-01-03POSSE

Day 13 was about system call.

Similar to SBI Call implementation, the system calls are invoked in a similar way.

The syscall function sets the system call number in the a3 register and the system call arguments in the a0 to a2 registers, then executes the ecall instruction. The ecall instruction is a special instruction used to delegate processing to the kernel. When the ecall instruction is executed, an exception handler is called, and control is transferred to the kernel. The return value from the kernel is set in the a0 register.

The first systemcall implemented is putchar. It takes a character as the first argument and the second and subsequent unused arguments are set to 0.

Then the ecall instruction is handled in the kernel. The calling of ecall can by determined by checking the value of scause. Before calling the handle_syscall function we also add the size of ecall instruction (4) to the value of sepc.

This is because sepc points to the program counter that caused the exception, which points to the ecall instruction. If we don't change it, the kernel goes back to the same place, and the ecall instruction is executed repeatedly.

Then a system call handler is made and is called from trap handler. It receives a structure of registers at the time of exception that was saved in the trap handler. It determined the type of system call by checking the value of a3 register.

The system call was then tested with a main print function in shell.c.

An exit system call is also implemented where it takes the first argument as 3 which is defined as SYS_EXIT.

The system call changes the process state to PROC_EXITED, and calls yield to give up the CPU to other processes. The scheduler will only execute processes in PROC_RUNNABLE state, so it will never return to this process. However, PANIC macro is added to cause a panic in case it does return.

A bare-bones shell was then implemented to use the syscalls to perform actions from the user mode.


Webmentions

Have you written a response to this? Let me know the URL, Or, you can send your response via mail:iac@scientiac.space