Ubuntu как изменить swap

Contents

Contents

  1. Introduction
  2. What is swap?
  3. Why do I need swap?
  4. How much swap do I need?
  5. How do I add more swap?
  6. How do I add or modify a swap partition?
  7. How do I add a swap file?
  8. What is swappiness and how do I change it?
  9. What is the priority of swap containers?
  10. Should I reinstall with more swap?
  11. Why is my swap not being used?
  12. Empty Swap

Introduction

  • This FAQ is aimed at Linux novices.

  • People always wonder how much swap they should create at install time, or after installing they may think, «have I made a large enough swap? Should I reinstall with a larger swap?»
  • This FAQ will tell you how much swap you need and how to add more swap after installation.
  • You will be given very simple answers (to prevent losing too much time reading this FAQ) and some explanations that may help you form your own opinion.

What is swap?

Swap space is the area on a hard disk. It is a part of your machine’s Virtual Memory, which is a combination of accessible physical memory (RAM) and the swap space. Swap holds memory pages that are temporarily inactive. Swap space is used when your operating system decides that it needs physical memory for active processes and the amount of available (unused) physical memory is insufficient. When this happens, inactive pages from the physical memory are then moved into the swap space, freeing up that physical memory for other uses. Note that the access time for swap is slower, depending on the speed of the hard drive. Do not consider it to be a complete replacement for the physical memory. Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap file(s).

Why do I need swap?

Memory consuming programs Sometimes, a large program (like LibreOffice, Neverwinter Nights, or a video editor) make the entire system need extra memory. A significant number of the pages used by these large programs during its startup may only be used for initialization and then never used again. The system can swap out those pages and free the memory for other programs or even for the disk cache. In these cases, swap will be used to help the system handle any extra load.

Hibernation (suspend-to-disk) The hibernation feature (suspend-to-disk) writes out the contents of RAM to the swap partition before turning off the machine. Therefore, your swap partition should be at least as big as your RAM size. Although the latest versions of Ubuntu don’t support hibernation OOTB you may configure your system to allow Hibernation. In both alternatives (PM-UTILS or SYSTEMD) you may use a partition or a file.

Unforeseeable Circumstances Unforeseeable events can and will happen (a program going crazy, some action needing much more space than you thought, or any other unpredictable combination of events). In these cases, swap can give you an extra delay to figure out what happened, or to finish what you are working on.

Optimizing memory usage Since mechanical hard drives are considerably slower than RAM (SSD — Solid State Drive — storage is not as slow as physical drives, but still slower than RAM), when you need a file (be it a data file like a video, executables like Firefox, or libraries), the Linux kernel reads the file into RAM and keeps it there, so that the next time you need it, it is already in RAM and data access is much faster. The portions of RAM that accelerate disk read are called «cached memory.» You will notice that they make a huge difference in terms of responsiveness. The Linux kernel automatically moves RAM reserved by programs—but not really used—into swap, so that it can serve the better purpose of extending cached memory.

Optimizing Swap performance Because swap space uses a disk device, this can cause performance issues in any system that uses swap space significantly because the system itself may also be using the same disk device at the same time that it is required for swap operations. One way to reduce this problem is to have swap space on a different physical drive so that the competition for that resource is either reduced or eliminated.

How much swap do I need?

For less than 1GB of physical memory (RAM), it’s highly recommended that the swap space should, as a base minimum, be equal to the amount of RAM. Also, it’s recommended that the swap space is maximum twice the amount of RAM depending upon the amount of hard disk space available for the system because of diminishing returns.

For more modern systems (>1GB), your swap space should be at a minimum be equal to your physical memory (RAM) size «if you use hibernation», otherwise you need a minimum of round(sqrt(RAM)) and a maximum of twice the amount of RAM. The only downside to having more swap space than you will actually use, is the disk space you will be reserving for it.

The «diminishing returns» means that if you need more swap space than twice your RAM size, you’d better add more RAM as Hard Disk Drive (HDD) access is about 10³ slower then RAM access, so something that would take 1 second, suddenly takes more then 15 minutes! And still more than a minute on a fast Solid State Drive (SSD)…

Example Scenarios

(last 3 columns denote swap space)

        RAM   No hibernation    With Hibernation  Maximum
      256MB            256MB               512MB    512MB 
      512MB            512MB              1024MB   1024MB
     1024MB           1024MB              2048MB   2048MB

        RAM   No hibernation    With Hibernation  Maximum
        1GB              1GB                 2GB      2GB
        2GB              1GB                 3GB      4GB
        3GB              2GB                 5GB      6GB
        4GB              2GB                 6GB      8GB
        5GB              2GB                 7GB     10GB
        6GB              2GB                 8GB     12GB
        8GB              3GB                11GB     16GB
       12GB              3GB                15GB     24GB
       16GB              4GB                20GB     32GB
       24GB              5GB                29GB     48GB
       32GB              6GB                38GB     64GB
       64GB              8GB                72GB    128GB
      128GB             11GB               139GB    256GB
      256GB             16GB               272GB    512GB
      512GB             23GB               535GB      1TB
        1TB             32GB              1056GB      2TB
        2TB             46GB              2094GB      4TB
        4TB             64GB              4160GB      8TB
        8TB             91GB              8283GB     16TB

