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):
root@xps:/ # touch /swapfile root@xps:/ # chattr +C /swapfile
Step 2: Allocate required amount of space to the file
root@xps:/ # fallocate -l 8G /swapfile
This file is 8GB now:
root@xps:/ # ls -ald /swapfile -rw------- 1 root root 8589934592 Jul 17 19:55 /swapfile
Step 3: Update permissions
root@xps:/ # chmod 0600 /swapfile
Step 4: Initialise /swapfile as swap storage
root@xps:/ # 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
root@xps:/ # swapon /swapfile
Step 6: Confirm newly activated swap space
root@xps:/ # 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!