Home >Operation and Maintenance >Linux Operation and Maintenance >What is the use of linux swap space?

What is the use of linux swap space?

藏色散人
藏色散人Original
2023-03-25 10:35:252073browse

The function of Linux swap space is to increase the virtual memory available to the host; swap space is the second type of memory in modern Linux systems. The main function of swap space is when all RAM is occupied and more memory is needed. When, disk space is used instead of RAM memory.

What is the use of linux swap space?

#The operating environment of this tutorial: linux5.9.8 system, Dell G3 computer.

What is the use of Linux swap space?

Introduction to swap space on Linux systems

Learn how to modify the capacity of swap space on your system and how much swap space you need.

No matter what operating system today Swap space is very common. Linux uses swap space to increase the virtual memory available to the host. It can use one or more dedicated swap partitions or swap files on regular files or logical volumes.

There are two basic types of memory in a typical computer. The first type, random access memory (RAM), is used to store data and programs used by the computer. The computer can only use programs and data if they are stored in RAM. Random access memory is volatile memory; that is, the data stored in RAM is lost if the computer is turned off.

Hard disk is a magnetic medium used for long-term storage of data and programs. This magnetic media can preserve data very well; even if the computer loses power, the data stored on the disk will be retained. The CPU (central processing unit) cannot directly access programs and data on the hard disk; they must first be copied to RAM, which is where the CPU accesses code instructions and manipulates data. During the boot process, the computer copies specific operating system programs (such as the kernel, init, or systemd) and data on the hard disk to RAM, where the computer's processor, the CPU, can directly access the data.

Swap space

Swap space is the second type of memory in modern Linux systems. The main function of swap space is to replace RAM memory with disk space when all RAM is occupied and more memory is needed.

For example, assume you have a computer with 8GB RAM. If the program you launch doesn't fill up RAM, everything is fine and no swap is needed. Let's say you're working on a spreadsheet. As you add more rows, your spreadsheet will grow and, with all the programs running, will take up all of your RAM. If there is no swap space available at this time, you will have to stop working on the spreadsheet until you close some other programs to free up some RAM.

The kernel uses a memory manager to detect memory blocks (memory pages) that have not been used recently. The memory management program swaps these relatively infrequently used memory pages to special partitions on the hard disk that are designated for "paging" or swapping. This frees up RAM, making room for entering more data into the spreadsheet. Those memory pages swapped out to disk are tracked by the kernel's memory management code and can be paged back into RAM if necessary.

The total amount of memory in a Linux computer is the RAM swap partition, and the swap partition is called virtual memory.

Linux swap partition type

Linux provides There are two types of swap space. By default, most Linux installations create a swap partition, but it is also possible to use a specially configured file as a swap file. As the name suggests, the swap partition is a standard disk partition, and the swap space is specified by the mkswap command.

You can use a swap file if there is no disk space available to create a new swap partition, or there is no space in the volume group to create a logical volume for swap space. This is just a regular file that is created and pre-allocated to a specified size. Then run the mkswap command to configure it as swap space. I don't recommend using files for swap space unless absolutely necessary. (LCTT Translation: Recent versions of Ubuntu use swap files instead of swap space, so I reserve my opinion on this statement)

Frequent swap

When the total virtual memory Frequent swapping may occur when (RAM and swap space) becomes nearly full. The system spends so much time paging blocks of memory between swap space and RAM that it leaves little time for actual work. Typical symptoms of this condition are: the system becomes sluggish or completely unresponsive, and the hard drive light lights up almost constantly.

Use the free command to display the CPU load and memory usage. You will find that the CPU load is very high, possibly 30 to 40 times the number of CPU cores in the system. Another situation is when RAM and swap space are almost completely allocated.

In fact, looking at SAR (System Activity Report) data can also reveal these things. Install SAR on each of my systems and use these for data analysis.

What is the correct size of swap space?

