2.5 Swap and Virtual Memory

2.5 Swap and Virtual Memory

If you run out of real memory, Linux has a virtual memory system that automatically moves memory pages (chunks) to and from a hard disk. This is called swapping, because the pages of idle programs are swapped to the disk in exchange for active pages residing on the disk. The disk area used to store memory pages is called swap space.

The free command's output includes the current swap usage in kilobytes as follows:

            total      used        free
...          ...       ...         ...
Swap:      514072    189804      324268

2.5.1 Using a Disk Partition as Swap Space

To use an entire disk partition as swap, follow these steps:

  1. Make certain that the partition is empty.

  2. Run mkswap dev, where dev is the partition's device. This command puts a swap signature on the partition.

  3. Execute swapon dev to register the space with the kernel.

After creating a swap partition, you can put a new swap entry in your /etc/fstab to make the system use the swap space as soon as the machine boots. This entry is from the fstab example in Section 2.4.6:

/dev/hda2  none   swap     sw                       0 0

2.5.2 Using a File as Swap Space

You can also use a regular file as swap space. It's not quite as fast as a swap partition, but if you're in a pinch where you would be forced to repartition the disk to use a swap partition, using a file as swap space works fine.

Use these commands to create an empty file, initialize it as swap, and add it to the swap pool:

dd if=/dev/zero of=swap_file bs=1024k count=num_mb
mkswap swap_file
swapon swap_file

Here, swap_file is the name of the new swap file, and num_mb is the desired size, in megabytes.

To remove a swap partition or file from the kernel's active pool, use the swapoff command.

2.5.3 How Much Swap do You Need?

At one time, the Unix conventional wisdom said that you should always reserve at least twice as much swap as you have real memory. The enormous disk and memory capacities now available cloud the issue. On one hand, disk space is so plentiful that double the memory size may seem inadequate, given the amount of disk space available. On the other hand, you may never even dip into your swap space because you have so much real memory.

Some things never change, though. Reserve two to five times as much disk space as you have real memory for swap. It doesn't make sense to go any lower, because you may actually risk running out of memory. If you go higher and actually intend to use all of this swap space, you will likely suffer serious performance problems because the system will spend all of its time swapping (a condition known as thrashing).