Linux Kernel Memory Management: Swap Space

Chưa phân loại

Part One. The Swap space

In order to work properly a computer depends on having an adequate amount of memory. Simply saying that there can never be enough. The more physical memory is installed the more costly it is. Mostly, the result is a clever compromise between costs and speed to access the memory cells.

To achieve this compromise UNIX/Linux systems combine two types of memory — physical memory (RAM), and swap space. Altogether this is called the virtual memory of a computing system. Physical memory is rather expensive but fast and accessible within nanoseconds. In contrast, swap memory is rather cheap, but slow, and accessible within milliseconds.

There exist a few reasons why swap memory is useful. First, sometimes single processes need more memory than the system physically owns and can provide more to the processes that demands it. As a result, all data that is kept in physical memory cannot be stored there any longer. Now, the swap space comes into play, and a selection of memory pages are transferred to the swap space to free physical memory.

Second, not all the data is needed in memory at the same time. That’s why less used memory pages are parked on swap space to have as much free physical memory available as possible. This method is named the Least Recently Used Page Replacement Algorithm (LRU) [1].

Types of swap

Swap space exists in two variants. Version 1 is a separate disk partition which is the so-called swap partition. There are no files stored onto that partition but memory information (dumps). Simply, version 2 is a file on a disk that resides in the file system on your harddisk. Version 1 is very common on UNIX/Linux systems, BSD and OS X, whereas version 2 exists on systems that run Microsoft Windows. Version 2 can also be enabled on UNIX/Linux systems (see below).

To see which swap space is active on your UNIX/Linux system run the following command in a terminal:

$ /sbin/swapon -s
Filename      Type       Size        Used      Priority
/dev/dm-3   partition  16150524   316484  -1

As an alternative you may send a request to the proc file system, and run the command cat /proc/swaps

This Linux system has a swap partition with a size of about 15 GB in which over 300M are in use, currently. The Priority column shows which swap space to use first. The default value is -1. The higher the priority value, the earlier this swap space is taken into account. The option -s is the short version of –summary. This option is deprecated, and it is recommended to use the option –show as follows, instead:

$ /sbin/swapon –show=NAME,TYPE,SIZE,USED,PRIO
/dev/dm-3 partition 15,4G 307,1M   -1

The option –show accepts a list of values that represent the column headers. In order to achieve a specific output order choose the desired column headers and its sequence.

Swap size

As a general rule the size of the swap space it is recommended to be twice as much as the system has physical memory. Keep this in mind for general-purpose setups and desktop machines. For UNIX/Linux servers with much more physical memory you may lower the size of swap space to 50% of RAM. Laptops that can hibernate need to be slightly larger than the physical memory.


For a swap partition, it is recommended to think of swap space right from the beginning of splitting the disk into single partitions, or to leave enough unused disk space to use it later, eventually. Usually, during the configuration of the disks to be used the setup routine asks you about the size of the swap space. As an example, on Debian GNU/Linux this looks as follows:

As mentioned above, as long as you have space for new partitions on your harddisk you can create and include swap partitions with the use of commands like fdisk, and swapon.

Alternatively, swap space can also be enabled later on as a swap file. Linux supports this way so that you can create, prepare, and mount it in a fashion similar to that of a swap partition. The advantage of this way is that you do not need to repartition a disk to add additional swap space.

As an example, we create a file named /swapfile with a size of 512M, and enable this as additional swap space. First, with the help of the dd command we create an empty file. Second, mkswap uses this file to transform it into swap style. You may notice that the contents of the file is treated like a partition, and a corresponding UUID is assigned. Third, we enable this using swapon. Finally, the command swapon –show displays two swap entries — a partition, and the newly created file.

# dd if=/dev/zero of=/swapfile bs=1024 count=524288
524288+0 datasets in
524288+0 datasets out
536870912 bytes (537 MB) copied, 0,887744 s, 605 MB/s

# mkswap /swapfile
Setting up swapspace version 1, size = 524284 KiB
no label, UUID=e47ab7fe-5efc-4175-b287-d0e83bc10f2e

# swapon /swapfile
/dev/dm-3 partition 15,4G 288,9M   -1
/swapfile file       512M      0B   -2

To use this swap file at boot time add, as administrator, the following line to the file /etc/fstab:

/swapfile  none   swap  sw   0   0

Disabling a swap space

Least but not last there is one command to disable the swap file, again. The command is called swapoff. It requires a single parameter that indicates the swap device to be disabled. This command disables the previously activated swap file:

# swapoff /swapfile

Also, swapoff can work with the UUID of a file system. To make swapoff act this way use the option -U followed by the UUID of the according file system. In case it is needed to disable all the swap spaces at once the option -a (long option –all) is quite handy. The full command is swapoff -a.

Tuning the swap ecosystem

