- All about linux swap space
- Contents
- Swap space
- Swap partition
- Activation by systemd
- Disabling swap
- Swap file
- Manually
- Swap file creation
- Remove swap file
- Automated
- zram-generator
- systemd-swap
- Swap encryption
- Performance
- Swappiness
- VFS cache pressure
- Priority
- Using zswap or zram
- Striping
- Linux Find Out What Process Are Using Swap Space
- Finding out process ID and swap usage
- Listing all process swap space usage
- Say hello to smem
- Installation
- How do I use smem command?
- Options
- A note about top command
- RootUsers
- Guides, tutorials, reviews and news for System Administrators.
- Managing Swap Space In Linux
- What Is Using Swap Space?
- Modify Swapping Likelihood
- Add More Swap Space
- Summary
All about linux swap space
This page provides an introduction to swap space and paging on GNU/Linux. It covers creation and activation of swap partitions and swap files.
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.
Contents
Swap space
Swap space can take the form of a disk partition or a file. Users may create a swap space during installation or at any later time as desired. Swap space can be used for two purposes, to extend the virtual memory beyond the installed physical memory (RAM), and also for suspend-to-disk support.
If it is beneficial to extend the virtual memory with swap depends on the amount of installed physical memory. If the amount of physical memory is less than the amount of memory required to run all the desired programs, then it may be beneficial to enable swap. This avoids out of memory conditions, where the Linux kernel OOM killer mechanism will automatically attempt to free up memory by killing processes. To increase the amount of virtual memory to the required amount, add the necessary difference (or more) as swap space.
The biggest drawback of enabling swap is its lower performance, see section #Performance. Hence, enabling swap is a matter of personal preference: some prefer programs to be killed over enabling swap and others prefer enabling swap and slower system when the physical memory is exhausted.
To check swap status, use:
Or to show physical memory as well as swap usage:
Swap partition
The factual accuracy of this article or section is disputed.
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(8) command is used. For example:
To enable the device for paging:
To enable this swap partition on boot, add an entry to /etc/fstab :
where the device_UUID is the UUID of the swap space.
See fstab for the file syntax.
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 GUID, see systemd#GPT partition automounting for more information.
Disabling swap
To deactivate specific swap space:
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).
Manually
Swap file creation
Use dd to create a swap file the size of your choosing. For example, creating a 512 MiB swap file:
Set the right permissions (a world-readable swap file is a huge local vulnerability):
After creating the correctly sized file, format it to swap:
Activate the swap file:
Finally, edit the fstab configuration to add an entry for the swap file:
For additional information, see fstab#Usage.
Remove swap file
To remove a swap file, it must be turned off first and then can be removed:
Finally remove the relevant entry from /etc/fstab .
Automated
zram-generator
The aim of this tool is the creation of zram devices. It is written in Rust and resides in systemd’s GitHub. It can be installed with the zram-generator package. Configuration is straightforward and explained in the README.
systemd-swap
systemd-swap is a script for creating hybrid swap space from zram swaps, swap files and swap partitions. It is not affiliated with the systemd project.
Install the systemd-swap package. Uncomment and set swapfc_enabled=1 in the Swap File Chunked section of /etc/systemd/swap.conf . Start/enable the systemd-swap service.
Visit the authors GitHub page for more information and setting up the recommended configuration.
Swap encryption
Performance
Swap operations are usually significantly slower than directly accessing data in RAM. Disabling swap entirely to improve performance can sometimes lead to a degradation, since it decreases the memory available for VFS caches, causing more frequent and costly disk I/O.
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 200 (max 100 if Linux /sys/fs/cgroup/memory/memory.swappiness or /proc/sys/vm/swappiness can be read in order to obtain the raw integer value.
To temporarily set the swappiness value:
To set the swappiness value permanently, create a sysctl.d(5) configuration file. For example:
To test and more on why this may work, take a look at this article.
VFS cache pressure
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[1]. 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 fastest device. Priorities can be assigned in fstab via the pri parameter:
Or via the —priority parameter of swapon:
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.
Using zswap or zram
Zswap is a Linux kernel feature providing a compressed write-back cache for swapped pages. This increases the performance and decreases the IO-Operations. ZRAM creates a virtual compressed Swap-file in memory as alternative to a swapfile on disk.
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.
Источник
Linux Find Out What Process Are Using Swap Space
T he top and free command display the total amount of free and used physical and swap memory in the server. How do I determine which process is using swap space under Linux operating systems? How do I find out swap space usage of a particular process such as memcached?
Tutorial details | |
---|---|
Difficulty level | Intermediate |
Root privileges | Yes |
Requirements | Linux with smem and /proc |
Est. reading time | 6 minutes |
You can use the any one of the following techniques but keep in mind that because of shared pages, there is no reliable way to get this information [ 1]
- /proc/meminfo – This file reports statistics about memory usage on the system. It is used by free to report the amount of free and used memory (both physical and swap) on the system as well as the shared memory and buffers used by the kernel. You can also use free, vmstat and other tools to find out the same information.
- /proc/$
/smaps , /proc/$ /status , and /proc/$ /stat : Use these files to find information about memory, pages and swap used by each process using its PID. - smem – This command (python script) reports memory usage with shared memory divided proportionally.
Finding out process ID and swap usage
- No ads and tracking
- In-depth guides for developers and sysadmins at Opensourceflare✨
- Join my Patreon to support independent content creators and start reading latest guides:
- How to set up Redis sentinel cluster on Ubuntu or Debian Linux
- How To Set Up SSH Keys With YubiKey as two-factor authentication (U2F/FIDO2)
- How to set up Mariadb Galera cluster on Ubuntu or Debian Linux
- A podman tutorial for beginners – part I (run Linux containers without Docker and in daemonless mode)
- How to protect Linux against rogue USB devices using USBGuard
Join Patreon ➔
To see swap space used by memcached (PID # 48440), enter (number #2):
# grep —color VmSwap /proc/48440/status
Sample outputs (number #4):
Or the following awk command (number #3):
# awk ‘/VmSwap/
Sample outputs (number #4):
Fig.01: Finding out memcached process swap usage on Linux
Listing all process swap space usage
Type the following bash for loop command to see swap space usage per process:
Type the following command to sort out output:
Say hello to smem
The smem command reports physical memory usage, taking shared memory pages into account. Unshared memory is reported as the USS (Unique Set Size). Shared memory is divided evenly among the processes sharing that memory. The unshared memory (USS) plus a process’s proportion of shared memory is reported as the PSS (Proportional Set Size). The USS and PSS only include physical memory usage. They do not include memory that has been swapped out to disk. Memory can be reported by process, by user, by mapping, or system-wide. Both text mode and graphical output are available.
Installation
To install smem [ 2] type the following command under Debian / Ubuntu Linux:
$ sudo apt-get install smem
RHEL / CentOS Linux user type the following command:
$ wget https://www.selenic.com/smem/download/smem-1.4.tar.gz
$ tar xvf smem-1.4.tar.gz
# cp /tmp/smem-1.2/smem /usr/local/bin/
# chmod +x /usr/local/bin/smem
How do I use smem command?
To see basic process information, enter:
# smem
Sample outputs:
To see library-oriented view, enter:
# smem -m
To see user-oriented view, enter:
# smem -u
Sample outputs:
To see systemwide memory usage summary pass the -w option:
# smem -w
Sample outputs:
To see system view
# smem -R 8G -K /path/to/vmlinux/on/disk -w
To see totals and percentages, enter:
# smem -t -p
Sample outputs:
Options
Type the following command to see all other supported options:
# smem —help
Sample outputs:
A note about top command
Type the top command as root:
# top
To sort process as per swap page usage (SWAP = VIRT – RES) type capital O (option) followed by p (small p ) and [Enter] key:
Fig.02 top command – sored process by swap usage (click to enlarge)
References:
It is not possible to get the exact size of used swap space of a process. The top command fakes this information by making SWAP = VIRT – RES, but that is not a good metric, because other stuff such as video memory counts on VIRT as well (for example: top says my X process is using 81M of swap, but it also reports my system as a whole is using only 2M of swap. Therefore, I will not add a similar Swap column to htop because I don’t know a reliable way to get this information (actually, I don’t think it’s possible to get an exact number, because of shared pages).
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Источник
RootUsers
Guides, tutorials, reviews and news for System Administrators.
Managing Swap Space In Linux
Swap space is an area of disk that is used to store memory to. Here we’ll take a look at managing swap space in Linux by determining what is actually using the swap space, controlling how frequently swap space is written to, and finally adding additional swap space if required.
What Is Using Swap Space?
There are a few things we can do to check our memory and swap usage, however seeing what is actually using the swap space is another question.
My favourite tool for getting this sort of information is ‘smem’.
First we’ll install smem in our CentOS 7 server, which comes from the EPEL repository.
The smem package is also available for installation in Debian based Linux distributions as well.
Now we can make use of smem, which will show us how much swap space our processes are using.
In this example the whole swap column is 0 as we’re not using any at the moment. Here we use the -t option to display the totals at the bottom, and the -p option to display the swap space usage as a percentage.
We can also use the -u flag to see which users are using memory and swap space on the Linux system.
If we install the python-matplotlib package we can then make pie and graph bars of swap usage for reporting purposes, checkout the —pie and —bar options in the manual page for further information on this.
Now that we have an idea of what is actually using the swap space, there are a few things we can do. We can investigate the specific processes and confirm if they need to be running, and also investigate any particular applications specific configuration settings further as we may be able to modify the memory allocation for example. We could also upgrade the server by adding more memory if required so that swap space does not need to be used.
If these options are not possible, we can also reduce how frequently swap space is used.
Modify Swapping Likelihood
We can set the swappiness, which is a kernel run time parameter that defines how frequently swap will be used.
The swappiness value is a kernel parameter that can be set between 0 and 100. The lower the value, the less likely the kernel is to make use of swap. The higher the value, the more likely the kernel will try to use swap. For example, setting swappiness to 100 will result in the kernel performing aggressive levels of swapping that may cause performance degradation, while setting it to 0 will only swap to avoid running out of memory.
Generally in Linux the default swappiness is set to 60, in my CentOS 7 virtual machine it appears to be 30.
Over on my Debian 8 virtual machine it has the usual 60.
We can set the value of vm.swappiness both for the current runtime or to last persistently over reboot.
To change the current value we can simply echo a new value to /proc/sys/vm/swappiness, as shown below.
This change will not last a reboot, to do that we need to create a file in the /etc/sysctl.d directory which ends in .conf.
At this point we can either reboot to apply the changes, confirming that this will set vm.swappiness permanently, or we can run sysctl with the -p flag to specify the configuration file to load as shown below which will avoid the reboot.
Now our Linux server will only use the minimum amount of swap space possible.
Add More Swap Space
If we are not able to increase memory, control the amount of memory the process may use, or change the level of vm.swappiness then you can next look at increasing the available swap space.
By default in CentOS 7 and Debian 8 the swap space comes from a logical volume, we can add more space in the form of a disk partition, LVM, or even a file. If you have the option to add a new disk partition or logical volume this is the recommended method of adding new swap space.
Here’s an example of how we can create an additional swap partition and mount it automatically at boot. I have added a new 1GB disk to the virtual machine which will be dedicated to swap space, /dev/sdb.
We can also make a file on the file system that acts as swap space, in this example we first create a 1GB file at /root/swapfile, format it as swap space, and then mount it.
The priorities of our newly added swap spaces are both -2, meaning that they should only be used after the swap space at priority -1 has been exhausted.
The ‘swapon -a’ command will attempt to mount all swap space defined in the /etc/fstab file. The contents of this file are also automatically mounted at boot, so the new swap space will be there ready to use even after reboot. The ‘swapon -s’ command will list the summary of available swap space, above we can see the swap file that we have added is now in use.
We can also see a warning that recommends our swap file be set to permissions 600 rather than the default 644 file permissions, which makes sense as we likely only want the root user to have access to a file that will potentially contain sensitive parts of memory.
Summary
Ideally we would want to troubleshoot the root cause of the swap usage, or even just add more memory to a Linux system, or look at putting some sort of limitation on the processes responsible for using large amounts of RAM, however these options are not always possible.
Here we have covered how you can track down the processes and users that are actually using memory and swap space with smem, shown how you can adjust the swappiness levels to control how often the system will use swap space, and finally how we guided you through adding more swap space if required.
Источник