With the release of btrfs-progs
6.1 (available in Debian Bookworm), you can create a swap file using the btrfs
utility. It will take care of both preallocating the file and marking it as NODATACOW
. As BTRFS can’t snapshot a subvolume that contains an active swap file, we will create a new subvolume for the swap file to reside in.
$ sudo btrfs subvolume create /swap
$ sudo btrfs filesystem mkswapfile --size 4g /swap/swapfile
$ sudo swapon /swap/swapfile
To auto-activate the swap file at boot, add the following line to /etc/fstab
:
/swap/swapfile none swap defaults 0 0
Encrypted swap file
My entire root filesystem is encrypted, but having unencrypted swap can still lead to sensitive data being inadvertently exposed. The solution is to encrypt the swap file using random keys at boot. Add the following line to /etc/crypttab
:
swap /swap/swapfile /dev/urandom swap,cipher=aes-xts-plain64
And change the swap file location in /etc/fstab
to point to /dev/mapper/swap
like this:
/dev/mapper/swap none swap defaults 0 0
The new swap file will automatically start upon boot. To start it immediately, run:
$ sudo systemctl daemon-reload
$ sudo systemctl start systemd-cryptsetup@swap.service
$ sudo swapon /dev/mapper/swap
PSI-Notify
Adding a small amount of swap can significantly help in preventing the system from running out of memory. psi-notify
can alert you when your running low on memory.
$ sudo apt install psi-notify
$ systemctl --user start psi-notify
Add the following line to ~/.config/psi-notify
:
threshold memory some avg10 2.00
You may need to adjust the threshold to ensure it triggers at the right time for your needs. To test memory pressure, you can use the following command:
$ </dev/zero head -c 20G | tail