Create swapfile on btrfs

Mike Litoris
1 min readMar 26, 2021

--

if you try to create a swapfile on btrfs, the swapon always fails with a cryptic error “invalid argument”. reason for this is that swapfile cannot be placed on a filesystem with COW and/or compression enabled.

solution is to create a subvolume, turn COW off on it, and create swapfile there.

first, find out ID of your / partition. this can be either UUID=a1b2c3 or /dev/xyz path. you can find it in your /etc/fstab.

1. mount bare root volume

mount -t btrfs <ID> /mnt

2. create subvolume named swap and disable COW and compression on it

btrfs subvolume create /mnt/@swap
chattr -R +C /mnt/@swap
btrfs property set /mnt/@swap compression none

3. create swapfile (change the size 4G as you need). also change it’s access to root-only.

truncate -s 0 /mnt/@swap/swapfile
fallocate -l 4G /mnt/@swap/swapfile
chmod 600 /mnt/@swap/swapfile
mkswap /mnt/@swap/swapfile

now, you need to update the /etc/fstab. it has two steps — mounting the subvolume and mounting the swapfile.

<ID> /swap btrfs defaults,subvol=@swap
/swap/swapfile swap swap defaults 0 0

reboot and check if it works

swapon --show

end

--

--