요약·해설과 원문, 전문 번역을 서로 분리했습니다. API 이름, symbol, source path는 원문 표기를 사용합니다.
1. 요약·해설
원문의 핵심 논리와 kernel programming 관점의 보충 설명입니다. 아래의 전문 번역과는 별도로 작성했습니다.
2. 영어 원문 전체
번역 기준이 된 Linux v6.18.37 원문입니다. 줄 번호는 이 버전의 파일 좌표입니다.
원문 전체 펼치기
=============
HugeTLB Pages
=============
Overview
========
The intent of this file is to give a brief summary of hugetlbpage support in
the Linux kernel. This support is built on top of multiple page size support
that is provided by most modern architectures. For example, x86 CPUs normally
support 4K and 2M (1G if architecturally supported) page sizes, ia64
architecture supports multiple page sizes 4K, 8K, 64K, 256K, 1M, 4M, 16M,
256M and ppc64 supports 4K and 16M. A TLB is a cache of virtual-to-physical
translations. Typically this is a very scarce resource on processor.
Operating systems try to make best use of limited number of TLB resources.
This optimization is more critical now as bigger and bigger physical memories
(several GBs) are more readily available.
Users can use the huge page support in Linux kernel by either using the mmap
system call or standard SYSV shared memory system calls (shmget, shmat).
First the Linux kernel needs to be built with the CONFIG_HUGETLBFS
(present under "File systems") and CONFIG_HUGETLB_PAGE (selected
automatically when CONFIG_HUGETLBFS is selected) configuration
options.
The ``/proc/meminfo`` file provides information about the total number of
persistent hugetlb pages in the kernel's huge page pool. It also displays
default huge page size and information about the number of free, reserved
and surplus huge pages in the pool of huge pages of default size.
The huge page size is needed for generating the proper alignment and
size of the arguments to system calls that map huge page regions.
The output of ``cat /proc/meminfo`` will include lines like::
HugePages_Total: uuu
HugePages_Free: vvv
HugePages_Rsvd: www
HugePages_Surp: xxx
Hugepagesize: yyy kB
Hugetlb: zzz kB
where:
HugePages_Total
is the size of the pool of huge pages.
HugePages_Free
is the number of huge pages in the pool that are not yet
allocated.
HugePages_Rsvd
is short for "reserved," and is the number of huge pages for
which a commitment to allocate from the pool has been made,
but no allocation has yet been made. Reserved huge pages
guarantee that an application will be able to allocate a
huge page from the pool of huge pages at fault time.
HugePages_Surp
is short for "surplus," and is the number of huge pages in
the pool above the value in ``/proc/sys/vm/nr_hugepages``. The
maximum number of surplus huge pages is controlled by
``/proc/sys/vm/nr_overcommit_hugepages``.
Note: When the feature of freeing unused vmemmap pages associated
with each hugetlb page is enabled, the number of surplus huge pages
may be temporarily larger than the maximum number of surplus huge
pages when the system is under memory pressure.
Hugepagesize
is the default hugepage size (in kB).
Hugetlb
is the total amount of memory (in kB), consumed by huge
pages of all sizes.
If huge pages of different sizes are in use, this number
will exceed HugePages_Total \* Hugepagesize. To get more
detailed information, please, refer to
``/sys/kernel/mm/hugepages`` (described below).
``/proc/filesystems`` should also show a filesystem of type "hugetlbfs"
configured in the kernel.
``/proc/sys/vm/nr_hugepages`` indicates the current number of "persistent" huge
pages in the kernel's huge page pool. "Persistent" huge pages will be
returned to the huge page pool when freed by a task. A user with root
privileges can dynamically allocate more or free some persistent huge pages
by increasing or decreasing the value of ``nr_hugepages``.
Note: When the feature of freeing unused vmemmap pages associated with each
hugetlb page is enabled, we can fail to free the huge pages triggered by
the user when the system is under memory pressure. Please try again later.
Pages that are used as huge pages are reserved inside the kernel and cannot
be used for other purposes. Huge pages cannot be swapped out under
memory pressure.
Once a number of huge pages have been pre-allocated to the kernel huge page
pool, a user with appropriate privilege can use either the mmap system call
or shared memory system calls to use the huge pages. See the discussion of
:ref:`Using Huge Pages <using_huge_pages>`, below.
The administrator can allocate persistent huge pages on the kernel boot
command line by specifying the "hugepages=N" parameter, where 'N' = the
number of huge pages requested. This is the most reliable method of
allocating huge pages as memory has not yet become fragmented.
Some platforms support multiple huge page sizes. To allocate huge pages
of a specific size, one must precede the huge pages boot command parameters
with a huge page size selection parameter "hugepagesz=<size>". <size> must
be specified in bytes with optional scale suffix [kKmMgG]. The default huge
page size may be selected with the "default_hugepagesz=<size>" boot parameter.
Hugetlb boot command line parameter semantics
hugepagesz
Specify a huge page size. Used in conjunction with hugepages
parameter to preallocate a number of huge pages of the specified
size. Hence, hugepagesz and hugepages are typically specified in
pairs such as::
hugepagesz=2M hugepages=512
hugepagesz can only be specified once on the command line for a
specific huge page size. Valid huge page sizes are architecture
dependent.
hugepages
Specify the number of huge pages to preallocate. This typically
follows a valid hugepagesz or default_hugepagesz parameter. However,
if hugepages is the first or only hugetlb command line parameter it
implicitly specifies the number of huge pages of default size to
allocate. If the number of huge pages of default size is implicitly
specified, it can not be overwritten by a hugepagesz,hugepages
parameter pair for the default size. This parameter also has a
node format. The node format specifies the number of huge pages
to allocate on specific nodes.
For example, on an architecture with 2M default huge page size::
hugepages=256 hugepagesz=2M hugepages=512
will result in 256 2M huge pages being allocated and a warning message
indicating that the hugepages=512 parameter is ignored. If a hugepages
parameter is preceded by an invalid hugepagesz parameter, it will
be ignored.
Node format example::
hugepagesz=2M hugepages=0:1,1:2
It will allocate 1 2M hugepage on node0 and 2 2M hugepages on node1.
If the node number is invalid, the parameter will be ignored.
hugepage_alloc_threads
Specify the number of threads that should be used to allocate hugepages
during boot. This parameter can be used to improve system bootup time
when allocating a large amount of huge pages.
The default value is 25% of the available hardware threads.
Example to use 8 allocation threads::
hugepage_alloc_threads=8
Note that this parameter only applies to non-gigantic huge pages.
default_hugepagesz
Specify the default huge page size. This parameter can
only be specified once on the command line. default_hugepagesz can
optionally be followed by the hugepages parameter to preallocate a
specific number of huge pages of default size. The number of default
sized huge pages to preallocate can also be implicitly specified as
mentioned in the hugepages section above. Therefore, on an
architecture with 2M default huge page size::
hugepages=256
default_hugepagesz=2M hugepages=256
hugepages=256 default_hugepagesz=2M
will all result in 256 2M huge pages being allocated. Valid default
huge page size is architecture dependent.
hugetlb_free_vmemmap
When CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP is set, this enables HugeTLB
Vmemmap Optimization (HVO).
When multiple huge page sizes are supported, ``/proc/sys/vm/nr_hugepages``
indicates the current number of pre-allocated huge pages of the default size.
Thus, one can use the following command to dynamically allocate/deallocate
default sized persistent huge pages::
echo 20 > /proc/sys/vm/nr_hugepages
This command will try to adjust the number of default sized huge pages in the
huge page pool to 20, allocating or freeing huge pages, as required.
On a NUMA platform, the kernel will attempt to distribute the huge page pool
over all the set of allowed nodes specified by the NUMA memory policy of the
task that modifies ``nr_hugepages``. The default for the allowed nodes--when the
task has default memory policy--is all on-line nodes with memory. Allowed
nodes with insufficient available, contiguous memory for a huge page will be
silently skipped when allocating persistent huge pages. See the
:ref:`discussion below <mem_policy_and_hp_alloc>`
of the interaction of task memory policy, cpusets and per node attributes
with the allocation and freeing of persistent huge pages.
The success or failure of huge page allocation depends on the amount of
physically contiguous memory that is present in system at the time of the
allocation attempt. If the kernel is unable to allocate huge pages from
some nodes in a NUMA system, it will attempt to make up the difference by
allocating extra pages on other nodes with sufficient available contiguous
memory, if any.
System administrators may want to put this command in one of the local rc
init files. This will enable the kernel to allocate huge pages early in
the boot process when the possibility of getting physical contiguous pages
is still very high. Administrators can verify the number of huge pages
actually allocated by checking the sysctl or meminfo. To check the per node
distribution of huge pages in a NUMA system, use::
cat /sys/devices/system/node/node*/meminfo | fgrep Huge
``/proc/sys/vm/nr_overcommit_hugepages`` specifies how large the pool of
huge pages can grow, if more huge pages than ``/proc/sys/vm/nr_hugepages`` are
requested by applications. Writing any non-zero value into this file
indicates that the hugetlb subsystem is allowed to try to obtain that
number of "surplus" huge pages from the kernel's normal page pool, when the
persistent huge page pool is exhausted. As these surplus huge pages become
unused, they are freed back to the kernel's normal page pool.
When increasing the huge page pool size via ``nr_hugepages``, any existing
surplus pages will first be promoted to persistent huge pages. Then, additional
huge pages will be allocated, if necessary and if possible, to fulfill
the new persistent huge page pool size.
The administrator may shrink the pool of persistent huge pages for
the default huge page size by setting the ``nr_hugepages`` sysctl to a
smaller value. The kernel will attempt to balance the freeing of huge pages
across all nodes in the memory policy of the task modifying ``nr_hugepages``.
Any free huge pages on the selected nodes will be freed back to the kernel's
normal page pool.
Caveat: Shrinking the persistent huge page pool via ``nr_hugepages`` such that
it becomes less than the number of huge pages in use will convert the balance
of the in-use huge pages to surplus huge pages. This will occur even if
the number of surplus pages would exceed the overcommit value. As long as
this condition holds--that is, until ``nr_hugepages+nr_overcommit_hugepages`` is
increased sufficiently, or the surplus huge pages go out of use and are freed--
no more surplus huge pages will be allowed to be allocated.
With support for multiple huge page pools at run-time available, much of
the huge page userspace interface in ``/proc/sys/vm`` has been duplicated in
sysfs.
The ``/proc`` interfaces discussed above have been retained for backwards
compatibility. The root huge page control directory in sysfs is::
/sys/kernel/mm/hugepages
For each huge page size supported by the running kernel, a subdirectory
will exist, of the form::
hugepages-${size}kB
Inside each of these directories, the set of files contained in ``/proc``
will exist. In addition, two additional interfaces for demoting huge
pages may exist::
demote
demote_size
nr_hugepages
nr_hugepages_mempolicy
nr_overcommit_hugepages
free_hugepages
resv_hugepages
surplus_hugepages
The demote interfaces provide the ability to split a huge page into
smaller huge pages. For example, the x86 architecture supports both
1GB and 2MB huge pages sizes. A 1GB huge page can be split into 512
2MB huge pages. Demote interfaces are not available for the smallest
huge page size. The demote interfaces are:
demote_size
is the size of demoted pages. When a page is demoted a corresponding
number of huge pages of demote_size will be created. By default,
demote_size is set to the next smaller huge page size. If there are
multiple smaller huge page sizes, demote_size can be set to any of
these smaller sizes. Only huge page sizes less than the current huge
pages size are allowed.
demote
is used to demote a number of huge pages. A user with root privileges
can write to this file. It may not be possible to demote the
requested number of huge pages. To determine how many pages were
actually demoted, compare the value of nr_hugepages before and after
writing to the demote interface. demote is a write only interface.
The interfaces which are the same as in ``/proc`` (all except demote and
demote_size) function as described above for the default huge page-sized case.
.. _mem_policy_and_hp_alloc:
Interaction of Task Memory Policy with Huge Page Allocation/Freeing
===================================================================
Whether huge pages are allocated and freed via the ``/proc`` interface or
the ``/sysfs`` interface using the ``nr_hugepages_mempolicy`` attribute, the
NUMA nodes from which huge pages are allocated or freed are controlled by the
NUMA memory policy of the task that modifies the ``nr_hugepages_mempolicy``
sysctl or attribute. When the ``nr_hugepages`` attribute is used, mempolicy
is ignored.
The recommended method to allocate or free huge pages to/from the kernel
huge page pool, using the ``nr_hugepages`` example above, is::
numactl --interleave <node-list> echo 20 \
>/proc/sys/vm/nr_hugepages_mempolicy
or, more succinctly::
numactl -m <node-list> echo 20 >/proc/sys/vm/nr_hugepages_mempolicy
This will allocate or free ``abs(20 - nr_hugepages)`` to or from the nodes
specified in <node-list>, depending on whether number of persistent huge pages
is initially less than or greater than 20, respectively. No huge pages will be
allocated nor freed on any node not included in the specified <node-list>.
When adjusting the persistent hugepage count via ``nr_hugepages_mempolicy``, any
memory policy mode--bind, preferred, local or interleave--may be used. The
resulting effect on persistent huge page allocation is as follows:
#. Regardless of mempolicy mode [see
Documentation/admin-guide/mm/numa_memory_policy.rst],
persistent huge pages will be distributed across the node or nodes
specified in the mempolicy as if "interleave" had been specified.
However, if a node in the policy does not contain sufficient contiguous
memory for a huge page, the allocation will not "fallback" to the nearest
neighbor node with sufficient contiguous memory. To do this would cause
undesirable imbalance in the distribution of the huge page pool, or
possibly, allocation of persistent huge pages on nodes not allowed by
the task's memory policy.
#. One or more nodes may be specified with the bind or interleave policy.
If more than one node is specified with the preferred policy, only the
lowest numeric id will be used. Local policy will select the node where
the task is running at the time the nodes_allowed mask is constructed.
For local policy to be deterministic, the task must be bound to a cpu or
cpus in a single node. Otherwise, the task could be migrated to some
other node at any time after launch and the resulting node will be
indeterminate. Thus, local policy is not very useful for this purpose.
Any of the other mempolicy modes may be used to specify a single node.
#. The nodes allowed mask will be derived from any non-default task mempolicy,
whether this policy was set explicitly by the task itself or one of its
ancestors, such as numactl. This means that if the task is invoked from a
shell with non-default policy, that policy will be used. One can specify a
node list of "all" with numactl --interleave or --membind [-m] to achieve
interleaving over all nodes in the system or cpuset.
#. Any task mempolicy specified--e.g., using numactl--will be constrained by
the resource limits of any cpuset in which the task runs. Thus, there will
be no way for a task with non-default policy running in a cpuset with a
subset of the system nodes to allocate huge pages outside the cpuset
without first moving to a cpuset that contains all of the desired nodes.
#. Boot-time huge page allocation attempts to distribute the requested number
of huge pages over all on-lines nodes with memory.
Per Node Hugepages Attributes
=============================
A subset of the contents of the root huge page control directory in sysfs,
described above, will be replicated under each the system device of each
NUMA node with memory in::
/sys/devices/system/node/node[0-9]*/hugepages/
Under this directory, the subdirectory for each supported huge page size
contains the following attribute files::
nr_hugepages
free_hugepages
surplus_hugepages
The free\_' and surplus\_' attribute files are read-only. They return the number
of free and surplus [overcommitted] huge pages, respectively, on the parent
node.
The ``nr_hugepages`` attribute returns the total number of huge pages on the
specified node. When this attribute is written, the number of persistent huge
pages on the parent node will be adjusted to the specified value, if sufficient
resources exist, regardless of the task's mempolicy or cpuset constraints.
Note that the number of overcommit and reserve pages remain global quantities,
as we don't know until fault time, when the faulting task's mempolicy is
applied, from which node the huge page allocation will be attempted.
The hugetlb may be migrated between the per-node hugepages pool in the following
scenarios: memory offline, memory failure, longterm pinning, syscalls(mbind,
migrate_pages and move_pages), alloc_contig_range() and alloc_contig_pages().
Now only memory offline, memory failure and syscalls allow fallbacking to allocate
a new hugetlb on a different node if the current node is unable to allocate during
hugetlb migration, that means these 3 cases can break the per-node hugepages pool.
.. _using_huge_pages:
Using Huge Pages
================
If the user applications are going to request huge pages using mmap system
call, then it is required that system administrator mount a file system of
type hugetlbfs::
mount -t hugetlbfs \
-o uid=<value>,gid=<value>,mode=<value>,pagesize=<value>,size=<value>,\
min_size=<value>,nr_inodes=<value> none /mnt/huge
This command mounts a (pseudo) filesystem of type hugetlbfs on the directory
``/mnt/huge``. Any file created on ``/mnt/huge`` uses huge pages.
The ``uid`` and ``gid`` options sets the owner and group of the root of the
file system. By default the ``uid`` and ``gid`` of the current process
are taken.
The ``mode`` option sets the mode of root of file system to value & 01777.
This value is given in octal. By default the value 0755 is picked.
If the platform supports multiple huge page sizes, the ``pagesize`` option can
be used to specify the huge page size and associated pool. ``pagesize``
is specified in bytes. If ``pagesize`` is not specified the platform's
default huge page size and associated pool will be used.
The ``size`` option sets the maximum value of memory (huge pages) allowed
for that filesystem (``/mnt/huge``). The ``size`` option can be specified
in bytes, or as a percentage of the specified huge page pool (``nr_hugepages``).
The size is rounded down to HPAGE_SIZE boundary.
The ``min_size`` option sets the minimum value of memory (huge pages) allowed
for the filesystem. ``min_size`` can be specified in the same way as ``size``,
either bytes or a percentage of the huge page pool.
At mount time, the number of huge pages specified by ``min_size`` are reserved
for use by the filesystem.
If there are not enough free huge pages available, the mount will fail.
As huge pages are allocated to the filesystem and freed, the reserve count
is adjusted so that the sum of allocated and reserved huge pages is always
at least ``min_size``.
The option ``nr_inodes`` sets the maximum number of inodes that ``/mnt/huge``
can use.
If the ``size``, ``min_size`` or ``nr_inodes`` option is not provided on
command line then no limits are set.
For ``pagesize``, ``size``, ``min_size`` and ``nr_inodes`` options, you can
use [G|g]/[M|m]/[K|k] to represent giga/mega/kilo.
For example, size=2K has the same meaning as size=2048.
While read system calls are supported on files that reside on hugetlb
file systems, write system calls are not.
Regular chown, chgrp, and chmod commands (with right permissions) could be
used to change the file attributes on hugetlbfs.
Also, it is important to note that no such mount command is required if
applications are going to use only shmat/shmget system calls or mmap with
MAP_HUGETLB. For an example of how to use mmap with MAP_HUGETLB see
:ref:`map_hugetlb <map_hugetlb>` below.
Users who wish to use hugetlb memory via shared memory segment should be
members of a supplementary group and system admin needs to configure that gid
into ``/proc/sys/vm/hugetlb_shm_group``. It is possible for same or different
applications to use any combination of mmaps and shm* calls, though the mount of
filesystem will be required for using mmap calls without MAP_HUGETLB.
Syscalls that operate on memory backed by hugetlb pages only have their lengths
aligned to the native page size of the processor; they will normally fail with
errno set to EINVAL or exclude hugetlb pages that extend beyond the length if
not hugepage aligned. For example, munmap(2) will fail if memory is backed by
a hugetlb page and the length is smaller than the hugepage size.
Examples
========
.. _map_hugetlb:
``map_hugetlb``
see tools/testing/selftests/mm/map_hugetlb.c
``hugepage-shm``
see tools/testing/selftests/mm/hugepage-shm.c
``hugepage-mmap``
see tools/testing/selftests/mm/hugepage-mmap.c
The `libhugetlbfs`_ library provides a wide range of userspace tools
to help with huge page usability, environment setup, and control.
.. _libhugetlbfs: https://github.com/libhugetlbfs/libhugetlbfs
3. 한국어 전문 번역
영어 원문의 문단 순서와 의미를 유지한 전체 번역입니다. 코드, 함수명, symbol과 URL은 원문 표기를 유지합니다.
HugeTLB 개요와 준비
1-25이 문서는 Linux kernel의 hugetlbpage 지원을 간략히 정리합니다. 대부분의 현대 architecture가 여러 page size를 지원하는 기능 위에 구축되며, x86은 보통 4 KiB와 2 MiB, architecture가 지원하면 1 GiB를 사용합니다. ia64는 4 KiB부터 256 MiB까지 여러 크기를, ppc64는 4 KiB와 16 MiB를 지원합니다.
TLB는 virtual-to-physical translation cache이며 processor에서 수가 매우 제한된 자원입니다. Physical memory가 수 GiB 이상으로 커질수록 큰 page로 한 TLB entry가 더 넓은 범위를 덮게 하는 최적화가 중요해집니다.
사용자는 `mmap` system call이나 표준 SYSV shared memory call인 `shmget`, `shmat`으로 huge page를 사용할 수 있습니다. Kernel은 `CONFIG_HUGETLBFS`를 켜서 빌드해야 하며, 이를 선택하면 `CONFIG_HUGETLB_PAGE`가 자동으로 선택됩니다.
pool 상태와 /proc/meminfo
26-77`/proc/meminfo`는 kernel huge page pool의 기본 크기 persistent page 총수, free·reserved·surplus 수, 기본 huge page 크기를 보여 줍니다. Huge page mapping system call의 주소 정렬과 길이를 올바르게 만들려면 이 크기를 알아야 합니다.
HugePages_Total: uuu
HugePages_Free: vvv
HugePages_Rsvd: www
HugePages_Surp: xxx
Hugepagesize: yyy kB
Hugetlb: zzz kB
| 필드 | 의미 |
|---|---|
| HugePages_Total | 기본 크기 persistent huge page pool의 전체 page 수 |
| HugePages_Free | pool에서 아직 할당되지 않은 huge page 수 |
| HugePages_Rsvd | fault 시 pool에서 할당하겠다고 약속했지만 아직 실제 할당하지 않은 page 수 |
| HugePages_Surp | `nr_hugepages`를 넘어 normal page pool에서 임시 확보한 surplus page 수 |
| Hugepagesize | 기본 huge page 크기, kB |
| Hugetlb | 모든 크기의 huge page가 소비하는 총 memory, kB |
`HugePages_Rsvd`는 application이 fault 시 pool에서 page를 받을 수 있도록 미리 약속한 수입니다. `HugePages_Surp`의 일반 상한은 `/proc/sys/vm/nr_overcommit_hugepages`지만, unused vmemmap page를 해제하는 기능이 켜져 있고 memory pressure가 있으면 잠시 상한을 넘을 수 있습니다.
`Hugetlb`는 모든 page size의 총 사용량이므로 여러 크기를 함께 쓰면 `HugePages_Total * Hugepagesize`보다 큽니다. 크기별 상세 상태는 `/sys/kernel/mm/hugepages`에서 봅니다. `/proc/filesystems`에는 kernel이 지원하는 `hugetlbfs` filesystem type도 나타나야 합니다.
persistent pool과 제약
78-101`/proc/sys/vm/nr_hugepages`는 현재 kernel pool의 persistent huge page 수입니다. root 사용자는 값을 늘리거나 줄여 persistent page를 동적으로 할당하거나 해제할 수 있고, task가 page를 반환하면 normal memory가 아니라 huge page pool로 돌아갑니다.
unused vmemmap page 해제 기능을 사용할 때 memory pressure가 있으면 사용자가 요청한 huge page 해제가 실패할 수 있으므로 나중에 다시 시도해야 합니다. Huge page로 예약된 memory는 다른 목적으로 쓸 수 없고 memory pressure에서도 swap out되지 않습니다.
pool을 미리 만든 뒤 적절한 권한을 가진 사용자는 `mmap` 또는 shared memory system call로 page를 사용합니다. Boot command line의 `hugepages=N`은 memory fragmentation이 시작되기 전에 N개를 확보하므로 가장 신뢰할 수 있는 할당 방법입니다.
boot command line parameter
102-177여러 huge page size를 지원하는 platform에서는 `hugepages=N` 앞에 `hugepagesz=<size>`를 두어 크기를 선택합니다. `<size>`는 byte 단위이며 `[kKmMgG]` suffix를 쓸 수 있습니다. 기본 크기는 `default_hugepagesz=<size>`로 선택합니다.
| parameter | 동작 |
|---|---|
| hugepagesz=<size> | 뒤따르는 `hugepages`가 사용할 huge page 크기를 선택합니다. 크기별 한 번만 지정할 수 있습니다. |
| hugepages=N | boot 때 preallocate할 page 수입니다. 첫 HugeTLB parameter이면 기본 크기에 암시적으로 적용하며 node 형식도 지원합니다. |
| hugepage_alloc_threads=N | non-gigantic huge page boot allocation thread 수입니다. 기본값은 사용 가능한 hardware thread의 25%입니다. |
| default_hugepagesz=<size> | architecture가 허용하는 기본 huge page 크기를 선택하며 command line에서 한 번만 지정할 수 있습니다. |
| hugetlb_free_vmemmap | `CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP` build에서 HugeTLB Vmemmap Optimization(HVO)을 켭니다. |
`hugepagesz`와 `hugepages`는 보통 다음처럼 짝으로 쓰며, 같은 크기의 `hugepagesz`는 command line에서 한 번만 지정할 수 있습니다. 유효한 크기는 architecture에 따라 다릅니다.
hugepagesz=2M hugepages=512
`hugepages`가 첫 번째이거나 유일한 hugetlb parameter이면 기본 크기 page 수를 암시합니다. 이 암시적 기본값은 이후 같은 기본 크기의 `hugepagesz,hugepages` pair로 덮어쓸 수 없습니다. 다음 예에서 기본 크기가 2 MiB라면 256개만 할당하고 `hugepages=512`는 무시했다는 warning을 냅니다. 앞의 `hugepagesz`가 유효하지 않아도 뒤의 `hugepages`는 무시됩니다.
hugepages=256 hugepagesz=2M hugepages=512
Node format은 node별 page 수를 지정합니다. 다음 값은 node0에 2 MiB page 1개, node1에 2개를 할당하며 node 번호가 유효하지 않으면 parameter를 무시합니다.
hugepagesz=2M hugepages=0:1,1:2
`hugepage_alloc_threads`는 대량 할당 시 boot 시간을 줄이며 기본값은 사용 가능한 hardware thread의 25%입니다. 다음은 8개 thread를 쓰는 예이고 gigantic huge page에는 적용되지 않습니다.
hugepage_alloc_threads=8
`default_hugepagesz`는 command line에서 한 번만 지정할 수 있습니다. 기본 크기가 2 MiB일 때 다음 세 표기는 모두 2 MiB page 256개를 할당합니다.
hugepages=256
default_hugepagesz=2M hugepages=256
hugepages=256 default_hugepagesz=2M
`CONFIG_HUGETLB_PAGE_OPTIMIZE_VMEMMAP`가 설정된 build에서 `hugetlb_free_vmemmap`은 HugeTLB Vmemmap Optimization(HVO)을 활성화합니다.
runtime pool과 NUMA 분산
178-213여러 크기를 지원하더라도 `/proc/sys/vm/nr_hugepages`는 기본 크기의 pre-allocated page 수를 나타냅니다. 다음 명령은 기본 크기 persistent pool을 20개로 맞추기 위해 필요한 만큼 할당하거나 해제합니다.
echo 20 > /proc/sys/vm/nr_hugepages
NUMA에서는 `nr_hugepages`를 수정한 task의 NUMA memory policy가 허용한 node 집합 전체에 pool을 분산하려고 합니다. Default policy라면 memory가 있는 모든 online node가 허용됩니다. Contiguous memory가 부족한 허용 node는 조용히 건너뛰고, 다른 허용 node에 여유가 있으면 부족분을 추가 할당합니다.
실제 할당 성공 여부는 시점의 physically contiguous memory 양에 달려 있습니다. 관리자는 fragmentation이 적은 boot 초기에 실행하도록 local rc init file에 명령을 둘 수 있고, sysctl 또는 meminfo로 실제 할당 수를 확인합니다. NUMA node별 분포는 다음 명령으로 봅니다.
cat /sys/devices/system/node/node*/meminfo | fgrep Huge
surplus와 pool 축소
214-241`/proc/sys/vm/nr_overcommit_hugepages`는 application이 persistent pool보다 더 많은 page를 요청할 때 pool이 추가로 커질 수 있는 상한입니다. 0이 아닌 값을 쓰면 persistent pool이 소진됐을 때 normal page pool에서 그 수까지 surplus huge page를 만들 수 있고, 사용이 끝나면 normal pool로 반환합니다.
`nr_hugepages`로 persistent pool을 늘릴 때는 기존 surplus page를 먼저 persistent page로 승격하고, 그래도 부족할 때 새 page를 할당합니다. Pool을 줄이면 수정 task의 memory policy가 선택한 node들에 걸쳐 free page를 균형 있게 normal page pool로 반환합니다.
사용 중인 huge page 수보다 `nr_hugepages`를 작게 만들면 초과 사용분은 surplus로 전환됩니다. 이때 `nr_overcommit_hugepages` 상한을 넘을 수 있으며, `nr_hugepages + nr_overcommit_hugepages`를 충분히 늘리거나 기존 surplus가 해제될 때까지 새 surplus 할당은 허용되지 않습니다.
크기별 sysfs와 demotion
242-291Runtime에 여러 huge page pool을 지원하면서 `/proc/sys/vm` interface 대부분이 sysfs에도 복제됐습니다. `/proc`는 backward compatibility를 위해 유지되며 root control directory는 다음과 같습니다.
/sys/kernel/mm/hugepages
실행 중인 kernel이 지원하는 각 크기에는 `hugepages-${size}kB` 형식의 child directory가 생깁니다.
hugepages-${size}kB
각 directory에는 `/proc`에 대응하는 파일과, 가능한 경우 huge page를 더 작은 huge page로 분할하는 `demote`, `demote_size`가 있습니다.
demote
demote_size
nr_hugepages
nr_hugepages_mempolicy
nr_overcommit_hugepages
free_hugepages
resv_hugepages
surplus_hugepages
| 파일 | 접근 | 의미 |
|---|---|---|
| demote | write-only | 지정한 수의 huge page를 `demote_size` page들로 분할 |
| demote_size | RW | demotion 결과 page 크기, 현재 크기보다 작은 지원 크기 |
| nr_hugepages | RW | 해당 크기의 persistent huge page 수 |
| nr_hugepages_mempolicy | RW | task NUMA memory policy를 적용해 조정하는 persistent huge page 수 |
| nr_overcommit_hugepages | RW | normal page pool에서 추가로 확보할 수 있는 surplus page 상한 |
| free_hugepages | RO | 해당 크기 pool의 free huge page 수 |
| resv_hugepages | RO | 예약됐지만 아직 할당되지 않은 huge page 수 |
| surplus_hugepages | RO | persistent 목표를 넘는 surplus huge page 수 |
예를 들어 x86의 1 GiB huge page 하나는 2 MiB huge page 512개로 demote할 수 있습니다. 가장 작은 지원 크기에는 demote interface가 없습니다. `demote_size` 기본값은 다음으로 작은 크기이며, 더 작은 크기가 여러 개면 그중 하나를 지정할 수 있지만 현재 크기보다 작아야 합니다.
`demote`에는 root가 분할할 page 수를 씁니다. 요청한 수만큼 성공하지 않을 수 있으므로 쓰기 전후 `nr_hugepages`를 비교해 실제 demote 수를 확인합니다. `demote`는 write-only이고, 나머지 공통 파일은 기본 크기의 `/proc` interface와 같은 방식으로 동작합니다.
task memory policy 적용
292-318`/proc` 또는 sysfs의 `nr_hugepages_mempolicy`로 huge page를 할당·해제하면 이 값을 수정하는 task의 NUMA memory policy가 대상 node를 제어합니다. 반대로 `nr_hugepages` attribute를 쓰면 mempolicy를 무시합니다.
권장 방법은 `numactl`로 node list를 지정한 process가 `nr_hugepages_mempolicy`를 수정하는 것입니다. 다음 두 명령은 같은 의도로 사용할 수 있습니다.
numactl --interleave <node-list> echo 20 \
>/proc/sys/vm/nr_hugepages_mempolicy
numactl -m <node-list> echo 20 >/proc/sys/vm/nr_hugepages_mempolicy
현재 persistent 수가 20보다 작으면 `<node-list>`에 `abs(20 - nr_hugepages)`개를 할당하고, 크면 같은 수를 해제합니다. 목록에 포함되지 않은 node에서는 할당도 해제도 하지 않습니다.
mempolicy와 cpuset 규칙
319-359`nr_hugepages_mempolicy`를 조정할 때 bind, preferred, local, interleave 중 어느 mode도 사용할 수 있지만 persistent huge page 배치에는 다음 규칙이 적용됩니다. Mempolicy mode 자체의 자세한 설명은 `Documentation/admin-guide/mm/numa_memory_policy.rst`를 참조합니다.
| 규칙 | 결과 |
|---|---|
| 모든 policy mode | bind·preferred·local·interleave 모두 결과는 지정 node들에 interleave한 것처럼 분산합니다. |
| fallback | 허용 node에 contiguous memory가 부족해도 인접하거나 허용되지 않은 node로 fallback하지 않습니다. |
| preferred·local | preferred에 여러 node가 있으면 가장 낮은 ID만 사용하고, local은 mask 생성 시 task가 실행 중인 node를 고릅니다. |
| 상속 policy | task 또는 numactl 같은 ancestor가 설정한 non-default policy에서 nodes_allowed mask를 만듭니다. |
| cpuset | task mempolicy는 현재 cpuset의 resource limit로 제한되어 cpuset 밖에는 할당할 수 없습니다. |
| boot allocation | memory가 있는 모든 online node에 요청한 page를 분산하려고 시도합니다. |
지정 mode와 관계없이 page는 policy node들에 interleave한 것처럼 분산됩니다. 한 node의 contiguous memory가 부족해도 인접 node로 fallback하지 않는데, fallback은 pool 불균형이나 task policy가 허용하지 않은 node 할당을 만들 수 있기 때문입니다.
Bind와 interleave는 여러 node를 지정할 수 있습니다. Preferred에 여러 node를 주면 numeric ID가 가장 낮은 node만 사용합니다. Local은 nodes_allowed mask를 만들 때 task가 실행 중인 node를 선택하므로 결정적인 결과가 필요하면 한 node의 CPU에 task를 bind해야 하며, 이 용도에는 실용성이 낮습니다.
Task가 직접 설정했거나 `numactl` 같은 ancestor에서 상속한 non-default policy가 nodes_allowed mask의 기반입니다. `numactl --interleave all` 또는 `--membind all`로 system이나 cpuset의 모든 node를 선택할 수 있습니다. 다만 모든 task policy는 현재 cpuset limit를 넘을 수 없으므로 원하는 node를 포함한 cpuset으로 먼저 이동해야 합니다.
node별 attribute와 migration
360-395Memory가 있는 각 NUMA node에는 root huge page control directory의 일부가 다음 path 아래에 복제됩니다.
/sys/devices/system/node/node[0-9]*/hugepages/
각 지원 page size directory에는 다음 세 attribute가 있습니다.
nr_hugepages
free_hugepages
surplus_hugepages
| 파일 | 접근 | 의미 |
|---|---|---|
| nr_hugepages | RW | 해당 node의 total huge page 수를 직접 조정 |
| free_hugepages | RO | parent node의 free huge page 수 |
| surplus_hugepages | RO | parent node의 overcommitted huge page 수 |
Node별 `nr_hugepages`에 값을 쓰면 task의 mempolicy와 cpuset 제약을 무시하고 자원이 허용하는 범위에서 그 parent node의 persistent page 수를 직접 맞춥니다. Overcommit과 reserve 수는 fault task의 mempolicy가 적용되기 전에는 어느 node에서 할당할지 알 수 없으므로 global 값으로 유지됩니다.
Hugetlb page는 memory offline, memory failure, long-term pinning, `mbind`, `migrate_pages`, `move_pages`, `alloc_contig_range()`, `alloc_contig_pages()` 상황에서 node별 pool 사이를 이동할 수 있습니다. 현재 다른 node에 새 hugetlb를 할당하는 fallback은 memory offline, memory failure, syscall migration에만 허용되므로 이 세 경우는 per-node pool 분포를 깨뜨릴 수 있습니다.
hugetlbfs mount
396-423Application이 filesystem-backed `mmap`으로 huge page를 요청하려면 administrator가 hugetlbfs를 mount해야 합니다.
mount -t hugetlbfs \
-o uid=<value>,gid=<value>,mode=<value>,pagesize=<value>,size=<value>,\
min_size=<value>,nr_inodes=<value> none /mnt/huge
이 명령은 `/mnt/huge`에 hugetlbfs pseudo filesystem을 mount하며 그 아래에 만든 모든 file은 huge page를 사용합니다.
`uid`와 `gid`는 filesystem root의 owner와 group을 설정하고 생략하면 현재 process 값을 사용합니다. `mode`는 octal 값의 `value & 01777`로 root mode를 설정하며 기본값은 0755입니다. 여러 huge page size를 지원하면 `pagesize`로 사용할 크기와 pool을 byte 단위로 선택하고, 생략하면 platform 기본값을 사용합니다.
mount limit와 접근 방식
424-464| option | 의미 |
|---|---|
| uid | filesystem root owner UID, 기본값은 현재 process UID |
| gid | filesystem root group GID, 기본값은 현재 process GID |
| mode | filesystem root mode를 `value & 01777`로 설정, 기본값 0755 |
| pagesize | 사용할 huge page 크기와 pool, 생략하면 platform 기본 크기 |
| size | filesystem이 사용할 수 있는 huge page memory 상한, byte 또는 pool 비율 |
| min_size | mount 시 reserve할 최소 huge page memory, 부족하면 mount 실패 |
| nr_inodes | filesystem에서 사용할 수 있는 inode 수 상한 |
`size`는 filesystem이 쓸 huge page memory 상한이며 byte 또는 선택한 pool의 `nr_hugepages` 비율로 지정하고 HPAGE_SIZE 경계로 내림합니다. `min_size`도 byte 또는 비율이며 mount 시 해당 수를 reserve합니다. Free page가 부족하면 mount가 실패하고, 이후 allocated와 reserved 합이 항상 `min_size` 이상이 되도록 reserve 수를 조정합니다.
`size`, `min_size`, `nr_inodes`를 생략하면 해당 limit는 없습니다. `pagesize`, `size`, `min_size`, `nr_inodes`에는 `[G|g]`, `[M|m]`, `[K|k]` suffix를 쓸 수 있어 `size=2K`는 `size=2048`과 같습니다.
Hugetlbfs file의 `read` system call은 지원하지만 `write` system call은 지원하지 않습니다. 권한이 있으면 일반 `chown`, `chgrp`, `chmod`로 file attribute를 바꿀 수 있습니다.
`shmat`·`shmget`만 쓰거나 `mmap`에 `MAP_HUGETLB`를 쓰는 application에는 hugetlbfs mount가 필요 없습니다. Shared memory segment로 hugetlb memory를 쓰려는 사용자는 supplementary group member여야 하고 administrator는 그 GID를 `/proc/sys/vm/hugetlb_shm_group`에 설정해야 합니다. MAP_HUGETLB 없는 mmap에는 filesystem mount가 필요합니다.
system call 정렬 제약
465-472Hugetlb-backed memory를 다루는 syscall의 length parameter 자체는 processor native page size에 맞춰지지만, huge page 경계에 맞지 않으면 보통 `EINVAL`로 실패하거나 length 밖으로 넘어가는 hugetlb page를 제외합니다.
예를 들어 hugetlb page가 backing하는 memory에 `munmap(2)`을 호출하면서 length를 huge page size보다 작게 주면 실패합니다. Address와 length를 해당 huge page 크기에 맞춰야 합니다.
예제와 libhugetlbfs
473-490| 예제 | source path | 초점 |
|---|---|---|
| map_hugetlb | tools/testing/selftests/mm/map_hugetlb.c | mmap과 MAP_HUGETLB |
| hugepage-shm | tools/testing/selftests/mm/hugepage-shm.c | System V shared memory |
| hugepage-mmap | tools/testing/selftests/mm/hugepage-mmap.c | hugetlbfs-backed mmap |
`map_hugetlb`, `hugepage-shm`, `hugepage-mmap`의 실제 C 예제는 각각 위 selftest source path에 있습니다.
`libhugetlbfs` library는 huge page 사용성, environment 설정, 제어를 돕는 폭넓은 user-space tool을 제공합니다.
HugeTLB 운영 지도
hugetlbpage.rst:1-490HugeTLB는 큰 page로 TLB pressure를 줄이지만 memory를 별도 pool에 고정하고 swap할 수 없으므로 사전 용량 계획이 필요합니다. 가장 안정적인 방법은 boot 때 page size와 수를 예약하고, runtime에는 global·크기별·node별 interface의 차이를 이해해 조정하는 것입니다.
NUMA system에서는 `nr_hugepages_mempolicy`가 task policy와 cpuset을 따르는 반면 per-node `nr_hugepages`는 이를 무시합니다. Application은 hugetlbfs-backed mmap, `MAP_HUGETLB`, SYSV shared memory 중 요구에 맞는 경로를 선택하고 huge page 크기에 주소와 길이를 정렬해야 합니다.