Create swap from File on BTRFS Filesystem

mkswap and swapon mkswap and swapon

I didn’t create any swap during initial Ubuntu 19.04 install on Dell XPS laptop, so had to improvise when compiling a massive opensource project recently. This post shows you how to temporarily add swap memory using a regular file.

Create swap Using Regular File

The usual approach is fairly simple:

  • you create a large enough file (the desired size of your swap memory) – 1GB or 4GB or something like that
  • you initialise it as swap
  • you activated it as swap

Swap Files Support in BTRFS

Since I’ve used BTRFS filesystem for root in my Ubuntu setup, I discovered that there are additional steps needed: BTRFS filesystem creates and writes files in a way that’s been mostly incompatible with swap usage.

But as luck would have it, BTRFS supports swap files with Linux Kernel 5.0.x, so you just need to create file with specific attribute.

Swap Space Using File Procedure

Step 1: Create new empty file

We need to create a file with NOCOW (NO Copy-On-Write) property (no harm anywhere but is a requirement for BTRFS):

[email protected]:/ # touch /swapfile
[email protected]:/ # chattr +C /swapfile

Step 2: Allocate required amount of space to the file

[email protected]:/ # fallocate -l 8G /swapfile

This file is 8GB now:

[email protected]:/ # ls -ald /swapfile 
-rw------- 1 root root 8589934592 Jul 17 19:55 /swapfile

Step 3: Update permissions

[email protected]:/ # chmod 0600 /swapfile 

Step 4: Initialise /swapfile as swap storage

[email protected]:/ # mkswap /swapfile 
Setting up swapspace version 1, size = 8 GiB (8589930496 bytes)
no label, UUID=16d35c04-78de-4dd3-aeb0-e2228bb7ce36

Step 5: Activate swap space from /swapfile

[email protected]:/ # swapon /swapfile

Step 6: Confirm newly activated swap space

[email protected]:/ # free -h
total used free shared buff/cache available
Mem: 15Gi 6.1Gi 1.7Gi 3.1Gi 7.5Gi 5.8Gi
Swap: 8.0Gi 0B 8.0Gi

That’s it for today!

See Also




Keep Learning with Me

Follow me on Facebook and Twitter or jump into Telegram chat!:
I'm using Brave browser
Give it a try, it's awesome: Brave Browser
IT Consultancy
I'm a principal consultant with Tech Stack Solutions. I help with cloud architectrure, AWS deployments and automated management of Unix/Linux infrastructure. Get in touch!

Recent Tweets