- Linux swap: what it is and how to use it
- Video
- What is Linux Swap?
- Do you need Linux Swap?
- Linux Swap Partition
- Linux Swap File
- How to remove a Linux Swap File
- How to adjust the Swappiness value
- Conclusion
- Swap ������� linux ���
- Размещение
- Безопасность
- Размер
- Создание SWAP на разделе диска
- SWAP с динамически изменяемым размером
- Hibernate (suspend to disk, гибернация)
- Параметр vm.swappiness
- Какое значение выбрать?
- Swap ������� linux ���
- 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 swap: what it is and how to use it
If you are a Linux user you have definitely heard about Linux Swap, but you may not know what it is exactly or have only superficial knowledge about it. Time to change that!
I mention Linux swap and swappiness in almost every article on things to do after installing Linux. You know that Linux swap is somehow related to RAM and swappiness can affect your system performance. It is time to explain what it is and how to use it in little more details.
Video
What is Linux Swap?
The Linux Kernel divides RAM into chunks of memories and the swapping process is when the Linux Kernel uses a hard disk space (swap space) to store information from RAM and thus releases some RAM space. That is why when you install a Linux distribution, the installation wizard usually asks you to assign some space for the system and another for the swap.
Using swap is a very useful way to extend the RAM because it provides the necessary additional memory when the RAM space has been exhausted and a process has to be continued. It is especially recommended when you have less than 1Gb of RAM. Although in the end, everything depends on you.
Do you need Linux Swap?
This is a question many novice users ask themselves when they begin to discover Linux. In fact, this will depend on the use and amount of RAM your computer has. Regarding the use, there are processes and applications that really use a lot of memory, for example, Google Chrome. However, most of the current equipment comes with at least 8Gb of RAM and that makes the swap process less necessary. Nevertheless, having a swap space is desirable even if you have a lot of RAM.
For example, usually, when your RAM gets full and the Linux kernel has no space to write into, your system will crash. On the other hand, if you have a swap space, it will be used by the Linux kernel and your system will keep working, though much slower. So, it is safer to have swap space.
Note: swap space has one disadvantage — it is much slower than RAM. So, adding a swap space will not make your computer faster, it will only help to overcome some limitations posed by RAM size.
Linux Swap Partition
I recommend that you create the swap partition during the installation of your Linux distribution. In general, these are the recommended sizes for the swap partition.
- If your computer has 1Gb of RAM or less, then the swap partition should be twice the size of the RAM.
- But, If you have between 2gb and 4gb of RAM, the size of the swap partition should be half the RAM.
- Finally, If you have more than 4gb of RAM, then it is enough to have 2Gb.
But everything depends on your use case.
You can check the type and size of your swap with this command:
Above, I have a swap partition of 2Gb.
Linux Swap File
Alternatively, you can create a Linux Swap File after the installation. The modern Linux Kernel allows Swapping to a swap file instead of a swap partition. A swap file has an advantage over a swap partition that you can change the size of your swap any time easily by changing a swap file size.
If you want to create a swap file, run this command first:
Note: this command is to create a 1Gb swap file. Replace 1G with the value you want.
Next, you have to set the correct permissions.
Then, format the file to swap.
Finally, enable the swap.
If you want the changes to be permanent, you need to edit the /etc/fstab file and add the following.
In the end, check the status of the swapfile:
If you see the size of a swap file in the total column, you have done everything correctly.
How to remove a Linux Swap File
In case you need to remove a Linux swap file for any reason, you need to follow these steps.
First, deactivate the swap.
If you created the entry in the /etc/fstab file, remove it. To remind you, it is the line: /swapfile swap swap defaults 0 0 entry.
Finally, delete the actual Linux Swap File.
How to adjust the Swappiness value
Swappiness is a property of the Linux Kernel to define how often the swap space will be used. As you know RAM is faster than a hard drive. So, every time you need to use swap, you will notice that some processes and applications will run slower. However, you can adjust the system to use much more RAM than swap. This can help improve overall system performance.
Normally, the default swappiness value is 60. The smaller this value, the more of your RAM will be used.
To verify the swappiness value, run this command:
You should see the value of 60.
If you want to modify the default value, you need to edit the file /etc/sysctl.conf .
And add the following (10 is the most commonly recommended value):
Save the file and close it with Ctrl+O and Ctrl+X shortcuts. In order to apply the changes, you need to reboot the system.
This way your Linux kernel will use more RAM and less swap, but it still will swap when your RAM memory gets critically full. Usually, this setting is recommended when you have more than 4Gb of RAM.
Conclusion
In conclusion, it is safer to have some swap space on your computer. You can use either a swap partition or a swap file. The latter becomes more and more common.
Linux swap is a technical concept but knowing how it works can improve the performance of the system. Just play with the swappiness value.
Do you have anything to add about Linux swap? Have you changed the default value of swappiness? Let me know in the comments.
Источник
Swap ������� linux ���
SWAP – один из механизмов виртуальной памяти, при котором отдельные фрагменты памяти (обычно неактивные) перемещаются из ОЗУ во вторичное хранилище (отдельный раздел или файл), освобождая ОЗУ для загрузки других активных фрагментов памяти.
Более подробно о механизме своппинга можно прочитать в Википедии.
Дополнительно SWAP используется при организации режима сна (hibernation или suspend to disk). При этом в SWAP сохраняется образ оперативной памяти.
Размещение
SWAP может быть размещен на разделе диска, в файле или в RAM. Исторически в Linux SWAP размещался на разделе, но в современных дистрибутивах производительность SWAP-файла не уступает SWAP-разделу. Однако стандартный установщик Ubuntu (до версии 17.04) не умеет создавать SWAP-файл при установке и выдает предупреждение, если SWAP-раздел не определен при разметке диска. Начиная с версии 17.04, Ubuntu предлагает по умолчанию создавать SWAP в файле (объем определяется как 5% от свободного на диске места, но не более 2 Гб). Использование SWAP-файла имеет некоторые преимущества: он не занимает отдельный раздел, его легко создать, изменить его размер или удалить.
Дополнительно при выборе размещения SWAP нужно учитывать, что не все файловые системы позволяют использовать прямую адресацию блоков SWAP-файла. Так, к примеру, нельзя использовать SWAP в файле на разделе с файловой системой btrfs(по состоянию на середину 2017).
Безопасность
При работе с секретными/зашифрованными данными часть этих данных в процессе работы либо при гибернации может оказаться в SWAP в расшифрованном виде. В таких случаях рекомендуется шифровать не только данные, но и сам SWAP. Однако нужно учитывать, что у режима сна при шифровании SWAP могут возникнуть сложности.
Размер
В Интернете можно найти множество рекомендаций по определению размера SWAP, однако универсального ответа не существует.
При определении размера SWAP следует учесть следующие аспекты:
В зависимости от ответов на эти вопросы рекомендации по размеру SWAP будут значительно различаться.
Для машин с незначительным объемом памяти (меньше 2 Гб) рекомендуется создавать SWAP размером от 1,5 до 2-х размеров оперативной памяти. И стоит попробовать изменять vm.swappiness, но лучше поискать возможность увеличить объем оперативной памяти.
Для машин с объемом памяти 3-4 Гб нужно решить, будет ли использоваться suspend to disk. Если да, то нужно создавать SWAP размером на 10-15% больше размера оперативной памяти. Если же suspend to disk использоваться не будет, то можно создать SWAP небольшого размера (размером от половины до 1 объема оперативной памяти). Можно не создавать SWAP при установке системы, а при необходимости добавить его позже как файл.
На компьютерах с объемами оперативной памяти более 6Gb имеет смысл создать SWAP размером в половину от объема оперативной памяти. При этом, если вы хотите использовать гибернацию, следует оценить загрузку оперативной памяти в процессе работы и задать величину SWAP, исходя из этого. К примеру, если объем оперативной памяти составляет 16 ГБ, а рабочая загрузка не превышает в среднем 5-6 ГБ, величины SWAP-раздела в 8 ГБ вам хватит для гибернации. При таком подходе следует помнить, что при использовании ресурсоёмких программ (рендеринг изображения, компиляция огромных проектов и т.п.) оперативная память может заполняться полностью, а SWAP — использоваться в качестве подкачки. В таких ситуациях размер SWAP нужно выбирать индивидуально.
При работе с секретными (зашифрованными) данными стоит либо шифровать SWAP, либо рассмотреть вариант с отказом от SWAP вовсе (зависит от размера оперативной памяти). Стоит также рассмотреть вариант с шифрованием всего диска.
Создание SWAP на разделе диска
Разобравшись с требованиями к SWAP, можно приступить к его созданию или изменению.
Ядро Linux может работать с несколькими частями SWAP. Поэтому если вы решили, что созданного при установке системы SWAP-раздела недостаточно, то стоит создать дополнительный SWAP (выделить место под раздел или файл). Однако нужно учитывать, что для гибернации нужен непрерывный блок SWAP, который должен иметь размер больший, чем оперативная память.
К примеру, у нас есть раздел /dev/sdc2 (ваше имя раздела может отличаться). Создадим на нем необходимую структуру данных для работы SWAP:
Подключим раздел как SWAP:
Проверить результат можно, посмотрев на вывод команды
Сделаем автомонтирование SWAP-раздела при запуске системы. Узнаем UUID раздела:
Теперь пропишем строку в /etc/fstab
SWAP с динамически изменяемым размером
Если вы не хотите думать об объеме SWAP, имеет смысл воспользоваться утилитой swapspace (динамический менеджер подкачки). Эта утилита работает в фоновом режиме и динамически управляет подкачкой. При необходимости swapspace автоматически создаёт дополнительные файлы подкачки требуемого размера. Неиспользуемые файлы подкачки удаляются и не занимают место.
Однако, если вы работаете с секретными документами, не забудьте указать swapspace создавать SWAP-файлы на зашифрованном диске или внутри шифрованного контейнера 1) .
Hibernate (suspend to disk, гибернация)
О настройке режима гибернации можно прочитать здесь.
Параметр vm.swappiness
Основной параметр, влияющий на работу системы со swap, — это vm.swappiness. Очень приблизительно этот параметр можно определить так: он задает процент свободной оперативной памяти, при котором начинается использование подкачки. Более точное определение смысла этой переменной можно уяснить из описания которое было дано в рассылке kernel.org — статья на английском.
Без особой необходимости трогать его не рекомендуется.
Скорректировать значение, применяемое при загрузке системы, можно, указав в файле /etc/sysctl.conf значение vm.swappiness. Пример:
Мгновенно применить эту настройку можно с помощью следующей команды:
Актуальное значение, используемое ядром в настоящее время, можно просмотреть или изменить в /proc/sys/vm/swappiness.
Изменения в /proc/sys/vm/swappiness будут сброшены при следующей перезагрузке.
Значение vm.swappiness по умолчанию — 60.
Какое значение выбрать?
Маленькое значение vm.swappiness (минимальное значение: 0) будет заставлять ядро использовать больше оперативной памяти под память процессов (в ущерб буферам и кэшам), тогда как большое значение (максимальное значение: 100) будет выделять больше памяти под кэши и буфера (в ущерб памяти для процессов).
Нужно понимать: ни одно значение vm.swappiness не увеличит волшебным образом производительность компьютера многократно. Урезаете кеши — понижаете отзывчивость системы при работе с файлами, урезаете память процессов — снижаете отзывчивость системы при переключении задач.
Нужное вам значение, скорее всего, стоит подбирать экспериментально.
Источник
Swap ������� linux ���
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.
Источник