Linux swap partition delete

Создание, редактирование и удаление SWAP в Linux

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

Содержание

В системе Линукс для размещения виртуальной памяти можно выделить отдельный раздел жесткого диска или использовать обычный файл. Линукс позволяет комбинировать эти два способа. По умолчанию в Unix системах применяется SWAP раздел. Производительность отдельного SWAP раздела жесткого диска выше, чем производительность виртуальной памяти размещенной в файле. Единственным минусом SWAP раздела является сложность его редактирования.

Если Вы до эксплуатации сервера знаете какой емкости нужна SWAP область, то обязательно используйте отдельный раздел жесткого диска. Если нагрузка на SWAP область пока неизвестна, то лучше разместить виртуальную память в файле, после чего определив потребности системы, создать раздел нужного размера.

Система Linux позволяет одновременно использовать несколько SWAP разделов и SWAP файлов. Это позволяет более гибко подойти к вопросу расширения виртуальной памяти в случае нехватке размера SWAP области на сервере. Чаще всего, на работающем сервере с существующим SWAP разделом выясняется, что текущего размера виртуальной памяти уже не хватает. Целесообразнее добавить тестовый файл подкачки для определения нагрузки на SWAP область, а уже после увеличить размер раздела.

Создание, редактирование и удаление любых разделов из под загруженной в данный момент операционной системы не безопасно, поэтому создание SWAP раздела, вместо SWAP файла, делается только с использованием LiveCD. Статья на тему безопасного редактирования разделов будет написана в будущее время.

В системе Windows виртуальная память размещена только в отдельном файле — pagefile.sys (для Windows 2000 и выше) и win386.swp (для Windows 9x).

Для любой операционной системы, если используется спящий режим (Hebernation), размер виртуальной памяти следует делать не меньше объема оперативной памяти. В общих случаях наиболее эффективно использовать размер виртуальной памяти кратный 4 (1024 Мб, 2048 Мб и т.д.), так как ядро системы производит обмен страницами с памятью по 4 Кб в каждой. Размер виртуальной памяти легче посчитать от объема оперативной памяти *2, *3. Область подкачки стоит размещать на самом быстром жестком диске ближе к началу.

Хочу обратить Ваше внимани, что приведенные ниже инструкции касается только изменения размера ФАЙЛА ВИРТУАЛЬНОЙ ПАМЯТИ, а не изменение размера отдельной директории SWAP.

Ниже приведены пошаговые инструкции, которые позволят создать, изменить и удалить файл SWAP.

  1. Создаем файл необходимого размера для swap области, где /home/swap-tmp — это имя и путь файла, а count=1024K его размерв, в данном случае — 1024 Мб):

Редактировать файл fstab можно самостоятельно или командой, которая добавляет в конец файла fstab строку /home/swap-tmp swap swap defaults 0 0:

  1. Просматриваем все объекты, которые используются для размещения виртуальной памяти

Если Вы раньше добавляли строчку в fstab, для автоматической загрузки SWAP файла при старте операционной системы, то следует ее удалить. Выводим файл /etc/fstab для редактирования на экран:

Действия по редактирование объема SWAP файла сводятся к удалению уже созданного файла SWAP и созданию нового файла требуемого размера. То есть нужно сначало сделать пункт 3, а после пункт 2.

А что насчёт отдельных разделов? С ними как быть?
Или тоже достаточно удалить раздел и стереть его из fstab?

С разделами все так же, только следите, чтобы SWAP все же остался в каком-то виде. Я не знаю как будет работать Linux без SWAP , не даром, при установке ОС, объязательные разделы: / и своп

Линукс без SWAP работает нормально, если есть около 2Гб Ram и комп используется как десктоп. Сам только что создал раздел свопа только ради ресурсоемкого приложения.

Amiro: Линукс без SWAP работает нормально, если есть около 2Гб Ram и комп используется как десктоп. Сам только что создал раздел свопа только ради ресурсоемкого приложения.

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

P.S. В вашем случае я бы создал скрипт, который создает swap и запускает ресурсоемкое приложение. После завершения работы этого приложение удаляется swap файл. И повесил бы его на кнопку запуска приложения.

Mut@NT
P.S. В вашем случае я бы создал скрипт, который создает swap и запускает ресурсоемкое приложение. После завершения работы этого приложение удаляется swap файл. И повесил бы его на кнопку запуска приложения.

