How to create swapfile on ssd disk with btrfs
I have SSD with btrfs, I tried creating a swapfile like:
dd if=/dev/zero of=swapfile01 bs=1M count=10240
mkswap swapfile01
chmod 600 swapfile01
swapon swapfile01
In dmesg I see
[238434.731654] swapon: swapfile has holes
I understand that there are probably some holes caused by disk fragmentation, but this is SSD disk so it probably shouldn't matter? Is there a way to ignore the holes? Or how can I fix this?
Off topic - why I want this (to avoid irrelevant questions in comments): I have encrypted disk which is pain in the **** to resize, so I just decided to create a swapfile instead of resizing the swap partition (I added 14GB of ram, from 4gb to 16gb and can't hibernate now).
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:
- Create an empty file:
touch /swap
- Use
chattr
to setNoCOW
attribute to it:chattr +C /swap
- Verify that
C
attribute appeared:lsattr /swap
- Fill it:
dd if=/dev/zero of=/swap bs=1M count=1024
# for 1 gigabyte 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 chattr
ing 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.