Ask Sawal

Discussion Forum
Notification Icon1
Write Answer Icon
Add Question Icon

How to enable swap space on linux?

4 Answer(s) Available
Answer # 1 #
  • Become a superuser (root) by typing: % su Password: root-password.
  • Create a file in a selected directory to add swap space by typing: dd if=/dev/zero of=/ dir / myswapfile bs=1024 count =number_blocks_needed.
  • Verify that the file was created by typing: ls -l / dir / myswapfile.
Robbie Khosla
Answer # 2 #

Hard drives are magnetic media used for long-term storage of data and programs. Magnetic media is nonvolatile; the data stored on a disk remains even when power is removed from the computer. The CPU (central processing unit) cannot directly access the programs and data on the hard drive; it must be copied into RAM first, and that is where the CPU can access its programming instructions and the data to be operated on by those instructions. During the boot process, a computer copies specific operating system programs, such as the kernel and init or systemd, and data from the hard drive into RAM, where it is accessed directly by the computer’s processor, the CPU.

The second type of memory in modern Linux systems is swap space.

The primary function of swap space is to substitute disk space for RAM memory when real RAM fills up and more space is needed.

For example, assume you have a computer system with 8GB of RAM. If you start up programs that don’t fill that RAM, everything is fine and no swapping is required. But suppose the spreadsheet you are working on grows when you add more rows, and that, plus everything else that's running, now fills all of RAM. Without swap space available, you would have to stop working on the spreadsheet until you could free up some of your limited RAM by closing down some other programs.

The kernel uses a memory management program that detects blocks, aka pages, of memory in which the contents have not been used recently. The memory management program swaps enough of these relatively infrequently used pages of memory out to a special partition on the hard drive specifically designated for “paging,” or swapping. This frees up RAM and makes room for more data to be entered into your spreadsheet. Those pages of memory swapped out to the hard drive are tracked by the kernel’s memory management code and can be paged back into RAM if they are needed.

The total amount of memory in a Linux computer is the RAM plus swap space and is referred to as virtual memory.

Linux provides for two types of swap space. By default, most Linux installations create a swap partition, but it is also possible to use a specially configured file as a swap file. A swap partition is just what its name implies—a standard disk partition that is designated as swap space by the mkswap command.

A swap file can be used if there is no free disk space in which to create a new swap partition or space in a volume group where a logical volume can be created for swap space. This is just a regular file that is created and preallocated to a specified size. Then the mkswap command is run to configure it as swap space. I don’t recommend using a file for swap space unless absolutely necessary.

Thrashing can occur when total virtual memory, both RAM and swap space, become nearly full. The system spends so much time paging blocks of memory between swap space and RAM and back that little time is left for real work. The typical symptoms of this are obvious: The system becomes slow or completely unresponsive, and the hard drive activity light is on almost constantly.

If you can manage to issue a command like free that shows CPU load and memory usage, you will see that the CPU load is very high, perhaps as much as 30 to 40 times the number of CPU cores in the system. Another symptom is that both RAM and swap space are almost completely allocated.

After the fact, looking at SAR (system activity report) data can also show these symptoms. I install SAR on every system I work on and use it for post-repair forensic analysis.

