Make swap memory on btrfs

Ho Yipyik
2 min readApr 5, 2022

Intro

Brtfs is a new generation of Linux file system, which allows us to create subvolumes. Creating snapshot using the software named Timeshift is quite a sensible idea.

Swap memory is still essential for whose computers with small memery. Linux kernel didn’t support creating swapfile on btrfs filesystem untill kernel 5.

Thanks to this new feature kernel 5 brought, we could make a swap memory on our pc now. Today let me show you how to do it.

Our aim

Creating a swap memory on btrfs filesystem without disabling snapshot feature of btrfs.

Create subvolume

Mount the partition where your system root located.

List your device

sudo fdisk -l

It will list all of your devices available (I take my result as an example)

/dev/nvme0n1p2 is the device I am looking for.

Mount root

sudo mount /dev/nvme0n1p2 /mnt

Create a subvolume

Create a btrfs subvolume at /mnt/@swap

sudo btrfs sub create /mnt/@swap

Unmount /dev/nvme0n1p2

sudo umount /mnt

Create /swap directory where we plan to mount the @swap subvolume

sudo mkdir /swap

Mount the @swap subvolume to /swap

sudo mount -o subvol=@swap /dev/nvme0n1p2 /swap

Swap file settings

Create and configure the swap file

sudo touch /swap/swapfile
sudo chmod 600 /swap/swapfile
sudo chattr +C /swap/swapfile

Allocate space for swap memory

We use 4G as an example.

sudo dd if=/dev/zero of=/swap/swapfile bs=1M count=4096

Format and turn on

sudo mkswap /swap/swapfile
sudo swapon /swap/swapfile

Add new subvolume to fstab

Show UUID of your root partition

blkid

Add code below to /etc/fstab

My UUID is “41d742a1-f3d9–4dce-b46b-fbfd27c5fa27”

UUID=“41d742a1-f3d9-4dce-b46b-fbfd27c5fa27” /swap btrfs subvol=@swap 0 0
/swap/swapfile none swap sw 0 0

Reference Link

https://askubuntu.com/questions/1206157/can-i-have-a-swapfile-on-btrfs/1299060#1299060?newreg=8424f6e8b77547dc844437dc8d3ffa85

https://www.unixtutorial.org/create-swap-from-file-on-btrfs-filesystem/

--

--