# xv6 Lab4 Traps - MIT 6.1810 Fall 2025 Operating System

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/xv6-lab4-traps/>). I am continuously working to improve the translation.

> [!important]
>
> **Some thoughts on doing this lab**: It's better to choose the Fall 2020 / Fall 2021 versions rather than the 2025 one. That's because the Chinese internet's materials for this course are concentrated on the first two versions, and the same goes for the various source code analyses.

## Reading

I originally planned to watch the recorded lectures, but found I couldn't really get into them, so I switched back to reading the documentation.

Summarizing the more important mechanisms:

### mode

Compared to user mode, supervisor mode has only two special privileges:

- It can read and write control registers
- It can use PTEs whose `PTE_U` flag is 0. When the `PTE_U` flag is 1, **only** user code can use that page table entry; if the flag is 0, only supervisor mode can use it

**Privileges/settings it does not have**:

- It cannot read and write arbitrary physical addresses; like ordinary user code, it must access memory through the page table
- The trap mechanism does not control the kernel's ability to view register contents; it only saves them

### Some important registers

- The SATP (Supervisor Address Translation and Protection) register, which contains the physical memory address pointing to the page table (see section 4.3 for details).
- The STVEC (Supervisor Trap Vector Base Address Register) register, which points to the starting address of the instructions in the kernel that handle traps.
- The SEPC (Supervisor Exception Program Counter) register, which holds the value of the program counter during a trap.

### `ecall`

`ecall` is a system instruction provided by RISC-V that performs:

- Switching the code from user mode to supervisor mode
- Saving the value of the program counter in the SEPC register
- Jumping to the instruction pointed to by the STVEC register (the so-called jump is just pointing the PC there)

For xv6, STVEC points to the trampoline page, which contains the trap handling code.

> ecall does not switch the page table, which is a very important characteristic of the ecall instruction. This means that the trap handling code must exist in every user page table. Because ecall does not switch the page table, we need somewhere in the user page table to execute the initial kernel code. This trampoline page is carefully mapped by the kernel into every user page table, so that while we are still using the user page table, the kernel can execute the very first few instructions of the trap mechanism in one place.

**`ecall` does very little**, which reflects the RISC philosophy.

### `uservec`

An assembly function used to save user registers.

Basically, each process has a `trapframe` struct, and each user page table has a corresponding trapframe page (seen in the syscall lab), which defines all the registers one by one. The assembly implementation is just a bunch of stores like `sd ra, 40(a0)`.

But before that, one more thing needs to be done:

- Before entering user space, the kernel saves the trapframe page address 0x3fffffe000 in the SSCRATCH register
- The first line of `uservec` executes `csrrw a0, sscratch, a0`, which means swapping the values of the two registers

> [!note]
>
> But this seems to be the 2020 version; the new version already uses `csrw sscratch, a0` and `li a0, TRAPFRAME`.
>
> <img src="https://image.wendaining.top/image-20260731010850344.png" alt="Rough difference" style="zoom:67%;" />

> [!important]
>
> **The meaning of the register swap here (mainly the significance of a0)**:
>
> a0 points to the trapframe, and the subsequent assembly code uses a0 as the base register.

Then:

1. Load the kernel's stack top pointer into the sp register
2. Load the kernel's hartid (CPU core number) into the tp register
3. Load the address of the `usertrap()` function into the t0 register (when printed it is `0x800027a0`, which belongs to the kernel text region of the virtual address space)
4. Load the pointer to the kernel page table into the t1 register
5. Switch the page table by loading the kernel page table pointer into the satp register
6. Jump to the function `usertrap()` via a jump instruction; this is kernel C code

To summarize what was done:

1. Save the user register data
2. Set up stack space for the kernel code
3. Switch the page table

###  `usertrap`

Details omitted—there are too many, and I simply can't remember them all.

usertrap is responsible for determining **the cause of the trap** and performing the corresponding handling:

- If it is a syscall, call the corresponding system call
- If it is a device interrupt, jump to the corresponding handling code
- If it is a page fault, kill the process
- Finally, execute the `usertrapret()` function

### Some changes

From the later part onward, the 2025 version differs from the 2020 one.

