Page faults

Easy

Recall the first exercise from Lab 3 where you implemented pretty printing for traps. When a program attempts to access memory in a way that violates the permissions set in the corresponding page table entry (PTE), the CPU generates a page fault exception (commonly referred to as a page fault).

When such an exception occurs, the trap handler is executed, identifying the source of the trap and handling it appropriately. Some exceptions lead to program termination, as you saw in Lab 3. When this occurs, the operating system terminates the faulty process and displays some diagnostic information, such as the dreadful Segmentation fault (core dumped) error message. xv6 reports the trap cause along with other relevant details for program-terminating exceptions.

Not all page faults will terminate a program. Page faults also occur when the paging hardware fails to find a PTE in the process’s page table, essentially, when a virtual page is not mapped to a physical page. In this case, we say the page is unmapped. While this triggers a page fault, instead of terminating the program, the operating system can choose to map the page at that moment. This mechanism is known as demand paging.

The table below provides an overview of the possible trap causes that can be handled in supervisor mode, as specified via the scause register defined in the privileged RISC-V ISA specification.

Supervisor exception codes

Thought experiment

Consider a C program that invokes a function using an uninitialized function pointer. Which of the exceptions from the table above could potentially occur in this scenario?

Task

Add the following code as a user-space program named pf to the xv6 codebase and run it from the command line in the QEMU emulator.

#include "user/user.h"
#include "kernel/riscv.h"

int main(void)
{
  int *p = (int *) MAXVA;

  printf("%d", *p);

  return 0;
}

What happens? And why? What is the value of the exception code (displayed as a hexadecimal value)?

:bulb: In the trap handler message, you will encounter the terms scause, sepc, and stval. The scause register distinguishes different exception types, as specified in the table above. The sepc register provides the program counter of the instruction that suffered the exception, and the stval register provides optional extra data associated with the exception (e.g., data address for a load/store page fault). For the exact semantics, you can refer to the xv6 header file kernel/riscv.h and Section 4.1 (RISC-V Trap Machinery) of the xv6 book.


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