xv6 Lab9 mmap - MIT 6.1810 Fall 2025 Operating System

Last updated on August 20, 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.

Feels like the hardest lab... at least the one with the largest amount of code.

My implementation:

wendaining/xv6-lab-2025 at mmap

Reading

In fact, this is exactly the content covered in the section 8.1 Page Fault Basics | MIT6.S081 mentioned in Lab5 COW (a single subsection). So there isn't much to read; it's just a mechanism.

The core idea of memory mapped files is to load the complete or partial file into memory, so that the file can be manipulated directly using memory load store operations, reducing disk I/O.

The interfaces to implement (from man 2 mmap):

void *mmap(void *addr, size_t len, int prot, int flags,
           int fd, off_t offset);
           
int munmap(void *addr, size_t len);

This lab does not require fully implementing the POSIX specification; you can make the following simplifying assumptions:

For mmap():

  • addr is always 0, meaning the kernel decides which virtual address to map to.

  • mmap returns the mapped address on success, and 0xffffffffffffffff on failure.

  • len is the number of bytes to map; it may differ from the file length.

  • prot indicates whether this memory region is readable, writable, and/or executable. In this Lab you only need to handle PROT_READ, PROT_WRITE, or a combination of both.

  • flags will only be MAP_SHARED or MAP_PRIVATE.

  • MAP_SHARED means modifications to the mapped memory should be written back to the file.

  • MAP_PRIVATE means modifications should not be written back to the file.

  • fd is an already-opened file descriptor of the file to be mapped.

  • offset can be assumed to always be 0, i.e., mapping always starts from the beginning of the file.

  • Regarding lazy allocation: this lab uses the lazy allocation mode. That is, mmap() itself should not allocate physical memory, nor should it read the file. Only when a page fault occurs should the actual allocation and file reading be done in usertrap() or the page fault handling code it calls.

    Recall the cow lab

  • If two processes map the same MAP_SHARED file, this Lab allows them to not share the same physical page.

About munmap():

  • Remove the mmap mapping within the specified range.
  • If the process has already modified this memory, and it corresponds to a MAP_SHARED mapping, then the modifications should be written back to the file before unmapping.
  • In principle it might be possible to unmap only part of an entire mmap mapping (punching a hole in the middle) (recall splitting super pages), but in this lab it's either the beginning, the end, or the whole thing — never only the middle.

Implementation

Still using the hints as the guide.

Setting up the system call

The same old routine.

Recording mmap regions per process

Create a per-process struct vma, i.e., Virtual Memory Area, which records the virtual address range information created by mmap().

// kernel/proc.h
struct vma {
  int valid;
  uint64 addr;
  uint64 len;
  uint64 offset;
  int prot;
  int flags;
  struct file *f;
};
引用offset and len do not use the same types as in the original signature. T...

offset and len do not use the same types as in the original signature.

The reason is that size_t and off_t belong to the mmap interface types, which are currently defined in defs.h; but many source files include proc.h before defs.h, so when parsing struct vma they are not yet known.

uint64 is defined in the more fundamental types.h, and in xv6:

  • size_t is actually a 64-bit unsigned integer;
  • the offset in this lab is fixed at 0, so the signed semantics of off_t are not needed;
  • virtual addresses, lengths, and file offsets are themselves well suited to being stored as uint64.

Therefore, the user interface and sys_mmap() parameters still follow the man page:

size_t len;
off_t offset;

while the VMA is a kernel-internal data structure, so storing the converted values as uint64 is fine. The two layers are not required to use exactly the same type names; the values just need to be represented correctly.

Then, since the xv6 kernel has no variable-size kernel allocator, just declare a fixed-size (16) array of VMAs and allocate from it when needed.

// kernel/def.h
#define NVMA 16
// kernel/proc.c
struct vma vma[NVMA];

Implementing mmap()

First you need to understand which parts of the virtual address space the mmap mapping region actually occupies:

The address space can be roughly understood as:

Low addresses
┌──────────────────────┐
│ Program code, data, heap │
├──────────────────────┤ ← original p->sz┤
│ Unused address space      │
├──────────────────────┤ ← limit / TRAPFRAME
│ TRAPFRAME            │
├──────────────────────┤
│ TRAMPOLINE           │
└──────────────────────┘ ← MAXVA
High addresses

