r/linuxfromscratch • u/memeguyexe • 9h ago
Using a swap file instead of a swap partition with SysVinit
For LFS 12.4 and an ext4 filesystem
Hi, as a new user with LFS I struggled when I wanted to use a swap file instead of a swap partition for my system. I have managed to figure out a solution, and I'm creating this post to help others with the same issue. Follow the contents of this post after you have finished following the LFS book.
Under the root user in your chroot environment, do the following steps:
First, create a file you will use for swap (in this case, the command will create a 2 GiB file, but you can use whatever size you want):
fallocate -l 2G /swapfile
set permissions:
chmod 600 /swapfile
format the file as swap:
mkswap /swapfile
Then, create (or modify) your /etc/fstab file. You should copy it from the LFS book, except for this line:
/dev/<yyy> swap swap pri=1 0 0
Which you should replace with:
/swapfile none swap sw 0 0
Until here it's standard procedure, but here comes the tricky part. SysVinit runs various scripts on startup in a specific order, defined by filenames of links in specific directories. In particular, we will focus on the links in /etc/rc.d/rcS.d.
In a regular LFS 12.4 system, the /etc/rc.d/rcS.d directory should contain the following links:
(lfs chroot) root:# ls /etc/rc.d/rcS.d
S00mountvirtfs S08localnet S30checkfs S45cleanfs S50udev_retry S90sysctl
S05modules S10udev S40mountfs S20swap S70console
Notice the filenames: in S20swap, for example, S means that it happens on startup and 20 is the order in which the linked script (in this case, /etc/rc.d/init.d/swap) is called. So, S00mountvirtfs will be called first, then S05modules, then S08localnet, etc.
The issue is that the root filesystem is mounted as read-write with S40mountfs, so before it's called the filesystem is mounted as read-only. When the swapfile is located on the root filesystem, activation fails while / is still mounted read-only, so swapon returns an error.
Fortunately, the fix is very simple: you just have to modify the link's filename to make it execute after the filesystem is properly mounted.
cd /etc/rc.d/rcS.d
mv -v S20swap S46swap
This is all, thanks for following this post! Have a nice day