swap to a sparse file

Polytropon freebsd at edvax.de
Thu Oct 11 03:52:40 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:

/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"

Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...

More information about the freebsd-questions mailing list