The OS needs to swap out some pages to external drive, to provide address spaces larger than physical memory.

Swap space

Swap space is a space for moving pages back and forth. The system move pages into physical memory when needed, and move them back when not needed.

Example of physical memory and swap space

Example of physical memory and swap space

Swap space is not the only destination of swapping. Sometimes when a process starts, the pages are initially in the disk, and then fetched to physical memory.

Present bit

To mark if a page has been swapped out, add a present bit to PTE. If the present bit is 1, then it’s in physical memory.

Accessing a page not present in physical memory is called a page fault. It’s not necessarily a fault, however.

Page fault

The OS uses some bits in the PTE (such as PFN bits) to store disk address.

When OS receives a page fault, it finds the address, and send an IO request to fetch the page. When IO completes, the present bit is marked 1, and the memory access is retried. In the second attempt, the PTE is recorded in TLB, and retry. Finally it completes in 3 attempts.

When it’s performing IO, the process is blocked and other processes can be continued.

What if memory is full?

Selecting which pages should be swapped out or replaced is called page-replacement policy (页交换策略).

When replacements really occur

The system won’t wait until the physical memory is full; instead, most of them sets a High Watermark (高水位线) and a Low Watermark (低水位线).

If there are less available pages than LW, a swap daemon (or page daemon) runs to release memory, until there are HW available pages.

Disk IO performance can be optimized by clustering or grouping several swapping process.