Part 2 of 7 · 2 min read
Swap
In plain words: A page of a file can always be dropped from memory and read again, since the file holds them (Level 6 page 7). A page of the heap or the stack has no file. If the kernel wants its frame, it must keep the content somewhere first. That place is swap space: a disk partition or file that the administrator sets aside. A page written there is said to be swapped out, and a later access to it causes a major fault, which reads it back (swapped in). The analogy of a desk and a filing cabinet fits: swap is the cabinet in the basement, and the desk is memory. The analogy stops in one place: the basement is thousands of times slower than the desk.
The tools show the traffic. vmstat 1 prints the columns si and so, the memory swapped in and out each second. The counters pswpin and pswpout in /proc/vmstat count pages since boot. The setting vm.swappiness (60 by default, 60 on the test machine) tells the kernel how willingly to swap out anonymous pages instead of dropping file pages from the cache.
The test machine is a common case in the cloud and in containers: SwapTotal is 0 kB. With no swap, the kernel can drop file pages, but the pages of the heap and the stacks stay in memory for as long as the process lives. A process that keeps asking for memory cannot be helped by swapping, and the system moves to the last resort of section 3. The measurements of swap speed are therefore not part of this page. Their effect is the one that page 9 of Level 6 showed in a model: a system that swaps heavily spends most of its time waiting for the disk.
Swap space
Swap space is an area of disk, a partition or a file, to which the kernel writes the contents of anonymous pages (those with no file behind them) so that their frames can be reused, and from which it reads them back when the process touches them again.
Example: a page of a process's heap that was idle for an hour may be written to swap, and read back by a major fault when the process uses it.
Check yourself:
1. Why can a file page be dropped from memory without swap, and a heap page not?
2. What do si and so in vmstat show?
3. What can the kernel do for a heap page when there is no swap space?