xv6 Lab5 Copy on-write - MIT 6.1810 Fall 2025 Operating System

Last updated on August 9, 2026 pm

This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.

Reading

This lab's guidance, unusually, gives no instruction to read the xv6 book. But I still took a look at the course documentation: 8.1 Page Fault Basics | MIT6.S081

This chapter actually covers the original Lazy Allocation Lab, Copy-on-write Lab, and the mmap lab.

Here I'll just briefly summarize the idea of Copy-on-write:

After a process forks, it creates a complete copy of the parent process. In the current implementation, the physical space is copied directly; and if exec is executed immediately after fork, this address space will be discarded, which is very wasteful.

The idea of COW is that the child process and the parent process map their virtual address spaces to the same physical address, but the PTE is set to read-only. If a write occurs (whether performed by the parent or the child), a page fault is triggered, the corresponding page is copied, the PTE is set to read-write, and execution continues.

To mark a page as a COW page, the last bit of the PTE is used.

Meanwhile, since the previous implementation had no mapping where one physical address corresponds to multiple virtual addresses, the release at process exit would also have problems. The solution is to add a reference count to physical page frames.

Implement copy-on-write fork

Actually, the lab's explanation of what copy-on-write is quite clear, even a bit clearer and easier to understand than the course documentation.

Just follow the provided steps one by one, but first you need to implement some infrastructure (i.e., the content of the hints):

Recording COW mappings in the PTE

In riscv.h

#define PTE_COW (1L << 8)

Afterwards, just modify it freely when changing flags.

Modifying uvmcopy()

This function's original purpose is to completely copy the parent process's page table into the new process when creating a child process (analyzed thoroughly in the Page table Lab).

What needs to be done here: no longer allocate new physical pages for the child process and copy data; instead, directly map the parent process's physical pages into the child process's page table, and clear PTE_W in the pages of both the parent and child processes.

代码C · 29 行
int
uvmcopy(pagetable_t old, pagetable_t new, uint64 sz)
{
  pte_t *pte;
  uint64 pa, i;
  uint flags;

  for(i = 0; i < sz; i += PGSIZE){
    if((pte = walk(old, i, 0)) == 0)
      continue;   // page table entry hasn't been allocated
    if((*pte & PTE_V) == 0)
      continue;   // physical page hasn't been allocated
    pa = PTE2PA(*pte);
    flags = PTE_FLAGS(*pte);
    if(flags & PTE_W) {
      flags &= ~PTE_W;
      flags |= PTE_COW;
      *pte = PA2PTE(pa) | flags;
    }
    if(mappages(new, i, PGSIZE, pa, flags) != 0)
      goto err;
  }
  // TODO: 是否要刷新 TLB?留待之后分析
  return 0;

 err:
  uvmunmap(new, 0, i / PGSIZE, 1);
  return -1;
}

Modifying vmfault() to handle COW page faults

Regarding the purpose of the vmfault() function, see the explanation in the Page table Lab; it is mainly related to Lazy Allocation.

In the current vmfault() function, the read parameter is unused. I guess its purpose is to distinguish between different types of page faults. The answer I got from asking an LLM:

引用The read parameter of vmfault() is used to distinguish whether this page...

The read parameter of vmfault() is used to distinguish whether this page fault was caused by a "read" or a "write".

In trap.c:

vmfault(p->pagetable, r_stval(),
        (r_scause() == 13) ? 1 : 0)

The correspondence is:

scause Meaning read
13 Load page fault, read failed 1
15 Store page fault, write failed 0

Your current vmfault() only handles lazy allocation: as long as the page is unmapped, it allocates a zero page. Reads and writes are handled the same way, so read is currently unused.

At the COW stage, it becomes meaningful:

read == 0, and the page has PTE_COW
    → this is a write to a COW page
    → allocate a new page, copy the contents, restore PTE_W

read == 1
    → cannot be treated as a COW write

Because a COW page only has PTE_W cleared, while PTE_R is still retained:

Reading a COW page: normal, should not fault
Writing a COW page: produces a store page fault

Therefore, if a read fault occurs on an already-mapped page, it usually means it is not a legitimate COW write, and the page must not be copied into a writable page.