How do I add more swap?

Swap is generally associated with a swap partition, perhaps because the user is prompted to create a swap partition at the time of installation. In fact, any file can be used as a swapping device, be it a partition or a conventional file. Swap can be added by increasing the size of the swap partition or by adding a swap file. Keep in mind that when creating a swap file that it may not necessarily be using contiguous disk blocks (as a swap partition will), and this could have a negative impact on performance as disk access times may be longer, and the more your system uses swap, the worse it will be. The Linux kernel also accesses swap disk block IO directly bypassing all caching, metadata and filesystem code, so a swap file should have no ill effect on the stability of your base filesystem. Since kernel 2.6.29 the swap system has automatically supported TRIM capable devices like SSDs.

The advantages of a swap file are many, but it is problematic for using the default swsusp hibernation method for powerless sleep. The best solution for maintaining hibernate capability after adding RAM is to increase the size of the swap partition.

How do I add or modify a swap partition?

Process to Increase Size of Swap Partition and use it for Hibernation

  • Creating the swap partition
  • Activating the swap partition
  • Making the new swap partition work for hibernate (optional)

Creating the swap partition

  1. Boot to Ubuntu install CD and choose the option to run Ubuntu now
  2. Go to system -> GParted Partition Editor

  3. Delete the swap partition and, if there is nothing else in it, the extended partition that holds it. (If by some miracle you’re able to resize your swap partition from here, I imagine your life will be a lot easier than mine.)
  4. Decrease the size of your primary partition by the amount you want your new swap to be (I made mine 2x RAM + 500MB just to be safe). The easiest way to do this is to fill in the amount of space you want swap to be in the «free space following» field
  5. In the free space that has now been created, choose new, type linux-swap and you can name the partition «swap» if you like
  6. Hit the *Apply* button (should be a check mark) to write the changes to disk
  7. When done, reboot back into Ubuntu

Activating the swap partition

(If your swap is on your primary hard drive, you don’t need to do anything here.) Now you need to find what partition your swap is on and what its UUID is. UUID?! you say? Well that’s the Universally Unique IDentifier for the partition so you can reference it even if it’s on a different mount point from boot-to-boot due to adding disks, etc.

  1. Pull up a terminal and run gksu gparted & and enter your root password. The & lets this process run while still giving you access to the command line.

  2. Right-click on your swap partition and choose *Information*. You should see the **Path** and **UUID** listed there. Keep this open for further reference.
  3. Run gksu gedit /etc/fstab & and look for the line that has *swap* in it. It should be the third column, separated by spaces or tabs. You can either use the path or the UUID to tell Linux where to find your swap partition. I recommend UUID because it’ll stay constant even if you move the partition around or the disk somehow becomes sdb instead of sda or something like that. Make the appropriate edits and save the file. Your line should look something like this if you used UUID (with your UUID instead, of course):

    • UUID=41e86209-3802-424b-9a9d-d7683142dab7 none swap sw 0 0

    • or this if you used path: /dev/sda2 none swap sw 0 0

  4. Save the file.
  5. Enable the new swap partition with this command.

    sudo swapon --all

    OR

    $ sudo swapon --all --verbose
    swapon on /dev/sda2
    swapon: /dev/sda2: found swap signature: version 1, page-size 4, same byte order
    swapon: /dev/sda2: pagesize=4096, swapsize=2147483648, devsize=2147483648

  6. Confirm that the swap partition exists.

    $ cat /proc/swaps
    Filename                                Type            Size    Used    Priority
    /dev/sda2                               partition       2097148 0       -1

  7. Reboot to make sure the new swap gets activated properly at startup

Making the swap partition work for hibernate (optional)

‘INFO: This will not work for 12.04, resume from hibernate work differently in 12.04.

  1. Pull up a Terminal again and run cat /proc/swaps and hopefully you see the path to your swap partition listed there. If not chances are something went wrong in the steps above. Here’s my output:

Filename                                Type            Size    Used    Priority
/dev/sda2                               partition       2676732 73380   -1
  1. gksu gedit /etc/default/grub & to pull up the boot loader configuration

  2. Look for the line GRUB_CMDLINE_LINUX=»» and make sure it looks like this (using your UUID of course) GRUB_CMDLINE_LINUX=»resume=UUID=41e86209-3802-424b-9a9d-d7683142dab7″ and save the file

  3. sudo update-grub and wait for it to finish

  4. gksu gedit /etc/initramfs-tools/conf.d/resume & and make sure its contents are resume=UUID=41e86209-3802-424b-9a9d-d7683142dab7 (with your UUID of course in place of mine). Save the file!

  5. sudo update-initramfs -u

  6. Reboot!

Now you should be able to hibernate and resume!

How do I add a swap file?

Note: btrfs does not support swap files at the moment. See man swapon. and btrfs Faq

Create the Swap File:

We will create a 1 GiB file (/mnt/1GiB.swap) to use as swap:

sudo dd if=/dev/zero of=/mnt/1GiB.swap bs=1024 count=1048576

We need to set the swap file permissions to 600 to prevent other users from being able to read potentially sensitive information from the swap file.

sudo chmod 600 /mnt/1GiB.swap

Format the file as swap:

sudo mkswap /mnt/1GiB.swap

