How to create swapfile on ssd disk with btrfs

Status in 2019

The development of Btrfs and Linux kernel rendered my original answer obsolete. Please see this other answer.


Original answer from 2016

From btrfs FAQ:

Does btrfs support swap files? Currently no. Just making a file NOCOW does not help, swap file support relies on one function that btrfs intentionally does not implement due to potential corruptions. (...) A workaround, albeit with poor performance, is to mount a swap file via a loop device.

So there is no good way to create swapfile on btrfs partition yet.


As mentioned above, since Linux 5.0 it is now possible to create swap files on BTRFS. But they should be non-compressed and NoCOW. Here is how do you actually create such a file:

  1. Create an empty file: touch /swap
  2. Use chattr to set NoCOW attribute to it: chattr +C /swap
  3. Verify that C attribute appeared: lsattr /swap
  4. Fill it: dd if=/dev/zero of=/swap bs=1M count=1024 # for 1 gigabyte
  5. mkswap /swap && chmod 600 /swap && swapon /swap

Alternatively, you can create a directory, set chattr +C to that directory and then create a swapfile under it.

Note that you cannot do chattr +C to already existing non-empty file. It is documented to be undefined behaviour (in fact it just doesn't change attributes). So you should either create an empty file and then chattr, or create a directory with chattr and then create a file in it (in such case all files created after chattring the directory will have the nocow attribute).

Caveat: as mentioned, this requires kernel version 5.0 or higher. Raspberry Pi for example uses 4.19.* kernels so you won't be able to use this technique on it.


Swap file support has been added to kernel version 5.0 as can be seen at commit https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=ed46ff3d423780fa5173b38a844bf0fdb210a2a7 To activate swap file on btrfs, file must be fully allocated as NOCOW with no compression on one device.

Tags:

Linux

Swap