# xv6 Lab3 Page tables - 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-lab3-page-tables/>). I am continuously working to improve the translation.

## Reading the xv6 book

I found two good Chinese translations:

- [Course Introduction · 6.S081 All-In-One](https://xv6.dgs.zone/)
- [HelloYJohn/xv6-riscv-book-zh-cn: translation of xv6-riscv-book](https://github.com/HelloYJohn/xv6-riscv-book-zh-cn)

So let's try skimming through Chapter 3.

- I found that I still can't really get into reading the book, so I might as well just start doing the lab and learn along the way.

## Inspect a user-process page table

No code needs to be written here; it's mainly about inspecting things.

Run `pgtbltest`:

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

What gets printed is the first 10 and last 10 PTEs of this process.

Let's analyze. First, according to the xv6 book, the structure of a PTE is as shown in the figure:

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

So:

- `va`: the virtual page address as seen by the process
- `pte`: the full page table entry
- `pa`: the physical page address it maps to
- `perm`: the flag bits in the low 10 bits of the PTE

Since one page is 4096 Bytes, i.e. 0x1000 Bytes, we can see the va values are `0x0 0x1000 0x2000...`.

Parsing the perm of each PTE one by one:

| Virtual address                | `perm` | Interpretation              |
| ------------------------------ | ------ | --------------------- |
| `0x0`                          | `0x5B` | `V R X U A`           |
| `0x1000`                       | `0x5B` | `V R X U A`           |
| `0x2000`                       | `0x17` | `V R W U`             |
| `0x3000`                       | `0x07` | `V R W`, but no `U`   |
| `0x4000`                       | `0xD7` | `V R W U A D`         |
| `0x5000`–`0x9000`             | `0`    | No valid mapping      |
| `0x3FFFFF6000`–`0x3FFFFFD000` | `0`    | No valid mapping      |
| `0x3FFFFFE000`                 | `0xC7` | `V R W A D`, no `U` |
| `0x3FFFFFF000`                 | `0x4B` | `V R X A`, no `U`   |

 Now consider Figure 3.4:

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

Analyzing from the low bits, both `va 0x0` and `va 0x1000` have `perm 0x5B = R-XU`, i.e.: readable, executable, user-accessible, not writable. So obviously, this is the `text` section.

Next, analyzing `va 0x2000`, `perm 0x17 = R-WU` corresponds to readable, writable, user-accessible, not executable, which corresponds to `data` `R-WU`.

The subsequent analysis follows the same logic; just compare against the figure. And quite obviously, the top two pages are the trampoline and the trapframe respectively.

## Speed up system calls

Although this problem is labeled easy, I still did a bit of "answer-oriented learning" (meaning I couldn't do it, so I asked an Agent and then looked at the answer).

Let's sort out the requirements: `kernel/memlayout.h` defines a virtual address (va) like this:

```c
#define USYSCALL (TRAPFRAME - PGSIZE)
```

The requirement is: define a struct like this at that page:

```c
struct usyscall {
  int pid;  // Process ID
};
```

Initialize it to the current process's PID, thereby eliminating the need to call the `getpid()` system call (trapping into kernel mode); user space can read the pid directly from memory.

The hint tells us:

> - Choose permission bits that allow userspace to only read the page.
> - There are a few things that need to be done over the lifecycle of a new page. For inspiration, understand the trapframe handling in `kernel/proc.c`.
>     A new page needs several operations over its lifecycle. Use the trapframe handling in `kernel/proc.c` as a reference.

To briefly summarize: referring to Figure 3.4, we have a va for the trapframe, and now we've added a usyscall **right below** the trapframe. For the implementation of usyscall, we can completely follow the trapframe handling in `kernel/proc.c`.

So, first we need to add a `struct usyscall *usyscall` to `struct proc` in `kernel/proc.h`, modeled after `trapframe`:

```c
struct trapframe *trapframe; // data page for trampoline.S
struct usyscall *usyscall;   // USYSCALL page, shared read-only with user
```

Then, in `kernel/proc.c`, Ctrl + F search for trapframe, and implement the usyscall parts one by one by following the trapframe implementation.

```c
// static struct proc* allocproc(void)
 // Allocate a trapframe page.
  if((p->trapframe = (struct trapframe *)kalloc()) == 0){
    freeproc(p);
    release(&p->lock);
    return 0;
  }
  if((p->usyscall = (struct usyscall *)kalloc()) == 0) {
    freeproc(p);
    release(&p->lock);
    return 0;
  }
  p->usyscall->pid = p->pid;
```

Since this is actually a per-process value that doesn't change after the process is created, the `pid` logic is already fully implemented here.

Next up: this is pure imitation.

```c
static void
freeproc(struct proc *p)
{
  if(p->trapframe)
    kfree((void*)p->trapframe);
  p->trapframe = 0;
  if(p->usyscall)
    kfree((void *)p->usyscall);
  p->usyscall = 0;	
  ...
}
```

Here is a rather critical part: creating the page table.

```c
// Create a user page table for a given process, with no user memory,
// but with trampoline and trapframe pages.
pagetable_t
proc_pagetable(struct proc *p)
{
  pagetable_t pagetable;

  // An empty page table.
  pagetable = uvmcreate();
  if(pagetable == 0)
    return 0;

  // map the trampoline code (for system call return)
  // at the highest user virtual address.
  // only the supervisor uses it, on the way
  // to/from user space, so not PTE_U.
  if(mappages(pagetable, TRAMPOLINE, PGSIZE,
              (uint64)trampoline, PTE_R | PTE_X) < 0){
    uvmfree(pagetable, 0);
    return 0;
  }

  // map the trapframe page just below the trampoline page, for
  // trampoline.S.
  if(mappages(pagetable, TRAPFRAME, PGSIZE,
              (uint64)(p->trapframe), PTE_R | PTE_W) < 0){
    uvmunmap(pagetable, TRAMPOLINE, 1, 0);
    uvmfree(pagetable, 0);
    return 0;
  }

  if(mappages(pagetable, USYSCALL, PGSIZE,
              (uint64)(p->usyscall), PTE_R | PTE_U) < 0){
    uvmunmap(pagetable, TRAPFRAME, 1, 0);
    uvmunmap(pagetable, TRAMPOLINE, 1, 0); // !!!
    uvmfree(pagetable, 0);
    return 0;
  }

  return pagetable;
}
```

`mappages()` establishes the mapping from va to the actual physical address, and also sets the perm; here, following the original text, user mode is allowed to read.

The key point is this cleanup step:

```c
uvmunmap(pagetable, TRAPFRAME, 1, 0);
uvmunmap(pagetable, TRAMPOLINE, 1, 0); // !!!
uvmfree(pagetable, 0);
```

What it actually means is (summarized by LLM):

> First, look at your bug
>
> The error handling for USYSCALL in your `proc_pagetable` (lines 214-219):
>
> ```c
> if(mappages(pagetable, USYSCALL, PGSIZE,
>             (uint64)(p->usyscall), PTE_R | PTE_U) < 0){
>     uvmunmap(pagetable, TRAPFRAME, 1, 0);   // 只 unmap 了 TRAPFRAME
>     uvmfree(pagetable, 0);
>     return 0;
> }
> ```
>
> **You missed `uvmunmap(pagetable, TRAMPOLINE, 1, 0)`.** Compare with the error handling when TRAPFRAME fails (lines 207-211) — it unmaps TRAMPOLINE, so here you should also unmap both TRAMPOLINE + TRAPFRAME.
>
> Error rollback in `proc_pagetable`
>
> Imagine you're building with blocks, **building from the top down** (because TRAMPOLINE is at the very top):
>
> ```TEXT
> TRAMPOLINE  ✓ built
> TRAPFRAME   ✓ built
> USYSCALL    ✗ failed while building this one!
> ```
>
> At this point you must tear down everything that was **successfully built**, and in **reverse order** — you can't leave a crippled page table for `freeproc` to use. `freeproc` assumes the page table structure is intact. That's why:
>
> - TRAPFRAME fails → roll back TRAMPOLINE (only one succeeded)
> - USYSCALL fails → roll back TRAMPOLINE **and** TRAPFRAME (two succeeded)
>

Afterwards, check the handling of `trapframe` in `kfork`:

```c
// copy saved user registers.
*(np->trapframe) = *(p->trapframe);

// Cause fork to return 0 in the child.
np->trapframe->a0 = 0;
```

We can easily notice that the trapframe logic is actually implemented here (inheriting from the parent process). But for `usyscall`, since the PID stays unchanged once the process is created, there's actually no need to handle this.

At this point, this problem is complete.

> [!note]
>
> By the way, where is the trapframe logic actually implemented?

> The trapframe and the C language function call stack frame are **completely different things**. The "frame" here refers to "a saved snapshot of CPU state".
>
> Its full logic is spread across **three files**:
>
> ---
>
> 1. Data structure definition — `kernel/proc.h` lines 43-80
>
> ```c
> struct trapframe {
>   /*   0 */ uint64 kernel_satp;   // kernel page table
>   /*   8 */ uint64 kernel_sp;     // top of process's kernel stack
>   /*  16 */ uint64 kernel_trap;   // usertrap()
>   /*  24 */ uint64 epc;           // saved user program counter
>   /*  32 */ uint64 kernel_hartid; // saved kernel tp
>   /*  40 */ uint64 ra;
>   /*  48 */ uint64 sp;
>   /*  56 */ uint64 gp;
>   ...
>   /* 280 */ uint64 t6;
> };
> ```
>
> Note the comment numbers next to each field — those are **byte offsets**. That's why you see things like `sd ra, 40(a0)` in `trampoline.S`: the offset of the `ra` register in the trapframe struct is exactly 40.
>
> ---
>
> 2. Assembly layer: physical saving/restoring of registers — `kernel/trampoline.S`
>
> This is the core of the whole mechanism, in two parts:
>
> **Entering the kernel (`uservec`, line 22):**
>
> ```TEXT
> A trap occurs in user mode
>   → hardware switches to kernel mode, jumps to uservec
>   → sd (store) all user registers to the TRAPFRAME address
>      sd ra, 40(a0)    // save to trapframe->ra (offset 40)
>      sd sp, 48(a0)    // save to trapframe->sp (offset 48)
>      ...
>   → load kernel context from the trapframe
>      ld sp, 8(a0)     // load kernel stack
>      ld t0, 16(a0)    // load usertrap() address
>      ld t1, 0(a0)     // load kernel page table
>   → switch page table
>   → jalr t0           // jump to the C code usertrap()
> ```
>
> **Returning to user mode (`userret`, line 101):**
>
> ```TEXT
> After the C code usertrap() returns
>   → switch back to the user page table
>   → restore all user registers from TRAPFRAME
>      ld ra, 40(a0)
>      ld sp, 48(a0)
>      ...
>   → sret             // hardware switches back to user mode
> ```
>
> ---
>
> 3. C layer: filling in kernel-side information — `kernel/trap.c`
>
> **On entry (`usertrap`, line 38):**
>
> ```c
> p->trapframe->epc = r_sepc();   // 保存用户被中断时的 PC
> // ... 处理系统调用、中断、缺页异常 ...
> ```
>
> **Before returning (`prepare_return`, line 100):**
>
> ```c
> p->trapframe->kernel_satp = r_satp();         // 内核页表地址
> p->trapframe->kernel_sp = p->kstack + PGSIZE; // 内核栈顶
> p->trapframe->kernel_trap = (uint64)usertrap; // 下次 trap 跳到哪
> p->trapframe->kernel_hartid = r_tp();         // CPU 编号
> ```
>
> This way, the next time the process traps, `uservec` in `trampoline.S` can read the correct kernel stack, kernel page table, and C handler address from the trapframe.
>
> ---
>
> Complete data flow
>
> ```TEXT
> Running in user mode
>     │
>     ▼ (trap: system call/interrupt/exception)
> uservec (trampoline.S)
>     │  save user registers ──→ trapframe.ra, .sp, .a0...
>     │  load kernel context ←── trapframe.kernel_sp, .kernel_satp, .kernel_trap
>     ▼
> usertrap() (trap.c)
>     │  handle trap logic
>     │
> prepare_return() (trap.c)
>     │  write kernel context ──→ trapframe.kernel_sp, .kernel_satp...
>     │
> userret (trampoline.S)
>     │  restore user registers ←── trapframe.ra, .sp, .a0...
>     ▼
> Continue running in user mode
> ```
>
> So the trapframe is essentially a **swap area**:
>
> - Entering the kernel: user registers are unloaded here, kernel context is loaded from here
> - Leaving the kernel: kernel context is unloaded here, user registers are loaded from here
>
> It has nothing to do with the C language function call stack (which is the compiler-generated prologue/epilogue, manipulated via `sp` and `fp`). Every `sd`/`ld` here is hand-written assembly.

## Print a page table

Although it's labeled easy, I spent about 5+ hours on it, grilling AI while thinking for myself...

Let me roughly summarize. First, I found that I wasn't familiar with multi-level page tables, so I simply wrote out a summary by hand:

<img src="https://image.wendaining.top/3c37e1f880d2b030accf9e4241addadd.jpg" alt="The handwriting is so ugly..." style="zoom:50%;" />

The hint says: refer to the `freewalk` function:

```C
// Recursively free page-table pages.
// All leaf mappings must already have been removed.
void
freewalk(pagetable_t pagetable)
{
  // there are 2^9 = 512 PTEs in a page table.
  for(int i = 0; i < 512; i++){
    pte_t pte = pagetable[i];
    if((pte & PTE_V) && (pte & (PTE_R|PTE_W|PTE_X)) == 0){
      // this PTE points to a lower-level page table.
      uint64 child = PTE2PA(pte);
      freewalk((pagetable_t)child);
      pagetable[i] = 0;
    } else if(pte & PTE_V){
      // backtrace();
      panic("freewalk: leaf");
    }
  }
  kfree((void*)pagetable);
}
```

You can implement it by roughly imitating its framework.

One point of confusion: why is the condition for determining that a PTE points to the next-level page table:

```c
// 此条件等于该 pte 不是终末层，而是指向下一层
(pte & (PTE_R|PTE_W|PTE_X)) == 0
```

Actually, this is a RISC-V rule: a PTE that points to the next-level page table (a non-leaf PTE) must have its R, W, X bits all set to 0. Only PTEs pointing to the final data page (leaf PTEs) are allowed to have R/W/X set.

Analyzing the source code confirms this:

```c
# kernel/vm.c mappages()
if(*pte & PTE_V)
  panic("mappages: remap");
*pte = PA2PTE(pa) | perm | PTE_V;
```

The perm passed in here is guaranteed to contain at least one of R W X, otherwise it panics.

Then start implementing `vmprint`. Since the parameters are fixed, we need to set up a helper function to do the recursive traversal:

```c
void
vmprint_recur(pagetable_t pagetable, int level, uint64 va)
{
  for (int i = 0; i < 512; ++i) {
    pte_t pte = pagetable[i];
    if (pte & PTE_V) { // is a valid PTE
      // 这里记得强转 i
      uint64 newva = va | ((uint64)i << PXSHIFT(level));
      for (int j = 0; j <= 2 - level; j++) {
        printf(" ..");
      }
      printf("%p: pte %p pa %p\n", (void *)newva, (void *)pte, (void *)PTE2PA(pte));
      if ((pte & (PTE_R|PTE_W|PTE_X)) == 0) {
        vmprint_recur((pagetable_t)PTE2PA(pte), level - 1, newva);
      }
    }
  }
}

void
vmprint(pagetable_t pagetable)
{
  printf("page table %p\n", pagetable);
  // ！！从 2 开始 而不是从 1 开始！！
  vmprint_recur(pagetable, 2, 0);
}
```

Everything else is fine; the main thing is **computing `newva`**, which deserves a detailed explanation:

**The `i` in `pagetable[i]` corresponds linearly to the VA.** I initially thought that iterating like `for(int i=0;i<512;i++) pagetable[i]` would yield something completely chaotic and illogical, but in fact, considering how multi-level page tables work, this `i` corresponds to the `i`-th segment of the virtual address va. More specifically:

> The real principle is: each page table entry represents a range of virtual addresses. `newva` computes the starting virtual address of the range represented by the current PTE.
>
> Don't think about bit operations yet; first think about "splitting up the address space"
>
> Each page table has 512 PTEs, so it evenly splits the address range it's responsible for into 512 parts.
>
> When `level = 2`:
>
> The root page table manages the entire Sv39 address space.
>
> Each of its PTEs is responsible for `1 GiB` ($\frac{2^{39}}{2^9}=2^{30}bit=1GiB$)
>
> So the root page table:
>
> ```text
> pagetable[0] → starting from 0 GiB
> pagetable[1] → starting from 1 GiB
> pagetable[2] → starting from 2 GiB
> ...
> ```
>
> Suppose currently:
>
> ```c
> i = 3;
> ```
>
> Then the starting point of the range represented by entry 3 is:
>
> ```text
> 3 × 1 GiB
> ```
>
> i.e.:
>
> ```c
> 3 << 30
> ```
>
> Because:
>
> ```text
> 1 GiB = 2^30
> ```
>
> ------
>
> `level = 1`
>
> After entering the next page table, it splits that `1 GiB` into 512 parts again.
>
> Each entry is responsible for:
>
> ```text
> 1 GiB / 512 = 2 MiB
> ```
>
> So the offset produced by entry `i` at this point is:
>
> ```text
> i × 2 MiB
> ```
>
> And:
>
> ```text
> 2 MiB = 2^21
> ```
>
> Therefore:
>
> ```c
> i << 21
> ```
>
> ------
>
> `level = 0`
>
> The last-level page table splits `2 MiB` into 512 parts again.
>
> Each entry is responsible for:
>
> ```text
> 2 MiB / 512 = 4 KiB
> ```
>
> So the offset produced by entry `i`:
>
> ```text
> i × 4 KiB
> ```
>
> And:
>
> ```text
> 4 KiB = 2^12
> ```
>
> So:
>
> ```c
> i << 12
> ```
>
> ------
>
> The fundamental meaning of `PXSHIFT(level)`
>
> ```c
> #define PXSHIFT(level) (12 + 9 * level)
> ```
>
> What it actually computes is: **the size of the region represented by one PTE at the current level is `2^PXSHIFT(level)` bytes.**
>
> Because:
>
> ```text
> level 0: one PTE covers 4 KiB  = 2^12
> level 1: one PTE covers 2 MiB  = 2^21
> level 2: one PTE covers 1 GiB  = 2^30
> ```
>
> So:
>
> ```c
> (uint64)i << PXSHIFT(level)
> ```
>
> is equivalent to:
>
> ```c
> i * 当前层每个 PTE 负责的字节数
> ```
>
> ------
>
> A complete example
>
> Suppose the traversal path is:
>
> ```text
> Root page table[1]
>   → Middle page table[3]
>     → Lowest page table[5]
> ```
>
> Initially:
>
> ```c
> va = 0;
> ```
>
> Entry 1 of the root page table
>
> Each entry covers `1 GiB`:
>
> ```c
> newva = 0 + 1 * 1 GiB;
>       = 0x40000000;
> ```
>
> It's now determined: the address is in the first `1 GiB` region.
>
> Entry 3 of the next level
>
> Each entry covers `2 MiB`:
>
> ```c
> newva = 0x40000000 + 3 * 2 MiB;
>       = 0x40000000 + 0x600000;
>       = 0x40600000;
> ```
>
> Entry 5 of the last level
>
> Each entry covers `4 KiB`:
>
> ```c
> newva = 0x40600000 + 5 * 4 KiB;
>       = 0x40600000 + 0x5000;
>       = 0x40605000;
> ```
>
> So the virtual page corresponding to this page table path is:
>
> ```text
> 0x40605000
> ```
>
> Why the code uses `|` instead of `+`
>
> ```c
> newva = va | ((uint64)i << PXSHIFT(level));
> ```
>
> You can first understand it as:
>
> ```c
> newva = va + i * 当前层每项负责的大小;
> ```
>
> Here, `|` and `+` give the same result, because each level uses different address bits, so they don't overlap.
>
> So the most literal translation of this line of code is:
>
> ```c
> 当前区域的起点
> +
> 当前页表第 i 项在区域内的偏移
> =
> 当前 PTE 所代表区域的起点
> ```
>
> `level` is not used to compute `i`. It only determines:
>
> ```text
> Whether each PTE of the current page table represents 4 KiB, 2 MiB, or 1 GiB.
> ```

The parameters passed when calling the recursive function are also an issue; **and most importantly, how do you compute the virtual address va**? Let me explain these two problems together.

First, it's essential to be clear about this model:

```text
[ VPN2 ][ VPN1 ][ VPN0 ][ offset ]
                              ↑ 12 bits
```

Also, by reading the `walk` function, we can easily notice that **level only takes the values 0, 1, 2, and it starts high**, so the `level` passed in at the beginning must be 2.

> [!note]
>
> For example, you can also look at the macros:
>
> ```c
> #define PXMASK          0x1FF // 低 9 位是 1
> #define PXSHIFT(level)  (PGSHIFT+(9*(level)))
> #define PX(level, va) ((((uint64) (va)) >> PXSHIFT(level)) & PXMASK)
> ```
>
> If you want to extract `VPN[0]`, you compute `(va >> 12) & 0x1FF`
>
> Right-shifting by 12 bits means: **discard the page offset and move bits 12–20 down to the lowest bits**, then AND with `0b111111111`, and you naturally get what that block is.

Now, considering how `newva` is computed (`uint64 newva = va | ((uint64)i << PXSHIFT(*level*));`), it becomes very clear: it's just accumulating the offset of this level on top of the previous one.

> [!important]
>
> Each traversal is **per page table**.

> [!tip]
>
> **Remember to cast i here**.

Anyway, I feel my understanding of the concepts is really quite poor, which is a bit troubling. Spending 5 hours on such an easy problem is indeed a bit frustrating, but there's no way around it — let's keep going.
## Use superpages

Seeing that this was a Hard problem, I got a bit nervous, so I went online to search for explanations of this knowledge, and unexpectedly found some good resources:

- MIT6.s081/6.828 lecture04: page tables and Lab3 notes - an article by 逆风的大船 (Ship Against the Wind) - Zhihu https://zhuanlan.zhihu.com/p/651171058
    - This blogger's handwritten notes are extremely detailed and very useful
- https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081
    - The "text version of the recorded lectures" for each class — I think it's much better than the xv6 book, and the questions students ask are quite good too.

Let me excerpt a few things:

- The `kvminithart` function, which is very important:

    > This function first sets the SATP register; the kernel_pagetable variable comes from the first line of kvminit. So here, the kernel is effectively telling the MMU to use the page table that was just set up. What happens to the address of the next instruction after this instruction executes?
    >
    > Before this instruction, there was no usable page table, so there was no address translation either. After this instruction executes, the program counter increases by 4. And when the next instruction after that is executed, **the program counter will be translated through the page table in memory**.
    >
    > So the moment this instruction executes is a very important moment. Because address translation only takes effect after this instruction, and every memory address used afterwards may map to a different physical memory address. Before this instruction, we were using physical memory addresses; after this instruction, the page table takes effect, and all memory addresses take on a different meaning — they become virtual memory addresses.

- Why is a 3-level page table better than one huge page table?

    > Professor Frans: That's a good question. The reason is that in a 3-level page table, a large number of PTEs can go unstored. For example, in the top-level page table, if a PTE is empty, then you don't need to create the corresponding middle-level and lowest-level page tables, or the PTEs inside them, at all. So it's as if a large stretch of addresses in the entire virtual address space simply doesn't need any mapping.

- The `proc_mapstacks()` function is quite interesting; read it with reference to [MIT6.s081/6.828 lecture4: page tables and Lab3 notes - byFMH - cnblogs](https://www.cnblogs.com/looking-for-zihuatanejo/p/17629873.html)

- What is the purpose of a guard page?

    > A guard page is a page of **virtual memory that is deliberately forbidden to be accessed**, placed next to the stack to detect stack overflow.
    >
    > For example, kernel stacks:
    >
    > ```TEXT
    > kernel stack
    > guard page    ← not mapped
    > kernel stack
    > guard page
    > ```
    >
    > If the kernel stack keeps growing downward and crosses the boundary into the guard page, a page fault is triggered, eventually causing the kernel to `panic`.
    >
    > This is better than the stack silently overwriting other kernel data: **expose errors as early as possible, rather than continuing to run with corrupted data.**
    >
    > There are two kinds in xv6:
    >
    > - **Kernel stack guard pages**: the PTE is invalid, so even kernel access faults.
    > - **User stack guard pages**: `PTE_U` is cleared, so user mode cannot access it; on stack overflow the process faults.

- Understanding the questions students ask in this section is important: [4.5 Kernel Page Table | MIT6.S081](https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/lec04-page-tables-frans/4.5-kernel-page-table)

    The kernel page table also contains mappings for user processes, and for the kernel, va == pa — they are the same.

Anyway, after reading through all this content (though it's still a bit muddled), I started implementing this Lab:

The goal is to implement superpages:

- The default RISC-V page size is 4KB
- Here we need to implement pages of size 2MB

Reading the hint:

> Read `superpg_fork` and `superpg_free` in `user/pgtbltest.c`.

Reading it myself was a bit of a struggle, so I let an Agent do the work:

> Key background definitions
>
> | Macro/Function        | Value/Purpose                                            |
> | --------------------- | -------------------------------------------------------- |
> | `SUPERPGSIZE`         | **2MB** (2,097,152 bytes) — the size of one superpage    |
> | `SZ`                  | `8 * SUPERPGSIZE` = **16MB**                             |
> | `SUPERPGROUNDUP(a)`   | Aligns an address **up** to a 2MB boundary               |
> | `SUPERPGROUNDDOWN(a)` | Aligns an address **down** to a 2MB boundary             |
> | `pgpte(void *va)`     | System call, returns the PTE for `va` in the current process's page table |
> | `SBRK_ERROR`          | `(char *)-1`, the return value when sbrk fails           |
>
> ---
>
> `superpg_fork()` — tests whether fork correctly copies superpages
>
> This function has **two phases**:
>
> Phase one (lines 138-156): verify that fork correctly copies superpages
>
> ```TEXT
> sbrk(SZ=16MB)
>     │
>     ▼
> ┌─────────────────────────────┐
> │  8 × 2MB superpages         │  ← parent process address space
> │  (16MB total)               │
> └─────────────────────────────┘
>     │
>     │ supercheck(end) — parent verifies superpages exist
>     │
>     │ fork()
>     │
>     ├── Parent: wait()
>     │
>     └── Child: supercheck(end) — the child must also see the same superpages
>                   exit(0)
> ```
>
> **Core logic**: if fork correctly copies the page table (including superpage mappings), then in the child's address space, the same virtual address range should also have superpage mappings, and the PTE attributes should be exactly identical.
>
> Phase two (lines 159-173): verify that a forked child cannot access freed memory
>
> ```TEXT
> sbrk(-16MB)  — free all memory
>     │
>     │ fork()
>     │
>     ├── Parent: wait(&status)
>     │           if status == 0 (child exited normally), it means the child successfully
>     │           accessed freed memory → test failed!
>     │
>     └── Child: *(end + 1) = '9'  — attempt to write to memory already freed by the parent
>                  if the kernel works correctly → page fault → kernel kills the child (status ≠ 0)
> ```
>
> This is a **safety test**: ensure that after a process frees memory, a forked child cannot access that already-freed memory.
>
> The `supercheck()` helper function (lines 94-128)
>
> This function verifies whether a memory region ending at `end` uses superpages:
>
> 1. **Lines 98-105**: check the ordinary pages (the non-superpage portion) between `end` and the next 2MB-aligned boundary, ensuring each has a valid PTE
> 2. **Lines 107-118**: check the **512 PGSIZE pages** after the aligned boundary (i.e., one 2MB superpage), verifying:
>    - All PTEs are **non-zero** (the mapping exists)
>    - **All PTE values are exactly identical** (this is the key characteristic of a superpage — one L2-level PTE covers the entire 2MB region)
>    - The PTE has the `PTE_V | PTE_R | PTE_W` flags
> 3. **Lines 120-127**: perform read/write tests on the superpage region to verify data correctness
>
> ---
>
> OK, let me break down the logic of `superpg_free` step by step in a more intuitive way. The core confusion may be: **what exactly is the object of the sbrk operation, and what does SUPERPGROUNDDOWN alignment actually do**.
>
> ---
>
> Prerequisite knowledge
>
> - **`sbrk(n)`**: grows/shrinks the process's heap by `n` bytes, returning **the old top-of-heap address**
> - **`sbrk(0)`**: doesn't change the heap size, only returns **the current top-of-heap address** (used to query where the heap top is)
> - **The heap grows contiguously**, from low addresses to high addresses. `sbrk(正数)` = heap grows upward, `sbrk(负数)` = heap shrinks downward
>
> The heap's memory layout is roughly:
>
> ```TEXT
> Low addresses
> ├── code / data
> ├── heap (allocated)  ← region managed by sbrk
> ├── ... unallocated ...
> └── stack
> High addresses
> ```
>
> ---
>
> Line-by-line breakdown of `superpg_free`
>
> Step 1: allocate 16MB (lines 185-188)
>
> ```c
> char *end = sbrk(SZ);  // SZ = 8 * SUPERPGSIZE = 16MB
> ```
>
> At this point `end` = **the old top of the heap before allocation** (which is also the start of the newly allocated region). Drawn as a diagram:
>
> ```TEXT
>                     end (old heap top)
>                     │
>                     ▼
> ┌───────────────────┼────────────────────────────────┐
> │   Original heap   │     Newly allocated 16MB        │
> │                   │   = 8 × 2MB superpages          │
> └───────────────────┼────────────────────────────────┘
>                     ▲                                ▲
>                     │                                │
>                   end                        end + 16MB
>                                             = new heap top
> ```
>
> At this point `sbrk(0)` would return `end + 16MB`.
>
> ---
>
> Step 2: free the part "beyond a superpage boundary" (lines 190-193)
>
> This is the most crucial and most confusing part. Let me draw it out:
>
> ```c
> char *a = sbrk(0);                      // a = 当前堆顶
> uint64 s = SUPERPGROUNDDOWN((uint64)a); // s = 将堆顶向下对齐到 2MB 边界
> sbrk(-((uint64)a - s));                 // 释放 a-s 字节
> a = sbrk(0);                            // a = 新堆顶（现在对齐到 2MB 了）
> ```
>
> **Why is this step needed?** Because the 16MB allocated by `sbrk(16MB)` is exactly 8 superpages, but if the heap was not 2MB-aligned before the allocation, then the **end position** of this 16MB won't be 2MB-aligned either. The later tests need the heap top to be aligned exactly to a 2MB boundary, so this step trims off the "overhanging" fragment.
>
> Drawn as a concrete example (assume the heap top value is unaligned):
>
> ```TEXT
> Suppose heap top a = 0x10_300_000 (not aligned to 2MB)
> 
> SUPERPGROUNDDOWN(0x10_300_000)
> = align down to 2MB
> = 0x10_200_000  ← this is s
> 
> Difference = a - s = 0x10_300_000 - 0x10_200_000 = 0x100_000 = 1MB
> 
> sbrk(-1MB) = free 1MB, heap top retreats to 0x10_200_000
> ```
>
> Drawn as a diagram:
>
> ```TEXT
> Before freeing:
> ┌────────────────────────────────────────┬─────────────┐
> │         Complete superpages            │  Fragment   │
> │         each 2MB                       │  (< 2MB)    │
> └────────────────────────────────────────┴─────────────┘
>                                          ▲             ▲
>                                          │             │
>                                     s = 2MB boundary  a = heap top
>                                     (aligned)         (unaligned)
> 
> After freeing sbrk(-(a-s)):
> ┌────────────────────────────────────────┐
> │         Complete superpages            │
> │         each 2MB                       │
> └────────────────────────────────────────┘
>                                          ▲
>                                          │
>                                     a = new heap top = s
>                                     (aligned exactly to 2MB)
> ```
>
> **Simplified understanding**: this step is "trimming the edge", ensuring the heap top lands exactly on a 2MB boundary. At this point, the address returned by `sbrk(0)` is 2MB-aligned.
>
> ---
>
> Step 3: verify the last two 4KB pages belong to the same superpage (lines 195-199)
>
> ```c
> pte_t pte1 = (pte_t) pgpte((void *)(a - PGSIZE));      // 倒数第 1 页的 PTE
> pte_t pte2 = (pte_t) pgpte((void *)(a - 2*PGSIZE));     // 倒数第 2 页的 PTE
> if (pte1 != pte2) {
>     err("not a super page");
> }
> ```
>
> ```TEXT
> Heap top a (2MB-aligned)
> │
> │  a - 1*PGSIZE  ← last 4KB page  → pte1
> │  a - 2*PGSIZE  ← second-to-last 4KB page → pte2
> │  ...
> │  a - 512*PGSIZE (= a - 2MB) ← start of the superpage
> │
> ▼
> ```
>
> **If pte1 == pte2**, it means these two 4KB pages share the same 2MB-level PTE → they belong to the same superpage ✓
>
> (If they were unrelated ordinary 4KB pages, the PTE values would differ, because the physical addresses differ.)
>
> ---
>
> Step 4: write data (lines 201-203)
>
> ```c
> *(a - PGSIZE + 1) = '8';      // 倒数第 1 页
> *(a - 2*PGSIZE + 1) = '9';    // 倒数第 2 页
> ```
>
> ```TEXT
> ┌──────────────────────────────┬───────────┬───────────┐
> │   Remaining superpage part   │ 2nd-to-last │  Last page  │
> │   ...                        │ write '9' │ write '8' │
> └──────────────────────────────┴───────────┴───────────┘
>                                               ▲
>                                               │
>                                           a = heap top
> ```
>
> ---
>
> Step 5: free the last 4KB → triggers superpage splitting! (lines 205-207)
>
> ```c
> sbrk(-PGSIZE);   // 释放最后 4KB
> a = sbrk(0);     // 新堆顶
> ```
>
> ```TEXT
> Before freeing:
> ┌──────────────────────────────┬───────────┬───────────┐
> │   One 2MB superpage          │   '9'     │   '8'     │
> │   (512 4KB pages, sharing 1 PTE)  │           │           │
> └──────────────────────────────┴───────────┴───────────┘
>                                               ▲
>                                               │
>                                          old heap top a
> 
> After freeing sbrk(-PGSIZE):
> ┌──────────────────────────────┬───────────┐
> │   Split into 510 independent │   '9'     │  freed '8'
> │   4KB pages                  │  kept     │  ← should be inaccessible
> │   (no longer 1 superpage)    │           │
> └──────────────────────────────┴───────────┘
>                                ▲
>                                │
>                           new heap top a
> ```
>
> **This is the core test point**: when `sbrk(-PGSIZE)` frees only the last 4KB page of the superpage, the kernel **must** split the original 2MB superpage into 511 independent ordinary 4KB pages + free the last page. It cannot simply free the entire 2MB.
>
> ---
>
> Step 6: verify data is not lost after splitting (lines 209-211)
>
> ```c
> if (*(a - PGSIZE + 1) != '9') {
>     err("lost content after freeing part of super page");
> }
> ```
>
> After freeing, `a` is the new heap top. `a - PGSIZE` is now the last **still valid** 4KB page (where `'9'` was written earlier), and the data must still be there.
>
> ---
>
> Step 7: fork to verify isolation (lines 213-230)
>
> ```c
> if ((pid = fork()) < 0) {
>     ...
> } else if (pid == 0) {
>     // 子进程尝试访问 a 处的内存（已被父进程释放）
>     if (*(a + 1) == '9') {
>         exit(0);  // 如果能读到 → 安全漏洞！
>     }
> }
> ```
>
> - The parent freed the 4KB page starting at `a`
> - When the child is forked, this page **should not** appear in the child's address space
> - If the child accesses `*(a + 1)` successfully and exits normally → **test failed** (isolation broken)
> - Correct behavior: child page faults → killed by the kernel → parent sees `status ≠ 0` → **test passes**
>
> ---
>
> Steps 8-9: verify PTE cleanup + page-by-page freeing (lines 232-244)
>
> ```c
> pte1 = (pte_t)pgpte((void *)a);
> if (pte1 != 0) {
>     err("pte for freed memory is valid");  // 已释放页的 PTE 必须为 0
> }
> 
> s = SUPERPGROUNDDOWN((uint64)a);  // 找到这个（已拆分）superpage 的起始地址
> for (; (uint64)a > s; a -= PGSIZE) {
>     a = sbrk(-PGSIZE);           // 逐页释放
>     pte1 = (pte_t)pgpte(sbrk(0));
>     if (pte1 != 0) {
>         err("page hasn't been freed");  // 每释放一页，其 PTE 必须变 0
>     }
> }
> ```
>
> The meaning of the loop is: starting from the current heap top, free one page at a time going down, and after each page is freed, check whether that page's PTE has become 0. Keep freeing until the starting boundary `s` of this 2MB region.
>
> ---
>
> Overall logic summary
>
> The test chain of `superpg_free`:
>
> ```TEXT
> Allocate 16MB
>   → trim the edge so the heap top is 2MB-aligned
>     → confirm the last two pages belong to the same superpage
>       → write test data
>         → free only the last 4KB (forcing the superpage to split)
>           → verify: remaining data intact ✓
>           → verify: child cannot access the freed page ✓
>           → verify: freed page's PTE = 0 ✓
>           → free remaining pages one by one, verifying each page's PTE goes to zero ✓
> ```
>
> In one sentence: **verify that when only part of a superpage is freed, the kernel can correctly "break up" the superpage into ordinary pages, while keeping the data of the un-freed part intact and maintaining inter-process isolation.**
>
> ---
>
> The relationship between the two tests
>
> | Test           | What it verifies                                             |
> | -------------- | ------------------------------------------------------------ |
> | `superpg_fork` | whether superpages are **fully copied on fork**, and that after freeing, the child **cannot access freed memory** |
> | `superpg_free` | whether a superpage is **correctly split when partially freed**, data integrity, and **isolation** after freeing |
>
> Together they cover the core correctness of superpage (2MB huge page) support in xv6: **creation, copying, splitting, freeing, isolation**.

Next, look at the next hint:

> A good place to start is `sys_sbrk` in `kernel/sysproc.c`, which is called by the `sbrk` system call. Trace the code path to the `growproc` function, which allocates memory for `sbrk` eagerly.

```C
// kernel/sysproc.c
uint64
sys_sbrk(void)
{
  uint64 addr;
  int t;
  int n;

  argint(0, &n); // 第 0 个参数：要增长/缩减的字节数
  argint(1, &t); // 第 1 个参数：分配策略 (SBRK_EAGER=1 或 SBRK_LAZY=2)
  addr = myproc()->sz; // 保存旧堆顶地址，作为返回值

  if(t == SBRK_EAGER || n < 0) {
    if(growproc(n) < 0) {
      return -1;
    }
  } else {
    // Lazily allocate memory for this process: increase its memory
    // size but don't allocate memory. If the processes uses the
    // memory, vmfault() will allocate it.
    if(addr + n < addr)
      return -1;
    myproc()->sz += n;
  }
  return addr;
}
```

Here you might mistakenly think that `sbrk()` takes two arguments, but in fact there are two call entry points in user space:

```c
// user/ulib.c
char* sbrk(int n)     { return sys_sbrk(n, SBRK_EAGER); }  // 立即分配
char* sbrklazy(int n)  { return sys_sbrk(n, SBRK_LAZY);  }  // 惰性分配
```

**Eager allocation**: call `growproc(n)` to allocate physical memory immediately:

```c
// kernel/proc.c
// Shrink user memory by n bytes.
// Return 0 on success, -1 on failure.
int
growproc(int n)
{
  uint64 sz;
  struct proc *p = myproc();

  sz = p->sz;
  if(n > 0){
    if((sz = uvmalloc(p->pagetable, sz, sz + n, PTE_W)) == 0) {
      return -1;
    }
  } else if(n < 0){
    sz = uvmdealloc(p->pagetable, sz, sz + n);
  }
  p->sz = sz;
  return 0;
}
```

- If n > 0, allocate physical pages + establish page table mappings (established inside the `uvmalloc` function)
- If n < 0, free physical pages immediately

Note here that when n < 0, the **lazy allocation strategy is ignored**.

**Lazy allocation**:

Only change `p->sz` without allocating physical memory; the actual allocation is deferred until a page fault occurs: "`vmfault()` will allocate it.":

```c
// kernel/vm.c
// allocate and map user memory if process is referencing a page
// that was lazily allocated in sys_sbrk().
// returns 0 if va is invalid or already mapped, or if
// out of physical memory, and physical address if successful.
uint64
vmfault(pagetable_t pagetable, uint64 va, int read)
{
  uint64 mem;
  struct proc *p = myproc();
  
  if (va >= p->sz)
    return 0;
  va = PGROUNDDOWN(va);
  if(ismapped(pagetable, va)) {
    return 0;
  }
  mem = (uint64) kalloc();
  if(mem == 0)
    return 0;
  memset((void *) mem, 0, PGSIZE);
  if (mappages(p->pagetable, va, PGSIZE, mem, PTE_W|PTE_U|PTE_R) != 0) {
    kfree((void *)mem);
    return 0;
  }
  return mem;
}
```

The core is: when `va < p->sz` (legal but not yet allocated), allocate memory.

> [!note]
>
> Why is `myproc()->sz` the old top-of-heap address?
>
> At its core, this is still the memory layout of xv6's **user** processes:
>
> > [!tip]
> >
> > This is definitely a user process, because `sbrk` is a syscall invoked from user mode
>
> ```text
>   0x0
>   ├── text (code)
>   ├── data (data)
>   ├── guard page (guard page)
>   ├── heap (heap) ← managed by sbrk, grows upward
>   │   ...
>   │   └── heap top = p->sz
>   │
>   │   (unallocated)
>   │
>   └── MAXVA
>       └── trampoline / trapframe
> ```

> [!note]
>
> Let's analyze the `ismapped` function:
>
> ```c
> int
> ismapped(pagetable_t pagetable, uint64 va) {
>   pte_t *pte = walk(pagetable, va, 0);
>   if (pte == 0) {
>     return 0;
>   }
>   if (*pte & PTE_V){
>     return 1;
>   }
>   return 0;
> }
> ```
>
> First, understand the return value of `walk(pagetable, va, 0)`: a non-zero pointer means it exists, 0 (NULL) means it doesn't.
>
> So, if it's a null pointer, that must be avoided first, otherwise an exception will occur later.
>
> Then, only `*pte & PTE_V` qualifies.

Next, look at the next hint:

> Your kernel will need to be able to allocate and free 2MB regions. Modify `kalloc.c` to reserve a few two-megabyte regions of physical memory, and create `superalloc()` and `superfree()` functions. You will only need a handful of two-megabyte regions of memory.

What does "***reserve a few memory regions***" mean? We can read the source code to find the answer.

First, look at `main.c`:

```c
// start() jumps here in supervisor mode on all CPUs.
void
main()
{
  if(cpuid() == 0){
    consoleinit();
    printfinit();
    printf("\n");
    printf("xv6 kernel is booting\n");
    printf("\n");
    kinit();         // physical page allocator
    kvminit();       // create kernel page table
    kvminithart();   // turn on paging
    procinit();      // process table
    trapinit();      // trap vectors
    trapinithart();  // install kernel trap vector
    plicinit();      // set up interrupt controller
    plicinithart();  // ask PLIC for device interrupts
    binit();         // buffer cache
    iinit();         // inode table
    fileinit();      // file table
    virtio_disk_init(); // emulated hard disk
    userinit();      // first user process
    __sync_synchronize();
    started = 1;
  } else {
    while(started == 0)
      ;
    __sync_synchronize();
    printf("hart %d starting\n", cpuid());
    kvminithart();    // turn on paging
    trapinithart();   // install kernel trap vector
    plicinithart();   // ask PLIC for device interrupts
  }

  scheduler();        
}
```

Note that here `kinit(); // physical page allocator`, a function defined in `kalloc.c`, plays the role of allocating physical pages — which is really just building the free list.

> [!note]
>
> This was also mentioned in the part about booting xv6.

Then go look at `kalloc.c`:

```c
extern char end[]; // first address after kernel.
                   // defined by kernel.ld.

struct run {
  struct run *next;
};

struct {
  struct spinlock lock;
  struct run *freelist;
} kmem;

void
kinit()
{
  initlock(&kmem.lock, "kmem");
  freerange(end, (void*)PHYSTOP);
}
```

`kmem` is a free list with a lock. Looking at `kinit`, temporarily ignoring the lock parts (to be covered in later chapters), we find it calls the `freerange` function, so let's look at that:

```c
void
freerange(void *pa_start, void *pa_end)
{
  char *p;
  p = (char*)PGROUNDUP((uint64)pa_start);
  for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
    kfree(p);
}
```

Here the `PGROUNDUP` macro's role is to round up, ensuring the starting address is a multiple of `PGSIZE`.

We can see that it starts from the new start and goes up to `pa_end`, calling `kfree(p)` page by page to free them.

> [!note]
>
> Why is it defined as `char*`? This has nothing to do with strings. Using `char *` is purely because **`char` is, in C, just an alias for 1 byte**.
>
> **The core reason: pointer arithmetic**
>
> When you write `p + 1`, the actual number of bytes added depends on the pointer's type:
>
> ```TEXT
> char*   p + 1  →  address + 1 byte   ✓ fine-grained down to each byte
> int*    p + 1  →  address + 4 bytes  ✗ too coarse
> uint64* p + 1  →  address + 8 bytes  ✗ too coarse
> ```
>
> When operating on physical memory addresses, you need **byte-by-byte** level control (e.g., aligning to some address, skipping some number of bytes). `char`'s `sizeof` is guaranteed to be 1, so `char *` is the only natural pointer type with a "step size of 1".
>
> Can't `void *` work? No — standard C doesn't allow arithmetic on `void *` (`p + PGSIZE` would be a compile error).
>
> ---
>
> Looking at the concrete code: here `p += PGSIZE` is doing a **byte-level address offset**:
>
> - `PGSIZE = 4096`
> - `p` is a `char *`, so `p += 4096` advances the address by 4096 **bytes** (exactly one page)
>
> If `p` were a `uint64 *`, then `p += 4096` would advance the address by `4096 × 8 = 32768` bytes, which would completely break it.
>

Then let's look at `kfree()`:

```c
// Free the page of physical memory pointed at by pa,
// which normally should have been returned by a
// call to kalloc().  (The exception is when
// initializing the allocator; see kinit above.)
void
kfree(void *pa)
{
  struct run *r;

  if(((uint64)pa % PGSIZE) != 0 || (char*)pa < end || (uint64)pa >= PHYSTOP)
    panic("kfree");

  // Fill with junk to catch dangling refs.
  memset(pa, 1, PGSIZE);

  r = (struct run*)pa;

  acquire(&kmem.lock);
  r->next = kmem.freelist;
  kmem.freelist = r;
  release(&kmem.lock);
}
```

First there's a sanity check. Although when reading OSTEP it said this part is mainly implemented by the hardware MMU, I don't know why it's implemented at the OS code level here.

Then it fills this block of memory with garbage.

Finally, this part ensures the original `r->next` isn't lost, thereby freeing the page at the original `pa`.

> [!caution]
>
> ...It's been too long since I've handwritten code; even this spot took me a while to think through. I should write some LeetCode linked-list problems.

Might as well finish reading and look at the `kalloc` function:

```c
// Allocate one 4096-byte page of physical memory.
// Returns a pointer that the kernel can use.
// Returns 0 if the memory cannot be allocated.
void *
kalloc(void)
{
  struct run *r;

  acquire(&kmem.lock);
  r = kmem.freelist;
  if(r)
    kmem.freelist = r->next;
  release(&kmem.lock);

  if(r)
    memset((char*)r, 5, PGSIZE); // fill with junk
  return (void*)r;
}
```

Nothing else much, but here I started having a doubt: `r` here is clearly a pointer allocated on the stack — shouldn't it disappear once the function ends?

But actually, `r` stores an address, not the memory itself. This pointer variable is indeed on the stack, and after the function returns it is destroyed as a local variable.

Anyway, after reading this part of the code, let's go back and understand "***reserve***": it's really just this `freerange` part:

```c
for(; p + PGSIZE <= (char*)pa_end; p += PGSIZE)
```

Each allocation is only done in units of `PGSIZE`, so of course there's no room for superpages.

So let's start implementing:

Copy the `freelist` for 4KB pages as a template:

```c
struct {
  struct spinlock lock;
  struct run *freelist;
} ksupermem;
```

Incidentally, define in `kernel/riscv.h` exactly how many the `a handful of` mentioned in the hint is; considering xv6's memory isn't that large, let's set it to 8 for now:

```c
#define SUPERPGAMOUNT 16
```

Then, the logic basically follows the same pattern.

One question left here: should `cnt_superpage` be set in `superfree` or `superalloc`? To be resolved later.

Next, look at the next two hints (implement them together):

> Processes with huge pages need to allocate huge pages on fork and free them on exit; you will need to modify the relevant logic in `uvmcopy()` and `uvmunmap()`.
>
> When `sbrk` partially frees a superpage (e.g., frees the last 4096 bytes of a superpage), you will need to "downgrade" the superpage to normal pages.

Read the code:

```c
void
uvmunmap(pagetable_t pagetable, uint64 va, uint64 npages, int do_free)
{
  uint64 a;
  pte_t *pte;
  int sz = PGSIZE;                    // 每次跳 4KB（后面 superpage 需要改这里）

  if((va % PGSIZE) != 0)
    panic("uvmunmap: not aligned");

  for(a = va; a < va + npages*PGSIZE; a += sz){
    if((pte = walk(pagetable, a, 0)) == 0)   // ① 找 PTE
      continue;                              //    没找到 → 跳过（允许不存在）
    if((*pte & PTE_V) == 0)                  // ② V 位没置
      continue;                              //    已失效 → 跳过
    sz = PGSIZE;                             // ③ 重置 sz（后面 superpage 需要改这里）

    if(PTE_FLAGS(*pte) == PTE_V)
      panic("uvmunmap: not a leaf");         // ④ 必须是叶节点

    if(do_free){
      uint64 pa = PTE2PA(*pte);
      kfree((void*)pa);                      // ⑤ 释放物理页
    }
    *pte = 0;                                // ⑥ 清空 PTE
  }
}
```

> [!note]
>
> **Note the `do_free` parameter here**:
>
> - If it's an ordinary user memory page:
>     - The physical page is allocated by `uvmalloc` / `kalloc`
>     - When unmapping, the physical memory must be freed at the same time
>     - `do_free = 1`
> - If it's a special page (`trampoline` / `trapframe` / `usyscall`)
>     - The physical page is shared by multiple processes
>     - Or the pointer to the physical page is stored in the proc struct and managed separately
>     - The physical memory is freed elsewhere
>     - `do_free = 0`
>
> Look at an example, in `kernel/proc.c`:
>
> ```c
> // 场景：创建页表，先 map 了 trampoline，然后 map trapframe 失败了
> if(mappages(pagetable, TRAPFRAME, ...) < 0){
>     uvmunmap(pagetable, TRAMPOLINE, 1, 0);   // ← do_free=0
>     uvmfree(pagetable, 0);
>     return 0;
> }
> ```
>
> Here it's `do_free = 0`, because the physical page of the **trampoline** must not be freed.

```c
int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
  pte_t *pte;
  uint64 pa, i;
  uint flags;
  char *mem;
  int szinc = PGSIZE;              // 步长（后面 superpage 需要改这里）

  for(i = 0; i < sz; i += szinc){
    if((pte = walk(old, i, 0)) == 0)    // ① 在父进程页表中找 i 对应的 PTE
      continue;                          //    没有 → 跳过
    if((*pte & PTE_V) == 0)             // ② PTE 无效
      continue;                          //    跳过

    szinc = PGSIZE;                      // ③ 重置步长
    pa = PTE2PA(*pte);                   // ④ 提取物理地址
    flags = PTE_FLAGS(*pte);             // ⑤ 提取权限位

    if((mem = kalloc()) == 0)            // ⑥ 分配新物理页
      goto err;
    memmove(mem, (char*)pa, PGSIZE);     // ⑦ 把父进程物理页内容拷贝过来

    if(mappages(new, i, PGSIZE, (uint64)mem, flags) != 0){  // ⑧ 映射到子进程页表
      kfree(mem);
      goto err;
    }
  }
  return 0;

 err:
  uvmunmap(new, 0, i / PGSIZE, 1);      // 失败回滚：释放已分配的所有页
  return -1;
}
```

Right now both functions **hard-code 4KB granularity** (`szinc = PGSIZE`, `sz = PGSIZE`). After supporting superpages, `walk` may return an L2-level leaf PTE (representing a 2MB huge page), which is why modifications are needed.

But there's a problem here: how do you determine whether a PTE is a superpage? The LLM's explanation was that if, at the L1 level, you find that this PTE is a leaf page (L2 -> L1 -> L0), then it's a superpage.

```c
// return the page size of a specific pte
int
pagesize(pagetable_t pagetable, uint64 va)
{
  pte_t *pte;
  pte = &pagetable[PX(2, va)];
  if ((*pte & PTE_V) == 0) {
    return PGSIZE;
  }
  pagetable_t l1 = (pagetable_t)PTE2PA(*pte);
  pte = &l1[PX(1, va)];
  if ((*pte & PTE_V) && PTE_LEAF(*pte)) {
    return SUPERPGSIZE;
  }
  return PGSIZE;
}
```

Then, the next part took me almost two days to write...

First, analyze `uvmunmap`; its purpose is to unmap `[va, va + npages*PGSIZE)`. This PTE could be a 4KB page or a 2MB superpage.

For 4KB pages, handle them normally; for superpages:

- First determine whether it's a superpage; the method is `if(pagesize(*pagetable*, a) == SUPERPGSIZE)`

- Find some key parameters:

    ```c
    uint64 sp_start = ((a % SUPERPGSIZE) == 0) ? a : SUPERPGROUNDDOWN(a); // 这里注意一下，这个宏有问题
    uint64 sp_end = sp_start + SUPERPGSIZE;
    uint64 unmap_end = va + npages * PGSIZE;
    ```

- Then, there are three cases:

    - Free the whole block: `a == sp_start && sp_end <= unmap_end`, then just call `superfree` directly

    - Partial free: here you need to consider downgrading the current superpage into one or more 4KB pages; implement a function `split_superpage`:

        ```c
        // Split a 2MB superpage into 512 individual 4KB pages.
        // Pages within [unmap_start, unmap_end) are left unmapped (L0[j]=0).
        // All other pages within the superpage are allocated new 4KB pages
        // with data copied from the original 2MB block.
        // The original 2MB physical block is freed.
        static void
        split_superpage(pagetable_t pagetable, uint64 sp_start,
                        uint64 unmap_start, uint64 unmap_end)
        {
          if (pagesize(pagetable, sp_start) != SUPERPGSIZE) {
            panic("split_sp: not superpage");
          }
          uint64 sp_end = sp_start + SUPERPGSIZE;
          unmap_end = unmap_end < sp_end ? unmap_end : sp_end;
          pte_t *l2_pte = &pagetable[PX(2, sp_start)];
          pagetable_t l1 = (pagetable_t)PTE2PA(*l2_pte);
          pte_t *sp_pte = &l1[PX(1, sp_start)];
          uint64 sp_pa = PTE2PA(*sp_pte);
          int flags = PTE_FLAGS(*sp_pte);
        
          pagetable_t l0 = (pagetable_t)kalloc();
          if (l0 == 0) {
            panic("split_sp: kalloc l0");
          }
          memset((void*)l0, 0, PGSIZE);
          for (int i = 0; i < 512; ++i) {
            uint64 va = sp_start + i * PGSIZE;
            if (va >= unmap_start && va < unmap_end) {
              continue;
            }
            uint64 new_page = (uint64) kalloc();
            if (new_page == 0) {
              panic("split_sp: kalloc page");
            }
            memmove((void*)new_page, (void*)(sp_pa + i * PGSIZE), PGSIZE);
            l0[i] = PA2PTE(new_page) | flags | PTE_V;
          }
          *sp_pte = PA2PTE(l0) | PTE_V;
          superfree((void*)sp_pa);
        }
        ```

        The general idea is: originally, the L1 pointed to by L2 directly pointed to a superpage; now we need to break this superpage apart into several ordinary pages, record these ordinary pages in an L0 page table, and finally directly change the PTE that the original L1 pointed to (which was the superpage's physical address) to the newly allocated L0's location

Then modify `uvmcopy`:

The original function just used `mappages` to establish virtual-to-physical address mappings, using only 4KB pages. To support superpages, in `uvmcopy`, if the page at the original process's location is a superpage, then the child process's should also be a superpage, so we must first create a `map_superpage`:

As for `map_superpage`, it's nothing more than the **inverse operation** of `split_superpage`: **create** a new L1 leaf PTE in the child's page table.

- First, get the L1 page table; if it doesn't exist, create it yourself (why doesn't `mappages` need this "create if it doesn't exist" step? Because it's handled inside `walk`)
- Then, at the PTE in the L1 page table where it would originally point to the L0 page table, change it to `PA2PTE(*pa*) | *perm* | PTE_V`
- Why is this a superpage? Because by setting the flags, a leaf page at the L1 level is of course a superpage.
- After implementing this, modifying `uvmcopy` is basically just copying the 4KB logic.

> [!note]
>
> You can see that, compared to `mappages`, it's really just removing the loop, implementing the mapping one level earlier, and incidentally handling part of the logic that would originally have been handled by the `walk` function.

```c
// Create a 2MB superpage mapping at L1.
// va and pa must be 2MB-aligned. Returns 0 on success, -1 on failure.
static int
map_superpage(pagetable_t pagetable, uint64 va, uint64 pa, int perm)
{
  // Ensure the L1 page table exists (L2 already points to it)
  pte_t *l2 = &pagetable[PX(2, va)];
  pagetable_t l1;
  if(*l2 & PTE_V){
    l1 = (pagetable_t)PTE2PA(*l2);
  } else {
    if((l1 = (pagetable_t)kalloc()) == 0)
      return -1;
    memset(l1, 0, PGSIZE);
    *l2 = PA2PTE(l1) | PTE_V;
  }

  pte_t *l1_pte = &l1[PX(1, va)];
  if(*l1_pte & PTE_V)
    return -1;  // already mapped
  *l1_pte = PA2PTE(pa) | perm | PTE_V;  // R/W/X bits → hardware sees a leaf
  return 0;
}
```

Finally, you also need to modify the `uvmalloc` function, because currently there's no logic handling superpage allocation yet.

> [!note]
>
> I didn't think of this myself, because it wasn't in the hints — I'm just not sensitive enough to the call/dependency relationships in `vm.c`.

This part isn't troublesome either: if the remaining range has 2MB and the address is aligned, try calling `superalloc` to allocate one; the logic here is no different from the logic below that calls `kalloc` to allocate normal pages.

And with that, it's done. When testing, first run `make qemu`, then type `pgtbltest`.

> [!caution]
>
> As a postscript: first, I think I should implement a `superwalk` function, and inside it determine whether a PTE corresponds to a superpage, which would also simplify the logic of `map_superpage`.

<img src="https://image.wendaining.top/8602f1d7-882e-499d-bf5a-61d8b8ac8e89.png" alt="All tests passed" style="zoom:67%;" />
