I'm using native-zfs and was wondering if there is a way to use a ZFS partition for SWAP. I'm running my server off of a thumbdrive and thought that would be a good way to speed it up a little bit.
3Be warned that, as of today, there's an open bug about swap to ZFS causing deadlocks. As this doc explains, writing to a ZFS zvol causes memory allocation, which can get stuck if data's being written to swap due to a low-memory situation.– poolieMay 24, 2020 at 17:21
Here's a more elaborate guide, copied from the zfsonlinux wiki:
Step 1: Create a volume dataset (zvol) for use as a swap device
zfs create -V 4G -b $(getconf PAGESIZE) -o compression=zle \ -o logbias=throughput -o sync=always \ -o primarycache=metadata -o secondarycache=none \ -o com.sun:auto-snapshot=false rpool/swap
You can adjust the size (the
4G part) to your needs.
The compression algorithm is set to
zle because it is the cheapest available algorithm. With
ashift=12 (4 kiB blocks on disk), the common case of a 4 kiB page size means that no compression algorithm can reduce I/O. The exception is all-zero pages, which are dropped by ZFS; but some form of compression has to be enabled to get this behavior. If your pool uses
ashift=9, you could use
Step 2: Format the swap device
mkswap -f /dev/zvol/rpool/swap
Step 3: Update
echo /dev/zvol/rpool/swap none swap defaults 0 0 >> /etc/fstab
Warning: Always use long
/dev/zvol aliases in configuration files. Never use a short
/dev/zdX device name.
Step 4: Enable the swap device
Using ZFS for swap should just work, just like it does under Solaris and FreeBSD.
zfs create pool/swap -V 1G -b 4K mkswap -f /dev/pool/swap swapon /dev/pool/swap
Swapping onto a ZFS zvol is possible, but is not a good idea, because of an open bug that can cause your machine to deadlock when low on space.
Swap space is used when the machine is low on memory and trying to free some up by swapping out less-frequently used data.
When ZFS processes writes to a zvol, it can need to allocate new memory inside the kernel to handle updates to various ZFS data structures. If the machine is low on space already, it might need to swap something out to make this space available, but this causes an infinite loop.
So, instead of swapping to ZFS, just allow a small additional partition for swap space. Or for many situations you can just not have swap, and rely on other data being paged out to the filesystem to free up memory.