swapon failed: Input/output error

Often when I'm at a client's site and need a good, flexible linux toolkit, I use Linux Mint (11 currently) on a usb stick with a 4GB persistent file.

Mostly, the PC's I work on at Client sites have > 512MB. Occasionally I do encounter a PC with less memory and even though I use LXDE (lightweight desktop environment) I run out of memory pretty rapidly. (Web Browsers especially...)

A quick run of "free" shows 0 swap and confirms why applications are silently vanishing:

total used free shared buffers cached
Mem: 442204 409116 33088 0 20912 111456
-/+ buffers/cache: 276748 165456
Swap: 0 0 0

So lets create a quick 512MB swapfile. 512*1024 is 524288 so the dd command is
sudo dd if=/dev/zero of=/swapfile bs=1024 count=524288

sudo mkswap /swapfile

mkswap: /swapfile: warning: don't erase bootbits sectors
on whole disk. Use -f to force.
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=b997f6aa-20af-493f-8067-fffbeb0875c9

(You may want to note the UUID if we want to mount this everytime... we'll deal with that further down...)

sudo chown 0600 /swapfile

and a final ls -l / to confirm swapfile is owned by root.

But we hit a snag:

swapon /swapfile
swapon: swapfile: swapon failed: Input/output error

Hmmm...

swapon -v /swapfile
swapon on swapfile
swapon: /swapfile: found swap signature: version 1, page-size 4, same byte order
swapon: /swapfile: pagesize=4096, swapsize=536870912, devsize=536870912
swapon: swapfile: swapon failed: Input/output error

So we find the swap file, recognise it as a swapfile, but something is wrong.

Running mount shows something of interest:
aufs on / type aufs (rw)
...
/dev/loop2 on /cow

Cow? Right - lets ls -l /cow

Ahha... susiciously similar to ls -l / but just different enough. And there's out swapfile - at /cow/swapfile

So let's try - just out of sheer bloodymindedness - sudo swapon -v /cow/swapfile

swapon on /cow/swapfile
swapon: /cow/swapfile: found swap signature: version 1, page-size 4, same byte order
swapon: /cow/swapfile: pagesize=4096, swapsize=536870912, devsize=536870912

And free now shows something like

total used free shared buffers cached
Mem: 442204 433384 8820 0 21324 137080
-/+ buffers/cache: 274980 167224
Swap: 524284 117368 406916

We have something approaching stability! If we want to we can add an fstab entry using the UUID we noted above. Personally I'm not going to bother since it's pretty unusual I need a swapfile, and if I do we have swapon /cow/swapfile in our armoury.