Enable use of Swap File

sudo swapon /mnt/1GiB.swap

The additional swap is now available and verified with: cat /proc/swaps

Enable Swap File at Bootup

Add the swap file details to /etc/fstab so it will be available at bootup:

echo '/mnt/1GiB.swap swap swap defaults 0 0' | sudo tee -a /etc/fstab

Example of making a swap file

This is an example of making and using a swap file on a computer with no swap partition.

$ sudo fallocate -l 1g /mnt/1GiB.swap
$ sudo chmod 600 /mnt/1GiB.swap
$ sudo mkswap /mnt/1GiB.swap
Setting up swapspace version 1, size = 1048576 kB
$ sudo swapon /mnt/1GiB.swap
$ cat /proc/swaps 
Filename                                Type            Size    Used    Priority
/home/swapfile                          file            1048576 1048576 -1
$ echo '/mnt/4GiB.swap swap swap defaults 0 0' | sudo tee -a /etc/fstab
$ reboot
$ free -h
              total        used        free      shared  buff/cache   available
Mem:            15G        9.3G        454M        4.0G        5.8G        1.9G
Swap:          1.0G        1.0G          0B

Disable and Remove a Swap File

Disable the swap file from the running system and the delete it:

sudo swapoff /mnt/1Gib.swap 
sudo rm /mnt/1Gib.swap

Remove the swap file details from fstab:

gksudo gedit /etc/fstab

Removing the swap file line

/mnt/1GiB.swap swap swap defaults 0 0

What is swappiness and how do I change it?

The swappiness parameter controls the tendency of the kernel to move processes out of physical memory and onto the swap disk. Because disks are much slower than RAM, this can lead to slower response times for system and applications if processes are too aggressively moved out of memory.

  • swappiness can have a value of between 0 and 100
  • swappiness=0 tells the kernel to avoid swapping processes out of physical memory for as long as possible
  • swappiness=100 tells the kernel to aggressively swap processes out of physical memory and move them to swap cache

The default setting in Ubuntu is swappiness=60. Reducing the default value of swappiness will probably improve overall performance for a typical Ubuntu desktop installation. A value of swappiness=10 is recommended, but feel free to experiment. Note: Ubuntu server installations have different performance requirements to desktop systems, and the default value of 60 is likely more suitable.

To check the swappiness value

cat /proc/sys/vm/swappiness

To change the swappiness value A temporary change (lost on reboot) with a swappiness value of 10 can be made with

sudo sysctl vm.swappiness=10

To make a change permanent, edit the configuration file with your favorite editor:

gksudo gedit /etc/sysctl.conf

Search for vm.swappiness and change its value as desired. If vm.swappiness does not exist, add it to the end of the file like so:

vm.swappiness=10

Save the file and reboot.

What is the priority of swap containers?

The Linux kernel assigns priorities to all swap containers. To see the priorities that the Linux Kernel assigns to all the swap containers use this command.

cat /proc/swaps

Priorities can be changed by using the swapon command or defined in /etc/fstab. Consult the manual page of swapon for more info

man swapon

Should I reinstall with more swap?

Definitely not. With the 2.6 kernel, «a swap file is just as fast as a swap partition.» (Wikipedia:Paging, LKML).

Why is my swap not being used?

My swap is not being used! When I issue the free command, it shows something like this:

tom@tom:~$ free
             total       used       free     shared    buffers     cached
Mem:        515980     448664      67316          0      17872     246348
-/+ buffers/cache:     184444     331536
Swap:       674688          0     674688

Note: This regards mainly swap on hard disk partitions, but it could help anyway. In these examples /dev/hda8 is considered as swap.

Swap may not be needed

Start many memory consuming applications (e.g. Gimp, web browsers, LibreOffice etc) and then issue the free command again. Is swap being used now?

Ubuntu Desktop uses Swap to Hibernate (PC off, no power needed, program states saved). If Hibernation is important to you, have more swap space than ram + swap overflow.

Is there a swap partition at all?

Use this command to see all partitions

sudo parted --list

You should be able to see something like this in the output

 5      236GB   256GB   20.0GB  linux-swap(v1)

If not, you either need to create a swapfile or create a swap partition. To create a swap partition you can

  • boot from your Ubuntu install CD, create a swap partition out of the free space on your hard disk and then interrupt your installation.
  • use Cfdisk.

Enabling a swap partition

In case you do have a swap partition, there are several ways of enabling it.

  • Use the following command
    cat /etc/fstab

  • Ensure that there is a line link below. This enables swap on boot.
    /dev/sdb5       none            swap    sw              0       0

  • Then disable all swap, recreate it, then re-enable it with the following commands.
    sudo swapoff -a
    sudo /sbin/mkswap /dev/sdb5
    sudo swapon -a

Empty Swap

Even if you have lots of RAM and even if you have a low swappiness value, it is possible that your computer swaps. This can hurt the multitasking performance of your desktop system.