> **The new version of xv6 no longer has `usertrapret()`, but the functionality hasn't disappeared—it was just renamed and reorganized.**
>
> Officially, in **October 2025**, it was changed from:
>
> ```c
> usertrapret()
> ```
>
> to:
>
> ```c
> prepare_return()
> ```
>
> ([GitHub](https://github.com/mit-pdos/xv6-riscv/commits?utm_source=chatgpt.com))
>
> The current return path is:
>
> ```text
> usertrap()
>     ├─ prepare_return()
>     └─ return the satp of the user page table
>            ↓
> trampoline.S: userret
>     ├─ switch to the user page table
>     ├─ restore user registers
>     └─ sret to return to user mode
> ```
>
> Here, `prepare_return()` handles most of the preparation work of the old `usertrapret()`:
>
> - Setting `stvec = uservec`
> - Filling in the kernel information in the trapframe
> - Setting `sstatus`
> - Setting `sepc`
>
> Then `usertrap()` returns, and the assembly code goes directly into `userret`. `usertrapret` can no longer be found in the current source code. ([GitHub](https://github.com/mit-pdos/xv6-riscv/blob/riscv/kernel/trap.c))
>
> So when watching the 2020 course, you can map it directly like this:
>
> ```text
> Old usertrapret()
> ≈ New prepare_return() + usertrap returning satp + userret
> ```
>
> The 2025 version of the xv6 book you uploaded has also been changed to explain `prepare_return()`.

## RISC-V assembly

A series of not-so-difficult questions, so I'll just put the answers out directly:

```txt
Which registers contain arguments to functions? For example, which register holds 13 in main's call to printf?

RISC-V uses a0–a7 to pass the first eight function arguments. In main's call to printf, the value 13 is in the a2 register.

Where is the call to function f in the assembly code for main? Where is the call to g? (Hint: the compiler may inline functions.)

There are no calls to f or g; the compiler inlined the expression f(8) + 1 as 12, which shows up in the assembly as li a1,12

At what address is the function printf located?

According to the line 30:	6c6000ef          	jal	6f6 <printf>, it is located at 6f6

What value is in the register ra just after the jalr to printf in main?

According to the RISC-V documentation, when `jal` jumps to the target function, it saves the address of the next instruction into ra, as the address to jump to after the target function finishes executing, so it is 0x30 + 4 = 0x34

Run the following code.

	unsigned int i = 0x00646c72;
	printf("H%x Wo%s", 57616, (char *) &i);
      
What is the output? Here's an ASCII table that maps bytes to characters.
The output depends on that fact that the RISC-V is little-endian. If the RISC-V were instead big-endian what would you set i to in order to yield the same output? Would you need to change 57616 to a different value?

The output is HE110 World$. %x prints 57616 in hexadecimal, giving 0xe110; as for %s, since RISC-V is little-endian, i = 0x00646c72, and after converting to a 4-byte unsigned integer, the bytes from low to high are r l d 0. If it were big-endian, you would set i = 0x726c6400

Here's a description of little- and big-endian and a more whimsical description.

In the following code, what is going to be printed after 'y='? (note: the answer is not a specific value.) Why does this happen?

	printf("x=%d y=%d", 3);

What gets read is the leftover value in the a2 register, which is UB behavior.
```

## Backtrace

We need to walk up the stack pointer in the kernel stack, printing the return addresses in the current function call chain.

Consider this core principle:

```text
current fp
  fp - 8   → the return address saved in the current stack frame
  fp - 16  → the caller's fp
```

Then, we can just keep looping like this.

hint 1:

> Add the prototype for your `backtrace()` to `kernel/defs.h` so that you can invoke `backtrace` in `sys_pause`.

Nothing much to say, just do it.

hint 2:

> The GCC compiler stores the frame pointer of the currently executing function in the register `s0`. In the section marked by #ifndef __ASSEMBLER__ ... #endif, add the following function to `kernel/riscv.h`:
>
> ```c
> static inline uint64
> r_fp()
> {
>   uint64 x;
>   asm volatile("mv %0, s0" : "=r" (x) );
>   return x;
> }
> ```
>
> and call this function in `backtrace` to read the current frame pointer. `r_fp()` uses [in-line assembly](https://gcc.gnu.org/onlinedocs/gcc/Using-Assembly-Language-with-C.html) to read `s0`.

Nothing much to say here either. Just do it.

hint 3:

It's just the core principle mentioned above.

Concretely, in code:

```c
uint64 ra = *(uint64 *)(fp - 8);
fp = *(uint64 *)(fp - 16);
```

hint 4:

> Your `backtrace()` will need a way to recognize that it has seen the last stack frame, and should stop. A useful fact is that the memory allocated for each kernel stack consists of a single page-aligned page, so that all the stack frames for a given stack are on the same page. You can use `PGROUNDDOWN(fp)` (see `kernel/riscv.h`) to identify the page that a frame pointer refers to.

The point is that we need to loop, and the loop's termination condition is that `fp` is still valid, and the validity of `fp` is determined by whether the page is valid.

First, get the starting address of the page containing the current `fp`:

```c
uint64 stack_bottom = PGROUNDDOWN(fp);
```

The page's ending address:

```c
uint64 stack_top = stack_bottom + PGSIZE;
```

As long as `fp` is still within this page, we can keep traversing:

```c
fp >= stack_bottom + 16 && fp < stack_top
```

Nothing else worth mentioning; just do it as described.

```c
void
backtrace(void)
{
  printf("backtrace:\n");

  uint64 fp = r_fp();

  // 当前内核栈所在页面的范围
  uint64 stack_bottom = PGROUNDDOWN(fp);
  uint64 stack_top = stack_bottom + PGSIZE;

  while(fp >= stack_bottom + 16 && fp < stack_top){
    // 当前函数返回到调用者后的地址
    uint64 ra = *(uint64 *)(fp - 8);
    printf("%p\n", (void*)ra);

    // 切换到调用者的栈帧
    fp = *(uint64 *)(fp - 16);
  }
}
```
## Alarm

Follow the hints.

Hints 1, 2, and 3 have nothing much to say; the only thing worth noting is that I put the `sys_sigalarm` and `sys_sigreturn` function signatures in `sysproc.c`.

Hints 4 and 5: in `proc.h`, the addresses are recorded directly as `uint64`, and cast to pointers later.

Hints 6 and 7 are essentially one point; in fact, just following hint 7's instructions is enough.

Hints 8 and 9: do as instructed.

- Hint 8 means that to determine whether an alarm is valid, you should use `p->alarm_interval > 0`
- Hint 9 means that when the alarm expires, execute `p->trapframe->epc = p->alarm_handler;` to change the program counter for the jump back.

The content after hint 10 is the crux of this problem.

Hint 11 asks which registers should be saved, and hints that there are many. The answer is that all user registers should be saved, because executing the handler may change the contents of many registers. The simplest solution is to save the entire `trapframe`.

Thus, hint 12 addresses this point. Add a `struct trapframe alarm_trapframe` to `struct proc`:

- `p->trapframe`: the user context currently in use, which changes as the handler and system calls run
- `p->alarm_trapframe`: a fixed snapshot of the original program state before the alarm occurred

The solution is:

```c
memmove(&p->alarm_trapframe, p->trapframe, sizeof(struct trapframe));
p->trapframe->epc = p->alarm_handler;
```

> [!tip]
>
> `memmove()` copies from the latter argument to the former.

Hint 13 mainly addresses preventing handler reentrancy. Specifically: while the handler is running, a timer interrupt may obviously occur again; if the alarm is triggered again, the original handler recursively enters itself, causing `alarm_trapframe` to be overwritten by the trapframe from during the handler's execution, and `sigreturn()` can never find the interrupted original program.

The solution is to add a flag `int alarm_handling;`, initialized to 0 in `allocproc`. The alarm can only accumulate and trigger when `p->alarm_interval > 0 && !p->alarm_handling`, and upon triggering, set `p->alarm_ticks = 0;` and `p->alarm_handling = 1;`.

Finally, hint 14: `sys_sigreturn()` restores the backup into the current trapframe, i.e.:

```c
memmove(p->trapframe,
        &p->alarm_trapframe,
        sizeof(struct trapframe));
```

> [!note]
>
> `sigreturn()` is the last step of the handler, used to tell the kernel that the handler has finished executing and to send me back to the original program.

But `a0` is special, because `a0` is treated as the return value. Reading the code of `syscall()`, you'll find that system calls are executed like this:

```c
p->trapframe->a0 = syscalls[num]();
```

That is, the original `a0` must be saved and returned as the return value of `sigreturn()`.

```c
uint64
sys_sigreturn(void)
{
  struct proc *p = myproc();

  uint64 old_a0 = p->alarm_trapframe.a0;
  memmove(p->trapframe, &p->alarm_trapframe, sizeof(struct trapframe));
  p->alarm_handling = 0;
  return old_a0;
}
```

Running `make grade`:

<img src="https://image.wendaining.top/image-20260808105800805.png" style="zoom:33%;" />