Many years ago, the rule of thumb for the amount of swap space that should be allocated on the hard drive was 2X the amount of RAM installed in the computer (of course, that was when most computers' RAM was measured in KB or MB). So if a computer had 64KB of RAM, a swap partition of 128KB would be an optimum size. This rule took into account the facts that RAM sizes were typically quite small at that time and that allocating more than 2X RAM for swap space did not improve performance. With more than twice RAM for swap, most systems spent more time thrashing than actually performing useful work.

RAM has become an inexpensive commodity and most computers these days have amounts of RAM that extend into tens of gigabytes. Most of my newer computers have at least 8GB of RAM, one has 32GB, and my main workstation has 64GB. My older computers have from 4 to 8 GB of RAM.

When dealing with computers having huge amounts of RAM, the limiting performance factor for swap space is far lower than the 2X multiplier. The Fedora 28 online Installation Guide, which can be found online at Fedora Installation Guide, defines current thinking about swap space allocation. I have included below some discussion and the table of recommendations from that document.

The following table provides the recommended size of a swap partition depending on the amount of RAM in your system and whether you want sufficient memory for your system to hibernate. The recommended swap partition size is established automatically during installation. To allow for hibernation, however, you will need to edit the swap space in the custom partitioning stage.

Table 1: Recommended system swap space in Fedora documentation

At the border between each range listed above (for example, a system with 2 GB, 8 GB, or 64 GB of system RAM), use discretion with regard to chosen swap space and hibernation support. If your system resources allow for it, increasing the swap space may lead to better performance.

Of course, most Linux administrators have their own ideas about the appropriate amount of swap space—as well as pretty much everything else. Table 2, below, contains my recommendations based on my personal experiences in multiple environments. These may not work for you, but as with Table 1, they may help you get started.

Table 2: Recommended system swap space per the author

One consideration in both tables is that as the amount of RAM increases, beyond a certain point adding more swap space simply leads to thrashing well before the swap space even comes close to being filled. If you have too little virtual memory while following these recommendations, you should add more RAM, if possible, rather than more swap space. As with all recommendations that affect system performance, use what works best for your specific environment. This will take time and effort to experiment and make changes based on the conditions in your Linux environment.

Due to changing requirements for swap space on hosts with Linux already installed, it may become necessary to modify the amount of swap space defined for the system. This procedure can be used for any general case where the amount of swap space needs to be increased. It assumes sufficient available disk space is available. This procedure also assumes that the disks are partitioned in “raw” EXT4 and swap partitions and do not use logical volume management (LVM).

The basic steps to take are simple:

A reboot should not be necessary.

For safety's sake, before turning off swap, at the very least you should ensure that no applications are running and that no swap space is in use. The free or top commands can tell you whether swap space is in use. To be even safer, you could revert to run level 1 or single-user mode.

Turn off the swap partition with the command which turns off all swap space:

Now display the existing partitions on the hard drive.

This displays the current partition tables on each drive. Identify the current swap partition by number.

Start fdisk in interactive mode with the command:

For example:

At this point, fdisk is interactive and operates only on the specified disk drive.

Use the fdisk p sub-command to verify that there is enough free space on the disk to create the new swap partition. The space on the hard drive is shown in terms of 512-byte blocks and starting and ending cylinder numbers, so you may have to do some math to determine the available space between and at the end of allocated partitions.

Use the n sub-command to create a new swap partition. fdisk will ask you the starting cylinder. By default, it chooses the lowest-numbered available cylinder. If you wish to change that, type in the number of the starting cylinder.

The fdisk command now allows you to enter the size of the partitions in a number of formats, including the last cylinder number or the size in bytes, KB or MB. Type in 4000M, which will give about 4GB of space on the new partition (for example), and press Enter.

Use the p sub-command to verify that the partition was created as you specified it. Note that the partition will probably not be exactly what you specified unless you used the ending cylinder number. The fdisk command can only allocate disk space in increments on whole cylinders, so your partition may be a little smaller or larger than you specified. If the partition is not what you want, you can delete it and create it again.

Now it is necessary to specify that the new partition is to be a swap partition. The sub-command t allows you to specify the type of partition. So enter t, specify the partition number, and when it asks for the hex code partition type, type 82, which is the Linux swap partition type, and press Enter.

When you are satisfied with the partition you have created, use the w sub-command to write the new partition table to the disk. The fdisk program will exit and return you to the command prompt after it completes writing the revised partition table. You will probably receive the following message as fdisk completes writing the new partition table:

At this point, you use the partprobe command to force the kernel to re-read the partition table so that it is not necessary to perform a reboot.

Now use the command fdisk -l to list the partitions and the new swap partition should be among those listed. Be sure that the new partition type is “Linux swap”.

It will be necessary to modify the /etc/fstab file to point to the new swap partition. The existing line may look like this:

where X is the partition number. Add a new line that looks similar this, depending upon the location of your new swap partition:

Be sure to use the correct partition number. Now you can perform the final step in creating the swap partition. Use the mkswap command to define the partition as a swap partition.

The final step is to turn swap on using the command:

Your new swap partition is now online along with the previously existing swap partition. You can use the free or top commands to verify this.

If your disk setup uses LVM, changing swap space will be fairly easy. Again, this assumes that space is available in the volume group in which the current swap volume is located. By default, the installation procedures for Fedora Linux in an LVM environment create the swap partition as a logical volume. This makes it easy because you can simply increase the size of the swap volume.

Here are the steps required to increase the amount of swap space in an LVM environment:

First, verify that swap exists and is a logical volume using the lvs command (list logical volume).

You can see that the current swap size is 8GB. In this case, we want to add 2GB to this swap volume. First, stop existing swap. You may have to terminate running programs if swap space is in use.

Now increase the size of the logical volume.

Run the mkswap command to make this entire 10GB partition into swap space.

Turn swap back on.

Now verify the new swap space is present with the list block devices command. Again, a reboot is not required.

You can also use the swapon -s command, or top, free, or any of several other commands to verify this.

Manouk Henreid
Copy Editor
Answer # 3 #


1.  Preparing for Installation

2.  Installing the Oracle Solaris Studio 12.3 Software

3.  Uninstalling the Oracle Solaris Studio 12.3 Software

4.  Troubleshooting

A.  Command-Line Options for the Installer,Uninstaller,and install_patches Utility

B.  Adding Swap Space

Adding Swap Space

Adding Swap Space on a Solaris System

C.  Oracle Solaris 12.3 Components and Packages

D.  Patch Identification Numbers and Descriptions

E.  Version Numbers of the Oracle Solaris Studio 12.3 Components

Sissy Armisen
Section Gangs
Answer # 4 #

One way to guard against out-of-memory errors in applications is to add some swap space to your server. In this guide, we will cover how to add a swap file to an Ubuntu 22.04 server.

Swap is a portion of hard drive storage that has been set aside for the operating system to temporarily store data that it can no longer hold in RAM. This lets you increase the amount of information that your server can keep in its working memory, with some caveats. The swap space on the hard drive will be used mainly when there is no longer sufficient space in RAM to hold in-use application data.

The information written to disk will be significantly slower than information kept in RAM, but the operating system will prefer to keep running application data in memory and use swap for the older data. Overall, having swap space as a fallback for when your system’s RAM is depleted can be a good safety net against out-of-memory exceptions on systems with non-SSD storage available.

Before we begin, we can check if the system already has some swap space available. It is possible to have multiple swap files or swap partitions, but generally one should be enough.

We can see if the system has any configured swap by typing:

If you don’t get back any output, this means your system does not have swap space available currently.

You can verify that there is no active swap using the free utility:

As you can see in the Swap row of the output, no swap is active on the system.

Before we create our swap file, we’ll check our current disk usage to make sure we have enough space. Do this by entering:

The device with / in the Mounted on column is our disk in this case. We have plenty of space available in this example (only 1.4G used). Your usage will probably be different.

Although there are many opinions about the appropriate size of a swap space, it really depends on your personal preferences and your application requirements. Generally, an amount equal to or double the amount of RAM on your system is a good starting point. Another good rule of thumb is that anything over 4G of swap is probably unnecessary if you are just using it as a RAM fallback.

Now that we know our available hard drive space, we can create a swap file on our filesystem. We will allocate a file of the size that we want called swapfile in our root (/) directory.

The best way of creating a swap file is with the fallocate program. This command instantly creates a file of the specified size.

Since the server in our example has 1G of RAM, we will create a 1G file in this guide. Adjust this to meet the needs of your own server:

We can verify that the correct amount of space was reserved by typing:

Our file has been created with the correct amount of space set aside.

Now that we have a file of the correct size available, we need to actually turn this into swap space.

First, we need to lock down the permissions of the file so that only users with root privileges can read the contents. This prevents normal users from being able to access the file, which would have significant security implications.

Make the file only accessible to root by typing:

Verify the permissions change by typing:

As you can see, only the root user has the read and write flags enabled.

We can now mark the file as swap space by typing:

After marking the file, we can enable the swap file, allowing our system to start using it:

Verify that the swap is available by typing:

We can check the output of the free utility again to corroborate our findings:

Our swap has been set up successfully and our operating system will begin to use it as necessary.

Our recent changes have enabled the swap file for the current session. However, if we reboot, the server will not retain the swap settings automatically. We can change this by adding the swap file to our /etc/fstab file.

Back up the /etc/fstab file in case anything goes wrong:

Add the swap file information to the end of your /etc/fstab file by typing:

Next we’ll review some settings we can update to tune our swap space.

There are a few options that you can configure that will have an impact on your system’s performance when dealing with swap.

The swappiness parameter configures how often your system swaps data out of RAM to the swap space. This is a value between 0 and 100 that represents a percentage.

With values close to zero, the kernel will not swap data to the disk unless absolutely necessary. Remember, interactions with the swap file are “expensive” in that they take a lot longer than interactions with RAM and they can cause a significant reduction in performance. Telling the system not to rely on the swap much will generally make your system faster.

Values that are closer to 100 will try to put more data into swap in an effort to keep more RAM space free. Depending on your applications’ memory profile or what you are using your server for, this might be better in some cases.

We can see the current swappiness value by typing:

For a Desktop, a swappiness setting of 60 is not a bad value. For a server, you might want to move it closer to 0.

We can set the swappiness to a different value by using the sysctl command.

For instance, to set the swappiness to 10, we could type:

This setting will persist until the next reboot. We can set this value automatically at restart by adding the line to our /etc/sysctl.conf file:

At the bottom, you can add:

Save and close the file when you are finished.

Another related value that you might want to modify is the vfs_cache_pressure. This setting configures how much the system will choose to cache inode and dentry information over other data.

Basically, this is access data about the filesystem. This is generally very costly to look up and very frequently requested, so it’s an excellent thing for your system to cache. You can see the current value by querying the proc filesystem again:

As it is currently configured, our system removes inode information from the cache too quickly. We can set this to a more conservative setting like 50 by typing:

Again, this is only valid for our current session. We can change that by adding it to our configuration file like we did with our swappiness setting:

At the bottom, add the line that specifies your new value:

Save and close the file when you are finished.

Following the steps in this guide will give you some breathing room in cases that would otherwise lead to out-of-memory exceptions. Swap space can be incredibly useful in avoiding some of these common problems.

Teyonah McGivern
Chief Process Officer