You can use the following script to get the swap manually back into RAM:

  • Place the script e.g. /usr/local/sbin:
    gksudo gedit /usr/local/sbin/swap2ram.sh

  • Copy-paste the script into the file:
  • #!/bin/sh
    
    mem=$(LC_ALL=C free  | awk '/Mem:/ {print $4}')
    swap=$(LC_ALL=C free | awk '/Swap:/ {print $3}')
    
    if [ $mem -lt $swap ]; then
        echo "ERROR: not enough RAM to write swap back, nothing done" >&2
        exit 1
    fi
    
    swapoff -a &&
    swapon -a

  • Save and close gedit
  • Make the script executable:
    sudo chmod +x /usr/local/sbin/swap2ram.sh

  • Execute:
    sudo /usr/local/sbin/swap2ram.sh


CategoryFaq

Содержание

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 следует учесть следующие аспекты:

  1. Каков размер оперативной памяти?

  2. Какие приложения будут использоваться?

  3. Будет ли вестись работа с секретными данными?

  4. Нужен ли режим сна (suspend to disk)?

В зависимости от ответов на эти вопросы рекомендации по размеру 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:

sudo mkswap /dev/sdc2

Подключим раздел как SWAP:

sudo swapon /dev/sdc2

Проверить результат можно, посмотрев на вывод команды

sudo swapon -s

Сделаем автомонтирование SWAP-раздела при запуске системы. Узнаем UUID раздела:

sudo blkid

Теперь пропишем строку в /etc/fstab

echo "UUID=<UUID swap-раздела> swap swap defaults,pri=<Приоритет (от 0 до 32767)> 0 0"| sudo tee -a /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. Пример:

echo "vm.swappiness=30"| sudo tee -a /etc/sysctl.conf

Мгновенно применить эту настройку можно с помощью следующей команды:

# sysctl -f

Актуальное значение, используемое ядром в настоящее время, можно просмотреть или изменить в /proc/sys/vm/swappiness.

# cat /proc/sys/vm/swappiness
# echo 10 > /proc/sys/vm/swappiness

Изменения в /proc/sys/vm/swappiness будут сброшены при следующей перезагрузке.

Значение vm.swappiness по умолчанию — 60.

Какое значение выбрать?

Маленькое значение vm.swappiness (минимальное значение: 0) будет заставлять ядро использовать больше оперативной памяти под память процессов (в ущерб буферам и кэшам), тогда как большое значение (максимальное значение: 100) будет выделять больше памяти под кэши и буфера (в ущерб памяти для процессов).

Нужно понимать: ни одно значение vm.swappiness не увеличит волшебным образом производительность компьютера многократно. Урезаете кеши — понижаете отзывчивость системы при работе с файлами, урезаете память процессов — снижаете отзывчивость системы при переключении задач.

Нужное вам значение, скорее всего, стоит подбирать экспериментально.

Смотрите также

Ссылки

Оперативная память имеет очень важное значение для нормальной работы компьютера. В ней размещаются все программы и их данные во время работоспособности устройства. Когда память переполняется, программы могут выдавать различные ошибки или даже прекращать работу. Время отклика системы увеличивается настолько, что работать с ней становиться невозможным.

Самый простой способ увеличить количество оперативной памяти и защитить систему от переполнения памяти, это добавить раздел swap в Ubuntu. В этой статье будет рассмотрено как выполняется настройка swap в Ubuntu 20.04. Будет рассмотрен вариант с добавлением swap как на время работы устройства, так и на постоянное использование.

Обратите внимание

Хотя использование раздела подкачки на жестком диске HDD это привычное явление, применение такого метода для SSD может вызвать проблемы. SSD имеет ограниченное количество перезаписей одного сектора, а область swap постоянно перезаписывается, это очень сильно снизит срок службы вашего диска. Поэтому использование swap пространства на SSD строго не рекомендуется.

Swap (так же известна как пространство подкачки) — это область на жестком диске, которая используется для временного хранения данных из оперативной памяти, для которых там больше нет места. Это позволяет увеличить объем информации, которую система может хранить в рабочей памяти. Пространство подкачки используется только тогда, когда память уже полностью занята, и туда будут помещаться только данные, которые давно использовались.

Работа с информацией будет выполняться намного медленнее, чем в оперативной памяти, но операционная система будет продолжать работать и использовать swap только для старых данных. В целом, это может быть отличной защитой от переполнения оперативной памяти. Пространство подкачки можно настроить двумя способами, добавив раздел подкачки для Ubuntu на диске или создать файл подкачки.

Проверка Swap

Перед тем как перейти к настройке необходимо проверить не подключены ли разделы подкачки к системе. Для этого необходимо выполнить команду:

swapon --show

Если команда вернет строчку с названием swapfile, это означает что swap в системе уже присутствует:

qJQ2DxsvBYQAAAAASUVORK5CYII=

Если ничего не будет выведено, значит в системе swap не настроен:

A3cY5FQKomDiAAAAAElFTkSuQmCC

Также можно убедиться, что swap активирован или не активирован в системе с помощью утилиты free которая помимо отображения объёма оперативной памяти также отображает информацию об разделе swap:

free -h

Строка со swap отображает значение 2,0 GB. Это означает что swap включен и будет использоваться 2 ГБ жёсткого диска, когда память будет переполнена:

wPh8SYp013UQwAAAABJRU5ErkJggg==

Если значения в разделе swap отображаются по нулям это значит, что раздел swap не подключен:

UBzAeNQ8JV+GsqUS+iVd7P8BIqvvLekDC5MAAAAASUVORK5CYII=