Also, copyout() writes data from the kernel to user space, so when calling the COW handling logic later, it should be treated as a write operation, i.e., equivalent to:

read = 0;

Summary: read is currently unused in lazy allocation; it is prepared for distinguishing read/write page faults, especially the later COW write fault.

Then I roughly had an idea but was a bit too lazy to type it out myself (actually, I didn't quite know how), so I fed the LLM this prompt:

Regarding this step of modifying vmfault, I roughly have an idea: first, if read=1, handle it exactly the same as the original logic; if read=0, first check the page — the way to check is to walk() to find the pte and then check the flags, then kalloc to allocate a new physical page, modify the original pte's flags (mainly the write part, and remove cow along the way), then copy, and finally make the pte point to this new page. Since only pages originally set as writable get marked with cow, there's no need to check whether it's writable. But I'm having trouble organizing in my head how to couple this logic with the existing lazy allocation logic, so please directly modify this code for me and explain it along the way.

Code implementation:

代码C · 37 行
uint64
vmfault(pagetable_t pagetable, uint64 va, int read)
{
  uint64 mem, pa;
  uint flags;
  pte_t *pte;
  struct proc *p = myproc();

  if (va >= p->sz)
    return 0;
  va = PGROUNDDOWN(va);
  if(ismapped(pagetable, va)) {
    pte = walk(pagetable, va, 0);
    if(read || (*pte & PTE_U) == 0 || (*pte & PTE_COW) == 0)
      return 0;

    pa = PTE2PA(*pte);
    flags = PTE_FLAGS(*pte);
    mem = (uint64)kalloc();
    if(mem == 0)
      return 0;

    memmove((void *)mem, (void *)pa, PGSIZE);
    flags = (flags | PTE_W) & ~PTE_COW;
    *pte = PA2PTE(mem) | flags;
    return mem;
  }
  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;
}

A few key points:

  • va >= p->sz and ismapped() check two completely different questions:

    • va >= p->sz: is this virtual address within the process's legal address range?
    • ismapped(): does this legal virtual address currently have a corresponding physical page?
  • The original lazy allocation logic was to check ismapped(); if there is a mapping, it means a corresponding physical page exists, so ignore it. But now we need to couple in the COW logic, and a COW page must have a corresponding physical page (considering that the logic of uvmcopy is to establish mappings from virtual pages to actually existing physical pages, using mappages() in a loop). Therefore, the COW logic here falls entirely on the ismapped part that originally just did return 0.

  • Here we continue checking: if it's read-only, or not a COW page, or (*pte & PTE_U) == 0, i.e., this page is not accessible in user mode (such as the trampoline page, etc.), just return directly.

  • Then, get all the information corresponding to this page. Unlike the prompt I gave earlier, first copy the old page, then compute the new flags, and only then replace the PTE — this is to prevent the case where, if kalloc() fails, the original valid mapping could also be broken.

  • The so-called flags only exist on virtual pages, i.e., ptes; physical pages don't have them!

  • After that, the COW part of the logic is done, and the rest is handed off to the lazy allocation logic.

Implementing physical page reference counting

We must ensure that each physical page is only freed after the last PTE reference to it disappears.

Initially, I thought the rules for maintaining reference counts would be:

  • When kalloc() allocates a page, initialize the count to 1
  • When fork() lets the child process share physical pages, increment the reference count by 1. Although it's called fork(), it's actually implemented inside uvmcopy(), corresponding to uvmunmap() below.
  • When a process removes this page from its page table (uvmunmap()), decrement the reference count by 1.
  • The logic of kfree(): only when the reference count is 0 can the page be put back on the free list.
  • The so-called physical address, i.e., pa. Since physical page frame addresses are always PGSIZE-aligned, we can use pa / PGSIZE as the array index to record a page's reference count (in fact, this number is which physical page frame it is). The size of the array can just be based on PHYSTOP.
  • One thing to be careful about here: this array must not be modified arbitrarily. It's best to add a lock, and access it for increment/decrement through the dedicated functions krefinc() and krefdec(), to prevent concurrency conflicts.

But in reality there are several problems:

  • krefdec() actually shouldn't exist; instead, all reference count decrements should be placed inside kfree(). Because there are far more places that remove the reference between a virtual page and a physical page than just uvmunmap(). For example, vmfault() directly changes the old physical page to a new physical page, which is effectively a dereference, but it doesn't go through uvmunmap(). But in any case, this is equivalent to decrementing the reference count.
    • Therefore, the semantics of kfree() need to be modified here. It should first be responsible for decrementing the reference count by 1, then check — only if it really drops to 0 should it perform the release (put it back on the free list).
  • int phy_ref[PHYSTOP / PGSIZE]; is rather wasteful; better to use int phy_ref[(PHYSTOP - KERNBASE) / PGSIZE] and write an index mapping function.
  • freerange() needs special handling, because at the start of freerange() the pages' initial counts are all 0, but kfree() would make them -1, so first set them to 1.

Excerpting some core code:

代码C · 71 行
#define NPAGE ((PHYSTOP - KERNBASE) / PGSIZE)

struct {
  struct spinlock lock;
  int count[NPAGE];
} kref;

static int
paindex(uint64 pa)
{
  return (pa - KERNBASE) / PGSIZE;
}

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() drops a reference, so give each boot-time page one
    // reference before adding it to the free list.
    acquire(&kref.lock);
    kref.count[paindex((uint64)p)] = 1;
    release(&kref.lock);
    kfree(p);
  }
}

