How to create btrfs swap file for hibernation

After looking at different tutorials, I managed to combine a few tutorials to create a btrfs swap for hibernation, so I’m sharing what I’ve learnt. Make sure the partition is formatted with the btrfs file system before following this tutorial.

sudo mkdir /swap
sudo mount /dev/XXX /swap ## XXX is the partition where the swap will reside
sudo btrfs subvolume create /swap/@swap
sudo umount /swap
sudo mount -o subvol=@swap /dev/XXX /swap
cd /swap
sudo truncate -s 0 swapfile
sudo chattr +C swapfile
sudo dd if=/dev/zero of=swapfile bs=1M count=4096 status=progress ## count is the size of the swapfile
sudo chmod 600 swapfile
sudo mkswap swapfile
sudo swapon swapfile

## Add the following two lines in /etc/fstab:
UUID=NNNN /swap btrfs subvol=@swap ## replace NNNN with the UUID of the partition where the @swap resides
/swap/swapfile none swap defaults 0 0

##Edit /etc/default/grub and the follwoing in GRUB_CMDLINE_LINUX_DEFAULT
e.g. GRUB_CMDLINE_LINUX_DEFAULT="quiet splash apparmor=1 security=apparmor udev.log_priority=3 resume=UUID=NNNN"

sudo grub-mkconfig -o /boot/grub/grub.cfg

##Edit /etc/mkinitcpio.conf and add 'resume' in the HOOKS option after udev
e.g. HOOKS="base udev autodetect modconf block keyboard keymap plymouth filesystems resume"

sudo mkinitcpio -P

Hello @ak2022 :wink:

It’s nice to see that you want to contribute, but there is already a tutorial here: [HowTo] Enable and configure hibernation with BTRFS Please help to improve it and avoid duplicates. It is a wiki article and everyone can edit it. Thanks.

Closed, because it is duplicate.