/Teaching/Operating Systems/Tutorials/Page Faults

Page Faults

The Intel x86 CPU has many different Interrupts. A special type of Interrupts are the CPU Faults. You might already have heard of a Division By Zero CPU Fault or the term Segmentation Fault. A CPU Fault is not an error. A CPU Fault may be handled by the operating system. Only if the operating system is not able to handle the CPU Fault or decides not to handle the CPU Fault, it results in an error. CPU Faults occur very frequently in modern operating systems. For instance, while writing this my operating system handled more than 500 Page Faults per second.

We should first think about memory. Assuming you have already read about Paging on x86-64. Paging allows us to start a program without loading any of it’s data into memory. The program starts execution and every address in the program, even the addresses where the binary code should be, are not mapped and therefore invalid.

Of course, when the CPU tries executing the binary code it tries to access the according address, which does not work. In this case the CPU issues a Page Fault.

As already said, Page Faults are special interrupts and we know who handles interrupts: the operating system. In SWEB there is a C function:

extern "C" void pageFaultHandler(size_t address, size_t error)
{
// ...

This function gets the Page Fault address and the error code.

The operating system will now decide whether this address should be accessible. If so, it loads the according 4 KiB data from the binary (file) for this single page, copies the data to a free physical page, marks the physical page as used and maps the page in the page directory and the page table of the user process that produced the Page Fault.

Afterwards the operating system returns from the interrupt. Now there are two possible scenarios:

  1. The operating system loaded and mapped the page. The execution then continues. (Normal behaviour)
  2. The operating system decided that the address you requested is bad or not to be found in the binary (file). For instance accessing 0x0. The operating system then kills the user process which produced the page fault. This case is often referred to as Segmentation Fault. (Bug/Error in the User Program).