Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 96 of 9361. Foundations of Digital Logic and Computer ArchitectureFree lesson

Handling Page Faults and Demand Paging

Manage hardware-software interactions required to swap memory pages between physical RAM and secondary storage when requested data is not present.

In this lesson, you will learn how the processor detects missing data in physical memory and triggers the mechanism to fetch it from storage, a process known as demand paging.

The Missing Piece: What is a Page Fault?

In a virtual memory system, the operating system gives each program the illusion that it has access to a massive amount of RAM. However, the system only loads parts of the program into actual physical RAM as needed. When a CPU tries to access a virtual address that hasn't been mapped to a physical RAM location, the hardware triggers a Page Fault.

Think of your physical RAM like a desk and your hard drive like a bookshelf. You are working on a report (the program), but suddenly, you realize you need a specific document that isn't on your desk. The "Page Fault" is you noticing the document is missing, which forces you to stop your current task and go retrieve it from the bookshelf.

The Demand Paging Cycle

When the hardware detects that the "Present bit" in your page table is set to 0, it triggers an exception. Here is how the system handles it:

  1. Trap to OS: The CPU pauses the instruction and hands control to the Operating System’s kernel.
  2. Locate Data: The OS identifies where the missing page lives on the secondary storage (disk).
  3. Swap-in: The OS finds an empty frame in physical RAM (or clears one out) and copies the required data from the disk into that RAM frame.
  4. Update Table: The OS updates the page table entry to point to the new physical RAM address and sets the "Present bit" to 1.
  5. Resume: The CPU restarts the exact instruction that caused the fault. Because the page is now in RAM, the instruction succeeds this time.
// Pseudo-code logic for the Hardware-OS handshake
if (PageTable[virtual_page].present_bit == 0) {
    RaiseException(PAGE_FAULT); // Hardware signals the OS
    HandlePageFault();          // OS moves page from Disk to RAM
    UpdatePageTable();          // Point to new RAM address
    RetryInstruction();         // Resume execution
}

By only loading data when it is explicitly requested ("Demand Paging"), we keep our limited physical RAM free for the tasks the CPU is actively performing right now.

Key Takeaway: A page fault is a hardware-triggered exception that pauses execution so the OS can move requested data from slow storage to fast RAM, ensuring only necessary information occupies physical memory.