Sometimes, it’s preferrably to use a swap file instead of a swap partition in FreeBSD. It can be useful if you boot from a ZFS raidz1/2/mirror root, or if you just need to add additional swap space to an existing server.
Whatever your reasons for wanting to do it, here’s how to do it using FreeBSD 8.x and 9.x
I will create a 4GB swap file, but you can create any size you want by adjusting the figure in the dd command.
First, we need to create a swapfile of the desired size:
dd if=/dev/zero of=/swapfile.dat bs=1m count=4096
This will create /swapfile.dat with 4096 x 1MB blocks (4GB) – next change the permissions on it as follows:
chmod 0600 /swapfile.dat
And finally, add the following line to your /etc/rc.conf file:
Upon next reboot, your server will create a virtual node (using mdconfig) to the swapfile and add it as swapspace.
To activate it without rebooting, you can run:
It should be noted that swapfiles wont be used for kernel crashdumps. These need to be partitions in order to work.