swap to a sparse file

Lorenzo Salvadore phascolarctos at protonmail.ch
Thu Oct 11 07:47:29 UTC 2018

> On Thu, 11 Oct 2018 08:47:05 +0700, Victor Sudakov wrote:
> > I've inherited a swapless FreeBSD 11.2 host with no unused disk space.
> > I would like to add some swap to be on the safe side: in case there is
> > a memory leak etc.
> > On the other hand, I don't like to waste several gigabytes on a
> > precious SSD because perhaps the system will never need this swap
> > space anyway.
> Exactly my thoughts. :-)
> > The FreeBSD Handbook prescribes creating a swap file with "dd if=/dev/zero ..."
> > which would waste the space.
> A regular file as swap space also places additional
> load into the virtual file system, whereas one of the
> key advantages of a swap partition is that no file
> access (through a filesystem) has to take place.
> > Is there any good reason I can't just "truncate -s2G /swap0" and
> > make the swap a sparse file?
> I'm using a "pseudo-file" approach which hasn't shown any
> problems so far. I'm using dd, but no actual disk space
> will be allocated for the target file. That file then is
> used like a regular swap partition via mdconfig's virtual
> node facility, and also deleted.
> Sure, it probably isn't the ideal solution, but it works.
> Maybe you can use this for further inspiration?
> In /etc/rc.local:
> SWAP="/swap0"
> /bin/rm -f $SWAP
> /bin/dd if=/dev/zero of=$SWAP bs=16m seek=500 count=0
> /sbin/mdconfig -a -t vnode -u 0 -f $SWAP || /bin/sh
> /bin/chflags nodump $SWAP
> /bin/rm $SWAP
> /sbin/swapctl -a /dev/md0
> echo -n " swap"
> In /etc/rc.shutdown.local:
> /sbin/swapctl -d /dev/md0 > /dev/null 2>&1
> /sbin/mdconfig -d -u 0
> echo -n " swap"

Another solution if you have a zfs filesystem is to create a new
filesystem for swap that would contain only a swapfile. That way
the dedicated filesystem would use space only when needed and
shrink when unneeded, but you could also set a minimal amount
of space and a maximal amount.

I do not know what is your exact situation with this host you
inherited, but maybe it would not be a bad idea to just reinstall
a brand new FreeBSD on it with the partitioning scheme you want
(of course, you might need to backup something).

Lorenzo Salvadore.

More information about the freebsd-questions mailing list