Many years ago, the size of swap space allocated on the hard disk was twice the size of the RAM on the computer (of course, this was when most computers' RAM was measured in KB or MB). Therefore, if a computer has 64KB of RAM, a 128KB swap partition should be allocated. This rule took into account the fact that RAM size was very small at the time and allocating more than 2x RAM for swap space did not improve performance. Most systems will spend more time using more than twice the RAM for swapping than actually doing useful work.

RAM is cheap now, and most computers today have several gigabytes of RAM. Most of my new computers have at least 8GB of RAM, one has 32GB of RAM, and my main workstation has 64GB of RAM. My old computer had 4 to 8GB of RAM.

When operating computers with large amounts of RAM, the limiting performance factor for swap space is well below 2x. The Fedora 28 Online Installation Guide defines the current approach to swap space allocation. What follows are my suggestions.

The following table provides recommended sizes for the swap partition based on the amount of RAM in the system and whether there is enough memory to hibernate the system. The recommended swap partition size is automatically established during installation. However, in order to satisfy system hibernation, you need to edit the swap space during the custom partition stage.

Table 1: Recommended system swap space in Fedora 28 documentation

System memory size Recommended swap space Recommended swap space size (supports hibernation mode) Less than 2 GB 2 times RAM 3 times RAM 2 GB - 8 GB equals RAM size 2 times RAM 8 GB - 64 GB 0.5 times RAM 1.5 times RAM greater than 64 GB Workload related Hibernate mode is not recommended

above The boundaries between each range listed (for example, with 2GB, 8GB, or 64GB of system RAM), please use caution based on selected swap space and hibernation support. If your system resources allow it, adding swap space may result in better performance.

Of course, most Linux administrators have their own ideas about how much swap space should be used. Table 2 below contains recommendations based on my personal experience in a variety of settings. These may not apply to you, but like Table 1, they may be helpful.

Table 2: System swap space recommended by the author

RAM size Recommended swap space ≤ 2GB2X RAM2GB – 8GB= RAM>8GB8GB

These two The common thread across the tables is that as the amount of RAM increases, adding more swap space beyond a certain point will only result in frequent swapping before the swap space is almost fully used. Based on the above suggestions, you should add more RAM instead of adding more swap space if possible. As with similar situations affecting system performance, please use the recommendations that work best for you. Testing and making changes based on conditions in a Linux environment takes time and effort.

Adding more swap space to a non-LVM disk environment

Facing hosts with Linux installed and changing needs for swap space, sometimes it is necessary to modify the system definition The size of the swap space. This procedure can be used in any situation where you need to increase the swap space size. It assumes sufficient free disk space. This procedure also assumes that the disk partitions are "raw" EXT4 and swap partitions, rather than using Logical Volume Management (LVM).

The basic steps are simple:

  1. Close the existing swap space.
  2. Create a new swap partition of the desired size.
  3. Reread the partition table.
  4. Configure the partition as swap space.
  5. Add new partition to /etc/fstab.
  6. Open the swap space.

There should be no need to restart the machine.

For safety reasons, before closing the swap space, you should at least make sure that no applications are running and no swap space is in use. The free or top command can tell you whether the swap space is in use. For greater security, you can revert to runlevel 1 or single-user mode.

Close the swap partition using the command to close all swap space:

swapoff -a

Now view the existing partitions on the hard drive.

fdisk -l

This will display the partition table on each drive. Identifies the current swap partition by number.

Use the following command to start fdisk in interactive mode:

fdisk /dev/<device name>

For example:

fdisk /dev/sda

此时,fdisk 是交互方式的,只在指定的磁盘驱动器上进行操作。

使用 fdiskp 子命令验证磁盘上是否有足够的可用空间来创建新的交换分区。硬盘上的空间以 512 字节的块以及起始和结束柱面编号的形式显示,因此您可能需要做一些计算来确定分配分区之间和末尾的可用空间。

使用 n 子命令创建新的交换分区。fdisk 会问你开始柱面。默认情况下,它选择编号最低的可用柱面。如果你想改变这一点,输入开始柱面的编号。

fdisk 命令允许你以多种格式输入分区的大小,包括最后一个柱面号或字节、KB 或 MB 的大小。例如,键入 4000M ,这将在新分区上提供大约 4GB 的空间,然后按回车键。

使用 p 子命令来验证分区是否按照指定的方式创建的。请注意,除非使用结束柱面编号,否则分区可能与你指定的不完全相同。fdisk 命令只能在整个柱面上增量的分配磁盘空间,因此你的分区可能比你指定的稍小或稍大。如果分区不是您想要的,你可以删除它并重新创建它。

现在指定新分区是交换分区了 。子命令 t 允许你指定定分区的类型。所以输入 t,指定分区号,当它要求十六进制分区类型时,输入 82,这是 Linux 交换分区类型,然后按回车键。

当你对创建的分区感到满意时,使用 w 子命令将新的分区表写入磁盘。fdisk 程序将退出,并在完成修改后的分区表的编写后返回命令提示符。当 fdisk 完成写入新分区表时,会收到以下消息:

The partition table has been altered!
Calling ioctl() to re-read partition table.
WARNING: Re-reading the partition table failed with error 16: Device or resource busy.
The kernel still uses the old table.
The new table will be used at the next reboot.
Syncing disks.

此时,你使用 partprobe 命令强制内核重新读取分区表,这样就不需要执行重新启动机器。

partprobe

使用命令 fdisk -l 列出分区,新交换分区应该在列出的分区中。确保新的分区类型是 “Linux swap”。

修改 /etc/fstab 文件以指向新的交换分区。如下所示:

LABEL=SWAP-sdaX   swap        swap    defaults        0 0

其中 X 是分区号。根据新交换分区的位置,添加以下内容:

/dev/sdaY         swap        swap    defaults        0 0

请确保使用正确的分区号。现在,可以执行创建交换分区的最后一步。使用 mkswap 命令将分区定义为交换分区。

mkswap /dev/sdaY

最后一步是使用以下命令启用交换空间:

swapon -a

你的新交换分区现在与以前存在的交换分区一起在线。您可以使用 freetop 命令来验证这一点。

在 LVM 磁盘环境中添加交换空间

如果你的磁盘使用 LVM ,更改交换空间将相当容易。同样,假设当前交换卷所在的卷组中有可用空间。默认情况下,LVM 环境中的 Fedora Linux 在安装过程将交换分区创建为逻辑卷。您可以非常简单地增加交换卷的大小。

以下是在 LVM 环境中增加交换空间大小的步骤:

  1. 关闭所有交换空间。
  2. 增加指定用于交换空间的逻辑卷的大小。
  3. 为交换空间调整大小的卷配置。
  4. 启用交换空间。

首先,让我们使用 lvs 命令(列出逻辑卷)来验证交换空间是否存在以及交换空间是否是逻辑卷。

[root@studentvm1 ~]# lvs
  LV     VG                Attr       LSize  Pool   Origin Data%  Meta%  Move Log Cpy%Sync Convert
  home   fedora_studentvm1 -wi-ao----  2.00g                                                      
  pool00 fedora_studentvm1 twi-aotz--  2.00g               8.17   2.93                            
  root   fedora_studentvm1 Vwi-aotz--  2.00g pool00        8.17                                   
  swap   fedora_studentvm1 -wi-ao----  8.00g                                                      
  tmp    fedora_studentvm1 -wi-ao----  5.00g                                                      
  usr    fedora_studentvm1 -wi-ao---- 15.00g                                                      
  var    fedora_studentvm1 -wi-ao---- 10.00g                                                      
[root@studentvm1 ~]#

你可以看到当前的交换空间大小为 8GB。在这种情况下,我们希望将 2GB 添加到此交换卷中。首先,停止现有的交换空间。如果交换空间正在使用,终止正在运行的程序。

swapoff -a

现在增加逻辑卷的大小。

[root@studentvm1 ~]# lvextend -L +2G /dev/mapper/fedora_studentvm1-swap
  Size of logical volume fedora_studentvm1/swap changed from 8.00 GiB (2048 extents) to 10.00 GiB (2560 extents).
  Logical volume fedora_studentvm1/swap successfully resized.
[root@studentvm1 ~]#

运行 mkswap 命令将整个 10GB 分区变成交换空间。

[root@studentvm1 ~]# mkswap /dev/mapper/fedora_studentvm1-swap
mkswap: /dev/mapper/fedora_studentvm1-swap: warning: wiping old swap signature.
Setting up swapspace version 1, size = 10 GiB (10737414144 bytes)
no label, UUID=3cc2bee0-e746-4b66-aa2d-1ea15ef1574a
[root@studentvm1 ~]#

重新启用交换空间。

[root@studentvm1 ~]# swapon -a
[root@studentvm1 ~]#

现在,使用 lsblk 命令验证新交换空间是否存在。同样,不需要重新启动机器。

[root@studentvm1 ~]# lsblk
NAME                                 MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda                                    8:0    0   60G  0 disk
|-sda1                                 8:1    0    1G  0 part /boot
`-sda2                                 8:2    0   59G  0 part
  |-fedora_studentvm1-pool00_tmeta   253:0    0    4M  0 lvm  
  | `-fedora_studentvm1-pool00-tpool 253:2    0    2G  0 lvm  
  |   |-fedora_studentvm1-root       253:3    0    2G  0 lvm  /
  |   `-fedora_studentvm1-pool00     253:6    0    2G  0 lvm  
  |-fedora_studentvm1-pool00_tdata   253:1    0    2G  0 lvm  
  | `-fedora_studentvm1-pool00-tpool 253:2    0    2G  0 lvm  
  |   |-fedora_studentvm1-root       253:3    0    2G  0 lvm  /
  |   `-fedora_studentvm1-pool00     253:6    0    2G  0 lvm  
  |-fedora_studentvm1-swap           253:4    0   10G  0 lvm  [SWAP]
  |-fedora_studentvm1-usr            253:5    0   15G  0 lvm  /usr
  |-fedora_studentvm1-home           253:7    0    2G  0 lvm  /home
  |-fedora_studentvm1-var            253:8    0   10G  0 lvm  /var
  `-fedora_studentvm1-tmp            253:9    0    5G  0 lvm  /tmp
sr0                                   11:0    1 1024M  0 rom  
[root@studentvm1 ~]#

您也可以使用 swapon -s 命令或 topfree 或其他几个命令来验证这一点。

[root@studentvm1 ~]# free
              total        used        free      shared  buff/cache   available
Mem:        4038808      382404     2754072        4152      902332     3404184
Swap:      10485756           0    10485756
[root@studentvm1 ~]#

请注意,不同的命令以不同的形式显示或要求输入设备文件。在 /dev 目录中访问特定设备有多种方式。

推荐学习:《linux视频教程

The above is the detailed content of What is the use of linux swap space?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:what is linux lunNext article:what is linux lun