The mmap region must not cover the two special pages at the top.

At first (and as in the Zhihu article I read, MIT XV6 操作系统 实验全解 - 知乎 ), the implementation was like this:

代码C · 69 行
uint64
sys_mmap(void)
{
  void *addr;
  size_t len;
  int prot, flags, fd;
  off_t offset;
  struct file *f;
  struct proc *p = myproc();

  argaddr(0, (uint64 *)&addr);
  argaddr(1, &len);
  argint(2, &prot);
  argint(3, &flags);
  argaddr(5, (uint64 *)&offset);

  // This lab only supports kernel-selected addresses and mappings that
  // start at the beginning of a regular file.
  if(addr != 0 || len == 0 || offset != 0) {
    return -1;
  }
  if((prot & ~(PROT_READ | PROT_WRITE)) != 0 ||
     (prot & (PROT_READ | PROT_WRITE)) == 0) {
      return -1;
  }
  if(flags != MAP_SHARED && flags != MAP_PRIVATE) {
    return -1;
  }
  // 将 fd 对应的文件对应到 struct file *f 上
  if(argfd(4, &fd, &f) < 0 || f->type != FD_INODE || !f->readable) {
    return -1;
  }
  if(flags == MAP_SHARED && (prot & PROT_WRITE) && !f->writable) {
    return -1;
  }

  // 为 mmap 选择一段虚拟地址进行映射,
  // p->sz 是目前的进程能用到的最高的地址空间,将新映射放在它后面
  addr = (void *)PGROUNDUP(p->sz);
  uint64 limit = MAXVA - 2 * PGSIZE;  // leave TRAPFRAME/TRAMPOLINE untouched
  if((uint64)addr >= limit || len > limit - (uint64)addr) {
    return -1;
  }
  // 长度 round up 到最近的页面字节数
  size_t maplen = PGROUNDUP(len);

  int idx;
  for(idx = 0; idx < NVMA; idx++){
    if(!p->vma[idx].valid) {
      break;
    }
  }
  if(idx == NVMA) {
    return -1;
  }
  struct vma *vma = &p->vma[idx];

  vma->valid = 1;
  vma->addr = (uint64)addr;
  vma->len = len;
  vma->permissions = prot;
  vma->offset = offset;
  vma->prot = prot;
  vma->flags = flags;
  vma->f = filedup(f);

  p->sz = (uint64)addr + maplen;
  return (uint64)addr;
}

If vma is allocated, following the author's implementation, upward from p->sz, the tests in the 2025 version of the lab (the author was on the Fall 2020 version) will not pass. The rough reasons are:

  • Since mmap and munmap are triggered at different times and the current VMA lookup is by index allocation, in fact there is no positive correlation between each vma's addr and its index, and in practice it is hard to manage p->sz — it can only grow and cannot shrink.
  • Then, suppose we munmap a certain vma; something like internal fragmentation is produced;
  • In the test data, if a page fault is triggered again in this already-munmap-ed region, since it satisfies va < p->sz and is not within the range of any vma, it will be judged as a lazy allocation page produced by sbrk(), and an actual physical page frame will be allocated again;
  • But the test data is: after unmapping a page, read it again, expecting an illegal access that kills the process. This clearly fails here.

So we should actually switch to a different way of allocating vmas. I thought of allocating in reverse, starting from MAXVA - 2*PGSIZE, i.e., two pages below the trampoline page.

Add a uint64 mmap_top; to struct proc, indicating the starting point of the next vma allocation. Since virtual addresses are nearly infinite, this has no impact on the OS.

But actually I'm not so sure. Because VMAs keep being allocated, p->mmaptop only grows monotonically.

In Linux's implementation, the OS looks for free fragments. But implementing that here is indeed a bit troublesome.

So the rough implementation is like this:

