How to create swap with btrfs
This article is a translation of the following my article:
Original: Btrfsでのスワップ作成方法
* Translated automatically by Google.
* Please note that some links or referenced content in this article may be in Japanese.
* Comments in the code are basically in Japanese.
by bokumin
How to create swap with btrfs
How it all started
When trying to create a swap file to reserve additional swap space on OpenSUSE Tumbleweed, I encountered the following error.
sudo swapon /swapfile
swapon: /swapfile: swapon failed: Invalid argument
Cause specific
- Attribute confirmation
- Check the file system
- Check kernel log
ls -lf /swapfile
-rw------- 1 root root 16G Oct 19 20:12 /swapfile
The specified file size also had permissions of 600.
sudo lsattr /swapfile
---------------------- /swapfile
No special attributes are set. It looks normal but I don’t know why
df -Th
/dev/sda2 btrfs 112G 30G 81G 27% /
I felt that the part that created the swap with Btfrs might be related.
sudo dmesg | grep -i swap
[ 0.114128] [ T0] Spectre V1 : Mitigation: usercopy/swapgs barriers and __user pointer sanitization
[ 1.388004] [ T1] systemd[1]: Reached target Swaps.
[ 8.764858] [ T798] Adding 2097148k swap on /dev/sdb1. Priority:-2 extents:1 across:2097148k
[107772.672920] [ T143757] BTRFS warning (device sda2): swapfile must not be copy-on-write
I found the cause from the last line “swapfile must not be copy-on-write” (swap file must not be CoW).
Btrfs uses CoW by default, which seems to have prevented swap from functioning properly. I realized that I need todisable CoW to create swap with Btrfs.
Solution
#空でファイル作成
sudo truncate -s 0 /swapfile
#ファイルのCoW属性無効
sudo chattr +C /swapfile
#btrfsのファイルの圧縮を無効に指定
sudo btrfs property set /swapfile compression none
#スワップ作成
sudo dd if=/dev/zero of=/swapfile bs=1M count=16384
#権限変更・スワップを有効にする
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
#永続的に有効にする
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab
#認識確認
sudo swapon --show
参考:
https://superuser.com/questions/1067150/how-to-create-swapfile-on-ssd-disk-with-btrfs
https://btrfs.readthedocs.io/en/latest/Swapfile.html
Summary
It was around this time that I decided to properly learn about the functions and limitations of the Btrfs file system.
End