Файл свапа на машине с 2-мя гигами оперативы размерами в 4 гига около двух минут создаеться, устанеш ждать загрузку своего приложения

Spec: Файл свапа на машине с 2-мя гигами оперативы размерами в 4 гига около двух минут создаеться, устанеш ждать загрузку своего приложения

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

Mut@NT: P.S. В вашем случае я бы создал скрипт, который создает swap и запускает ресурсоемкое приложение. После завершения работы этого приложение удаляется swap файл. И повесил бы его на кнопку запуска приложения.

Вот только никакой гарантии что это будет всегда работать -нет.

Читайте также:  Outlook mac os exchange ���������

Может найтись такая программа(не ваше ресурсоёмкое приложение, а иная) , которая при недостатке памяти сбрасывает данные на диск(если malloc возвращает NULL ), а если память есть, то хранит их в памяти. в результате после отработки вашего приложения для которого создавался своп, в нём может оказаться куча данных других приложений которые просто не влезут в память при вытеснении их из свопа. Что начнёт после этого происходить с системой – тема для отдельного разговора. Если своп у вас есть, то его можно только наращивать, но никак не уменьшать , чтоб это было безопасно

Вы правы. В статье отражено лишь то, что это в Linux возможно

Куча ошибок в тексте.
> или добавить строчка для автоматической
или добавить строчку для автоматической

> которая будет используется ядром
которая будет использоваться ядром

Прошу прощения за возможно дилетантское высказывание, просто я лучше знаю Solaris. По вопросу производительности и объёма SWAP , у меня опыт такой. SWAP хотят некоторые приложения, например Oracle, в то же время подкачка это всегда узкое место (если только диск не SSD ). По этому если есть возможность вообще без подкачки, то производительность максимальная, с другой стороны по опыту и рекомендациям вендоров при озу до 2Гб размер SWAP =озу, до 4Гб 50% озу, до 1Тб где то от 16 до 32Гб, свыше терабайта можно давать 64Гб. Опять же зависит от приложения, например SAP требует чтобы при 32Гб памяти SWAP был не менее 20Гб.

Значек # подразумевает что sudo не нужно, ошибка в # sudo dd if=/dev/zero of=/home/swap-tmp bs=1024 count=1024K; правильно: # dd if=/dev/zero of=/home/swap-tmp bs=1024K count=1024

Источник

Ubuntu Documentation

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 then 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.

    Читайте также:  Windows usb from debian

    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 then a minute on a fast Solid State Drive (SSD).

    Example Scenarios

    (last 3 columns denote swap space)

    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

      Boot to Ubuntu install CD and choose the option to run Ubuntu now

    Go to system -> GParted Partition Editor

  • 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.)
  • 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
  • In the free space that has now been created, choose new, type linux-swap and you can name the partition «swap» if you like
  • Hit the *Apply* button (should be a check mark) to write the changes to disk
  • 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.

    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.
    Right-click on your swap partition and choose *Information*. You should see the **Path** and **UUID** listed there. Keep this open for further reference.

    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

    Save the file.

    Enable the new swap partition with this command.

    Confirm that the swap partition exists.

  • 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.

    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:

    Читайте также:  Windows как называется удаленный рабочий стол

    gksu gedit /etc/default/grub & to pull up the boot loader configuration

    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

    sudo update-grub and wait for it to finish

    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!

    sudo update-initramfs -u

  • 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:

    fallocate size suffixes: g = Giga, m = Mega, etc. (See man fallocate).

    If fallocate fails or it not available, you can use dd:

    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.

    Format the file as swap:

    Enable use of Swap File

    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:

    Example of making a swap file

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

    Disable and Remove a Swap File

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

    Remove the swap file details from fstab:

    Removing the swap file line

    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

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

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

    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:

    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.

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

    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:

    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

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

    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.

    Enabling a swap partition

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

    • Use the following command
    • Ensure that there is a line link below. This enables swap on boot.
    • Then disable all swap, recreate it, then re-enable it with the following commands.

    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:
    • Copy-paste the script into the file:

    NOTE: The first «#!» is MoinMoin synxtax for comments, so we must double the line http://moinmo.in/HelpOnMoinWikiSyntax#Comments

    • Save and close gedit
    • Make the script executable:
    • Execute:

    SwapFaq (последним исправлял пользователь zubzou 2019-12-19 12:51:11)

    The material on this wiki is available under a free license, see Copyright / License for details
    You can contribute to this wiki, see Wiki Guide for details

    Источник

    Оцените статью