Linux – Swap on tmpfs (Obviously a bad idea, but is it possible?)

linuxswaptmpfs

This question originated with a joke between co-workers about increasing performance by moving swap files to a tmpfs. Clearly even if this is possible, it's not a good idea. All I want to know is, can it be done?

I'm currently on Ubuntu 14.04, but I'd imagine the process is similar for most Linux/Unix machines. Here's what I'm doing:

> mkdir /mnt/tmp
> mount -t tmpfs -o size=10m tmpfs /mnt/tmp
> dd if=/dev/zero of=/mnt/tmp/swapfile bs=1024 count=10240
> chmod 600 /mnt/tmp/swapfile
> mkswap /mnt/tmp/swapfile
# So far, so good!

> swapon /mnt/tmp/swapfile
swapon: /mnt/tmp/swapfile: swapon failed: Invalid argument

So, on either linux or unix (I'm interested in any solution) can you somehow set up swap on a file/partition residing in ram? Is there a way around the Invalid argument error I'm getting above?

Again, just want to emphasize that I'm not expecting this to be a solution to a real-world problem. Just a fun experiment, I guess.

Best Answer

So, on either linux or unix (I'm interested in any solution) can you somehow set up swap on a file/partition residing in ram?

Sure. On FreeBSD:

# swapinfo -h
Device          1024-blocks     Used    Avail Capacity
/dev/mirror/swap.eli     4194300       0B     4.0G     0%

That shows that currently, I have a 4G encrypted swap partition with mirrored redundancy. I'll add another 4G of non-redundant, non-encrypted swap:

First create a 4G RAM-backed "memory disk" (md) device:

# mdconfig -a -t malloc -s 4g; mdconfig -lv
md0
md0     malloc   4096M  -

Then tell swapon to add that to the pool of available swap devices, and swapinfo confirms that I now have 8G of swap:

# swapon /dev/md0; swapinfo -h
Device          1024-blocks     Used    Avail Capacity
/dev/mirror/swap.eli     4194300       0B     4.0G     0%
/dev/md0            4194304       0B     4.0G     0%
Total               8388604       0B     8.0G     0%
Related Question