Настройка файла подкачки в Ubuntu 20.04

На серверах часто используется файл подкачки, такой способ применяется, потому что не всегда есть возможность менять разметку диска для выделения раздела swap.

1. Проверка места на диске

Необходимо убедится, что на жёстком диске есть достаточно свободного места. Самый простой способ узнать количество свободного места в терминале – воспользоваться утилитой df:

df -h

+XxBVBSAALDlaAAAAAElFTkSuQmCC

В данном случае есть достаточно места для размещения и увеличения пространства подкачки. Размер swap в Ubuntu 20.04 зависит от потребностей. Обычно рекомендуют использовать объем в два раза больше, чем реальный размер оперативной памяти. Но как правило больше 4 Гб использовать не нужно. Если планируется использовать гибернацию на персональном компьютере, то нужно использовать объем, равный объему ОЗУ.

2. Создание файла подкачки

Самый быстрый способ создать swap файл в Ubuntu 20.04 – это использовать утилиту fallocate, она создает файл нужного размера мгновенно. Поскольку в качестве примера используется машина с 8 Гб оперативной памяти, необходимо добавить раздел подкачки на 3 Гб. Для этого необходимо выполнить команду:

sudo fallocate -l 3G /swapfile

SiSMholxvNzbOT14P8BylQiMlDAoy4AAAAASUVORK5CYII=

Далее, необходимо убедиться действительно ли зарезервировано нужное количество памяти. Для проверки необходимо выполнить команду:

ls -lh /swapfile

fBG1QUdPg9+33f4fgtonZcmABAAAAAElFTkSuQmCC

Активация swap

Когда файл готов, необходимо превратить его в файл swap. Сначала нужно заблокировать доступ к нему всем кроме суперпользователя. Для этого необходимо выполнить:

sudo chmod 600 /swapfile

Теперь только пользователь root может читать и изменить данный файл:

ls -lh /swapfile

8HGmNHSI0QOR0AAAAASUVORK5CYII=

Далее необходимо создать файловую систему swap командой:

sudo mkswap /swapfile

wHzZy75GQ2mTwAAAABJRU5ErkJggg==

Когда файл будет размещен и промаркирован необходимо включить файл подкачки чтобы начать его использовать:

sudo swapon /swapfile

v9x1DKSlc9uMgAAAABJRU5ErkJggg==

После этого можно убедиться, что swap включен, выполнив команду:

swapon --show

ob4+lbrbVzVelggXPXzf8PzYN09Od4zasAAAAASUVORK5CYII=

Так же наличие swap можно проверить при помощи утилиты free, выполнив команду:

free -h

x+0OpXwVbrkTQAAAABJRU5ErkJggg==

Файл подкачки был успешно создан и активирован. Теперь памяти доступно больше и система не зависнет при нехватке оперативной памяти. Но данный способ будет работать только до перезагрузки устройства.

Постоянный файл подкачки

Как уже было сказано ранее, данный swap будет работать только до перезагрузки сервера или компьютера. Чтобы настройка swap в Ubuntu 20.04 сохранялась после перезагрузки нужно отредактировать файл /etc/fstab. Можно вручную добавить строку в файл, но также можно использовать следующую команду:

echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

wUGkEFAhJkf4QAAAABJRU5ErkJggg==

Настройка раздела подкачки в Ubuntu 20.04

Настройка swap в Ubuntu 20.04 в виде раздела аналогична тем же методам, которые применяются для создания swap в виде файла, отличие только в том, что вместо файла используется раздел. Предположим, необходимо использовать раздел /dev/sda2. Сначала необходимо создать swap из обычного раздела:

sudo mkswap /dev/sda2

Далее активировать раздел подкачки:

sudo swapon /dev/sda2

И проверить все ли прошло правильно:

swapon --show

Если да, то в списке подключенных разделов отобразится нужный. Последним шагом остаётся добавить строку в /etc/fstab для автоматической активации после перезагрузки:

echo '/dev/sda2 none swap sw 0 0' | sudo tee -a /etc/fstab

Дополнительные настройки

Можно контролировать интенсивность использования пространства подкачки в Ubuntu 20.04 с помощью параметра ядра swappiness:

cat /proc/sys/vm/swappiness

wMf6qQE4DRUfgAAAABJRU5ErkJggg==

По умолчанию установлено значение 60. Если это значение ближе к 100, система будет пытаться поместить в подкачку больше данных и сберечь память, при значениях близких к нулю, ядро не переносит данные на диск, если в этом нет крайней необходимости. Этот вариант может сделать систему быстрее, особенно актуально для домашних компьютеров.

Чтобы установить значение 10 необходимо выполнить команду:

sudo sysctl vm.swappiness=10

lP1App8xjPQAAAAASUVORK5CYII=

А для сохранения этой настройки после перезагрузки:

sudo sysctl -w vm.swappiness=10

w879gLuUtXoKgAAAABJRU5ErkJggg==

Другой параметр, который влияет на количество используемой памяти —vfs_cache_pressure. Он указывает системе какое время нужно хранить открытые файлы в кэше оперативной памяти. Значение 100 заставляет систему удалять такие файлы очень быстро, 0 — держать их в памяти как можно дольше. Проверить текущее состояние можно при помощи команды:

