How to create a swapfile on a btrfs filesystem

Some things you should be aware of:

  1. Linux Kernel 5.x supports swapfiles natively on btrfs
  2. This is a bit of a kludge.

Summary:

Btrfs does not natively support swapfiles as the kernel wants them to be contiguous blocks on disk.To work around this, we create a loop-mounted filesystem that is formatted ext4, and in that filesystem, we create a swapfile.

Background:

Btrfs as a filesystem is much more similar to a modify on write filesystem like Netapp’s wafl or ZFS. It’s a copy-on-write filesystem, so it’s not quite the same, but under the hood, a files blocks aren’t necessarily stored next to each other. Historically, the kernel wanted the blocks in a swapfile to be next to each other and contiguous, because on spinning disk, seek time is what kills you.

Workflow:

Create a 2.5G  swapfile:

dd if=/dev/zero of=/var/loopdisk.img bs=1024 count=2500000

Format the file with ext4:

 mkfs.ext4 /var/loopdisk.img

Mount the file and make it permanent:

mkdir /mnt/loop-ext4fs
mount -t ext4 -o loop /var/loopdisk.img /mnt/loop-ext4fs/ && \
  grep '/mnt/loop-ext4fs' /etc/mtab >> /etc/fstab

Create the swapfile:

dd if=/dev/zero of=/mnt/loop-ext4fs/swapfile bs=1024 count=2000000
chmod 600 /mnt/loop-ext4fs/swapfile
mkswap /mnt/loop-ext4fs/swapfile
swapon /mnt/loop-ext4fs/swapfile

Verify that it worked:

 free -h --si
              total        used        free      shared  buff/cache   available
Mem:           4.0G        153M        123M        966K        3.8G        3.6G
Swap:          2.0G          0B        2.0G

Add an entry to the /etc/fstab for the swapfile:

/mnt/loop-ext4fs/swapfile       none    swap    sw       0      0

Verify that it will be used as swap when the sytem boots:

swapoff -a
free -h --si
              total        used        free      shared  buff/cache   available
Mem:           4.0G        152M        122M        966K        3.8G        3.6G
Swap:            0B          0B          0B
swapon -a
free -h --si
              total        used        free      shared  buff/cache   available
Mem:           4.0G        153M        121M        966K        3.8G        3.6G
Swap:          2.0G          0B        2.0G

It’s not a terrible idea to reboot to make sure that everything will work on startup.

This entry was posted in linux, tech. Bookmark the permalink.