Giving Android a swap file

I don’t know if it’s because I’m doing more with it than I used to, or the rose-tinted specs that come with the novelty value have worn off, or if the later updates have been designed for more powerful hardware, but my G1’s been lagging a bit recently, so I figured I’d have a look at what I can do to make it faster. Turns out it’s quite receptive to the idea of a swap file.
You’ll need root access for this – everything below is to be run as root. Following is how I did it on my cyanogen’d G1, but I don’t see why it wouldn’t work on anything else – it makes use of standard linux tools. This will likely advance the death of your sdcard – it increases the reads and writes by some large margin. I don’t know enough about sdcards to know how much quicker it will die, but modern ones will likely deal with it better than older ones.

Anyway, in your terminal emulator:

dd if=/dev/zero of=/sdcard/swap bs=1M count=100

You can call it whatever you like. The ‘count’ value (100 above) is how many MB of swap space you want. The above will create 100MB of swap.
This will take a few seconds (of the order of 50), so if it’s ‘hung’ it’s probably not crashed.

Then we make it into a swap file and activate it as swap space:

mkswap /sdcard/swap
swapon /sdcard/swap

Finally, we want to change the swappiness of the system. When the system memory is completely full, and more is requested, the kernel needs to work out how to create some space. It, generally, can do one of two things: drop some filesystem cache, or move some application memory to swap.
The swappiness value dictates the priority of either – a value of 0 means it will always try to drop fs cache rather than use swap, and a value of 100 means it will always try to use swap and preserve the fs cache. Only values between 0 and 100 inclusive are allowed, and neither guarantees any action – you can still find yourself swapping out at 0, for example – just the priority afforded each solution.
The default value for the Linux kernel is 60, which is generally not appropriate for something running completely from flash media (where the fs cache isn’t so important). So I’m dropping it to 20, which seems to work for me. If it doesn’t for you, try some other values, it’s an on-the-fly change.

echo 20 > /proc/sys/vm/swappiness

On rebooting the phone, the above settings wont hold. The swap file will still be available (assuming the SD card is still inserted), but on reboot you’ll need to run

swapon /sdcard/swap
echo 20 > /proc/sys/vm/swappiness 

On the plus side, you’ll be rebooting less.


Posted

in

by