cat /proc/sys/vm/vfs_cache_pressure

2IgWfMNN7QwAAAABJRU5ErkJggg==

Чтобы хранить файлы дольше, можно установить значение в 50 используя команду:

sudo sysctl -w vm.vfs_cache_pressure=50

B7v8POBFbt7CZog4AAAAASUVORK5CYII=

Выводы

С помощью данной инструкции можно на время решить проблему с пространством подкачки если серверу недостаточно памяти, или поможет предотвратить компьютер от зависания. Настройка swap в Ubuntu 20.04 выполняется очень просто. Если у вас остались вопросы, спрашивайте в комментариях!

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

(this answer completely rewritten since the downvote)

Notes about fallocate vs dd

Before we continue, I want to point out that some answers use fallocate to allocate space for a file, instead of dd. Don’t do that. Use dd. @muru pointed out some important points here and here. Although fallocate is much much faster, it may create files with holes. I think that simply means the space is not contiguous, which is bad for swap files. I picture this as meaning that fallocate creates a C-style linked-list of memory, whereas dd creates a C-array contiguous block of memory. Swap files need a contiguous block. dd does this by doing a byte-for-byte copy of binary zeros from the /dev/zero pseudo-file into a new file it generates.

man swapon also states not to use fallocate, and to use dd instead. Here is the quote (emphasis added):

NOTES

You should not use swapon on a file with holes. This can be seen in
the system log as

swapon: swapfile has holes.

The swap file implementation in the kernel expects to be able to
write to the file directly, without the assistance of the filesystem. This is a problem on preallocated files (e.g. fallocate(1)) on filesystems like XFS or ext4, and on copy-on-write filesystems like btrfs.

It is recommended to use dd(1) and /dev/zero to avoid holes on XFS and ext4.

And from man mkswap (emphasis added):

Note that a swap file must not contain any holes. Using cp(1) to
create the file is not acceptable. Neither is use of fallocate(1)
on file systems that support preallocated files, such as XFS or
ext4, or on copy-on-write filesystems like btrfs. It is recommended to use dd(1) and /dev/zero in these cases. Please read notes from swapon(8) before adding a swap file to copy-on-write filesystems.

So, use dd, not fallocate, to create the swap files.

Option 1 (my preference): delete the old swap file and create a new one of the correct size:

Rather than resizing the swap file, just delete it and create a new one at the appropriate size!

swapon --show               # see what swap files you have active
sudo swapoff /swapfile      # disable /swapfile
# Create a new 16 GiB swap file in its place (could lock up your computer 
# for a few minutes if using a spinning Hard Disk Drive [HDD], so be patient)
sudo dd if=/dev/zero of=/swapfile count=16 bs=1G
sudo mkswap /swapfile       # turn this new file into swap space
sudo chmod 0600 /swapfile   # only let root read from/write to it, for security
sudo swapon /swapfile       # enable it
swapon --show               # ensure it is now active

In case you are adding this swap file for the first time, ensure it is in your /etc/fstab file to make the swap file available again after each reboot. Just run these two commands:

# Make a backup copy of your /etc/fstab file just in case you
# make any mistakes
sudo cp /etc/fstab /etc/fstab.bak
# Add this swapfile entry to the end of the file to re-enable
# the swap file after each boot
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

Source: see the «Step 4: Make the changes permanent» section here.

Option 2: resize the old swap file:

The accepted answer by @Ravexina is correct. However, initially I didn’t understand all of its pieces, so I wanted to include some more descriptions and explain more of the details. See dd --help and man dd. Some of my learning on this comes from Bogdan Cornianu’s blog post as well. I also add a few commands at the end to show how to verify your swap space once you create it.

How to resize swap file:

Here we will increase the size of the existing swap file by writing 8 GiB (Gibibytes) of zeros to the end of it.

  1. Turn off usage of just this one swap file (located at «/swapfile«):

     # Do this
     sudo swapoff /swapfile
    
     # NOT this, which unnecessarily disables all swap files or partitions
     # sudo swapoff --all
     # or
     # sudo swapoff -a
    
  2. Increase the size of the swap file by 8 GiB by appending all zero bytes to the end of it (rather than rewriting the whole file, which would be slower):

     sudo dd if=/dev/zero of=/swapfile bs=1G count=8 oflag=append conv=notrunc
    
    • if = input file

    • /dev/zero = a special Linux «file» which just outputs all zero bytes every time you read from it

    • of = output file

    • bs = block size

      • Here, 1G stands for 1 Gibibyte, or GiB, which is the base-2 version of «Gigabyte, which is base-10. According to man dd, G =1024*1024*1024 bytes. This is how I like to size files since computers and hardware memory are base-2.
      • If you’d like to use 1 Gigabyte, or GB, which is the base-10 version of «Gibibyte», which is base-2, then you must instead use 1GB rather than 1G. man dd shows that GB =1000*1000*1000 bytes.
    • count = multiplier of blocks; the total memory written will be count * bs.

    • oflag=append means to append to the end of the output file, rather than rewriting the whole thing. See dd --help and man dd. From dd --help:

      append    append mode (makes sense only for output; conv=notrunc suggested)
      
    • conv=notrunc means when «converting» the file, «do not truncate the output file»; dd --help, as you can see just above, shows this is recomended whenever doing oflag=append

    • Note: if you wanted to rewrite the whole swap file rather than just appending to it, you could create a 32 GiB swapfile like this, for example:

        sudo dd if=/dev/zero of=/swapfile bs=1G count=32
      
  3. Make the file usable as swap

     sudo mkswap /swapfile
    
  4. Turn on the swap file

     sudo swapon /swapfile
    
  5. (Bonus/Optional): ensure this swap file you just created is now in usage:

     swapon --show
    

    Sample output:

    $ swapon --show
    NAME      TYPE SIZE USED PRIO
    /swapfile file  64G 1.8G   -2
    

    You can also look at some memory/swap info with these two commands as well:

     # 1. Examine the /proc/meminfo file for entries named "swap", such 
     # as the "SwapTotal" line
     cat /proc/meminfo | grep -B 1000 -A 1000 -i swap
    
     # 2. Look at total memory (RAM) and swap (virtual memory) used
     # and free:
     free -h
    

