Skip to content

Commit f36e7c5

Browse files
committed
Add ecall-based syscall trap
Implements syscall interface using the ecall instruction to trap into M-mode from user space. Follows RISC-V calling convention for system call arguments and return values. Introduces a dedicated file for kernel entry mechanisms following Linux conventions. This separation clarifies the distinction between trap-based entry and generic syscall dispatch logic.
1 parent 2e83c36 commit f36e7c5

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

arch/riscv/build.mk

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ LDFLAGS += --gc-sections
7070
ARFLAGS = r
7171
LDSCRIPT = $(ARCH_DIR)/riscv32-qemu.ld
7272

73-
HAL_OBJS := boot.o hal.o muldiv.o
73+
HAL_OBJS := boot.o hal.o muldiv.o entry.o
7474
HAL_OBJS := $(addprefix $(BUILD_KERNEL_DIR)/,$(HAL_OBJS))
7575
deps += $(HAL_OBJS:%.o=%.o.d)
7676

arch/riscv/entry.c

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/* RISC-V Kernel Entry Points
2+
*
3+
* This file implements architecture-specific entry mechanisms into the kernel,
4+
* primarily the system call trap interface using the RISC-V ecall instruction.
5+
*
6+
* System Call Calling Convention (RISC-V ABI):
7+
* - a7 (x17): System call number
8+
* - a0 (x10): Argument 1 / Return value
9+
* - a1 (x11): Argument 2
10+
* - a2 (x12): Argument 3
11+
*
12+
* The ecall instruction triggers an environment call exception that transfers
13+
* control to the M-mode exception handler (hal.c), which then dispatches to
14+
* the appropriate system call implementation via the syscall table.
15+
*/
16+
17+
#include <sys/syscall.h>
18+
19+
/* Architecture-specific syscall implementation using ecall trap.
20+
* This overrides the weak symbol defined in kernel/syscall.c.
21+
*/
22+
int syscall(int num, void *arg1, void *arg2, void *arg3)
23+
{
24+
register int a0 asm("a0") = (int) arg1;
25+
register int a1 asm("a1") = (int) arg2;
26+
register int a2 asm("a2") = (int) arg3;
27+
register int a7 asm("a7") = num;
28+
29+
/* Execute ecall instruction to trap into M-mode.
30+
* The M-mode exception handler will:
31+
* 1. Save the current task context
32+
* 2. Dispatch to the syscall handler based on a7
33+
* 3. Place the return value in a0
34+
* 4. Restore context and return to user mode via mret
35+
*/
36+
asm volatile("ecall"
37+
: "+r"(a0) /* a0 is both input (arg1) and output (retval) */
38+
: "r"(a1), "r"(a2), "r"(a7)
39+
: "memory");
40+
41+
return a0;
42+
}

0 commit comments

Comments
 (0)