- Swap (Русский)
- Contents
- Пространство подкачки
- Раздел подкачки
- Активация используя systemd
- Отключение подкачки
- Файл подкачки
- Вручную
- Создание файла подкачки
- Удаление файла подкачки
- Автоматически
- systemd-swap
- Подкачка с USB устройства
- Шифрование подкачки
- Производительность
- Swappiness
- VFS cache pressure
- Приоритет
- Использование zswap или zram
- Чередование
- Linux Add a Swap File Tutorial
- Procedure To Add a Swap File Under Linux
- Step 1 – Login as the Root User
- Step 2 – Create Storage File
- Step 3 – Secure swap file
- Step 4 – Set up a Linux swap area
- Step 5 – Enabling the swap file
- Step 6 – Update /etc/fstab file
- How do I verify Linux swap file is activated or not?
- How can I display swap usage summary on Linux?
- How can I disable devices and files for paging and swapping on Linux?
- How do I set swappiness on a Linux server?
- Conclusion
Swap (Русский)
Эта страница дает ознакомление с пространством подкачки и подкачкой страниц в GNU/Linux. Охватывает создание, активацию файлов и разделов подкачки.
Linux делит свою физическую RAM (оперативную память) на кусочки памяти, называемые страницами. Подкачка (swapping) это процесс, когда страницы памяти копируются на предварительно сконфигурированное пространство на жестком диске, называемое пространством подкачки, чтобы освободить эту страницу из памяти. Суммарный размер оперативной памяти и пространства подкачки это количество доступной виртуальной памяти.
Поддержка подкачки обеспечивается ядром Linux и утилитами в пользовательском пространстве из util-linux пакета.
Contents
Пространство подкачки
Пространство подкачки может быть разделом диска или файлом. Пользователи могут создать пространство подкачки во время установки или позднее в любое желаемое время. Пространство подкачки может быть использовано для двух целей, расширить виртуальную память за пределы установленной оперативной памяти (RAM), а также для сохранения данных при гибернации (suspend-to-disk).
Иногда стоит включать Swap в зависимости от установленной оперативной памяти и количества требований для запуска желаемых программ. Если количество оперативной памяти меньше требуемого, тогда стоит включить подкачку. Это позволяет избежать состояния нехватки памяти (OOM), при котором механизм ядра Linux, OOM Killer, будет автоматически пытаться освободить память, убивая процессы. Чтобы увеличить количество виртуальной памяти до требуемого уровня, добавьте необходимую разницу как пространство подкачки. Например, если программа требует 7,5 GB памяти для запуска, а у вас установлено 4 GB оперативной памяти, добавьте разницу 3,5 GB как подкачку. В будущем добавляйте больше пространства к подкачке, учитывая требования. Это вопрос личных предпочтений если вы считаете, что программы должны быть убиты, вместо включения подкачки. Самый большой недостаток в подкачке это снижение производительности, см. раздел #Производительность
Для проверки статуса подкачки, используйте:
free также покажет недостаток памяти, который может быть исправлен включением или увеличением подкачки.
Раздел подкачки
Раздел подкачки может быть создан различными GNU/Linux утилитами разметки. Разделы подкачки обычно обозначаются как тип 82 . Хотя есть возможность использовать разные типы как подкачку, рекомендуется использовать тип 82 , в большинстве случаев systemd, будет автоматически определять его и монтировать (см. ниже)
Для установки раздела как область Linux подкачки, можно использовать mkswap . Например:
Для подключения устройства как подкачку:
Чтобы подключить этот раздел подкачки при загрузке, добавьте запись в fstab:
где может быть получен из команды:
Активация используя systemd
Активация разделов подкачки в systemd базируется на двух различных механизмах. Оба исполняются в /usr/lib/systemd/system-generators . Генераторы запускаются при старте системы и создают нативные systemd юниты для монтирования. Первый systemd-fstab-generator , читает fstab, чтобы генерировать юниты, включая юнит для подкачки. Второй systemd-gpt-auto-generator , осматривает корневой диск, чтобы генерировать юниты. Это операция проходит только на GPT дисках и может идентифицировать разделы подкачки по их тип коду 82 .
Отключение подкачки
Чтобы деактивировать определенное пространство подкачки:
Также можно использовать -a ключ, чтобы деактивировать все пространства подкачки.
С тех пор, как systemd управляет подкачкой, она вновь будет активирована при старте системы, для долговременного отключения автоматической активации найденных пространств подкачки, выполните systemctl —type swap , чтобы найти связанные со .swap юниты и замаскируйте (systemctl mask юнит) их.
Файл подкачки
Как альтернатива к созданию целого раздела, файл подкачки даёт возможность менять свой размер на лету, а также его гораздо легче полностью удалить. Это может быть особенно важно, если дисковое пространство ограничено (например, небольшие SSD)
Вручную
Создание файла подкачки
Использовать под суперпользователем fallocate , чтобы создать файл подкачки размером на свой выбор (M = Mebibytes, G = Gibibytes). Например создание 512 MiB файла подкачки:
Установите права доступа (всеми читаемый файл подкачки это огромная локальная уязвимость)
После создания файла нужного размера, форматируйте его в подкачку:
Активируйте файл подкачки:
В завершении, отредактируйте fstab, добавив запись для файла подкачки:
Удаление файла подкачки
Чтобы удалить файл подкачки, сначала нужно отключить подкачку, а затем файл может быть удален:
В завершении, удалите соответствующую запись из /etc/fstab .
Автоматически
systemd-swap
Установить systemd-swap пакет. Установить swapfc_enabled=1 в Swap File Chunked разделе файла /etc/systemd/swap.conf . Start/enable systemd-swap сервис. Посетить страницу авторов на GitHub для получения подробностей и установить рекомендуемую конфигурацию.
Подкачка с USB устройства
Благодаря модульности, предлагаемой Linux, мы можем иметь множество разделов подкачки на различных устройствах. Если у вас полностью заполнен жесткий диск, то можно использовать USB устройство как временный раздел подкачки. Однако, этот метод имеет серьёзные недостатки:
- USB устройство медленнее чем жесткий диск
- Flash память имеет ограниченное количество циклов записи. Использование его как раздела подкачки, может быстро убить его.
Чтобы добавить USB устройство как подкачку, сначала необходимо разметить USB флешку для подкачки как описано в секции #Раздел подкачки.
Далее откройте /etc/fstab и добавьте
в опции монтирования первоначальной записи подкачки, таким образом USB подкачка будет иметь приоритет записи над старым разделом.
Данная инструкция будет работать и для других устройств хранения, таких как SD карты и т.д.
Шифрование подкачки
Производительность
Операции подкачки как правило существенно медленнее чем непосредственный доступ к RAM. Отключение подкачки полностью для повышения производительности, иногда может привести к ухудшению, поскольку это уменьшает доступную память для VFS кеша, вызывая более частые и дорогостоящие операции ввода/вывода.
Значения подкачки можно настроить, чтобы помочь производительности:
Swappiness
Swappiness sysctl параметр представляющий частоту использования пространства подкачки. Swappiness может иметь значение от 0 до 100, значение по умолчанию = 60. Низкое значение заставляет ядро избегать подкачки, высокое значение позволяет ядру использовать подкачку наперёд. Использование низкого значения на достаточном количестве памяти, улучшает отзывчивость на многих системах.
Чтобы проверить текущее значение swappiness:
Чтобы временно установить значение swappiness:
Чтобы постоянно установить значение swappiness, отредактируйте (создайте) конфигурационный файл sysctl
Чтобы проверить и больше узнать, почему оно так работает, посмотрите эту статью.
VFS cache pressure
Другой sysctl параметр, который действует на производительность подкачки это vm.vfs_cache_pressure , он контролирует склонность ядра к применению памяти, которая используется для кэширования VFS caches, напротив кэширования страниц и подкачки. Увеличение этого значения увеличивает коэффициент с которым VFS caches применяется[2] [устаревшая ссылка 2020-08-06] . Для подробной информации смотри документацию ядра Linux.
Приоритет
Если у вас больше одного файла или раздела подкачки, вы должны учитывать присвоение приоритетного значения (от 0 до 32767) для каждой области подкачки. Система будет использовать области подкачки с высоким приоритетом, перед использованием областей с низким приоритетом. Например, если у вас быстрый диск ( /dev/sda ) и медленный ( /dev/sdb ), назначьте высокий приоритет для подкачки расположенной на быстром устройстве. Приоритет может быть назначен в fstab как pri параметр:
Или как параметр в swapon —priority
Если две или более областей будут иметь одинаковый приоритет и он будет самым высоким из доступным приоритетов, то страницы будут распределяться по кругу между областями.
Использование zswap или zram
Zswap это особенность ядра Linux, обеспечивающая сжатие обратного кэша для страниц подкачки. Она увеличивает производительность и уменьшает операции ввода/вывода. ZRAM создаёт виртуальный сжатый файл подкачки в памяти, как альтернатива файлу подкачки на диске.
Чередование
Нет необходимости использовать RAID для повышения производительности подкачки. Ядро самостоятельно может чередовать подкачку на нескольких устройствах, если вы присвоите им одинаковый приоритет в /etc/fstab . Для подробной информации смотри The Software-RAID HOWTO.
Источник
Linux Add a Swap File Tutorial
I need additional swap space to improve my Linux server/desktop system performance. How do I add a swap file to Linux system using command line options without creating a new partitions?
In Linux, as in most other Unix-like operating systems, it is common to use a whole partition of a hard disk for swapping. However, with the 2.6 Linux kernel, swap files are just as fast as swap partitions, although I recommend using a swap partition. The administrative flexibility of swap files outweighs that of partitions; since modern high capacity hard drives can remap physical sectors, no partition is guaranteed to be contiguous. You can add swap file as a dedicated partition or use following instructions to create a swap file.
Tutorial details | |
---|---|
Difficulty level | Intermediate |
Root privileges | Yes |
Requirements | None |
Est. reading time | 5m |
Procedure To Add a Swap File Under Linux
Step 1 – Login as the Root User
Open a terminal window (select Applications > Accessories > Terminal) or login to remote server using the ssh client. Switch to the root user by typing su — (or sudo -s ) and entering the root password, when prompted:
$ su —
OR
$ sudo -s
Step 2 – Create Storage File
Type the following command to create 512MB swap file (1024 * 512MB = 524288 block size):
# dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
Sample outputs:
- 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 ➔
- if=/dev/zero : Read from /dev/zero file. /dev/zero is a special file in that provides as many null characters to build storage file called /swapfile1.
- of=/swapfile1 : Read from /dev/zero write storage file to /swapfile1.
- bs=1024 : Read and write 1024 BYTES bytes at a time.
- count=524288 : Copy only 523288 BLOCKS input blocks.
Step 3 – Secure swap file
Setup correct file permission for security reasons, enter:
# chown root:root /swapfile1
# chmod 0600 /swapfile1
A world-readable swap file is a huge local vulnerability. The above commands make sure only root user can read and write to the file.
Step 4 – Set up a Linux swap area
Type the following command to set up a Linux swap area in a file:
# mkswap /swapfile1
Sample outputs:
Step 5 – Enabling the swap file
Finally, activate /swapfile1 swap space immediately, enter:
# swapon /swapfile1
Step 6 – Update /etc/fstab file
To activate /swapfile1 after Linux system reboot, add entry to /etc/fstab file. Open this file using a text editor such as vi:
# vi /etc/fstab
Append the following line:
/swapfile1 none swap sw 0 0
Save and close the file. Next time Linux comes up after reboot, it enables the new swap file for you automatically.
How do I verify Linux swap file is activated or not?
Simply use the free command:
$ free -m
How can I display swap usage summary on Linux?
Type the following swapon command:
# swapon -s
Sample outputs:
Another option is to view /proc/meminfo file:
$ less /proc/meminfo
$ grep -i —color swap /proc/meminfo
Sample outputs:
You can also use top command, atop command, and/or htop command to display information about swap usage:
# top
# atop
# htop
Sample outputs from a database server running on a CentOS Linux server:
How can I disable devices and files for paging and swapping on Linux?
You need to use the swapoff command:
# swapoff /swapfile1
# swapon -s
How do I set swappiness on a Linux server?
The syntax is:
# sysctl vm.swappiness=VALUE
# sysctl vm.swappiness=20
OR
# echo VALUE > /proc/sys/vm/swappiness
# echo 30 > /proc/sys/vm/swappiness
The value in /proc/sys/vm/swappiness file controls how aggressively the kernel will swap memory pages. Higher values increase agressiveness, lower values descrease aggressiveness. The default value is 60. To make changes permanent add the following line to /etc/sysctl.conf :
Conclusion
You learned how to add swap file under Linux operating systems.
🐧 Get the latest tutorials on Linux, Open Source & DevOps via
Category | List of Unix and Linux commands |
---|---|
Documentation | help • mandb • man • pinfo |
Disk space analyzers | df • duf • ncdu • pydf |
File Management | cat • cp • less • mkdir • more • tree |
Firewall | Alpine Awall • CentOS 8 • OpenSUSE • RHEL 8 • Ubuntu 16.04 • Ubuntu 18.04 • Ubuntu 20.04 |
Linux Desktop Apps | Skype • Spotify • VLC 3 |
Modern utilities | bat • exa |
Network Utilities | NetHogs • dig • host • ip • nmap |
OpenVPN | CentOS 7 • CentOS 8 • Debian 10 • Debian 8/9 • Ubuntu 18.04 • Ubuntu 20.04 |
Package Manager | apk • apt |
Processes Management | bg • chroot • cron • disown • fg • glances • gtop • jobs • killall • kill • pidof • pstree • pwdx • time • vtop |
Searching | ag • grep • whereis • which |
Shell builtins | compgen • echo • printf |
Text processing | cut • rev |
User Information | groups • id • lastcomm • last • lid/libuser-lid • logname • members • users • whoami • who • w |
WireGuard VPN | Alpine • CentOS 8 • Debian 10 • Firewall • Ubuntu 20.04 |
Comments on this entry are closed.
TYPO: vi /etc/fstatb
It should be fstab
Thanks for heads up!
If you don’t want to reboot the machine to enable the new swapfile, after step f) you can issue these commands:
swapoff -a
swapon -a
to first stop and then start all swaps in /etc/fstab
this was really helpful for debugging my automounting issue. Turns out I had a typo on the swapfile name.
Thnx some_guy
Thanks for the help. But how would I go about deleting this swapfile? Also, how does creating a swapfile this way differ from creating a separate partition for one? I only ask because I would like to have multiple installs of linux on my system, and I would like them to share the same swapfile.
Recently, I’ve been trying to create a swapfile partition and it’s not being recognized, so I’ve been having trouble.
Thanks, I have been looking for the last step for months heh.
Thank you for the guide; I’d like to add another detail. In this line one may choose to use other units to make things more simple:
# dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
You can turn it into:
# dd if=/dev/zero of=/swapfile1 bs=1M count=512
This means that the block size is 1 MB, so count=512 means “I need 512 megs”, there is no need to do any other calculations.
hi,
i’m about to install ubuntu karmic on a new computer with thre sata hard drives.
I usually allocate a little more of current ram in swap partition (5 gigas) so I can safely hibernate, but on a post I read in FreeBSD forums there’s a link to FreeBSD manual where states there should be a swap partition for every disk, not just one swap for the whole system.
So, I know Linux is not *BSD but I wonder if the same is applicable here because installing a swap of 5 gigs in all three sata seems a waste of space to me!
Set swap priority:
• Swapiness is the priority of input/output for swap. To look the current value:
cat /proc/sys/vm/swappiness
To change the swap priority (lower value means less swapping):
sysctl vm.swappiness=10
To have this value set at boot add it to /etc/sysctl.conf
vm.swappiness=0
Hi!
First I must say thanks for a great how to.
And secondly, I’m referencing it in Arch Linux wiki how to create swap file.
Hope you agree with it.
If not please contact me.
Link: http://wiki.archlinux.org/index.php/HOWTO_Create_swap_file
Thanks! I’m newbie to Linux, It helped me in time.
After creating the swap file its permissions should be set so that only root can access the file:
chmod 600 /swapfile1
+1 to Thomas suggestion.
You MUST chmod 600 /swapfile1. Otherwise your box will get owned!
So, after following these steps I received the notification that my root partition is full. And then, after rebooting, I cannot log into gnome. It will start gdm but will not go into gnome from there, it will only bring me back to gdm. startx does not work as well. So how do I do the oposite of this?
You just have to:
-make sure the swap file is not active
swapon -s
-if it is active
swapoff /swapfile (or whatever you called it)
-comment out the line in your /etc/fstab file (Place a hashmark # in front of it or just delete the line)
-remove the swapfile:
rm /swapfile (or whatever you called it)
Reboot and you should be away unless you want to create a smaller swap file in which case you should just make sure it isn’t in use, delete the file and recreate it using a smaller size.
Since kernel 2.6.31, you can use the util fallocate instead of dd on btrfs, ext4, ocfs2, and xfs filesystems. It’s *much* faster than dd on really big swap files.
Hi Vivek,
5 years on and the page is still useful. Thanks 🙂
dd if=/dev/zero of=/swapfile1 bs=1024 count=524288
pls tell me the meaning and function of this command..why we are using if=/dev/zero and of=/swapfile..why this command started with dd..
dd is a command that does a low level copy of data from a to b. ‘if’ is the input file for the copy. /dev/zero is a device that generates as many null characters as it is asked to create and passes them on. ‘of’ is your output file or what will become your new (or additional) swapfile. the ‘/swapfile’ could be any name that you want it to be as long as you don’t forget what it is for the further manipulations. ‘bs’ is the block size of the file and ‘count’ is the number of bytes in the file. So, what the command does is takes 524288 null bytes from /dev/zero and puts them into /swapfile thus initially populating the file.
How do you increase the size of a swap file?
either create a new pagefile that’s larger mount it as swap, then umount the old swap and delete. then modify fstab as appropriate.
or if it’s a lightly loaded machine you can unmount the swap create a larger swap and remount. This has the benefit that you can reuse the name 😉
or…Of course you can create a 1gig file and just add that as swap as well. The only problem here is ensuring that the file is contiguous,
i.e. 1x 3gb swap or 3x 1gb swap (swapfile1+swapfile2+swapfile3) or indeed 1x 2gb swap + 1x1gb swap.
@Sergio, add another one. Or unmount the swap file and recreate a larger file.
“Or unmount the swap file and recreate a larger file.”
Why, when (as you first suggested) adding another one is so simple?
how to i increase swapfile to 2gig… or more im confused
You did not really say where you confusion lies. You have one of two options. You can either add a second swap file with whatever size will bring the total up to 2 GB or you can delete the current swapfile and establish a new one that is 2 GB in size. I believe both scenarios are covered in the comments above as well as the initial article so you will have to be a little more explicit if you want help …
thank u for a clarification of this doubt
We tried to add a swap file on one server and now using above steps but now it is growing big.
root@server [/]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 4.9G 3.9G 710M 85% /
tmpfs 1.9G 0 1.9G 0% /dev/shm
/dev/sda1 485M 86M 374M 19% /boot
/dev/sda6 176G 31G 136G 19% /home
/dev/sda5 20G 6.6G 12G 36% /usr
/dev/sda3 29G 6.3G 22G 23% /var
/usr/tmpDSK 485M 16M 444M 4% /tmp
root@server [/]# free -m
total used free shared buffers cached
Mem: 3810 3545 264 0 425 2288
-/+ buffers/cache: 831 2979
Swap: 2999 325 2674
root@server [/]# grep swap /etc/fstab
/swapfile swap swap defaults 0 0
root@server [/]# du -sch /swapfile
3.0G /swapfile
3.0G total
root@server [/]#
Thank you for this useful post 🙂
Thanks alot
I was wondering to create my swap space due to out of space for oracle installation
so the precheck was failed
this gave me the correct result to over come my problem
no need to restart the OS, it will apply after creating the swap file
again very big thank for the support list
Thanks a lot brother ! Saved a lot of effort on my tomcat dying silently.
ps (I’m a colleague of ashish gite)
It help me to solve a problem using Riak, the OS was installed without swap partition.
Unless something else has an express need to access /swapfile1 by a block device mount point “swap” this presents MORE of a security risk NOT LESS. The second ‘/etc/fstab’ field should be “none”. Consider ‘/media/sda1/pagefile.sys none swap defaults 0 0’.
You have used the example ‘/swapfile1 swap swap defaults 0 0’. During init, otherwise unmounted TRUE block devices REQUIRE mounting “swap”–designated in the second field ‘/dev/sda3 swap auto defaults 0 0’. A generic swap-file (not on the root device) requires patching: that it’s device has been previously mounted in some rc script ‘mount /dev/sda1’ (assuming valid entry in /etc/fstab) along with an existing contiguous /swapfile1 (else create–use dd), ‘delay 1’ (must wait for completion), ‘mkswap /mnt/sda1/swapfile1’ must be rw (defaults) and compatible permissions for the device file system, and of course ‘swapon /mnt/sda1/swapfile1’.
Thank you very much. I moved wordpress to AWS ec2 and started getting Database establishing error. I found that out of 1.7GB only 30-40 mb was left. Now with these steps I created additional 512 mb. Hope now I do not get any memory issue.
A much faster way to create a 1GB swapfile is…
dd if=/dev/zero of=/swapfile bs=1024 count=1 seek=1M
This skips to the end of the swapfile and writes just one block leaving a giant “hole” that will be read as zeros. Disk space is allocated as the file is written to. Beware, you are allowed to create a swap file larger than you have free disk space.
Nuts, ignore my last message. If you try to turn on swap using the above you will get…
# swapon /swapfile
swapon: /swapfile: skipping – it appears to have holes.
You can use simple way
# dd if=/dev/zero of=/opt/swapfile bs=1M count=1024
1. block size is 1 MB
2. count=1024 means 1GB (swap file Size)
3. /opt/swapfile (location as you want swap file)
then
# mkswap /opt/swapfile
Do entry in Fstab
# swanon -a
#Like?#
swapon /swapfile
swapoff -a
dd if=/dev/zero of=/opt/swapfile bs=1M count=5700
mkswap /opt/swapfile
swanon -a
sysctl vm.swappiness=100
swapon /swapfile
#
swapon -s is useful in showing how much swap space and on what drives.
Normally I would prefer to make a swap partition rather then making a swap file. That way your swap space does not crash if your filesystem does. (ie if / has an issue, at least your swap memory is safer…. )
Very helpful article.
Ultimate ….i have no words for these documentation
Источник