How Swap works (in Linux)

I was recently asked how swap works, and it turns out, I knew nothing about how it really worked … i.e. when, what and why does a linux kernel move memory into swap space. Its probably because I hate swap and I actually disable it on my desktop/laptop/netbook systems I own. I decided to learn more about swap and found this awesome article on Linux weekly (LWN.net) which describes this behaviour exactly http://lwn.net/Articles/83588/.

In Linux Kernel 2.6 (and still applicable in 3.0) the kernel has a swappiness parameter to allow configuration of how often should the kernel swap out to disk. When a process is requesting memory, the kernel uses the following equation to figure out whether it should re-claim cache memory or the already used memory by swapping it to disk.

swap_tendency = mapped_ratio/2 + distress + vm_swappiness;

Where these parameters are:
  • The “distress” value is a measure of how much trouble the kernel is having freeing memory. The first time the kernel decides it needs to start reclaiming pages, distress will be zero; if more attempts are required, that value goes up, approaching a high value of 100.
  • mapped_ratio

is an approximate percentage of how much of the system’s total memory is mapped (i.e. is part of a process’s address space) within a given memory zone.

  • vm_swappiness

is the swappiness parameter, which is set to 60 by default.

If the swap_tendancy is less than 100 then the kernel will release some of its cache to give to the process, whereas if it is >= 100 then the kernel will start rummaging through memory that was not recently accessed and move that to swap. An example from the LWN article states that if the distress is 0 and using the default swappiness of 60 the kernel will start to reclaim pages when 80% or more of memory is allocated out. Ubuntu suggests that desktops change the swappiness to 10 meaning that distress needs to go up to 40 (while the memory is at 100%) for the kernel to start swapping.
I found that knowledge exuberating … I will still avoid swap completely on my personal systems and leaving the defaults on servers as I am doing currently.
There is a few other things I learnt in the last few weeks … stay tuned.