Modern Ubuntu versions are using a swap file instead of a swap partition by default.
Before the 5.0 Linux kernel it was not possible to place a swap file on a btrfs
partition, btrfs
file system could be damaged.
Now kernels support swap files on btrfs partitions. Can I use a swap file on Ubuntu installed on btrfs
and what are possible problems?
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.Mount
/dev/sda1
to/mnt
.If you run
ls /mnt
, you'll see@
,@home
and other subvolumes that may be there.Create a new
@swap
subvolume.Unmount
/dev/sda1
from/mnt
Create
/swap
directory where we plan to mount the@swap
subvolume.Mount the
@swap
subvolume to/swap
.Create the swap file.
Set 600 permissions to the file.
Disable COW for this file.
Set size of the swap file to 4G as an example.
Format the swapfile
Turn the swap file on.
Now the new swap should be working.
You also need to update
/etc/fstab
to mount all this on boot. Add there two lines:The
UUID
is the one of your/dev/sda1
.Swap file can't be located on a btrfs raid of any sort.
Comments and suggestions are welcome.
Note that for modern systems/laptops with NVME SSDs, you have
/dev/nvme0n1p2
instead of/dev/sda1
and you should ignore /dev/nvme0n1p1 because that is your efi boot disk that your OS created when you installed it.In addition it should be recommended to add two mount options 'defaults' and 'noatime'. Defaults will automatically load the mount options for the drive (SSD, HDD). Noatime will prevent files being written if only opened:
The popular answer is correct except that you should not use fallocate(1) to allocate space to the swapfile. It can create file-system 'holes' which are incompatible with swapfile usage (swap needs 100% contiguous space since a filesystem is not used within the swap space). You should use 'dd if=/dev/zero ...' instead. See the answer on this thread: fallocate vs dd for swapfile? The mkswap(8) and swapon(8) manpages both explicitly discourage the use of fallocate(1) to instantiate a swapfile on the filesystem.
If your partition is encrypted (LUKS), the mount point is on
/dev/mapper
for example:To get the
uuids
run theblkid
command:And then replace the
mapper
location with the specificuuid