Linux 中的“大内存页”（hugepage）是个什么？
内存 hugepage

> 
> 学习 Linux 中的<ruby> 大内存页 <rt>  hugepage </rt></ruby>。理解什么是“大内存页”，如何进行配置，如何查看当前状态以及如何禁用它。
> 
> 
> 


![Huge Pages in Linux](/data/attachment/album/201803/16/002941pnzzezyqqqowny8u.png)


本文中我们会详细介绍<ruby> 大内存页 <rt>  huge page </rt></ruby>，让你能够回答：Linux 中的“大内存页”是什么？在 RHEL6、RHEL7、Ubuntu 等 Linux 中，如何启用/禁用“大内存页”？如何查看“大内存页”的当前值？


首先让我们从“大内存页”的基础知识开始讲起。


### Linux 中的“大内存页”是个什么玩意？


“大内存页”有助于 Linux 系统进行虚拟内存管理。顾名思义，除了标准的 4KB 大小的页面外，它们还能帮助管理内存中的巨大的页面。使用“大内存页”，你最大可以定义 1GB 的页面大小。


在系统启动期间，你能用“大内存页”为应用程序预留一部分内存。这部分内存，即被“大内存页”占用的这些存储器永远不会被交换出内存。它会一直保留其中，除非你修改了配置。这会极大地提高像 Oracle 数据库这样的需要海量内存的应用程序的性能。


### 为什么使用“大内存页”？


在虚拟内存管理中，内核维护一个将虚拟内存地址映射到物理地址的表，对于每个页面操作，内核都需要加载相关的映射。如果你的内存页很小，那么你需要加载的页就会很多，导致内核会加载更多的映射表。而这会降低性能。


使用“大内存页”，意味着所需要的页变少了。从而大大减少由内核加载的映射表的数量。这提高了内核级别的性能最终有利于应用程序的性能。


简而言之，通过启用“大内存页”，系统具只需要处理较少的页面映射表，从而减少访问/维护它们的开销！


### 如何配置“大内存页”？


运行下面命令来查看当前“大内存页”的详细内容。



```
root@kerneltalks # grep Huge /proc/meminfo
AnonHugePages:         0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB

```

从上面输出可以看到，每个页的大小为 2MB（`Hugepagesize`），并且系统中目前有 `0` 个“大内存页”（`HugePages_Total`）。这里“大内存页”的大小可以从 `2MB` 增加到 `1GB`。


运行下面的脚本可以知道系统当前需要多少个巨大页。该脚本取之于 Oracle。



```
#!/bin/bash
#
# hugepages_settings.sh
#
# Linux bash script to compute values for the
# recommended HugePages/HugeTLB configuration
#
# Note: This script does calculation for all shared memory
# segments available when the script is run, no matter it
# is an Oracle RDBMS shared memory segment or not.
# Check for the kernel version
KERN=`uname -r | awk -F. '{ printf("%d.%d\n",$1,$2); }'`
# Find out the HugePage size
HPG_SZ=`grep Hugepagesize /proc/meminfo | awk {'print $2'}`
# Start from 1 pages to be on the safe side and guarantee 1 free HugePage
NUM_PG=1
# Cumulative number of pages required to handle the running shared memory segments
for SEG_BYTES in `ipcs -m | awk {'print $5'} | grep "[0-9][0-9]*"`
do
   MIN_PG=`echo "$SEG_BYTES/($HPG_SZ*1024)" | bc -q`
   if [ $MIN_PG -gt 0 ]; then
      NUM_PG=`echo "$NUM_PG+$MIN_PG+1" | bc -q`
   fi
done
# Finish with results
case $KERN in
   '2.4') HUGETLB_POOL=`echo "$NUM_PG*$HPG_SZ/1024" | bc -q`;
          echo "Recommended setting: vm.hugetlb_pool = $HUGETLB_POOL" ;;
   '2.6' | '3.8' | '3.10' | '4.1' ) echo "Recommended setting: vm.nr_hugepages = $NUM_PG" ;;
    *) echo "Unrecognized kernel version $KERN. Exiting." ;;
esac
# End

```

将它以 `hugepages_settings.sh` 为名保存到 `/tmp` 中，然后运行之：



```
root@kerneltalks # sh /tmp/hugepages_settings.sh
Recommended setting: vm.nr_hugepages = 124

```

