Loop Mounting Swap Partition

From OptionC

How to loop mount a swap partition file

(See the note at the end as to why this can be useful for Xen)

All commands are run as root (although some need not be).

  1. Create your swap file (example, a 256 MB file):
# dd if=/dev/zero of=myswapfile bs=1k seek=256k count=1
  1. Change the big empty file into a swap file
# mkswap myswapfile
  1. Use the losetup utility to find the first unused loop device
# losetup -f
/dev/loop3
  1. Use the losetup utility to mount the swap file to the loop device
# losetup /dev/loop3 myswapfile
  1. Turn the swap file on
# swapon /dev/loop3

To see how much swap space you have, do one of the two following (or both if you want):

# cat /proc/meminfo | grep -i swap
# free

To unmount and remove the loop mounted swap partition:

# swapoff /dev/loop3
# losetup -d /dev/loop3
# rm myswapfile


Note: [VM-Tools (http://www.cs.utexas.edu/users/aliguori/vm-tools/|)] does not currently (officially) support using loop-mounted devices when booting a DomU. Actually it does, but you have to go the extra step of loop mounting and passing in the major/minor device number. Because I'm creating and recreating virtual machines all the time, I use file-backed (loop-mounted) VBDs rather than physical partitions -- purely a personal preference. Consequently I needed a way to loop mount a swap file to pass in to the booting machine. This, minus the part where we turn the swap file on, is it.