What is a page fault, and how does the OS handle it?
MediumConceptVirtual Memory & Paging
Answer
A page fault is the trap raised by the MMU when a process accesses a page whose page-table entry is marked invalid, usually because the page is on disk rather than in RAM. The OS loads the page and restarts the instruction, so the program notices nothing except the delay. The OS handles it in these steps:
- Check that the address is legal; if it is not, for example a null pointer, stop the process with a segmentation fault.
- Find a free frame. If there is none, choose a victim page with a page-replacement algorithm, and write it back to disk first if it is dirty (modified).
- Read the required page from disk into the frame. The process is blocked meanwhile, and the CPU runs other processes.
- Update the page table (frame number and valid bit) and restart the faulting instruction.
Example: memory access time = 100 ns, page-fault service time = 8 ms = 8,000,000 ns, and one access in 1,000 causes a fault (p = 0.001). The effective access time (EAT) is:
EAT = (1 − p) × 100 + p × 8,000,000 = 99.9 + 8,000 = 8,099.9 ns ≈ 8.1 µs.
Even this small fault rate makes memory about 81 times slower, which is why fault rates must stay very low.