Swap memory or Swap space is reserved space on disk which is part of virtual memory system. Swap space is configured as either partition or file on Linux. It can be added or removed any time. Operating System uses the configured swap space on disk when System runs out of RAM. Inactive parts of RAM called pages are moved to swap space to make room for frequently used resources. Inactive data from swap memory is retrieved and placed in RAM on demand. This process of retrieving data storing data from secondary storage for primary memory (RAM) is called paging.
Using swap space has it’s own advantages and disadvantages. Enabling swap memory can make the system stable. So that to free up memory sever won’t start killing applications if it runs out of memory. Some times it can even cause a crash, which can cause loss of data or even down time. On the other hand using swap is expensive and not that much effective in terms of performance, since secondary memory (HDD & SSD) are much slower than RAM.
It is not recommended to use swap on SSDs because of it’s hardware degradation over time. Flash cells in SSDs have a limited lifespan. Every write cycle effectively erasure erodes a memory cell. At some point in time which might stop working. Old SSD used to fail several year ago, but new SSDs became relatively smart(firmware) . Life span of SSDs can be measured using TWM(Total bytes written or TeraBytes written) which is the about of bytes writable before SSD fails. Alternatively try to add more RAM if it is a virtual machine instead of creating swap space on SSD which will lead to better results.
Yet you can create swap on SSD, but it is generally recommended for systems using traditional HDD
Check if swap is enabled
To check if swap is enabled we can use the command swapon .
swapon --show
If you don’t see any output for the command swapon –show . It means swap is not enabled .
NAME TYPE SIZE USED PRIO
/dev/dm-1 partition 976M 473.8M -2
Swap space usage can also be checked using another command free, which displays system’s overall memory usage including swap .
free -m
total used free shared buff/cache available
Mem: 985 608 140 0 237 203
Swap: 0 0 0
Swap is said to be disabled if you see 0 for total and used for swap in the output of free -m command.
If system is using swap space, output of free -m would be something like as follows
total used free shared buff/cache available Mem: 985 608 140 0 237 203
Swap: 975 438 537
There are two types of swap spaces, Swap Partition and Swap File. During installation Linux creates swap partition for swap space. We can create swap space either by using partition or file
Create Swap Space by using Swap Partition
If you have enough space on hard disk and provision to create a new partition. We can create new partition and mark it as swap space by using command “mkswap“.
Use command fdisk to create additional partition to use it for swap space
You can list the existing hard disks (devices) using command lsblk .
Display existing partitions on hard drives/ block devices
lsblk -io KNAME,TYPE,SIZE,MODEL
KNAME TYPE SIZE MODEL
sda disk 28.4G
sda1 part 28.4G
sr0 rom 75.6M CD-ROM
List partitions
fdisk -l
Start fdisk in interactive mode by passing selected disk as an argument
fdisk /dev/<device name>
fdisk /dev/sda
You will be taken to interactive prompt. By using different commands we can edit partitions. To learn more about fdisk read article on fdisk.
use the sub-command “p” to list existing partition table. “n” to create new partition. Use sub-command “m” to list all supported commands by category.
Here are steps to following inside fdisk interactive mode
- Create new partition using sub-command n . You will be prompted to enter first cylinder, leave it to default ( most of the cases), then you will be asked to enter last cylinder value, here you can enter size of the partition. For suppose if it is 1000MB you can give it as +1000M
- Once new partition is created, we can assign a partition type to it using sub-command “t”. Press “t” and hit enter. You will be prompted to enter hex code for partition type(refer partition types using command “l”). In our case it is 82 which is Linux swap partition type. type 82 and hit enter
- Press “w” to update partition table
When you create a new partition using sub command “n”, if there isn’t enough space. You will get the following message. In this case you can create swap using other method, which makes use of file as swap space.
Command (m for help): n
All space for primary partitions is in use.
After you exit from fdisk interactive mode, use partprobe command to force the kernel to re-read partition table to avoid necessity of rebooting system.
partprobe
Use command mkswap to mark created partition as swap space. Replace X with created partition number in the following commands
mkswap /dev/sdaX
Finally, turn on the swap using command swapon
swapon /dev/sdaX
Alternatively you can use swapon -a to enable all listed Linux swap spaces in /etc/fstab.
swapon -a
To make this swap space permanent across reboots we have to edit /etc/fstab. Open /etc/fstab using your favorite editor and add the following line
/dev/sdaX swap swap default 0 0
Replace sdaX with the swap partition you created ( which will be something like sda4)
Create Swap Space by using Swap File
Prerequisites
- root access or non-root user with sudo privileges
- Commands fallocate or dd, chmod, mkswap, swapon
Create file using command fallocate which will be used as swap space
sudo fallocate -l 1G /swapfile
(OR)
The command dd can also be used instead of fallocate to create file for swap space
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1048576
Where,
- if=/dev/zero is the special file which provides as many null characters as are read from it.
- of=/swapfile Read from if (/dev/zero) and writes to /swapfile
- bs=1024 read and write 1024 bytes at a time
- count=1048576 write only 1048576 Blocks
Before we proceed further we have to change permissions of swap file. Swap file should not be readable by any user other than root. Allowing other users to read or write swap file makes system vulnerable to threats.
Change permissions of /swapfile
sudo chmod 600 /swapfile
You can verify permissions using ls command
ls -lh /swapfile
-rw------- 1 root root 1.0G Mar 23 17:38 /swapfile
Make sure root owns the swap file and only root can read and write for security reasons.
Setup swap area on file using command “mkswap“
sudo mkswap /swapfile
Now, here comes the final part. Activates the swap by using created swapfile
sudo swapon /swapfile
Make the swap file permanent across reboots
To make swap file permanent we have to add it to the /etc/fstab file. Open /etc/fstab with you favorite text editor
sudo vim /etc/fstab
Add the following line at the bottom of the file (/etc/fstab)
/swapfile swap swap sw 0 0
Tune the Swappiness Value
Swappiness is the property of Linux kernel which determines how often system will use swap space. Swappiness value can be anything in between 0 and 100. Lower value of swappiness makes kernel less dependent of swap space and avoid using swap when ever possible on the other hand higher value makes kernel to use swap space more aggressively.
The default value of swappiness depends on operating system. On some machines it’s 60, on centOS 7 it is 30.
See current swappiness by reading file /proc/sys/vm/swappiness
cat /proc/sys/vm/swappiness
30
You change the kernel property swappiness by using command sysctl or updating /proc/sys/vm/swappiness file in proc file system.
sudo sysctl vm.swappiness=30
(OR)
echo 30 > /proc/sys/vm/swappiness
To make this change permanent update file /etc/sysctl.conf
echo 'vm.swappiness=30' >> /etc/sysctl.conf
For better performance on production machines it is recommended to set swappiness as low as possible. Possibly 10 or around.
Disable swap on Linux
Assuming swap is enabled by file and located at /swapfile
$ sudo swapoff /swapfile
$ swapon -s
Alternatively you can use following command to turn off all swap spaces
swapoff -a
Remove swap entry (/swapfile swap swap sw 0 0
) from /etc/fstab, so that it won’t be enabled on reboot
If you think you no longer need swap. You can delete swapfile created on disk to free up space on disk
sudo rm /swapfile