Page Fault - aryanjoshi0823/5143-Operating-System GitHub Wiki

What Is a Page Fault?

A page fault is a critical event in memory management where the operating system (OS) responds to a program's attempt to access a memory page not currently in RAM. This mechanism ensures that memory usage remains optimized and that the system can handle large datasets without requiring vast amounts of physical memory.

Sequence of Events During a Page Fault

  1. Hardware Trap:

    • The CPU detects the page fault and traps to the OS kernel.
    • The program counter (PC) and CPU register states are saved.
  2. Saving State:

    • The OS starts an assembly routine to save general-purpose registers and other volatile data to preserve system integrity.
  3. Determining the Fault Cause:

    • The OS identifies which virtual page caused the fault, using hardware registers or by analyzing the PC and the faulting instruction.
  4. Validation:

    • The OS checks if the address is valid and ensures there are no protection violations (e.g., access to read-only pages).
  5. Allocating or Replacing a Page Frame:

    • If no free frames are available, the OS runs a page replacement algorithm to evict an existing page.
    • If the evicted page is "dirty" (modified), it is written back to disk before freeing the frame.
  6. Loading the Page:

    • The required page is fetched from secondary storage into the free frame.
  7. Updating Page Tables:

    • The OS updates the page table to map the virtual address to the physical frame.
  8. Restoring Execution:

    • The faulting instruction is restarted, and the saved CPU state is restored, allowing the program to continue execution seamlessly.

Causes of Page Faults

  1. Demand Paging: Accessing a page not currently loaded into RAM.
  2. Invalid Memory Access: A program attempts to access memory outside its allocated range.
  3. Memory Protection Violations: A process writes to a read-only page or violates memory access permissions.

Types of Page Faults

  1. Minor Page Fault: The required page is in memory but not mapped to the current process’s page table.
  2. Major Page Fault: The page is not in memory and must be retrieved from disk.
  3. Invalid Page Fault: Occurs when a process tries to access an invalid or non-existent memory address.

Impact of Page Faults on System Performance

  1. Thrashing: Frequent page faults cause the system to spend more time handling faults than executing processes, leading to degraded performance.
  2. Increased Latency: Fetching pages from disk is significantly slower than accessing RAM, leading to delays.
  3. Reduced CPU Utilization: Excessive page faults can leave the CPU idle, waiting for memory operations to complete.