Swapon failed: Invalid argument on a Linux system with Btrfs filesystem

This bug report leads to this discussion

So "Invalid argument" should be read as "Your filesystem do not support swap file"

as posted by malat


In Linux kernel 5.0.0, btrfs natively supports swapfile now. (You must set it as no-COW)

Here's some information from kernel.org: https://btrfs.wiki.kernel.org/index.php/FAQ#Does_btrfs_support_swap_files.3F

From kernel 5.0+ btrfs have native swap files support, but with some limitations. Swap file - must be fully allocated as NOCOW with no compression on one device.

This link shows how to do it: https://wiki.archlinux.org/index.php/swap#Swap_file .

DO NOT TRY IT IN LINUX < 4.21 !!!

Warning: Btrfs on Linux kernel before version 5.0 does not support swap files. Failure to heed this warning may result in file system corruption. While a swap file may be used on Btrfs when mounted through a loop device, this will result in severely degraded swap performance.


I got the cryptic error now after an unclean shutdown. The only solution was to delete the old swapfile and recreate it.

As on btrfs, there are certain restrictions (e.g. copy-on-write has to be disabled), I recommend to follow the steps on the Arch Wiki (I copied the steps to create a 512M swap, but please read their documentation before executing):

# truncate -s 0 /swapfile
# chattr +C /swapfile
# btrfs property set /swapfile compression none
# fallocate -l 512M /swapfile
# chmod 600 /swapfile
# mkswap /swapfile

Now swapon /swapfile should succeed.

If not, ensure that the Kernel is at least 5.0, as is earlier Kernels swapfiles are not supported in btrfs (source: btrfs FAQ):

From kernel 5.0+ btrfs have native swap files support, but with some limitations. Swap file - must be fully allocated as NOCOW with no compression on one device.

For kernels before 5.0, swap files are not supported. 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. The swap implementation used to rely on some assumptions which may not hold in btrfs, like block numbers in the swap file while btrfs has a different block number mapping in case of multiple devices. There is a new API that could be used to port swap to btrfs; for more details have a look at project ideas#Swap file support.


If you want to swap on a file anyway, just use btrfs-swapon