Why using swap file over a SMB/NFS mounted filesystem is not possible in Linux?

I'd like to use another machine's unused RAM as swapspace for my primary Linux installation. I was just curious about performance of network ramdisks compared to local (slow) mechanical hard disks.

The swapfile is on a tmpfs mountpoint and is shared through samba. However, every time I try to issue:

swapon /mnt/ramswap/swapfile

I get:

swapon: /mnt/ramswap/swapfile: swapon failed: Invalid argument

and in dmesg I read:

[ 9569.806483] swapon: swapfile has holes

I've tried to allocate the swapfile with dd if=/dev/zero of=swapfile bs=1024 (but also =4096 and =1048576) and with truncate -s 2G (both followed by mkswap swapfile) but the result is always the same.

In this post (dated back to 2002) someone says that using a swapfile over NFS/SMB is not possible in Linux. Is this statement still valid? And if yes, what is the reason of this choice and is there any workaround to have this working?


Solution 1:

I know this is a bit of an old thread now but I've just run across this problem and found this it is possible to use an NFS swap partition by making use of the kernel loopback device:

Make an empty file (fill with zeros from /dev/zero):

root@machine:/# dd if=/dev/zero of=/swap bs=1024 count=1048576

Make a loop device:

root@machine:/# losetup /dev/loop0 /swap

Make it suitable for swapping:

root@machine:/# mkswap /dev/loop0
Setting up swapspace version 1, size = 1048572 KiB
no label, UUID=931d6e04-78ec-41fd-ab2c-22522ac2711d

Now use it:

root@machine:/# swapon /dev/loop0

Make the change permanent

Write a script to make this swap permanent. /etc/init.d/swap may be like this:

#!/bin/sh

set -e

case "$1" in
start)
losetup /dev/loop0 /swap
swapon /dev/loop0
;;
stop)
swapoff /dev/loop0
losetup -d /dev/loop0
;;
restart)
swapoff /dev/loop0
swapon /dev/loop0
;;
*)
echo "Usage: swap { start | stop | restart }" >&2
exit 1
;;
esac

exit 0

Make the file executable:

root@machine:/# chmod +x /etc/init.d/swap

Enable it:

root@machine:/# update-rc.d swap defaults

Source: http://www.emanuelis.eu/2010/06/21/how-to-swap-to-nfs-mount/

Solution 2:

To quote the man page...

This is due to the swap file implementation in the kernel expecting to be able to write to the file directly, without the assistance of the file system.

It's not possible to directly write to an NFS mount without going through the filesystem, so you get this slightly confusing error message.

As @MattH noted, you might be able to use iSCSI to do this, but the real question is whether it's worth it at all. RAM is quite cheap, after all.