void
kfree(void *pa)
{
  struct run *r;

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

  int index = paindex((uint64)pa);
  acquire(&kref.lock);
  if(kref.count[index] < 1)
    panic("kfree: no reference");
  kref.count[index]--;
  if(kref.count[index] > 0){
    release(&kref.lock);
    return;
  }
  release(&kref.lock);

  // 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);
}

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

  int index = paindex(pa);
  acquire(&kref.lock);
  if(kref.count[index] < 1)
    panic("krefinc: free page");
  kref.count[index]++;
  release(&kref.lock);
}

Modifying copyout()

First, let's clarify what copyout() is:

// Copy from kernel to user.
// Copy len bytes from src to virtual address dstva in a given page table.
// Return 0 on success, -1 on error.
int copyout(pagetable_t pagetable, uint64 dstva, char *src, uint64 len)

From this function signature, we can see that its purpose is to safely copy data from kernel space into a process's user virtual address.

The current copyout() logic includes handling for lazy allocation:

pa0 = walkaddr(pagetable, va0);
if(pa0 == 0) {
  if((pa0 = vmfault(pagetable, va0, 0)) == 0) {
    return -1;
  }
}

If this user address is not yet mapped, the current code attempts to allocate a page via vmfault().

But it currently cannot correctly handle the COW logic, because a COW page doesn't have PTE_W, but is actually writable — we just need to simulate a write page fault, which is simply calling vmfault() once.

代码C · 47 行
int
copyout(pagetable_t pagetable, uint64 dstva, char *src, uint64 len)
{
  uint64 n, va0, pa0;
  pte_t *pte;
  int needfault;

  while(len > 0){
    va0 = PGROUNDDOWN(dstva);
    if(va0 >= MAXVA) {
      goto err;
    }

    needfault = 0;
    pa0 = walkaddr(pagetable, va0);
    if(pa0 == 0){
      needfault = 1;
    } else {
      pte = walk(pagetable, va0, 0);
      if((*pte & PTE_W) == 0){
        if((*pte & PTE_COW) == 0) {
          goto err;
        }
        needfault = 1;
      }
    }
	// 这里运用了布尔语句的短路特性
    if(needfault && (pa0 = vmfault(pagetable, va0, 0)) == 0) {
      goto err;
    }
      

    n = PGSIZE - (dstva - va0);
    if(n > len) {
      n = len;
    }
    memmove((void *)(pa0 + (dstva - va0)), src, n);

    len -= n;
    src += n;
    dstva = va0 + PGSIZE;
  }
  return 0;

 err:
  return -1;
}

Passed all tests:


xv6 Lab5 Copy on-write - MIT 6.1810 Fall 2025 Operating System
https://blog.wendain.ing/en/posts/xv6-lab5-copy-on-write/
Author
wendaining
Posted on
August 8, 2026
Updated on
August 9, 2026
Licensed under