Friday, January 21, 2011

Swap in Ubuntu

Swap can a dedicated partition or just a file on your hard disk, mounted as a swap partition. I don't think, that anyone could have a problem marking partition as a swap, but creating swap as a file could be more interesting task to do.
Here is quotations from official Ubuntu documentation:
For Adding a 512 MB swap
  • Creating a file for 512 MB size you want:
We will create a /mnt/512Mb.swap swap file.
sudo dd if=/dev/zero of=/mnt/512Mb.swap bs=1M count=512

Here count=512, means we want our file to contain 512 blocks of bs=1M, which means block size = 1 mebibyte (1 048 576 bytes). Be careful *not* to do this dd of=/mnt/512Mb.swap bs=1M seek=512 count=0 Though the file grows to 512Mb immediately, it will have holes that makes it unusable.
  • Formatting that file to create a swapping device:
sudo mkswap /mnt/512Mb.swap

  • Adding the swap to the running system:
sudo swapon /mnt/512Mb.swap

The additional swap is now available and can be seen by "cat /proc/meminfo"
  • Making the change permanent:
Edit the /etc/fstab: 
gksudo gedit /etc/fstab

Add this line at the end of the file:
/mnt/512Mb.swap  none  swap  sw  0 0
Save. After the next reboot the swap will be used automatically.
Here we go! 

What is swappiness and how do I change it?

The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. Because disks are much slower than RAM, this can lead to slower response times for system and applications if processes are too aggressively moved out of memory.
  • swappiness can have a value of between 0 and 100
  • swappiness=0 tells the kernel to avoid swapping processes out of physical memory for as long as possible
  • swappiness=100 tells the kernel to aggressively swap processes out of physical memory and move them to swap cache
The default setting in Ubuntu is swappiness=60. Reducing the default value of swappiness will probably improve overall performance for a typical Ubuntu desktop installation. A value of swappiness=10 is recommended, but feel free to experiment. Note: Ubuntu server installations have different performance requirements to desktop systems, and the default value of 60 is likely more suitable.
To check the swappiness value
cat /proc/sys/vm/swappiness

To change the swappiness value A temporary change (lost on reboot) with a swappiness value of 10 can be made with
sudo sysctl vm.swappiness=10

To make a change permanent, edit the configuration file with your favorite editor:
gksudo gedit /etc/sysctl.conf

Search for vm.swappiness and change its value as desired. If vm.swappiness does not exist, add it to the end of the file like so:
Save the file and reboot.

We can check swap with the following commands:
  • sudo fdisk -l
  • cat /proc/swaps