代码C · 76 行
uint64
sys_mmap(void)
{
  void *addr;
  size_t len;
  int prot, flags, fd;
  off_t offset;
  struct file *f;
  struct proc *p = myproc();

  argaddr(0, (uint64 *)&addr);
  argaddr(1, &len);
  argint(2, &prot);
  argint(3, &flags);
  argaddr(5, (uint64 *)&offset);

  // This lab only supports kernel-selected addresses and mappings that
  // start at the beginning of a regular file.
  if(addr != 0 || len == 0 || offset != 0) {
    return -1;
  }
  if((prot & ~(PROT_READ | PROT_WRITE)) != 0 ||
     (prot & (PROT_READ | PROT_WRITE)) == 0) {
      return -1;
  }
  if(flags != MAP_SHARED && flags != MAP_PRIVATE) {
    return -1;
  }
  // 将 fd 对应的文件对应到 struct file *f 上
  if(argfd(4, &fd, &f) < 0 || f->type != FD_INODE || !f->readable) {
    return -1;
  }
  if(flags == MAP_SHARED && (prot & PROT_WRITE) && !f->writable) {
    return -1;
  }

  // 为了防止从 p->sz 开始分配,结果因为创建/销毁 vma 的顺序不同,导致 p->sz 没有可能正确回收的问题
  // 不使用 p->sz 开始分配的方法,而是从顶上开始倒着分配
  // 因为虚拟地址近乎是无穷大的,这样不会对 OS 产生影响
  // #define MMAPTOP (MAXVA - 2 * PGSIZE)
  if(len > MMAPTOP) {
    return -1;
  }
  size_t maplen = PGROUNDUP(len);
  if(maplen > p->mmap_top) {
    return -1;
  }

  uint64 mapaddr = p->mmap_top - maplen;
  if(mapaddr < PGROUNDUP(p->sz)) {
    return -1;
  }
  addr = (void *)mapaddr;

  int idx;
  for(idx = 0; idx < NVMA; idx++){
    if(!p->vma[idx].valid) {
      break;
    }
  }
  if(idx == NVMA) {
    return -1;
  }
  struct vma *vma = &p->vma[idx];

  vma->valid = 1;
  vma->addr = (uint64)addr;
  vma->len = maplen;
  vma->offset = offset;
  vma->prot = prot;
  vma->flags = flags;
  vma->f = filedup(f);

  p->mmap_top = (uint64)addr;
  return (uint64)addr;
}

Be sure to note that mmap() does not actually allocate pages; the actual allocation only happens when a page fault occurs.

Here it just records that this file (passed in via fd) should be mapped to this particular VMA.

Handling mmap page faults

Add code so that when a page fault occurs in an mmap region:

  1. Allocate a physical page;
  2. Read the relevant PGSIZE from the file into that page;
  3. Map that page into the user address space.

Use readi() to read the file.

readi() works as follows: read a number of bytes starting at a specified offset from the file represented by a given inode, and copy them to a specified memory address.

int readi(struct inode *ip, int user_dst, uint64 dst, uint off, uint n);

Parameter meanings:

  • ip: the inode of the file to read, e.g., vma->f->ip.

  • user_dst: the type of the destination address.

    • 1: dst is a user virtual address.
    • 0: dst is a kernel address.
  • dst: where to copy the data.

  • off: which byte of the file to start reading from.

  • n: the maximum number of bytes to read.

  • Return value: the number of bytes actually read; may return -1 on failure.

For example, readi(ip, 0, (uint64)mem, 4096, 4096);

means reading 4096 bytes starting at file offset 4096 and writing them to the kernel address mem.

Based on the experience from the cow lab, the place to modify should be the vmfault() function.

Code:

代码C · 65 行
uint64
vmfault(pagetable_t pagetable, uint64 va, int read)
{
  uint64 mem;
  struct proc *p = myproc();

  if(va >= MAXVA) {
    return 0;
  }
  va = PGROUNDDOWN(va);
  if(ismapped(pagetable, va)) {
    return 0;
  }

  int index = ismmaped(p, va);
  if(index != -1) {
    struct vma *vma = &p->vma[index];
    struct inode *ip = vma->f->ip;
    // mem 是 kalloc() 返回的内核地址
    if((mem = (uint64)kalloc()) == 0) {
      return 0;
    }
    memset((void *)mem, 0, PGSIZE);
    ilock(ip);
    // va - vma->addr = 当前产生 page fault 的页面与 vma 开始地址的距离
    // 看似没保证页对齐,但是 vma->offset 永远是 0,而前两者已经页对齐,所以无妨
    uint64 fileoff = (va - vma->addr) + vma->offset;
    if(readi(ip, 0, mem, fileoff, PGSIZE) == -1) {
      iunlock(ip);
      kfree((void *)mem);
      return 0;
    }
    int flags = PTE_U;
    if(vma->prot & PROT_READ) {
      flags |= PTE_R;
    }
    if(vma->prot & PROT_WRITE) {
      flags |= PTE_R | PTE_W;
    }
    if(mappages(pagetable, va, PGSIZE, mem, flags) != 0) {
      iunlock(ip);
      kfree((void *)mem);
      return 0;
    }
    iunlock(ip);
    return mem;
  }

  // Only addresses below p->sz belong to the ordinary lazy-allocation area.
  // A high address removed by munmap must remain invalid.
  if(va >= p->sz) {
    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 tricky part here is the fileoff, but it's really just computing an offset.

引用Assumptions vma->addr = 0x4000 vma->offset = 0 fault va = 0x6123 First a...

Assumptions

vma->addr   = 0x4000
vma->offset = 0
fault va    = 0x6123

First align the fault address down to a page boundary:

va = PGROUNDDOWN(0x6123) = 0x6000

Virtual address region:

VMA virtual address space

0x4000              0x5000              0x6000              0x7000
  │                   │                   │                   │
  ▼                   ▼                   ▼                   ▼
  ┌───────────────────┬───────────────────┬───────────────────┐
  │ VMA page 0        │ VMA page 1        │ VMA page 2        │
  └───────────────────┴───────────────────┴───────────────────┘
                                            ▲
                                            │
                                    fault va = 0x6123
                                    page = 0x6000

Compute how far it is from the start of the VMA:

va - vma->addr
= 0x6000 - 0x4000
= 0x2000

Therefore:

fileoff = (va - vma->addr) + vma->offset;

We get:

fileoff = 0x2000 + 0 = 0x2000

File contents:

File byte offsets

0x0000              0x1000              0x2000              0x3000
  │                   │                   │                   │
  ▼                   ▼                   ▼                   ▼
  ┌───────────────────┬───────────────────┬───────────────────┐
  │ File page 0       │ File page 1       │ File page 2       │
  └───────────────────┴───────────────────┴───────────────────┘
                                            ▲
                                            │
                                      fileoff = 0x2000

Final correspondence:

Virtual mmap region                    File

0x4000  VMA page 0  ───────────────▶  offset 0x0000
0x5000  VMA page 1  ───────────────▶  offset 0x1000
0x6000  VMA page 2  ───────────────▶  offset 0x2000

Therefore the following line:

readi(ip, 0, mem, fileoff, PGSIZE);

means:

File [0x2000, 0x3000)
          │
          │ readi()
          ▼
Newly allocated physical page mem
          │
          │ mappages()
          ▼
User virtual address [0x6000, 0x7000)

In one sentence: fileoff is used to determine "which page of the file corresponds to the virtual page where the page fault occurred."

Also, pay attention to flags.

Additionally:

The situation encountered in vm.c requires #include "file.h"

Implementing munmap()

The hardest sub-problem.

The system call's function signature:

int munmap(void *addr, size_t len);

Both addr and len are virtual addresses (the VMA part of the virtual address space).

The key point is that there is no need to handle the partial hole-punching case. That is, you only need to consider situations like:

The spec is not very detailed, but I think it's fine to handle things across VMAs, and since VMAs are always allocated forward, it's like this:

This diagram is fairly clear: for a vma:

  • the leftmost end is vma->addr
  • the length of the whole segment is vma->len
  • the rest doesn't matter; offset is assumed to be 0 throughout this problem

Such a situation is only possible.

So I considered: starting from addr, compute the byte-range window that needs to be freed, then shrink the window while freeing; in each loop iteration, scan all vmas and make the judgment based on where addr falls. (But each round only handles one; once scanned and matched, handle it.)

After that, through repeated comparisons, determine which case it is (head or tail), and then determine the specific range that needs to be handled.

Then, within this range, process page by page:

  • If vma->flags == MAP_SHARED, then a write-back operation is needed

    • Compute fileoff, i.e., the offset within the file. Since we are writing back to the file, but the adjustment inside the file is done via the offset in the inode structure, it needs to be specified manually here

      Why can't it be fully handled? Because unmapping can unmap only part of the region.

    • Write back to the file; how much to write is also a question. By default, we write one page at a time (since we process page by page). But sometimes the end may have less than a full page, in which case write_len becomes the remaining length at the end.

      The above part needs to obtain ip->size; even reading requires taking the inode lock.

    • Finally, write back. The spec says to refer to filewrite(), but there's a problem here, because filewrite()'s in-file offset cannot be specified by yourself. See the section below for details; in short, write a filewriteat() helper function that allows specifying the offset.

    • Finally, if exactly an entire vma was freed, then the file's ref count also needs to be decremented (fileclose(f)), and this vma cleared.

  • Finally, remember to update the window.

The core logic — since you'll find that the later modification to kexit() needs to do the same thing as munmap() — is extracted into a function taking parameters, placed in vm.c.

// kernel/sysfile.c
uint64
sys_munmap(void)
{
  uint64 addr;
  size_t len;

  argaddr(0, &addr);
  argaddr(1, &len);
  return vmaunmap(myproc(), addr, len);
}
代码C · 80 行
// kernel/vm.c
int
vmaunmap(struct proc *p, uint64 addr, uint64 len)
{
  addr = PGROUNDDOWN(addr);
  len = PGROUNDUP(len);
  if(len == 0 || addr + len < addr) {
    return -1;
  }

  while(len > 0) {
    struct vma *vma = 0;

    // Re-scan because VMA slot order need not match virtual-address order.
    for(int idx = 0; idx < NVMA; idx++) {
      struct vma *cand = &p->vma[idx];
      if(cand->valid && addr >= cand->addr &&
         addr - cand->addr < cand->len) {
        vma = cand;
        break;
      }
    }

    if(vma == 0) {
      return -1;
    }

    struct file *f = vma->f;
    struct inode *ip = f->ip;
    uint64 vma_end = vma->addr + vma->len;
    uint64 unmap_end = addr + len;
    uint64 free_end = unmap_end < vma_end ? unmap_end : vma_end;
    uint64 free_len = free_end - addr;

    for(uint64 pageva = addr; pageva < free_end; pageva += PGSIZE) {
      pte_t *pte = walk(p->pagetable, pageva, 0);
      if(pte == 0 || (*pte & PTE_V) == 0) {
        continue;
      }

      if(vma->flags == MAP_SHARED && (vma->prot & PROT_WRITE)) {
        uint64 pa = PTE2PA(*pte);
        uint64 fileoff = vma->offset + (pageva - vma->addr);
        uint write_len = PGSIZE;

        ilock(ip);
        if(fileoff >= ip->size) {
          write_len = 0;
        } else if(write_len > ip->size - fileoff) {
          write_len = ip->size - fileoff;
        }
        iunlock(ip);

        if(write_len > 0 &&
           filewriteat(f, 0, pa, fileoff, write_len) != write_len) {
          return -1;
        }
      }
      uvmunmap(p->pagetable, pageva, 1, 1);
    }

    if(addr == vma->addr && free_end == vma_end) {
      fileclose(f);
      memset(vma, 0, sizeof(*vma));
    } else if(addr == vma->addr) {
      vma->addr += free_len;
      vma->len -= free_len;
      vma->offset += free_len;
    } else if(free_end == vma_end) {
      vma->len -= free_len;
    } else {
      panic("vmaunmap: hole");
    }

    addr = free_end;
    len -= free_len;
  }

  return 0;
}

Why filewriteat() is needed

There are two main problems here: the in-file offset and the type of the source address.

First look at the most critical part of filewrite():

if ((r = writei(f->ip, 1, addr + i, f->off, n1)) > 0) {
  f->off += r;
}

filewrite() does not take a file offset parameter; it uses the f->off inside struct file. Each time a chunk of data is written, it also automatically advances f->off. This is correct for ordinary write(), since ordinary file reads and writes inherently need to maintain a current read/write position.

But when mmap writes back to the file, the file position cannot be determined by f->off; it is determined by the page's position within the VMA:

fileoff = vma->offset + (pageva - vma->addr);

For example, suppose the mapping starts at file offset 0, and now we want to unmap page 2 of the VMA:

VMA page 0  ────▶  file offset 0
VMA page 1  ────▶  file offset 4096
VMA page 2  ────▶  file offset 8192

At this point that page must be written to file offset 8192. But f->off might be 0, or might already have been moved elsewhere by ordinary read() / write() calls. Moreover, filedup() only increments the reference count of the original struct file; the VMA and the fd still point to the same struct file, so you cannot assume f->off always equals the position mmap needs.

Even writing the entire VMA back at munmap() time does not solve this problem. filewrite() would still start writing from f->off, not from vma->offset. Also, munmap() may unmap only part of the VMA, and the mapping length may be greater than the file length, so you still need to explicitly specify the file range to write back this time.

So the logic in filewrite() for writing to inode files was extracted into filewriteat():

int
filewriteat(struct file *f, int user_src, uint64 src, uint64 off, int n);

The final call is:

filewriteat(f, 0, pa, fileoff, write_len);

where:

  • 0 means it is pa, not va;

    Actually, passing va here (in vmunmap()) would also work (that is, the pageva in the loop), but it's the same.

  • pa is the physical page that currently needs to be written back;

  • fileoff is the correct position of this page within the file;

  • write_len is the length actually allowed to be written this time.

filewriteat() still keeps the chunked writing, file system transaction, and inode locking logic from filewrite(), but it uses the explicitly passed off, and does not read or modify f->off.

Modifying kexit()

Just free all VMAs, same as munmap().

// munmap all mmap regions
for(int i = 0; i < NVMA; i++) {
    struct vma *vma = &p->vma[i];
    if(vma->valid) {
      if(vmaunmap(p, vma->addr, vma->len) < 0) {
        panic("kexit: vmaunmap");
      }
    }
}

Modifying kfork()

That is, just copy it; there's no essential difference from copying the trapframe. The hints also mention that the file reference count needs +1; just do as told.

for (int i = 0; i < NVMA; ++i) {
    struct vma* vma = &p->vma[i];
    struct vma* nvma = &np->vma[i];
    *nvma = *vma;
    if (nvma->valid) {
      filedup(nvma->f);
    }
}

About the challenges

Actually, I think all of these are quite interesting, but I'm a bit tired. If I get interested later, I'll come back and implement them.

引用If two processes have the same file mmap-ed (as in the fork tests), shar...
  • If two processes have the same file mmap-ed (as in the fork tests), share their physical pages. You will need reference counts on physical pages.
  • Your solution probably allocates a new physical page for each page read from the mmap-ed file, even though the data is also in kernel memory in the buffer cache. Modify your implementation to use that physical memory, instead of allocating a new page. This requires that file blocks be the same size as pages (set BSIZE to 4096). You will need to pin mmap-ed blocks into the buffer cache. You will need worry about reference counts. One benefit of fixing this double-caching is that it also helps make read() and write() consistent with mmap. That is, if some mmaped file data is modified through the memory mapping, read should return those modifications, and likewise, if an application calls write, the write should appear in any active memory mappings of that file. You might find it interesting to read the paper on the unified buffer cache.
  • Remove redundancy between your implementation for lazy allocation and your implementation of mmap-ed files. (Hint: create a VMA for the lazy allocation area.)
  • Modify exec to use a VMA for different sections of the binary so that you get on-demand-paged executables. This will make starting programs faster, because exec will not have to read any data from the file system.
  • Implement page-out and page-in: have the kernel move some parts of processes to disk when physical memory is low. Then, page in the paged-out memory when the process references it.

After finishing, I realized I don't really understand xv6's logging and transaction system. I only briefly touched on simple APIs like bread() and brelse() in the file system lab, but never went as deep as I did with inode. That's a TODO as well.

Though it seems that just reading the book (the xv6 book) carefully would be enough.


xv6 Lab9 mmap - MIT 6.1810 Fall 2025 Operating System
https://blog.wendain.ing/en/posts/xv6-lab9-mmap/
Author
wendaining
Posted on
August 19, 2026
Updated on
August 20, 2026
Licensed under