References:

  1. @Ravexina’s answer
  2. Bogdan Cornianu’s blog post here: https://bogdancornianu.com/change-swap-size-in-ubuntu/
  3. «How to Create and Use Swap File on Linux»: https://itsfoss.com/create-swap-file-linux/

See also:

  1. My answer where I use the above information about increasing your swapfile size in order to solve an out-of-memory Bazel build error: Stack Overflow: java.lang.OutOfMemoryError when running bazel build

Though for the most part Linux applications run just fine, it’s not uncommon to run into «Out of Memory» errors when using particularly performance-intensive programs. As you may have gathered, this occurs when your server does not have enough RAM to hold the application in memory. This can be remedied with Ubuntu swap space, which we’ll show you how to adjust today.

What is Swap Space in Linux?

Swap, which you may know as the paging file or page file on Windows, is space set aside by the operating system to temporarily hold information that it can’t hold in RAM. Rather than throw up errors and force you to close other applications, Ubuntu «swaps» some of the information that’s in memory to a hard drive for later use.

This is not ideal – there’s a reason that PC’s have RAM instead of just regular hard drives – but it’s better than data loss. Though hard drives have the advantage of offering non-volatile storage, they’re much slower than RAM. As a result, the overall experience is likely to be degraded if you use a system than runs out of memory frequently. Essentially, It’s always better to have more RAM than you need, but Swap Space can protect against out-of-memory exceptions in a pinch.

Generally, though, you should be careful using swap storage if your server or personal system is using a Solid State Drive (SSD). As SSDs have a limited amount of writes in its lifespan, constantly swapping out data from the SSD to RAM can quickly degrade the drive.

If it’s very rare that you exceed your RAM, this isn’t likely to cause major issues, but for systems with low memory and an SSD, it’s not recommended.

How to Check Swap Space in Linux

It’s always a good idea to check how much Ubuntu swap space (if any) your system has before adjusting it. You can do so with the following command:

sudo swapon --show

If the command returns nothing, it means you don’t currently have any swap space configured. If you want to verify this, type:

free -h

total        used        free      shared  buff/cache   available
Mem:          991Mi       221Mi        67Mi       0.0Ki       702Mi       753Mi
Swap:            0B          0B          0B

Now we can move onto the next step – making sure your hard drive has enough space to create a swap file. Enter:

df -h

The output will look something like this:

Filesystem      Size  Used Avail Use% Mounted on
/dev/root        25G  4.7G   20G  20% /
devtmpfs        494M     0  494M   0% /dev
tmpfs           496M  8.0K  496M   1% /dev/shm
tmpfs           100M  488K   99M   1% /run
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           496M     0  496M   0% /sys/fs/cgroup
/dev/sda15      105M  9.1M   96M   9% /boot/efi
/dev/loop0       72M   72M     0 100% /snap/lxd/16530
/dev/loop1       55M   55M     0 100% /snap/core18/1880
/dev/loop5       30M   30M     0 100% /snap/snapd/8542
/dev/loop6       56M   56M     0 100% /snap/core18/1885
/dev/loop2       72M   72M     0 100% /snap/lxd/16723
/dev/loop4       30M   30M     0 100% /snap/snapd/8790
tmpfs           100M     0  100M   0% /run/user/0

The column /dev/root, which is mounted on / is our drive in this scenario. You can see that 4.7 GB out of 20 has been used, or a total of 20%. That gives us plenty to play with, considering that our server has 1 GB of RAM and it’s unlikely to even double that.

Here’s a helpful table from the Ubuntu community help wiki:

RAM No hibernation With Hibernation Maximum
256 MB 256 MB 256 MB 512 MB
512 MB 512 MB 1024 MB 1024 MB
1024 MB 1024 MB 2048 MB 2048 MB
1 GB 1 GB 2GB 2GB
2 GB 1 GB 3 GB 4 GB
3 GB 2 GB 5 GB 6 GB
4 GB 2 GB 6 GB 8 GB
5 GB 2 GB 7 GB 10 GB
6 GB 2 GB 8 GB 12 GB
8 GB 3 GB 11 GB 16 GB
12 GB 3 GB 15 GB 24 GB
16 GB 4 GB 20 GB 32 GB
24 GB 5 GB 29 GB 48 GB
32 GB 6 GB 38 GB 64 GB
64 GB 8 GB 72 GB 128 GB
128 GB 11 GB 139 GB 256 GB

