Linux › Section D · Disks and filesystems › Topic D.4

Swap space

When memory runs short, Linux can move idle pages of memory out to disk and bring them back later. That disk area is swap space. Setting it up takes three commands; deciding how much to have, and recognising when swapping hurts, takes judgement.

What swap does

The kernel manages memory in pages, usually 4 KiB each. When RAM fills, it must free some pages. Pages that came from files, such as cached data or program code, can be dropped (after writing back any changes) and read again later. Anonymous pages, a program's heap and stack, have no file behind them, so the only way to free them is to write them to swap space and read them back on demand. Swap therefore lets a machine hold more than its RAM, at the cost of disk speed. Moving rarely used pages out is harmless; constantly moving active pages in and out, called thrashing, makes everything crawl.

Seeing swap in use

free -h prints memory and swap in readable units: the Swap line gives total, used and free. swapon --show lists each swap area with its type (partition or file), size, amount used and priority; the same information is in /proc/swaps. vmstat 5 prints a line every five seconds, and its si and so columns show memory swapped in and out per second. A large Swap used figure with si and so near zero is fine: idle pages are parked on disk. Steady non-zero si and so mean the system is short of memory now. The topic "Resource monitoring: CPU, memory, and I/O" returns to these tools.

A swap partition

Any empty partition can become swap. 1. Make sure it holds nothing you need: mkswap overwrites it. 2. Run mkswap /dev/sdX3, which writes a swap header with its own UUID, so blkid then reports TYPE="swap". 3. Run swapon /dev/sdX3 to start using it at once. 4. For use at every boot, add a line to /etc/fstab: UUID=<its uuid> none swap defaults 0 0, with none as the mount point and 0 in both final fields. swapon -a enables every swap entry in fstab not marked noauto. On GPT disks the partition type should be Linux swap; on MBR it is type 82.

A swap file

A file works as well as a partition and needs no repartitioning, which is why some distributions use one by default. Current util-linux (2.40 onwards) can create it in one step: mkswap --file --size 4G /swapfile, which allocates the blocks and sets suitable permissions. The portable older method is: dd if=/dev/zero of=/swapfile bs=1M count=4096, then chmod 600 /swapfile so other users cannot read memory contents, then mkswap /swapfile. Either way, finish with swapon /swapfile and an fstab line: /swapfile none swap defaults 0 0. The file must have no holes, so never make it with cp or truncate. On Btrfs it must also have the nocow attribute, and swap over NFS may not work.

Worked example: sizing a swap file

Create a 4 GiB swap file with dd and check the numbers. 1. Size in bytes: \(4 \times 2^{30} = 4{,}294{,}967{,}296\). 2. With bs=1M, which dd reads as 1 MiB (\(2^{20}\) bytes), the count is \(4 \times 2^{30} \div 2^{20} = 4096\), so the command is dd if=/dev/zero of=/swapfile bs=1M count=4096. 3. In 4 KiB pages that is \(4{,}294{,}967{,}296 \div 4096 = 1{,}048{,}576\) pages the kernel can park. 4. A common slip is count=4000, which gives 4000 MiB, about 3.9 GiB. 5. After chmod 600, mkswap and swapon, swapon --show should list /swapfile with a size of 4G.

Turning swap off and priorities

swapoff /swapfile stops using an area. Before it finishes, every page stored there must be read back into memory or moved to other swap, so it fails if RAM plus the remaining swap cannot hold them; swapoff -a disables all swap. When several areas exist, each has a priority: the kernel fills higher-priority areas first and spreads pages across areas of equal priority. Set it with swapon -p 10 /dev/sdX3, or with pri=10 in the fstab options field. A fast NVMe swap partition might be given a higher priority than a swap file on a slow hard disk. To remove a swap area for good, run swapoff and delete its fstab line.

How much swap?

The old rule of twice the RAM dates from small, shared machines and no longer fits. Treat these as starting points, not laws. A desktop or laptop benefits from some swap so idle pages can make room for file caching; hibernation (suspend to disk) writes an image of memory in use to swap, so plan for about the RAM size. Servers vary: some run with little or no swap and rely on monitoring, but with no swap at all, a machine that runs out of RAM has only one option. The kernel's out-of-memory (OOM) killer then ends a process, chosen by a score, to free memory. If a system thrashes, more swap is not the cure; more RAM or fewer processes is.

zram and swappiness

zram creates a compressed block device in RAM and uses it as swap: pages are squeezed rather than written to disk, which is far faster and suits machines with modest memory. Fedora has set up swap on zram by default since Fedora 33 (2020), so swapon --show there lists /dev/zram0. The kernel's eagerness to swap is tuned by vm.swappiness, which defaults to 60 on a 0 to 200 scale. Lower values make the kernel prefer dropping file cache to swapping anonymous pages; higher values do the opposite. Read it with sysctl vm.swappiness, change it temporarily with sysctl -w vm.swappiness=10, and make it permanent with a file in /etc/sysctl.d/.

Worked example: is swap a problem?

A web server feels slow. free -h shows (illustrative) Mem total 16Gi, available 9.5Gi; Swap total 4.0Gi, used 1.2Gi. 1. Available memory is large, so RAM is not exhausted right now. 2. 1.2 GiB of swap used means idle pages were moved out at some earlier peak. 3. Run vmstat 5: the si and so columns stay at 0 for a minute, so nothing is moving between RAM and swap. 4. Conclusion: swap is not the cause of the slowness; look at CPU or I/O instead. 5. If si and so had shown thousands of KiB per second while available memory sat near zero, the system would be thrashing, and the fix would be more RAM or less load.

Common mistakes to avoid

First, running mkswap on a partition that still holds data. Second, leaving a swap file readable by everyone instead of mode 600. Third, making a swap file with cp or truncate, which leaves holes the kernel rejects. Fourth, miscounting dd blocks: bs=1M count=4000 is not 4 GiB. Fifth, writing swap in the fstab mount point field instead of none. Sixth, judging swap by the Used figure alone rather than by si and so activity. Seventh, removing all swap from a general-purpose machine and being surprised when the OOM killer ends an important program.

Key takeaways

Swap holds anonymous memory pages that the kernel moves out of RAM; file-backed pages are dropped instead. Check it with free -h, swapon --show, /proc/swaps and the si and so columns of vmstat. Create it with mkswap on an empty partition, or on a hole-free file with mode 600 (mkswap --file in current util-linux, or dd), enable it with swapon, and list it in fstab with none as the mount point. swapoff needs room to bring pages back. Size swap by workload, about RAM size for hibernation. zram compresses swap in RAM, and vm.swappiness (default 60) tunes eagerness.

Flashcards

Flashcard

Swap space

Disk or zram area holding memory pages moved out of RAM

A partition or a file.

Test your understanding

Question 1 of 5

Which dd command creates a file of exactly 4 GiB for swap?

Question 2 of 5

free -h shows 1.5 GiB of swap used, but vmstat shows si and so at 0 for several minutes. What does this mean?

Question 3 of 5

After running mkswap on /dev/sdb3, what makes the system use it at every boot?

Question 4 of 5

Why can swapoff /swapfile fail on a busy machine?

Question 5 of 5

Which change makes the kernel less eager to swap out anonymous pages?

← Previous topicNext topic →