Difference between revisions of "Swap"

From ArchWiki
Jump to: navigation, search
m (added link)
 
(78 intermediate revisions by 35 users not shown)
Line 2: Line 2:
 
[[es:Swap]]
 
[[es:Swap]]
 
[[fr:Swap]]
 
[[fr:Swap]]
 +
[[hu:Swap]]
 
[[it:Swap]]
 
[[it:Swap]]
[[ja:Swap]]
+
[[ja:スワップ]]
 
[[pt:Swap]]
 
[[pt:Swap]]
 
[[zh-CN:Swap]]
 
[[zh-CN:Swap]]
{{Article summary start}}
+
{{Related articles start}}
{{Article summary text|An introduction to swap space and paging on GNU/Linux. Covers creation and activation of swap partitions and swap files.}}
+
{{Related|fstab}}
{{Article summary heading|Related}}
+
{{Related|Suspend and hibernate}}
{{Article summary wiki|Swap on video ram}}
+
{{Related|Zswap}}
{{Article summary wiki|fstab}}
+
{{Related|Swap on video ram}}
{{Article summary end}}
+
{{Related|ZFS#Swap_volume}}
 +
{{Related|Dm-crypt/Swap encryption}}
 +
{{Related articles end}}
 +
This page provides an introduction to swap space and paging on GNU/Linux. It covers creation and activation of swap partitions and swap files.
  
 
From [http://www.linux.com/news/software/applications/8208-all-about-linux-swap-space All about Linux swap space]:
 
From [http://www.linux.com/news/software/applications/8208-all-about-linux-swap-space All about Linux swap space]:
  
:''Linux divides its physical RAM (random access memory) into chucks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.''
+
:Linux divides its physical RAM (random access memory) into chunks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.
 +
 
 +
Support for swap is provided by the Linux kernel and user-space utilities from the {{Pkg|util-linux}} package.
  
 
== Swap space ==
 
== Swap space ==
Line 21: Line 27:
  
 
To check swap status, use:
 
To check swap status, use:
  $ swapon -s
+
  $ swapon --show
  
 
Or:
 
Or:
  $ free -m
+
  $ free -h
  
 
{{Note|There is no performance advantage to either a contiguous swap file or a partition, both are treated the same way.}}
 
{{Note|There is no performance advantage to either a contiguous swap file or a partition, both are treated the same way.}}
  
== Swap partition ==
+
=== Swap partition ===
  
A swap partition can be created with most GNU/Linux partitioning tools (e.g. {{Ic|fdisk}}, {{Ic|cfdisk}}). Swap partitions are designated as type '''82'''.
+
A swap partition can be created with most GNU/Linux [[partitioning tools]]. Swap partitions are typically designated as type {{ic|82}}. Even though it is possible to use any partition type as swap, it is recommended to use type {{ic|82}} in most cases since systemd will automatically detect it and mount it (see below).
 +
 
 +
To set up a partition as Linux swap area, the {{ic|mkswap}} command is used. For example:
  
To set up a Linux swap area, the {{Ic|mkswap}} command is used. For example:
 
 
  # mkswap /dev/sda2
 
  # mkswap /dev/sda2
  
Line 41: Line 48:
  
 
To enable this swap partition on boot, add an entry to [[fstab]]:
 
To enable this swap partition on boot, add an entry to [[fstab]]:
/dev/sda2 none swap defaults 0 0
 
  
{{Note|If using a TRIM supported SSD, discard is a valid mount option for swap. If creating swap manually, using -d or --discard achieves the same.  For more information and other available mount options, see the swapon man page.}}
+
UUID=<UUID> none swap defaults 0 0
  
== Swap file ==
+
where the <UUID> is taken from the command:
  
As an alternative to creating an entire partition, a swap file offers the ability to vary its size on-the-fly, and is more easily removed altogether. This may be especially desirable if disk space is at a premium (e.g. a modestly-sized SSD). 
+
lsblk -no UUID /dev/sda2
  
{{Note|The BTRFS filesystem does not currently support swapfiles. Failure to heed this warning may result in filesystem corruption. Though it should be noted that one may use a swap file on btrfs if mounted through a loop device. This method will result in severely degraded swap performance.}}
+
{{Tip|UUIDs and LABELs should be favoured over the use of the device names given by the kernel as the device order could change in the future. See: [[fstab]].}}
  
=== Swap file creation ===
+
{{Note|
 +
* The fstab-entry is optional if the swap partition is located on a device using GPT. See the next subsection.
 +
* If using an SSD with [[TRIM]] support, consider using {{ic|defaults,discard}} in the swap line in [[fstab]]. If activating swap manually with ''swapon'', using the {{ic|-d}}/{{ic|--discard}} parameter achieves the same. See {{man|8|swapon}} for details.
 +
}}
 +
{{Warning|Enabling discard on RAID setups using mdadm will cause system lockup on boot and during runtime, if using swapon.}}
  
As root use {{Ic|fallocate}} to create a swap file the size of your choosing (M = Megabytes, G = Gigabytes) ({{Ic|dd}} can also be used but will take longer). For example, creating a 512 MB swap file:
+
==== Activation by systemd ====
 +
 
 +
[[systemd]] activates swap partitions based on two different mechanisms. Both are executables in {{ic|/usr/lib/systemd/system-generators}}. The generators are run on start-up and create native systemd units for mounts. The first, {{ic|systemd-fstab-generator}}, reads the fstab to generate units, including a unit for swap. The second, {{ic|systemd-gpt-auto-generator}} inspects the root disk to generate units. It operates on GPT disks only, and can identify swap partitions by their type code {{ic|82}}.
 +
 
 +
{{Out of date|The problem described below seems to be fixed now.|section=gets swap really still actived twice by systemd?}}
 +
 
 +
This can be solved by one of the following options:
 +
 
 +
* Removing the swap entry from {{ic|/etc/fstab}}
 +
* Changing the swap partition's type code from {{ic|82}} to an arbitrary type code
 +
* Setting the attribute of the swap partition to "'''63''': do not automount"
 +
 
 +
==== Disabling swap ====
 +
 
 +
To deactivate specific swap space:
 +
# swapoff /dev/sda2
 +
 
 +
Alternatively use the {{ic|-a}} switch to deactivate all swap space.
 +
 
 +
Since swap is managed by systemd, it will be activated again on the next system startup. To disable the automatic activation of detected swap space permanently, run {{ic|systemctl --type swap}} to find the responsible ''.swap'' unit and [[mask]] it.
 +
 
 +
=== Swap file ===
 +
 
 +
As an alternative to creating an entire partition, a swap file offers the ability to vary its size on-the-fly, and is more easily removed altogether. This may be especially desirable if disk space is at a premium (e.g. a modestly-sized SSD).
 +
 
 +
{{Warning|[[Btrfs]] does not support swap files. Failure to heed this warning may result in file system corruption. While a swap file may be used on Btrfs when mounted through a loop device, this will result in severely degraded swap performance.}}
 +
 
 +
==== Manually ====
 +
 
 +
===== Swap file creation =====
 +
 
 +
As root use {{ic|fallocate}} to create a swap file the size of your choosing (M = Megabytes, G = Gigabytes). For example, creating a 512 MB swap file:
  
 
  # fallocate -l 512M /swapfile
 
  # fallocate -l 512M /swapfile
Or
+
 
# dd if=/dev/zero of=/swapfile bs=1M count=512
+
{{Note|1=''fallocate'' may cause problems with some file systems such as [[F2FS]] or [[XFS]].[https://bugzilla.redhat.com/show_bug.cgi?id=1129205#c3] As an alternative, using ''dd'' is more reliable, but slower:
 +
{{bc|1=# dd if=/dev/zero of=/swapfile bs=1M count=512}}
 +
}}
  
 
Set the right permissions (a world-readable swap file is a huge local vulnerability)
 
Set the right permissions (a world-readable swap file is a huge local vulnerability)
Line 63: Line 106:
 
  # chmod 600 /swapfile
 
  # chmod 600 /swapfile
  
After creating the correctly-sized file, format it to swap:
+
After creating the correctly sized file, format it to swap:
  
 
  # mkswap /swapfile
 
  # mkswap /swapfile
  
Activate the swapfile:
+
Activate the swap file:
  
 
  # swapon /swapfile
 
  # swapon /swapfile
  
Edit {{ic|/etc/fstab}} and add an entry for the swap file:
+
Finally, edit [[fstab]] to add an entry for the swap file:
  
/swapfile none swap defaults 0 0
+
{{hc|/etc/fstab|/swapfile none swap defaults 0 0}}
  
=== Remove swap file ===
+
===== Remove swap file =====
  
 
To remove a swap file, the current swap file must be turned off.
 
To remove a swap file, the current swap file must be turned off.
Line 83: Line 126:
 
  # swapoff -a
 
  # swapoff -a
  
Remove swapfile:
+
Remove swap file:
  
 
  # rm -f /swapfile
 
  # rm -f /swapfile
  
== Swap with USB device ==
+
Finally remove the relevant entry from {{ic|/etc/fstab}}.
  
Thanks to modularity offered by Linux, we can have multiple swap partitions spread over different devices. If you have a very full hard disk, USB device can be used as partition temporally. But this method has some severe disadvantage:
+
==== systemd-swap ====
* USB device is slower than hard disk.
+
* flash memories have limited write cycles. Using it as swap partition will kill it quickly.
+
* when another device is attached to the computer, no swap can be used.
+
  
To add a a USB device to SWAP, first take a USB flash and partition it with a swap partition.You can use graphical tools such as Gparted or console tools like fdisk. Make sure to label the partition as SWAP before writing the partition table.
+
[[Install]] the {{pkg|systemd-swap}} package. Uncomment the lines containing {{ic|swapf}} in the swap file section of {{ic|/etc/systemd/swap.conf}}. [[Start/enable]] the {{ic|systemd-swap}} service.
{{Box RED||Make sure you are writing the partition to the correct disk!}}
+
  
Next open {{ic|/etc/fstab}}.
+
== Swap with USB device ==
  
Now add a new entry, just under the current swap entry, which take the current swap partition over the new USB one
+
Thanks to the modularity offered by Linux, we can have multiple swap partitions spread over different devices. If you have a very full hard disk, a USB device can be used as a swap partition temporarily. However, this method has some severe disadvantages:
 +
* A USB device is slower than a hard disk
 +
* Flash memory has a limited number of write cycles. Using it as a swap partition can kill it quickly
  
UUID=... none swap defaults,pri=10 0 0
+
To add a USB device to swap, first take a USB flash drive and partition it for swap as described in [[#Swap partition]].
  
where UUID is taken from the output of the command
+
Next open {{ic|/etc/fstab}} and add
 
+
ls -l /dev/disk/by-uuid/ | grep /dev/sdc1
+
 
+
Just replace sdc1 with your new USB swap partition. {{ic|sdb1}}
+
 
+
{{Box GREEN||We use UUID because when you attach other devices to the computer it could modify the device order}}
+
 
+
Last, add
+
  
 
  pri=0
 
  pri=0
  
in the ''original'' swap entry for teaching fstab to use HD swap only when USB is full
+
to the mount options of the ''original'' swap entry so that the USB swap partition will take priority over the old swap partition.
  
 
This guide will work for other memory such as SD cards, etc.
 
This guide will work for other memory such as SD cards, etc.
 +
 +
== Swap encryption ==
 +
 +
See [[dm-crypt/Swap encryption]].
  
 
== Performance Tuning ==
 
== Performance Tuning ==
Line 125: Line 162:
 
=== Swappiness ===
 
=== Swappiness ===
  
The ''swappiness'' [[sysctl]] parameter represents the kernel's preference (or avoidance) of swap space. Swappiness can have a value between 0 and 100.  Setting this parameter to a low value will reduce swapping from RAM, and is known to improve responsiveness on many systems.
+
The ''swappiness'' [[sysctl]] parameter represents the kernel's preference (or avoidance) of swap space. Swappiness can have a value between 0 and 100, the default value is 60A low value causes the kernel to avoid swapping, a higher value causes the kernel to try to use swap space. Using a low value on sufficient memory is known to improve responsiveness on many systems.
 +
 
 +
To check the current swappiness value:
 +
 
 +
$ cat /proc/sys/vm/swappiness
 +
 
 +
To temporarily set the swappiness value:
 +
 
 +
# sysctl vm.swappiness=10
 +
 
 +
To set the swappiness value permanently, edit a ''sysctl'' configuration file
  
{{hc|/etc/sysctl.conf|2=
+
{{hc|/etc/sysctl.d/99-sysctl.conf|2=
vm.swappiness=1
+
vm.swappiness=10
vm.vfs_cache_pressure=50
+
 
}}
 
}}
  
To test and more on why this may work, take a look at this [http://rudd-o.com/en/linux-and-free-software/tales-from-responsivenessland-why-linux-feels-slow-and-how-to-fix-that article].
+
To test and more on why this may work, take a look at [http://rudd-o.com/en/linux-and-free-software/tales-from-responsivenessland-why-linux-feels-slow-and-how-to-fix-that this article].
  
[http://askubuntu.com/questions/103915/how-do-i-configure-swappiness This] Q&A post explains a lot about swappiness.
+
Another ''sysctl'' parameter that affects swap performance is {{ic|vm.vfs_cache_pressure}}, which controls the tendency of the kernel to reclaim the memory which is used for caching of VFS caches, versus pagecache and swap. Increasing this value increases the rate at which VFS caches are reclaimed[http://doc.opensuse.org/documentation/leap/tuning/html/book.sle.tuning/cha.tuning.memory.html#cha.tuning.memory.vm.reclaim]. For more information, see the [https://www.kernel.org/doc/Documentation/sysctl/vm.txt Linux kernel documentation].
  
 
=== Priority ===
 
=== Priority ===
  
If you have more than one swap file or swap partition you should consider assigning a priority value (0 to 32767) for each swap area. The system will use swap areas of higher priority before using swap areas of lower priority. For example, if you have a faster disk ({{ic|/dev/sda}}) and a slower disk ({{ic|/dev/sdb}}), assign a higher priority to the swap area located on the faster device. Priorities can be assigned in fstab via the {{Ic|1=pri}} parameter:
+
If you have more than one swap file or swap partition you should consider assigning a priority value (0 to 32767) for each swap area. The system will use swap areas of higher priority before using swap areas of lower priority. For example, if you have a faster disk ({{ic|/dev/sda}}) and a slower disk ({{ic|/dev/sdb}}), assign a higher priority to the swap area located on the faster device. Priorities can be assigned in fstab via the {{ic|1=pri}} parameter:
  
 
  /dev/sda1 none swap defaults,pri=100 0 0
 
  /dev/sda1 none swap defaults,pri=100 0 0
 
  /dev/sdb2 none swap defaults,pri=10  0 0
 
  /dev/sdb2 none swap defaults,pri=10  0 0
  
Or via the {{Ic|−p}} (or {{Ic|−−priority}}) parameter of swapon:
+
Or via the {{ic|-p}} (or {{ic|--priority}}) parameter of swapon:
  
 
  # swapon -p 100 /dev/sda1
 
  # swapon -p 100 /dev/sda1
  
 
If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.
 
If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.
 +
 +
== Striping ==
 +
 +
There is no necessity to use [[RAID]] for swap performance reasons. The kernel itself can stripe swapping on several devices, if you just give them the same priority in the {{ic|/etc/fstab}} file. Refer to [http://unthought.net/Software-RAID.HOWTO/Software-RAID.HOWTO-2.html#ss2.3 The Software-RAID HOWTO] for details.

Latest revision as of 15:36, 29 November 2016

This page provides an introduction to swap space and paging on GNU/Linux. It covers creation and activation of swap partitions and swap files.

From All about Linux swap space:

Linux divides its physical RAM (random access memory) into chunks of memory called pages. Swapping is the process whereby a page of memory is copied to the preconfigured space on the hard disk, called swap space, to free up that page of memory. The combined sizes of the physical memory and the swap space is the amount of virtual memory available.

Support for swap is provided by the Linux kernel and user-space utilities from the util-linux package.

Swap space

Swap space will usually be a disk partition but can also be a file. Users may create a swap space during installation of Arch Linux or at any later time should it become necessary. Swap space is generally recommended for users with less than 1 GB of RAM, but becomes more a matter of personal preference on systems with gratuitous amounts of physical RAM (though it is required for suspend-to-disk support).

To check swap status, use:

$ swapon --show

Or:

$ free -h
Note: There is no performance advantage to either a contiguous swap file or a partition, both are treated the same way.

Swap partition

A swap partition can be created with most GNU/Linux partitioning tools. Swap partitions are typically designated as type 82. Even though it is possible to use any partition type as swap, it is recommended to use type 82 in most cases since systemd will automatically detect it and mount it (see below).

To set up a partition as Linux swap area, the mkswap command is used. For example:

# mkswap /dev/sda2
Warning: All data on the specified partition will be lost.

To enable the device for paging:

# swapon /dev/sda2

To enable this swap partition on boot, add an entry to fstab:

UUID=<UUID> none swap defaults 0 0

where the <UUID> is taken from the command:

lsblk -no UUID /dev/sda2
Tip: UUIDs and LABELs should be favoured over the use of the device names given by the kernel as the device order could change in the future. See: fstab.
Note:
  • The fstab-entry is optional if the swap partition is located on a device using GPT. See the next subsection.
  • If using an SSD with TRIM support, consider using defaults,discard in the swap line in fstab. If activating swap manually with swapon, using the -d/--discard parameter achieves the same. See swapon(8) for details.
Warning: Enabling discard on RAID setups using mdadm will cause system lockup on boot and during runtime, if using swapon.

Activation by systemd

systemd activates swap partitions based on two different mechanisms. Both are executables in /usr/lib/systemd/system-generators. The generators are run on start-up and create native systemd units for mounts. The first, systemd-fstab-generator, reads the fstab to generate units, including a unit for swap. The second, systemd-gpt-auto-generator inspects the root disk to generate units. It operates on GPT disks only, and can identify swap partitions by their type code 82.

Tango-view-refresh-red.pngThis article or section is out of date.Tango-view-refresh-red.png

Reason: The problem described below seems to be fixed now. (Discuss in Talk:Swap#gets swap really still actived twice by systemd?)

This can be solved by one of the following options:

  • Removing the swap entry from /etc/fstab
  • Changing the swap partition's type code from 82 to an arbitrary type code
  • Setting the attribute of the swap partition to "63: do not automount"

Disabling swap

To deactivate specific swap space:

# swapoff /dev/sda2

Alternatively use the -a switch to deactivate all swap space.

Since swap is managed by systemd, it will be activated again on the next system startup. To disable the automatic activation of detected swap space permanently, run systemctl --type swap to find the responsible .swap unit and mask it.

Swap file

As an alternative to creating an entire partition, a swap file offers the ability to vary its size on-the-fly, and is more easily removed altogether. This may be especially desirable if disk space is at a premium (e.g. a modestly-sized SSD).

Warning: Btrfs does not support swap files. Failure to heed this warning may result in file system corruption. While a swap file may be used on Btrfs when mounted through a loop device, this will result in severely degraded swap performance.

Manually

Swap file creation

As root use fallocate to create a swap file the size of your choosing (M = Megabytes, G = Gigabytes). For example, creating a 512 MB swap file:

# fallocate -l 512M /swapfile
Note: fallocate may cause problems with some file systems such as F2FS or XFS.[1] As an alternative, using dd is more reliable, but slower:
# dd if=/dev/zero of=/swapfile bs=1M count=512

Set the right permissions (a world-readable swap file is a huge local vulnerability)

# chmod 600 /swapfile

After creating the correctly sized file, format it to swap:

# mkswap /swapfile

Activate the swap file:

# swapon /swapfile

Finally, edit fstab to add an entry for the swap file:

/etc/fstab
/swapfile none swap defaults 0 0
Remove swap file

To remove a swap file, the current swap file must be turned off.

As root:

# swapoff -a

Remove swap file:

# rm -f /swapfile

Finally remove the relevant entry from /etc/fstab.

systemd-swap

Install the systemd-swap package. Uncomment the lines containing swapf in the swap file section of /etc/systemd/swap.conf. Start/enable the systemd-swap service.

Swap with USB device

Thanks to the modularity offered by Linux, we can have multiple swap partitions spread over different devices. If you have a very full hard disk, a USB device can be used as a swap partition temporarily. However, this method has some severe disadvantages:

  • A USB device is slower than a hard disk
  • Flash memory has a limited number of write cycles. Using it as a swap partition can kill it quickly

To add a USB device to swap, first take a USB flash drive and partition it for swap as described in #Swap partition.

Next open /etc/fstab and add

pri=0

to the mount options of the original swap entry so that the USB swap partition will take priority over the old swap partition.

This guide will work for other memory such as SD cards, etc.

Swap encryption

See dm-crypt/Swap encryption.

Performance Tuning

Swap values can be adjusted to help performance.

Swappiness

The swappiness sysctl parameter represents the kernel's preference (or avoidance) of swap space. Swappiness can have a value between 0 and 100, the default value is 60. A low value causes the kernel to avoid swapping, a higher value causes the kernel to try to use swap space. Using a low value on sufficient memory is known to improve responsiveness on many systems.

To check the current swappiness value:

$ cat /proc/sys/vm/swappiness

To temporarily set the swappiness value:

# sysctl vm.swappiness=10

To set the swappiness value permanently, edit a sysctl configuration file

/etc/sysctl.d/99-sysctl.conf
vm.swappiness=10

To test and more on why this may work, take a look at this article.

Another sysctl parameter that affects swap performance is vm.vfs_cache_pressure, which controls the tendency of the kernel to reclaim the memory which is used for caching of VFS caches, versus pagecache and swap. Increasing this value increases the rate at which VFS caches are reclaimed[2]. For more information, see the Linux kernel documentation.

Priority

If you have more than one swap file or swap partition you should consider assigning a priority value (0 to 32767) for each swap area. The system will use swap areas of higher priority before using swap areas of lower priority. For example, if you have a faster disk (/dev/sda) and a slower disk (/dev/sdb), assign a higher priority to the swap area located on the faster device. Priorities can be assigned in fstab via the pri parameter:

/dev/sda1 none swap defaults,pri=100 0 0
/dev/sdb2 none swap defaults,pri=10  0 0

Or via the -p (or --priority) parameter of swapon:

# swapon -p 100 /dev/sda1

If two or more areas have the same priority, and it is the highest priority available, pages are allocated on a round-robin basis between them.

Striping

There is no necessity to use RAID for swap performance reasons. The kernel itself can stripe swapping on several devices, if you just give them the same priority in the /etc/fstab file. Refer to The Software-RAID HOWTO for details.