Starting with Linux kernel releases 2.6 a new value was introduced. This is stored in the variable /proc/sys/vm/swappinessand controls the relative weight given to swapping out of runtime memory, as opposed to dropping memory pages from the system page cache [2]. The default value is 60 (percent of memory free before activating swap). The lower the value the less swapping is used, and the more memory pages are kept in physical memory.

  • 0: swap is disabled
  • 1: minimum amount of swapping without disabling it entirely
  • 10: recommended value to improve performance when sufficient memory exists in a system
  • 100: aggressive swapping

To set the value temporarily set the value in the /proc file system as follows:

# echo 10 > /proc/sys/vm/swappiness

As an alternative you may use the sysctl command as follows:

# sysctl -w vm.swappiness=10

To set the value permanently add the following line to the file /etc/sysctl.conf:

vm.swappiness = 10

Is swap still up to date?

You may ask why we deal with that topic. Modern computers have enough physical memory — so why do we have to care about that? There are a few reasons why this technology is worth more than a thought.

Keep in mind that you stick with your machine for a while, but may update the software you use on it from time to time. Currently, both the hardware and the software suit to each other. In the future it may change, and you need more memory than you have now. Unless upgrading or buying new hardware a Swap partition could save you a bit of money.

You may have heard about a feature called suspend to disk, or hibernate mode [3]. Your machine is going to sleep. Before doing that it has to store its current state somewhere. Now the swap space comes into play, and acts as a container to keep this data. As soon as the machine wakes up the next time the entire data is read from the Swap space, loaded into memory, and you can continue working where you have stopped before.

The system, if having only one permanent storage device, will have to read and write your files while swapping on the same device. You will see a huge improvement if you have a second device and can separate the swap device from conflicting file accesses.

The swap file must pass data through the file system. This adds a layer of indirection, to make it appear that there is a contiguous logical address space for the kernel to work with. This adds additional memory overhead and cpu cycles. You will get best results using a raw swap partition.


Even today the knowledge regarding Swap is essential. This topic is part of the knowledge that is required to pass the Linux Professional Institute Certificate Level 1 (LPIC 1). Most of the exams contain one or two questions about this topic.

Swap space helps your Linux system (kernel) to quickly organize memory if there is need for it. To be open with you, Swap space is not absolutely necessary in case your system has tons of RAM. In case of emergencies it helps your system to survive. That’s why I would never leave the path of a traditional setup without Swap space.

The combination of Swap and SSD is discussed in a controversial way because the number of disc writes on an SSD is quite limited. Both Swap and temporary files are built to write lots of data. On the other hand, modern SSDs have more than enough additional space (7%) to cope with sector failures. To be on the safe side: if possible have a separate Swap on a conventional hard drive — don’t use ramdisk, nor an SSD, at least for swap [4]. Your Linux system will thank you for this decision.

To avoid putting the swap space on your SSD you could use ZRAM, instead [5,6]. This is Virtual Swap Compressed in RAM, also named zSwap. This technology enables a compressed block device in memory. As soon as there is no more memory left memory pages are transferred to this block device. This results in less swap usage, and helps to extend the life of your harddisk, too.

Links and References

Linux Memory Management Series


The author would like to thank Mandy Neumeyer and Gerold Rupprecht for their support while preparing this article.

ONET IDC thành lập vào năm 2012, là công ty chuyên nghiệp tại Việt Nam trong lĩnh vực cung cấp dịch vụ Hosting, VPS, máy chủ vật lý, dịch vụ Firewall Anti DDoS, SSL… Với 10 năm xây dựng và phát triển, ứng dụng nhiều công nghệ hiện đại, ONET IDC đã giúp hàng ngàn khách hàng tin tưởng lựa chọn, mang lại sự ổn định tuyệt đối cho website của khách hàng để thúc đẩy việc kinh doanh đạt được hiệu quả và thành công.
Bài viết liên quan

Installing Arduino on Debian/Ubuntu

Arduino is a hardware open source project based on microcontrollers we can program to automate tasks or interact with the...

[Apache Tomcat] Làm thế nào để chạy ở cổng 80

Bài viết này sẽ hướng dẫn cho bạn vài cách để có thể thay đổi cổng khi chạy apache tomcat,...

How to Install Sopcast Player 0.8.5 P2P Internet TV on Ubuntu 16.04

Sopcast Player is a simple, free way to broadcast video and audio or watch the video and listen to radio on the Internet....
Bài Viết

Bài Viết Mới Cập Nhật


Mua Proxy v6 US Private chạy PRE, Face, Insta, Gmail

Mua shadowsocks và hướng dẫn sữ dụng trên window

Tại sao Proxy Socks lại được ưa chuộng hơn Proxy HTTP?

Mua thuê proxy v4 nuôi zalo chất lượng cao, kinh nghiệm tránh quét tài khoản zalo