Can I have a swapfile on btrfs?

It is possible to use a swap file on btrfs, but there are some considerations that need taking care of.

btrfs filesystem doesn't let to create snapshots if there is a working swap file on the subvolume. That means that it is highly recommended to place a swap file on a separate subvolume.

Lets assume that the current swap is already off, the / is on /dev/sda1 and Ubuntu is installed with / on @ subvolume and /home is on @home subvolume.

  1. Mount /dev/sda1 to /mnt.

     sudo mount /dev/sda1 /mnt
    

If you run ls /mnt, you'll see @, @home and other subvolumes that may be there.

  1. Create a new @swap subvolume.

     sudo btrfs sub create /mnt/@swap
    
  2. Unmount /dev/sda1 from /mnt

     sudo umount /mnt
    
  3. Create /swap directory where we plan to mount the @swap subvolume.

     sudo mkdir /swap
    
  4. Mount the @swap subvolume to /swap.

     sudo mount -o subvol=@swap /dev/sda1 /swap
    
  5. Create the swap file.

     sudo touch /swap/swapfile
    
  6. Set 600 permissions to the file.

     sudo chmod 600 /swap/swapfile
    
  7. Disable COW for this file.

     sudo chattr +C /swap/swapfile
    
  8. Set size of the swap file to 4G as an example.

     sudo fallocate /swap/swapfile -l4g
    
  9. Format the swapfile

    sudo mkswap /swap/swapfile
    
  10. Turn the swap file on.

    sudo swapon /swap/swapfile
    

Now the new swap should be working.

You also need to update /etc/fstab to mount all this on boot. Add there two lines:

UUID=XXXXXXXXXXXXXXX /swap btrfs subvol=@swap 0 0
/swap/swapfile none swap sw 0 0

The UUID is the one of your /dev/sda1.

Comments and sugestions are welcome.

Tags:

Swap

Btrfs