Swap

From Gentoo Wiki
Jump to:navigation Jump to:search
Resources
This article has some todo items:
  • swapiness, remove swap files

In the Linux/Unix world, the term swap is generally used as a synonym for memory paging. Swap refers to both the act of moving memory pages between RAM and disk and the allocated space on the disk itself.

Linux can use any combination of swap partition and/or swap files together; however swap space may not be necessary depending on the necessary requirements for the system in question. For example, a laptop that will be suspending to disk (hibernation) requires all pages in memory to be stored to disk, so swap is necessary in this case. Server systems equipped with large amount of memory and running at a constant load might not require swap at all. For further details, see the dedicated Knowledge Base article.

Swap partition

As best practice, the Gentoo Handbook recommends, as part of the installation process, creating a swap partition with a size of twice the available system memory[1].

Swap partitions can be created and activated at any time as long as partitions are available and formatted correctly.

Tip
Nowadays, having systems with plenty of memory, it may be sufficient to create a swap partition smaller than the available memory. When using hibernation, storing a compressed RAM image inside the swap partition, it's a good idea having a swap partition with the size of the installed memory.

Creation

Presuming /dev/sda2 is the partition available to be used for swap:

root #mkswap /dev/sda2 # Format the partition for swap.
root #swapon /dev/sda2 # # Activate the swap partition.

Review the activated swaps with the swapon command:

root #swapon --show

To avoid manually activating the swap file across reboots, append a line (adjusting the path as necessary) to fstab:

FILE /etc/fstab
/dev/sda2 none swap sw 0 0

Encrypted swap with hibernate option

Assuming the desired goal is a LUKS encrypted swap partition with the ability to still be able to perform hibernate (a.k.a. suspend to disk). The encrypted swap partition needs a known LUKS-key (keyfile, password, etc.). The user will be asked to enter the password from a very early phase of the boot process. The kernel then has to decide whether to regularly boot the system or to load a hibernated RAM image from SWAP – if if the system was hibernated in the previously power state.

The creation of a LUKS encrypted swap partition is not different to any other LUKS encrypted partition, described in creating an encrypted storage platform. Use mkswap instead of mkfs.* to the LUKS encrypted partition to create SWAP. The UUID (i.e. 01b37ea8-74a5-4526-85c7-9fdf6dad34cb), created when formatting as swap, is needed for the next step:

Tell the bootloader (GRUB) where to resume from if hibernated:

FILE /etc/default/grub
GRUB_CMDLINE_LINUX_DEFAULT="resume=UUID=01b37ea8-74a5-4526-85c7-9fdf6dad34cb"

In addition (when using OpenRC with dracut, systemd is presumed to be now used for this section of the guide) dracut will need to be told the major and minor number of the associated LUKS device, so it can create an appropriate initrd:

root #lsblk
..
└─sdb1                                          8:22   0    32G  0 part   
 └─luks-cc166689-4246-41ae-86e8-84705b81ecc2  253:1    0    32G  0 crypt [SWAP]
root #echo 253:1 > /sys/power/resume
Note
The default value is 0:0. echo this in again to deactivate hibernation.
Warning
Ensure LUKS UUID (cc166689-4246-41ae-86e8-84705b81ecc2) and the SWAP UUID (01b37ea8-74a5-4526-85c7-9fdf6dad34cb) are not confused!

Finally, the initrd needs to be updated with this changes:

root #dracut --hostonly --force

Do not forget the regular configuration of SWAP in /etc/fstab and restart the system afterwards.

FILE /etc/fstab
# /dev/sdb1 (SWAP) 
UUID=01b37ea8-74a5-4526-85c7-9fdf6dad34cb               none            swap    sw      0 0
Note
If a LUKS encrypted SWAP using dmcrypt is already setup by including a configuration in /etc/conf.d/dmcrypt, it will be obsolete, since this LUKS device will now be opened earlier with the help of the dracut generated initrd.

Using full disk encryption

When already using full disk encryption with LUKS, a decryption password prompt will appear twice when booting; once to enter the LUKS-key for the system's root partition (as before) and once to decrypt the SWAP partition. It is possible to just decrypt the root partition and then use a LUKS keyfile, stored on the just now decrypted root partition, to decrypt the SWAP partition automatically. Details and an easy example how to do this within /etc/default/grub, can be found on kernel.org.

Swap files

In order to work around the more ridged constraints of disk partitions, an alternative is to use swap as an on-disk file. Files have the ability to be located inside disk partitions. This allows the system administrator the flexibility to resize or move the swap space as necessary to meet the demands of the system without having to open a partitioning tool.

Creation

Begin by allocating a new file used for the backing store of the swapfile, the size of this file will be the size of the swap space. Standard utilities can be used for this purpose such as fallocate from sys-apps/util-linux:

root #fallocate -l 12GiB swapfile # Create the file.
root #chmod 600 swapfile # Restrict security on the file to root access only.
Note

If the partition the swapfile is located on is using Btrfs, swapon will fail unless copy-on-write and compression is disabled for the swapfile[2]:

root # truncate -s 0 swapfile
root # chattr +C swapfile
root # btrfs property set swapfile compression none

Now initialize and turn the swapfile on:

root #mkswap 12G-swapfile # Format the file swap.
root #swapon 12G-swapfile # Activate the swap file.

It's also possible to review the system swaps with the swapon command:

root #swapon --show

To avoid manually activating the swap file across reboots, append a line (adjusting the path as necessary) to fstab:

FILE /etc/fstab
/12G-swapfile none swap sw 0 0

Encrypted swap

Since swap contents do not need to persist between boots, it's a good idea to encrypt them. It's easy using a swap file.

root #dd if=/dev/zero of=swap count=2048 bs=1M
root #cryptsetup --type plain -d /dev/urandom open swap swap
root #swapon swap
root #swapon --show

Then, edit /etc/fstab and either /etc/crypttab (if using systemd) or /etc/conf.d/dmcrypt (if using OpenRC) to automatically active it:

FILE /etc/crypttab
swap /opt/swap  /dev/urandom swap
FILE /etc/conf.d/dmcrypt
swap=swap
source=/opt/swap
FILE /etc/fstab
/dev/mapper/swap                                        none            swap    sw      0 0

Finally, if using OpenRC, enable the dmcrypt service:

root #rc-update add dmcrypt boot

OpenRC configuration

When using swap files which are not on the root filesystem, the service ordering in OpenRC should be changed via /etc/conf.d/swap:

FILE /etc/conf.d/swap
# If you are only using local swap partitions, you should not change
# this file. Otherwise, you need to uncomment the below rc_before line
# followed by the appropriate rc_need line.
rc_before="!localmount"
#
# If you are using swap files stored on local file systems, uncomment
# this line.
rc_need="localmount"
#
# If you are using swap files stored on network file systems or swap
# partitions stored on network block devices such as iSCSI, uncomment
# this line.
#rc_need="netmount"

See also

  • Filesystem — a means to organize data expected to be retained after a program terminates by providing procedures to store, retrieve, and update data as well as manage the available space on the device(s) which contain it.
  • Zram — a Linux kernel feature and userspace tools for creating compressible RAM-based block devices.
  • Zswap — a lightweight compressed cache for swap pages.

External resources

References