Why does Linux use a swap partition rather than a file?

A swap file is more flexible but also more fallible than a swap partition. A filesystem error could damage the swap file. A swap file can be a pain for the administrator, since the file can't be moved or deleted. A swap file can't be used for hibernation. A swap file was slightly slower in the past, though the difference is negligible nowadays.

The advantage of a swap file is not having to decide the size in advance. However, under Linux, you still can't resize a swap file online: you have to unregister it, resize, then reregister (or create a different file and remove the old one). So there isn't that much benefit to a swap file under Linux, compared to a swap partition. It's mainly useful when you temporarily need more virtual memory, rather than as a permanent fixture.


A swap partition can be preferred because it avoids a dependency on the file system when all you need is an addressable memory pool.

But nothing prevents you from using a swap file instead of a swap partition, or in addition to a swap partition.

  • Create the file:

    dd if=/dev/zero of=/extraswap bs=1M count=512
    
  • Initialize file contents's:

    mkswap /extraswap
    
  • Use it:

    swapon /extraswap
    
  • See if it worked:

    free -m
    

In order to start using the swapfile always at bootup, edit /etc/fstab and add

/extraswap           swap          swap    defaults    0 0

[1] http://www.redhat.com/docs/manuals/linux/RHL-8.0-Manual/custom-guide/s1-swap-adding.html


Perhaps the main reason is that the main kernel suspend-to-disk does not work with swap files. For example the Debian wiki instructions are to install uswsusp if you need this.

More recently, swap files do not work if the filesystem is btrfs, so it is simplest for distributions to always create swap as a partition.

It is vaguely mentioned that using a file for swap had potentially lower performance than a partition, prior to kernel version 2.6. https://www.kernel.org/doc/gorman/html/understand/understand014.html#text15

Tags:

Linux

Swap