I have this crazy idea, and want to know the pitfalls of such an approach (or whether it can even work with no deadlocks.. etc).
The goal is to create an automatically expanding and contracting single swap space that provides enough capacity to match the entire hard drive. Performance isn't a big goal here. The idea is to present a buffer zone for rare occasions of over-committing memory usage.
Assuming we have 1 hard disk of 10 GB. We can create a sparse swap file via (this was derived from BTRFS swapfile workarounds):
swapfile=$(losetup -f)
truncate -s 10G /swap
losetup $swapfile /swap
mkswap $swapfile
swapon $swapfile
We needed to do the above because swapon
doesn't allow sparse files.
So we have 2 problems here:
- Being sparse increases fragmentation, although this reduces performance, it shouldn't prevent it from working right?
- The sparse file doesn't contract in size, so we need to do hole punching (https://stackoverflow.com/a/2026015/582917 & https://unix.stackexchange.com/a/52029/56970), so perhaps we can just periodically run
fallocate -d /swap
orfallocate -d $swapfile
(I haven't tried this yet), in order to punch holes into the swap file to make it contract after being used.
We can set vm.swappiness = 0
or vm.swappiness = 1
to make it so that processes (which are more important to me) are unlikely to use this swap.
Finally would this work with hibernation according to the instructions in https://wiki.archlinux.org/index.php/Power_management/Suspend_and_hibernate#Hibernation_into_swap_file ?