Part 2 of 7 · 2 min read
Demand paging
Think of it this way. A cook preparing a dinner does not carry every ingredient from the store room to the kitchen first. The cook fetches an ingredient when the recipe reaches the step that needs it, and some ingredients are never fetched because that dinner does not use them. Demand paging treats the pages of a program in the same way. The analogy stops in one place: the cook decides to fetch, while in demand paging the hardware notices the missing page and the kernel fetches it without the program knowing.
In plain words: A program file may be 50 MiB long, with error-handling code that never runs, features that the user never opens and tables that are read only in part. Loading all of it at the start would waste time and memory. With demand paging, the kernel sets up the page table and loads nothing, or very little. The program starts, touches a page, and that page is brought in at that moment.
The page table needs one extra fact for each page: is the page in memory now? Each entry carries a bit for it. OSTEP calls it the present bit, and OSC calls it the valid–invalid bit. The names differ, and the use is the same:
- Bit set: the entry holds a frame number, and translation works as on page 3.
- Bit clear: the page is not in memory. The entry may say where the page can be found, for example a place in the file or a place in swap space.
A system that starts a process with no pages in memory, and brings in each page only at its first use, is said to use pure demand paging. Real systems often load a few pages first, such as the page holding the first instruction.
Demand paging
Demand paging is the scheme in which a page is brought into memory only when a process first uses it, and the page table marks pages that are absent with a present bit set to zero.
Example: a program of 12,000 pages starts and touches 300 of them in the first second, so only those 300 pages take frames.
Check yourself: 1. What does the present bit tell the hardware? 2. Why does demand paging make a program start faster? 3. What is the difference between demand paging and pure demand paging?