Keep in mind that you’ll need a large page file if your system has hibernation enabled, as it writes the contents of the RAM to swap on shutdown.

How to Create a Swap File and Increase Swap Space

Now that we’ve verified it’s safe to proceed we can craft our swap file. There are a few ways to do this, but the easiest is via the fallocate program, which lets us allocate the exact size we want our swapfile to be.

As mentioned earlier, our server has 1 GB of RAM. We’re going to set our swapfile to 2 GB because we have plenty of free space, but 1 GB of swap would likely work just fine if we didn’t:

cd
sudo fallocate -l 2G /swapfile

As we didn’t specify a folder, our swapfile will be placed in our root directory, which is what we want. The command won’t give any output, so you can make sure the swap space was actually reserved with:

ls -lh /swapfile

In our case, the command returns:

-rw-r--r-- 1 root root 2.0G Aug 15 12:47 /swapfile

However, though we have space reserved for our swapfile, our system hasn’t yet be told this is where we want to it store information when out of memory. Before we do so, we want to make sure nobody but root can modify the file. Otherwise, an attacker could potentially use the file to perform an attack or steal information. Set the permissions with:

sudo chmod 600 /swapfile

Now verify that change using the same command as earlier:

ls -lh /swapfile

The output should have changed from rw-r--r-- 1 root root to -rw------- 1 root root 2.0G Aug 15 12:47 /swapfile, indicating that now only root has the read and write flags enabled.

With that done, dedicate the file as swap space by entering:

sudo mkswap /swapfile

The output should say something like:

`Setting up swapspace version 1, size = 2 GiB (2147479552 bytes)
no label, UUID=f9429158-ec78-4dce-98c0-986167b47016`

Now we just need to enable the swap file:

sudo swapon /swapfile

And verify that it’s available via the check commands from earlier:

sudo swapon --show

NAME      TYPE SIZE USED PRIO
/swapfile file   2G   0B   -2

free -h

              total        used        free      shared  buff/cache   available
Mem:          991Mi       222Mi        28Mi       0.0Ki       740Mi       752Mi
Swap:         2.0Gi          0B       2.0Gi

How to Make a Swap File Permanent and Adjust its Settings

Though we’ve technically created out swap space now, the changes won’t persist across a reboot unless we take further action. We remedy this by adding the swap file to /etc/fstab, Unix’s system configuration file:

sudo cp /etc/fstab /etc/fstab.bak
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

The first command backed up our old fstab file, so if anything goes wrong you should roll back to that. Now we can talk about configuration. Here are some of the most commonly adjusted options and their purpose:

  • Swappiness: How often your PC swaps data from RAM to your swap space. A value of 0 to 100, denoting the percentage of available RAM you want it to swap at.
  • Cache pressure: How often the system caches inode and dentry (file system) data. This often performance intensive and worth caching. The 0 to 100 value signifies how much the system will choose to cache.

How to Change Swapiness

You can see your current swapiness value by entering:

cat /proc/sys/vm/swappiness

By default, your swapiness value is probably 60. For reference, at 1 the kernel won’t swap data out of memory unless it would experience serious issues otherwise. At 99, the system will try to keep memory space free by swapping information into memory quite aggressively. At 60, it’ll swap when the RAM reaches 40% capacity.

It’s ultimately up to you what you set this to, but a guideline is a low value like 10 for a desktop installation with a good amount of RAM. For a server with low RAM, 60 could be a passable default value, but it’s worth experimenting with. Change it via the command:

sudo sysctl vm.swappiness=10

Once you’re happy, you can force it to persist across a reboot by adding the line to /etc/sysctl.conf. Type sudo nano /etc/sysctl.conf and add vm.swappiness=10 to the bottom of the file.

1.1-4

Press Crl+O to save, then Ctrl+X to exit.

Change your Cache Pressure Value

You can see your current cache pressure value by typing:

cat /proc/sys/vm/vfs_cache_pressure

The default will be 100, but 50 is generally a good number to start with. You can type sudo sysctl vm.vfs_cache_pressure=50 to set it for this boot.

To make the change permanent, add the vm.vfs_cache_pressure=50 to the bottom of your sysctl.conf with:

sudo nano /etc/sysctl.conf

1.2-3

Closing Words

Making these adjustments will almost always help your performance in Ubuntu 20.04 and prevent out of memory errors. Just make sure you aren’t too aggressive if you use an SSD or you could wear the hardware down slower.

However, it’s worth noting that even with these errors, with a low amount of RAM there’s only so much you can do. Tasks take far longer to complete on swap storage and you may still run into out of memory errors in some applications if you only have 1 GB. In these cases, it’s best to just upgrade your server. Jumping up a few gigabytes of RAM usually isn’t that expensive and can help a lot.

***Sign up to BitLaunch and grab a server with up to 32 GB of RAM for use with your Ubuntu swap space.

Понравилась статья? Поделить с друзьями:
  • Ue4 error 0x887a0006
  • Ubuntu журнал ошибок
  • Ue4 atlas fatal error как исправить
  • Ubuntu выдает ошибку при загрузке
  • Ue4 atlas engine fatal error crash