你的输出类似如上结果，只是数字会有一些出入。


这意味着，你系统需要 124 个每个 2MB 的“大内存页”！若你设置页面大小为 4MB，则结果就变成了 62。你明白了吧？


### 配置内核中的“大内存页”


本文最后一部分内容是配置上面提到的 [内核参数](https://kerneltalks.com/linux/how-to-tune-kernel-parameters-in-linux/)  ，然后重新加载。将下面内容添加到 `/etc/sysctl.conf` 中，然后输入 `sysctl -p` 命令重新加载配置。



```
vm.nr_hugepages=126

```

注意我们这里多加了两个额外的页，因为我们希望在实际需要的页面数量之外多一些额外的空闲页。


现在，内核已经配置好了，但是要让应用能够使用这些“大内存页”还需要提高内存的使用阀值。新的内存阀值应该为 126 个页 x 每个页 2 MB = 252 MB，也就是 258048 KB。


你需要编辑 `/etc/security/limits.conf` 中的如下配置：



```
soft memlock 258048
hard memlock 258048

```

某些情况下，这些设置是在指定应用的文件中配置的，比如 Oracle DB 就是在 `/etc/security/limits.d/99-grid-oracle-limits.conf` 中配置的。


这就完成了！你可能还需要重启应用来让应用来使用这些新的巨大页。


（LCTT 译注：此外原文有误，“透明大内存页”和“大内存页”不同，而且，在 Redhat 系统中，“大内存页” 不是默认启用的，而“透明大内存页”是启用的。因此这个段落删除了。）




---


via: <https://kerneltalks.com/services/what-is-huge-pages-in-linux/>


作者：[Shrikant Lavhate](https://kerneltalks.com) 译者：[lujun9972](https://github.com/lujun9972) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
*Learn about huge pages in Linux. Understand what is huge pages, how to configure it, how to check the current state, and how to disable it.*

![](https://z5.kerneltalks.com/wp-content/uploads/2020/06/hugepages-in-linux.png)

In this article, we will walk you through details about huge pages so that you will be able to answer: what are huge pages in Linux? How to enable/disable huge pages? How to determine huge page value? in Linux like RHEL6, RHEL7, Ubuntu, etc.

Lets start with Huge pages basics.

### What is Huge page in Linux?

Huge pages are helpful in virtual memory management in the Linux system. As the name suggests, they help is managing huge size pages in memory in addition to standard 4KB page size. You can define as huge as 1GB page size using huge pages.

During system boot, you reserve your memory portion with huge pages for your application. This memory portion i.e. these memory occupied by huge pages is never swapped out of memory. It will stick there until you change your configuration. This increases application performance to a great extent like Oracle database with pretty large memory requirements.

### Why use huge page?

In virtual memory management, the kernel maintains a table in which it has a mapping of the virtual memory address to a physical address. For every page transaction, the kernel needs to load related mapping. If you have small size pages then you need to load more numbers of pages resulting kernel to load more mapping tables. This decreases performance.

Using huge pages means you will need fewer pages. This decreases the number of mapping tables to load by the kernel to a great extent. This increases your kernel-level performance which ultimately benefits your application.

In short, by enabling huge pages, the system has fewer page tables to deal with and hence less overhead to access/maintain them!

### How to configure huge pages?

Run below command to check current huge pages details.

```
root@kerneltalks # grep Huge /proc/meminfo
AnonHugePages: 0 kB
HugePages_Total: 0
HugePages_Free: 0
HugePages_Rsvd: 0
HugePages_Surp: 0
Hugepagesize: 2048 kB
```

In the above output, you can see the one-page size is 2MB `Hugepagesize`

and a total of 0 pages on the system `HugePages_Total`

. This huge page size can be increased from 2MB to max 1GB.

Run below script to get how much huge pages your system needs currently. The script is from Oracle and can be found.

```
#!/bin/bash
#
# hugepages_settings.sh
#
# Linux bash script to compute values for the
# recommended HugePages/HugeTLB configuration
#
# Note: This script does calculation for all shared memory
# segments available when the script is run, no matter it
# is an Oracle RDBMS shared memory segment or not.
# Check for the kernel version
KERN=`uname -r | awk -F. '{ printf("%d.%d\n",$1,$2); }'`
# Find out the HugePage size
HPG_SZ=`grep Hugepagesize /proc/meminfo | awk {'print $2'}`
# Start from 1 pages to be on the safe side and guarantee 1 free HugePage
NUM_PG=1
# Cumulative number of pages required to handle the running shared memory segments
for SEG_BYTES in `ipcs -m | awk {'print $5'} | grep "[0-9][0-9]*"`
do
MIN_PG=`echo "$SEG_BYTES/($HPG_SZ*1024)" | bc -q`
if [ $MIN_PG -gt 0 ]; then
NUM_PG=`echo "$NUM_PG+$MIN_PG+1" | bc -q`
fi
done
# Finish with results
case $KERN in
'2.4') HUGETLB_POOL=`echo "$NUM_PG*$HPG_SZ/1024" | bc -q`;
echo "Recommended setting: vm.hugetlb_pool = $HUGETLB_POOL" ;;
'2.6' | '3.8' | '3.10' | '4.1' ) echo "Recommended setting: vm.nr_hugepages = $NUM_PG" ;;
*) echo "Unrecognized kernel version $KERN. Exiting." ;;
esac
# End
```

You can save it in `/tmp`

as `hugepages_settings.sh`

and then run it like below :

```
root@kerneltalks # sh /tmp/hugepages_settings.sh
Recommended setting: vm.nr_hugepages = 124
```

Output will be similar to some number as shown in above sample output.

This means your system needs 124 huge pages of 2MB each! If you have set 4MB as page size then the output would have been 62. You got the point, right?

### Configure hugepages in kernel

Now last part is to configure the above-stated [kernel parameter](https://kerneltalks.com/linux/how-to-tune-kernel-parameters-in-linux/) and reload it. Add below value in `/etc/sysctl.conf`

and reload configuration by issuing `sysctl -p`

command.

```
vm.nr_hugepages=126
```

Notice that we added 2 extra pages in the kernel since we want to keep a couple of pages spare than the actual required number.

Now, huge pages have been configured in the kernel but to allow your application to use them you need to increase memory limits as well. The new memory limit should be 126 pages x 2 MB each = 252 MB i.e. 258048 KB.

You need to edit below settings in `/etc/security/limits.conf`


```
soft memlock 258048
hard memlock 258048
```

Sometimes these settings are configured in app-specific files like for Oracle DB its in `/etc/security/limits.d/99-grid-oracle-limits.conf`


That’s it! You might want to restart your application to make use of these new huge pages.

### How to disable hugepages?

HugePages are generally enabled by default. Use the below command to check the current state of huge pages.

```
root@kerneltalks # cat /sys/kernel/mm/transparent_hugepage/enabled
[always] madvise never
```

`[always]`

flag in output shows that hugepages are enabled on system.

For RedHat based systems file path is `/sys/kernel/mm/redhat_transparent_hugepage/enabled`


If you want to disable huge pages then add `transparent_hugepage=never`

at the end of `kernel`

line in `/etc/grub.conf`

and reboot the system.

Hugepages and transparent hugepages are two distincts features.

Hugepage is not enabled by default in RHEL while transparent hugepage is.

It is recommended to have the SGA in hugepages (known as large page from Oracle) and have transparent hugepage disabled as this last one is not supported by Oracle.

The article seems to imply that this is a feature with no downsides. However, it is not enabled by default. Why?

It says it’s typically enabled by default, FWIW…

“less number of”? Oh, you mean fewer?

That’s not the only grammatical atrocity here.

!! Fewer seems appropriate! Edited.

Thanks.

Why would you be worried about grammatical atrocities in a page that talks about huge pages?

In the script you are checking the following kernel version:

‘2.6’ | ‘3.8’ | ‘3.10’ | ‘4.1’

My version is 4.15, I included it in the script and got an output. Just wanted to confirm if the script supports this kernel version and will provide a correct output for it ?

Hello there, Transparent HugePages and HugePages are two different things! Once you enable HugePages, you must disable TransparentHugePages. RHEL calls it as redhat_transparent_hugepage & oracle has it as transparent_hugepages. Once HugePages are configured for Oracle/other, the transparent hugepages must be disabled, using one of the methods.

Grammar? definitely 🙂 There are far more stuffs worry about.

Somehow, saving a script to be run as root in /tmp always looks like a great idea to tell the world about.