Mapping pages of memory

Hard

In an xv6 user-space process, new virtual-to-physical memory mappings can be added to the process’s page table as a result of the sbrk system call. This system call adjusts the size of the process’s heap segment within its address space (cf. Figure 3.4). The malloc function from the C standard library, for example, relies on sbrk in its underlying implementation.

In this exercise, you will implement an alternative method for allocating memory: a simplified version of the mmap system call, allowing a user-space program to map a virtual address of choice.

Our version of the mmap system call has the following specification:

/* int mmap(uint64 vaddr, uint perms)
 *
 * Allocates one page at virtual address 'vaddr' with the permissions specified by 'perms'
 *
 * Returns 0 on success, -1 otherwise
 *
 * Note: The permissions are a "bitwise or" combination of `PTE_R`, `PTE_W`, and `PTE_X`.
 */
int mmap(uint64 vaddr, uint perms);

There are three key differences between our implementation of mmap and the POSIX standard:

  • Private Pages Only: We only support private pages, meaning MAP_SHARED is not available. For reference, see the MAP_PRIVATE flag in the mmap man page.
  • Fixed Allocation Size: Unlike POSIX mmap, our implementation does not accept a size parameter. It always allocates a single memory page.
  • No File Descriptor Support: Our version does not accept file descriptors and only supports anonymous pages (i.e., pages not backed by a file). For more information, refer to the MAP_ANONYMOUS flag in the mmap man page.

Keeping track of mmapped pages

With this new functionality, the virtual address space of a process may no longer be contiguous, which must be dealt with when releasing resources upon process termination. To enable xv6 to keep track of the pages mapped with mmap, extend struct proc in proc.h with the following array field:

uint64 mmapped[MAXMMAP];

where MAXMMAP stands for the maximum number of pages that a process can allocate with mmap. Define this macro in param.h and set it to 10. Think of a way to keep track of how many pages a given process allocated with mmap. You can do this by initializing the mmapped array with entries that cannot be valid addresses when the process is created, or by allocating a new variable to explicitly keep a count.

:bulb: Refer to the numsyscalls exercise from Lab 2 if you forgot where in the xv6 code base to add struct proc initialization code.

Implementing the mmap system call

Next, implement our version of the mmap system call in sysproc.c:

  1. Verify that vaddr is not already mapped. You can use the walkaddr function to verify this.
  2. Sanitize the perms parameter:
    • Clear the bits not corresponding to PTE_R, PTE_W, or PTE_X.
    • Ensure that the perms is different from zero, as this would represent a page directory entry in RISC-V’s multi-level page table walk (cf. Figure 3.2), whereas mmap should only map non-directory pages (cf. privileged RISC-V ISA specification). rv-pt-walk
    • Mark the page as a user page (i.e., set PTE_U).
  3. Verify that the process will not exceed MAXMMAP number of mmapped pages.
  4. Allocate a new physical page, initialize it to zero, and update the process’ page table a new mapping from vaddr to the allocated physical page. You can get some inspiration by inspecting the implementation of uvmalloc.
  5. Record the mapped page in the mmapped array on success.

At this stage, user-space programs can use mmap to map new pages at specified virtual addresses, offering an alternative to memory allocation via sbrk. At the end of this exercise, you can find some code for testing your implementation.

Releasing mmapped pages

But first, we must ensure that mmapped pages are properly unmapped when a user process terminates, so that the corresponding physical memory becomes available for other processes. Implement this functionality in the freeproc function. Recall that pages that were mapped with mmap should be recorded by now in the mmapped array. You can unmap pages with uvmunmap.

Copying mmapped pages

When a process is forked, mmapped physical pages should not be shared between the parent and child. The final step in our mmap implementation is to ensure that these pages are copied to the child process during a fork, so that modifications made by either the parent or child do not affect the other.

To this end, modify fork to copy mmapped pages from the parent to the child. To copy a single page at a specified virtual address from the parent process to the child, use the uvmcopypage function, implemented as shown below. Add this code to kernel/vm.c. Don’t forget to declare the function in kernel/defs.h to make it accessible to other parts of the xv6 kernel.

// Given a parent process's page table, copy
// a single page of memory into a child's page table.
// Copies both the page table entry and the
// physical memory.
// returns 0 on success, -1 on failure.
int
uvmcopypage(pagetable_t old, pagetable_t new, uint64 va)
{
  pte_t *pte;
  uint64 pa;
  uint flags;
  char *mem;

  if((pte = walk(old, va, 0)) == 0)
    panic("uvmcopypage: pte should exist");

  if((*pte & PTE_V) == 0)
    panic("uvmcopypage: page not present");

  if((mem = kalloc()) == 0)
    return -1;

  pa = PTE2PA(*pte);
  flags = PTE_FLAGS(*pte);
  memmove(mem, (char*) pa, PGSIZE);

  if (mappages(new, va, PGSIZE, (uint64)mem, flags) != 0) {
    kfree(mem);
    return -1;
  }

  return 0;
}

Testing your implementation

You can test your implementation of mmap by adding the following user-space program to the xv6 codebase and running it in the xv6 shell. If your implementation is correct, you should see the message ‘All tests passed!’ at the end.

#include "user/user.h"
#include "kernel/memlayout.h"
#include "kernel/param.h"

#define BASE  0x0000000baddad000
#define PERMS (PTE_R | PTE_W)

int main(int argc, char **argv)
{
  printf("Before mmap()\n");
  vmprintmappings();

  // Call mmap() MAXMMAP times, in PGSIZE steps, starting at address BASE
  // All calls should succeed
  for (int i=0; i < MAXMMAP; i++) {
    uint64 vaddr = BASE + (i * PGSIZE);
    if (mmap(vaddr, PERMS) < 0) {
      fprintf(2, "mmap() failed\n");
      exit(1);
    }
  }

  // 2. mmap an already mapped address
  //   This should fail
  if (mmap(BASE, PERMS) == 0) {
    fprintf(2, "mmap() succeeded\n");
    exit(1);
  }

  printf("After mmap()\n");
  vmprintmappings();

  int pid = fork();
  if (pid < 0) {
    fprintf(2, "fork() failed\n");
    exit(1);
  }

  // Write the value of 42 at the base address (which is mmapped by now)
  int *base = (int *) BASE;
  *base = 42;

  if (pid == 0) {

    printf("In child\n");
    vmprintmappings();

    // The child should have inherited MAXMMAP mappings from the parent
    // Calling mmap() again should fail.
    uint64 vaddr = BASE + (MAXMMAP * PGSIZE);
    if (mmap(vaddr, PERMS) >= 0) {
      fprintf(2, "mmap() succeeded\n");
      exit(1);
    }

    // The value at the base address should be 42 in the child's address space
    //  as well. Incrementing it with one should not affect the parent process.
    *base = *base + 1;
    if (*base != 43) {
      fprintf(2, "43 expected, got %d\n", *base);
      exit(1);
    }

    exit(0);
  }

  int rc;
  wait(&rc);
  // The value at the base address should still be 42 in the parent's address
  //  space.
  printf("In parent\n");
  if (*base != 42) {
    fprintf(2, "42 expected, got %d\n", *base);
    exit(1);
  }

  if (rc == 0) {
    printf("All tests passed!\n");
  }

  return 0;
}

This site uses Just the Docs, a documentation theme for Jekyll.