Demand Paging - aryanjoshi0823/5143-Operating-System GitHub Wiki

What Is Demand Paging?

Demand paging delays the loading of a program’s memory pages into physical RAM until the program accesses them. If a page is not already in memory when accessed, the operating system triggers a page fault, retrieves the required page from secondary storage (e.g., disk), and loads it into RAM.

When a process is swapped into memory, only the pages expected to be used immediately are loaded into RAM. This method ensures efficient use of memory by reducing the number of pages loaded unnecessarily.

  • Pages not initially loaded are marked as invalid in the page table using an invalid bit.
  • The rest of the page table entry may either remain blank or contain metadata about the page's location in secondary storage (e.g., disk).

If a process accesses only the pages that are already memory-resident, it behaves as though all pages are loaded into memory.


How Does Demand Paging Work?

The process of demand paging involves the following steps:

  1. Page Table Initialization:

    • When a process starts, the OS initializes the page table with entries that indicate the required pages are in secondary storage (not in memory).
  2. Page Access by the Process:

    • As the process executes, it tries to access specific memory addresses. The OS checks if the corresponding page is in memory.
  3. Page Fault Handling (if needed):

    • If the page is not in memory, a page fault occurs.
    • The OS identifies the missing page, allocates space in memory, and retrieves the page from disk.
  4. Updating Page Table:

    • The OS updates the page table to reflect the new location of the page in physical memory.
  5. Process Continuation:

    • The process resumes execution, accessing the newly loaded page.

Example of Demand Paging

Consider a text editor application that supports multiple files:

  1. When the editor is launched, only the essential code and data (e.g., UI components) are loaded into memory.
  2. If the user opens a specific file, the OS loads the pages corresponding to that file into memory.
  3. If the user switches between files, demand paging ensures that only the necessary pages for the active file remain in memory, while others are stored on disk.