The amount of RAM in the computer is limited. Most often, for financial reasons, although purely technically, you will not install more OP in a specific motherboard than is provided for by its specifications. And if so, then situations when there is a lack of memory are not uncommon, especially for multitasking operating systems. These include Linux, and although it is considered less demanding on PC resources, it cannot be called ideal either. The RAM shortage is solved in different ways. One of the most optimal of them is the use of a file or partition on disk, where data is temporarily stored, which is retrieved into physical memory as needed.
Contents
What is swap
In Linux-like operating systems, a swap is understood as a mechanism for organizing virtual memory, in which part of the data stored in RAM (as a rule, rarely used) is moved for temporary storage to a special section or file on a hard or solid-state disk.
All physical memory in Linux is paginated. As needed, the contents of individual pages are moved to a dedicated disk partition called swap space or to a separate file (analogous to the swap file in Windows). The procedure for freeing the RAM itself is called swapping, and the total size of physical and swap memory is called the amount of available virtual memory.
What is swap for?
Multitasking does not mean opening many programs at the same time. Even if we launch a browser, it itself uses many libraries, each of which uses its own memory area. Each new tab, each open document is more and more pages of memory, which at a certain point in time may not be enough.
And if there are no free pages for the new tab, the operating system is forced to deal with freeing memory. And what to free if all pages are occupied with the necessary data or cache? Which is used less often. But sooner or later, the unloaded piece of code will be needed, but it will no longer be in memory. This situation is called a page fault, and the OS will have to handle it anew. If the missing data is not found on the disk, the process will terminate abnormally. If there is one, the system will load the code from disk, but this will require freeing up a certain number of other pages of memory. As a result, a process called thrashing begins, when the OS is only doing that, which frees up new pages, deleting their contents and loading the missing data into them.
Having a swap file solves this dilemma. Instead of just flushing memory pages, the system flushes their contents to disk, which, as it were, expands the amount of physical RAM. In this case, thrashing is replaced by a single read / write procedure.
Of course, we described the process quite schematically, in fact, it has many nuances and a rather complex implementation algorithm. In any case, the picture is as follows: if you make the swap file large enough, rarely used and unchanged data, when a deficit occurs from RAM, “leaves” to disk, from where it can be retrieved as many times as needed.
If the swap file / partition is small, it will be of little use, since sooner or later the free space on it will be exhausted, and then the “dancing” will start again with constant read-write operations to the swap file, which will cause the system to slow down.
Answering the question about the need for swap in Linux, we can state the following:
- it helps to unload the system when a program requests an amount of physical memory that the system does not have. In such cases, the Linux kernel analyzes which pages are least frequently accessed, flushes their contents to disk and allocates the required number of pages to the current process;
- the peculiarity of many programs is that at the time of their launch, some of the pages are occupied by data that is used only at the time of initialization of the process / application. The system can and should dump these pages into swap, unloading the OP.
But it’s not that simple. Swap is also not without its drawbacks, the main of which is the speed of write / read operations from the disk. Suffice it to say that during operations with physical memory, this speed is measured in nanoseconds (just look at the characteristics of RAM chips), while for a hard disk it is milliseconds, that is, several orders of magnitude more. SSD drives have much higher data exchange rates, but due to the slow interface, they are still incomparable with RAM. So it turns out that with frequent flushes of memory pages in swap, the system can also work slower.
This happens especially often if the computer is used as a server, and with Linux, this is the majority of PCs. If there is a lack of memory, databases are usually among the first to suffer, and if it is MySQL, then its fall is threatened by the inaccessibility of the site or its pages, therefore it is so important for servers to have a large swap section – let the site work better than it will be completely inaccessible …
How to create and configure a swap file using the example of Ubuntu
The procedure for creating a swap file is quite complex, requiring some command line skills.
And the first stage – we need to find out if the system has a partition or file allocated for swap.
Checking for swap in Ubuntu
We use the command:
swapon -s
or
free –m
If swap is absent, in the first case you will get an empty resulting string, in the second – a table of virtual memory usage, in which the Swap string will contain zeros.
If there is no swap file, you need to decide if it is possible to create one.
Checking for free disk space
We execute the command
df -h
A table similar to the following will be displayed:
The disk has about 23 GB of free space, which is more than enough to create a swap file.
What size to create swap
The paging file size depends on many factors:
- how much RAM is in the system;
- what is the composition of the programs / applications used;
- whether you intend to engage in sleep mode;
- whether files with confidential data will be used.
Of course, the main aspect is the amount of physical memory. If it is less than 2 GB, the sawp file is 1.5-2 times larger, that is, up to 4 GB.
If you have 3-4 GB of RAM, then decide first whether you will use sleep mode. If yes, it is advisable to choose the size of the swap file at the rate of 110-115% of the amount of RAM, if not, the ideal option would be a swap file of the same size.
If you have a powerful computer and the amount of RAM exceeds 6 GB, choose the size of the swap file in Linux based on half the amount of RAM. If you plan to use hibernation mode, you might need to experiment to find out how much RAM is used for sleep mode and select a value based on your results. Fortunately, you can create a swap file at any time, not necessarily at the Linux installation stage.
Recommended swap file sizes on Linux in Fedora documentation
Creating a swap file in Linux
There are several options for creating a swap file in Linux, one of which is considered traditional and the other is fast.
First, let’s take a look at a quick way, which is to use one command:
fallocate -l 2G /swapfile
Here the second parameter indicates the size of the file to be created, expressed in GB (if you do not specify the letter, the system will interpret the parameter in KB, this must be taken into account).
In this case, the file will be created and available immediately after the command is executed, so it is advisable to use this method.
The second option, traditional:
dd if=/dev/zero of=/swapfile bs=1М count=2096
Here the bs parameter indicates in which units we set the size of one block for the swap file. In this case, 1 megabyte. The count parameter indicates the number of such blocks allocated for the paging file, and the total is the same 2 GB as in the first option.
The dd command itself in Linux means byte copying, the if parameter specifies where to copy from, in our case it is / dev / zero – a special file with zero bytes. The of parameter indicates that we will write these zero bytes to the file / swapfile.
Note that no errors are allowed when using this command. If you enter the of parameter incorrectly, there is a possibility that important data will be corrupted.
If you indicated an insufficient paging file size (this may become clear much later), you can increase or simply change the size of the Ubuntu swap by disabling the current one (we will tell you how to do this later) and re-creating it according to the algorithm given here, indicating the correct size.
How to connect a swap file
The paging file is important from the point of view of the operating system, and editing it can lead to its crash. Therefore, it is important to restrict swap access to the following command:
chmod 600 /swapfile
As a result, only the root user will have the right to read and write to it (analogous to admin in Windows).
Further customization of the swap file is to convert / swapfile to a swap file using the command
mkswap /swapfile
And the final command, the action of which is to connect swap to the system (enable it):
swapon /swapfile
It is now fully operational.
Adding swap to startup
In order not to connect the swap file to the system after each reboot with the last command of the previous section, enter a line into the / etc / fstab file using any text editor that will be used at each Linux boot:
/swapfile none swap defaults 0 0
After restarting the computer, you can check if the free –m command worked correctly.
How to clear swap in Ubuntu
Sometimes it may be necessary to temporarily free up disk space, and often the paging file is the only viable candidate for this purpose.
Clearing swap (or rather, shutting down) is carried out with the command
swapoff –a
Enabling is done by the command
swapon -a
If you decide to stop using the swap file altogether, you can remove swap as follows:
cat /proc/swaps (определяем местоположение swap-файла)
swapoff / dir / swapXXXXX (disable the swap file, here dir is the result of the previous command, that is, the directory with the file, and swapXXXXX is the name of the swap file itself)
rm /dir/swapXXXXX (удаляем файл с диска)
If you added swap to startup, you need to remove it from there by removing the corresponding line in the / etc / fstab file (for example, using the gedit editor).
But remember that without a swap file, the system may be unstable, especially with a small amount of RAM, so deleting the swap file without creating a new one is strongly discouraged.