Hugepages linux что это

Обновлено: 03.07.2024

Performance tuning of large database systems can be a challenge. Depending on the operating system (OS) and hardware, there might be performance issues that are not readily detectable using normal analysis methods such as AWR reports and OS tools such as sar , top , and iostat .

Memory utilization in x86 environments is one of the issues that is not readily identifiable, but it can result in significant performance improvements if properly analyzed and configured.

Now more than ever, with systems that have larger amounts of memory, memory utilization is a critical issue that needs to be addressed. This article describes how to best configure x86 system memory performance for large databases.

Virtual Memory Architecture for x86 Platforms

The memory architecture of the x86 and x86-64 chipsets has changed significantly since its inception; however, the default memory page size has not changed. This can result in inefficiency and excessive overhead when large amounts of memory are used for large applications, such as databases.

The x86 architecture is a virtual memory architecture, which allows for more memory to be addressed than is physically available in the hardware. This is accomplished by allowing each process to have its own memory that it can address. The process believes that this memory is available to it for its use. This is known as the process's virtual memory. In reality, this memory can be either physical memory that is actually residing on the RAM chips, or it can be stored in a dedicated area on physical disk, which is known as the swap or paging area.

The process does not know whether the virtual memory is stored in RAM or on disk; the memory is managed by the OS. If more memory is needed than is physically available, the OS will move some memory out to the paging area. This activity is very inefficient and is a common cause of performance problems. Since disk is many times slower than RAM, a process that is "paging" will experience significant performance problems.

Oracle Database and Linux Memory Management

The more memory used in the system, the more resources are required to manage that memory. With the Linux OS, memory management is accomplished via the Linux kswapd process and the Page Tables memory structure, which consists of one record for each process that exists in the system. Each record consists of every page of virtual memory used by the process and its physical address (RAM or disk). This process is assisted via the use of the processor's translation lookaside buffer (TLB), a small cache.

When using large amounts of memory for Oracle Database, the OS consumes significant resources to manage the virtual-to-physical translation, which often results in a very large Page Tables structure. Since each Page Tables entry contains the virtual-to-physical translation of all memory pages being used by the process, for a very large System Global Area (SGA), the Page Tables entry can be very large for each process. For example, an Oracle Database process that uses 8 GB of memory will have a Page Tables entry of 8 GB/4 KB or 2,097,152 records, or pages. If there are one hundred Oracle Database sessions/processes, multiply the number of pages by 100. As you can see, that is a huge number of pages to manage.

Again, the Page Tables entries are used by the operating system to manage the memory used by the processes in the system. In Linux, the OS process that does this management is called kswapd and can be seen by operating system tools.

The TLB cache will cache the Page Tables entries in order to improve performance. The typical TLB cache holds between 4 and 4,096 entries. With millions or billions of Page Tables entries, this cache is insufficient.

As mentioned earlier, for systems using large SGAs, the Page Tables structure can get very large. The sample Linux system output in Listing 1 shows the Page Tables entries taking up 766 MB of RAM. This can be a significant overhead on the system. I have personally seen Page Tables entries in the gigabytes.

In Linux operating systems, HugePages is a kernel feature that allows the OS to support the large page size capabilities of modern hardware architectures. For Oracle Database, enabling HugePages and using the large page size reduces the operating system maintenance of page states and increases the TLB cache hit ratio by managing more memory with a single page table entry for a large page, rather than with many entries for a smaller page. In Linux, the large page size is 2 MB.

In Oracle Linux 6 or Red Hat Enterprise Linux 6 (RHEL 6), the number of HugePages allocated is available in /proc/meminfo , as shown in Listing 1:

Listing 1

In Oracle Linux 6, the HugePages allocated are slightly different, as shown in Listing 2:

Listing 2

The Oracle Linux 6 HugePages values are as follows:

  • AnonHugePages . The number of Anonymous HugePages. This counter has been removed in Oracle Linux 6.5. Related to Transparent HugePages. (See the "Transparent HugePages and Oracle Databases" section for more information on Transparent HugePages.)
  • HugePages_Total . The number of HugePages. The amount of space is the number of HugePages times 2M.
  • HugePages_Free . The number of HugePages in the pool that are not yet allocated.
  • HugePages_Rsvd . Short for "reserved," and is the number of HugePages for which a commitment to be allocated from the pool has been made, but no allocation has yet been made. Reserved HugePages guarantee that an application will be able to allocate HugePages from the pool of HugePages at the time they are requested, even if the system has been up for a while.
  • HugePages_Surp . Short for "surplus," and is the number of HugePages in the pool above the value in /proc/sys/vm/nr_hugepages . The maximum number of surplus HugePages is controlled by /proc/sys/vm/nr_overcommit_hugepages . It is not unusual for this to be 0 .
  • Hugepagesize . The size of the HugePage. This is currently 2048 or 2 MB.

Solution

By enabling HugePages in Linux, the number of TLB entries can be reduced by increasing the page size. With Linux, the HugePages size is 2 MB. By using larger pages for the Oracle Database SGA, the number of pages to manage is greatly reduced.

In the example shown in Listing 1, the number of virtual-to-physical translations for a single record will be reduced to 4,096 from 2,097,152. This will reduce the size of the Page Tables structure, improve the TLB cache hit ratio, and reduce kswapd usage.

Note: The performance improvement when enabling HugePages can be dramatic.

Enabling HugePages in Linux

In Linux, the HugePages capability is configured by setting the Linux initialization parameter vm.nr_hugepages to the number of 2 MB pages that you want to make available for the Oracle Database SGA. Setting this parameter can reduce the number of pages by making them larger.

Note: The automatic memory management feature of Oracle Database that was introduced in Oracle Database 11g is not compatible with Linux HugePages. The performance improvement that is provided by HugePages outweighs the ease of use provided by automatic memory management.

The details on implementing the HugePages configuration can be found in the My Oracle Support documents shown in Table 1.

Table 1. My Oracle Support Documents

My Oracle Support Document ID Document Name
1557478.1 "ALERT: Disable Transparent HugePages on SLES11, RHEL6, OEL6 and UEK2 Kernels"
361323.1 "HugePages on Linux: What It Is… And What It Is Not"
361468.1 "HugePages on Oracle Linux 64-bit"
749851.1 "HugePages and Oracle Database 11g Automatic Memory Management (AMM) on Linux"
1134002.1 "ASMM and LINUX x86-64 HugePages Support"
401749.1 "Shell Script to Calculate Values Recommended Linux HugePages / HugeTLB Configuration"

In addition to configuring vm.nr_hugepages , the optional parameter vm.hugetlb_shm_group can be set with the OS group that has permissions to use HugePages. This parameter is set to 0 by default, thus allowing all groups permissions to use HugePages. This parameter can be set to an OS group that the Oracle Database process is part of, such as oinstall .

Verifying that Large Pages Are Enabled for Your Oracle Database Instance

You can verify that large pages are enabled for your database instance by checking the alert log. At startup of the instance, you should see entries such as the following in your alert log before the parameter listing:

Transparent HugePages and Oracle Databases

Recently, in RHEL 6, Oracle Linux 6, and SUSE Linux Enterprise Server 11 a new feature, transparent HugePages was introduced. Transparent HugePages is an attempt to make the use of HugePages automatic and dynamic. Unfortunately the use of transparent HugePages in conjunction with the use of traditional HugePages is currently causing problems that can result in performance issues and system reboots. In My Oracle Support note 1557478.1, Oracle recommends not using transparent HugePages in conjunction with Oracle databases.

Note: In Oracle Linux version 6.5 Transparent HugePages have been removed.

Conclusion

By using larger pages, the number of Page Tables entries is reduced and, thus, significant overhead is minimized. The improvement achieved by the use of HugePages is very significant and increases with the amount of memory in the system and the size of the SGA.

See Also

About the Author

Edward Whalen is an Oracle ACE and the Chief Technologist at Performance Tuning Corporation, a consulting company specializing in database performance, administration, migrations, virtualization, and disaster recovery solutions with over 25 years of experience. He has extensive experience in system architectural design for optimal performance. His career has consisted of hardware, OS, database, and virtualization projects for many different companies. Edward has written six books on Oracle products and five books on Microsoft SQL Server, and he just completed the Oracle Enterprise Manager Cloud Control 12c Deep Dive book for Oracle Press. He has also worked on numerous benchmarks and performance tuning projects with both Oracle products and Microsoft SQL Server.

Edward has extensive architectural experience consisting of all layers of the cloud/application stack from storage and hardware, to hypervisor and OS, and to the database. This experience provided the foundation for the system architecture work he has done in the past.

Edward started out in college as an experimental physicist working in High Energy Physics on projects at both Fermi lab and the Stanford Linear Accelerator Center. After working briefly on the Superconducting Super Collider, he moved into computer software and then into computer hardware and OS development, which evolved into database performance engineering.

Ядро Linux предоставляет широкий спектр параметров конфигурации, которые могут повлиять на производительность. Главное — выбрать правильную конфигурацию для вашего приложения и рабочей нагрузки. Как и любой другой базе данных, PostgreSQL необходима оптимальная настройка ядра Linux. Неправильные настройки могут привести к снижению производительности. Важно проводить сравнительный анализ производительности базы данных после каждого сеанса настройки. В одном из своих предыдущих постов под названием "Tune Linux Kernel Parameters For PostgreSQL Optimization" я описал некоторые из наиболее полезных параметров ядра Linux и то, как они помогают повысить производительность базы данных. Теперь я поделюсь результатами сравнительного тестирования после настройки HugePages в Linux под различными нагрузками PostgreSQL. Я провел полный набор тестов под множеством различных нагрузок PostgreSQL с различным числом параллельных клиентов.

image

ПК, на котором выполнялось тестирование

  • Сервер Supermicro:
    1. Intel® Xeon® CPU E5-2683 v3 @ 2,00 ГГц
    2. 2 сокета / 28 ядер / 56 потоков
    3. Память: ОЗУ 256 ГБ
    4. Накопитель: SAMSUNG SM863 1,9 ТБ Enterprise SSD
    5. Файловая система: ext4/xfs
  • ОС: Ubuntu 16.04.4, ядро 4.13.0-36-generic
  • PostgreSQL: версия 11

Настройки ядра Linux

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

Настройки PostgreSQL

Я использовал одинаковые настройки PostgreSQL для всех тестов, чтобы записывать различные рабочие нагрузки PostgreSQL с различными настройками Linux HugePages. Для всех тестов применялись следующие настройки PostgreSQL:

Схема тестирования

Схема тестирования играет важную роль. Все тесты выполняются три раза, продолжительность каждого запуска — 30 минут. По итогам этих 3-х тестов я вывел среднее значение. Тестирование проводились с помощью инструмента PostgreSQL pgbench, он работает с коэффициентом масштабирования с шагом в примерно 16 МБ нагрузки.

HugePages

По умолчанию в Linux используются страницы памяти размером 4K, а также технология HugePages. В BSD применяется технология Super Pages, а в Windows — Large Pages. PostgreSQL поддерживает только технологию HugePages (Linux). В случаях, когда объем используемой памяти велик, страницы меньшего размера снижают производительность. Используя HugePages, вы увеличиваете выделенную память для приложения и, следовательно, уменьшаете «накладные расходы», которые возникают в процессе выделения/подкачки. Таким образом, HugePages повышают производительность.

Здесь представлены настройки для HugePages размером 1 ГБ. Эта информация доступна в любой момент, с помощью /proc.

Подробнее о HugePages я писал в предыдущем посте.

В общем случае HugePages имеют размеры 2 МБ и 1 ГБ, поэтому имеет смысл использовать 1 ГБ.

Результаты тестирования

Этот тест показывает общий эффект от использования HugePages различного размера. Первый набор тестов был создан с размером страницы 4K — используется в Linux по умолчанию — и без активации HugePages. Напомню: опцию Transparent HugePages я отключил на все время тестов.

Затем второй набор тестов был выполнен для HugePages размером 2 МБ. Наконец, третий набор тестов выполнялся для HugePages размером 1 ГБ.

Для всех сравнительных тестов использовалась СУБД PostgreSQL версии 11. Наборы включают комбинации различных размеров баз данных и различных клиентов. На графике ниже показаны результаты сравнения производительности с помощью этих тестов: TPS (число транзакций в секунду) — по оси Y, а размер базы данных и количество клиентов для базы данных определенного размера — по оси X.

image

Из приведенного выше графика видно, что, от использования HugePages, выигрыш растет по мере того, как увеличивается число клиентов и размер базы данных — до тех пор, пока этот размер остается в рамках предварительно выделенного общего буфера.

В этом тесте сопоставлялись показатели TPS и количество клиентов. В данном случае размер базы данных — 48 ГБ. На оси Y показано TPS, а на оси X — количество подключенных клиентов. Размер базы данных достаточно мал, чтобы она могла поместиться в общий буфер с установленным размером 64 ГБ.

image

Когда размер HugePages равен 1 ГБ, сравнительный выигрыш в производительности растет с увеличением числа клиентов.

Следующий график такой же, как и предыдущий, но размер базы данных — 96 ГБ. Это больше установленного размера общего буфера, равного 64 ГБ.


Главное, что здесь необходимо отметить: производительность с HugePages размером 1 ГБ повышается по мере увеличения числа клиентов и в конечном итоге обеспечивает лучшие показатели, чем при использовании HugePages размером 2 МБ или стандартных страниц размером 4 КБ.

Этот тест показывает соотношение TPS и размера базы данных. В данном случае число подключенных клиентов равно 32. На оси Y показано TPS, а на оси X — размеры базы данных.

image

Как и ожидалось, когда размер базы данных превышает размер заранее выделенных HugePages, производительность значительно снижается.

Заключение

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


Ранее я рассказал о том, как проверить и включить использование Hugepages в Linux.
Эта статья будет полезна, только если у вас действительно есть, где использовать Hugepages. Я встречал множество людей, которые обманываются перспективой того, что Hugepages волшебным образом повысят производительность. Тем не менее hugepaging является сложной темой, и при неправильном использовании он способен понизить производительность.

Проблема:
Необходимо проверить, включены ли HugePages в вашей системе.

Решение:
Оно довольно простое:

Вы получите что-то вроде этого:

Вы увидите список доступных опций (always, madvise, never), при этом текущая активная опция будет заключена в скобки (по умолчанию madvise).

madvise означает, что transparent hugepages включены только для областей памяти, которые явно запрашивают hugepages с помощью madvise(2).

always означает, что transparent hugepages включены всегда и для всех процессов. Обычно это повышает производительность, но если у вас есть вариант использования, где множество процессов потребляет небольшое количество памяти, то общая нагрузка на память может резко возрасти.

never означает, что transparent hugepages не будут включаться даже при запросе с помощью madvise. Чтобы узнать больше, обратитесь к документации ядра Linux.

Как изменить значение по умолчанию

Вариант 1: Напрямую изменить sysfs (после перезагрузки параметр вернется к значению по умолчанию):

Вариант 2: Измените системное значение по умолчанию, перекомпилировав ядро с измененной конфигурацией (этот вариант рекомендуется только если вы используете собственное ядро):

  • Чтобы поставить always по умолчанию, используйте:
  • Чтобы поставить madvise по умолчанию, используйте:

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

Обратите внимание, что мы говорим о 64-х разрядных x86 системах, работающих на Linux, и что я просто предполагаю, что система поддерживает transparent hugepages (так как не является недостатком то, что hugepages не подменяются), как это случается практически в любой современной среде Linux.

В ссылках ниже я прикреплю больше технического описания.

Виртуальная память

Если вы программист C++, вы знаете, что у объектов в памяти есть конкретные адреса (значения указателя).

Однако эти адреса необязательно отражают физические адреса в памяти (адреса в ОЗУ). Они представляют собой адреса в виртуальной памяти. Процессор имеет специальный модуль MMU (memory management unit), который помогает ядру сопоставлять виртуальную память с физическим местоположением.

Такой подход имеет множество преимуществ, но самые основные из них:

  • Производительность (по различным причинам);
  • Изоляция программ, то есть ни одна из программ не может читать из памяти другой программы.

Что такое страницы?

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

Большинство страниц, с которыми вы имеете дело, указывают либо на ОЗУ, либо подменяются (swap), то есть хранятся на жестком диске или SSD. Ядро управляет физическим расположением каждой страницы. Если осуществляется доступ к подмененной странице, ядро останавливает поток, который пытается получить доступ к памяти, считывает страницу с жесткого диска/SSD в оперативную память, а затем продолжает выполнение потока.

Этот процесс прозрачен для потока, то есть он не обязательно читает напрямую с жесткого диска/SSD. Размер нормальных страниц – 4096 байт. Размер Hugepages – 2 мегабайта.

Буфер ассоциативной трансляции (TLB)

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

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

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

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

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

Hugepages приходят на помощь

Итак, что мы можем сделать, чтобы избежать переполнения TLB? (Мы предполагаем, что программе все еще нужен тот же объем памяти).

Вот тут-то и появляются Hugepages. Вместо 4096 байт, требующих всего одну запись в TLB, одна запись в TLB теперь может указывать на колоссальные 2 мегабайта. Будем предполагать, что TLB имеет 512 записей, здесь без Hugepages мы можем сопоставить:

Тогда как с ними мы можем сопоставить:

Именно поэтому Hugepages – это круто. Они могут повысить производительность без значительного приложения усилий. Но здесь есть существенные оговорки.

Подмена Hugepages

Ядро автоматически отслеживает частоту использования каждой страницы памяти. Если физической памяти (ОЗУ) недостаточно, ядро переместит менее важные (реже используемые) страницы на жесткий диск, чтобы освободить часть ОЗУ для более важных страниц.
В принципе, то же самое касается и Hugepages. Однако ядро может менять местами только целые страницы, а не отдельные байты.

Предположим, у нас есть такая программа:

В этом случае ядру нужно будет подменить (прочитать) целых 2 мегабайта информации с жесткого диска/SSD только для того чтобы вы прочитали один байт. Что касается обычных страниц, с жесткого диска/SSD надо прочитать всего 4096 байт.

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

С другой стороны, если вам нужно получать доступ к большой части памяти последовательно, hugepages увеличат вашу производительность. Тем не менее, вам нужно проверить это самостоятельно (а не на примере абстрактного ПО) и посмотреть, что будет работать быстрее.

Аллокация в памяти

Если вы пишете на С, вы знаете, что вы можете запросить сколь угодно малые (или почти сколь угодно большие) объемы памяти из кучи с помощью malloc() . Допустим, вам нужно 30 байт памяти:

Программисту может показаться, что вы “запрашиваете” 30 байт памяти из операционной системы и возвращаете указатель на некоторую виртуальную память. Но на самом деле malloc () — это просто функция C, которая вызывает изнутри функции brk и sbrk для запроса или освобождения памяти из операционной системы.

Однако, запрашивать больше и больше памяти для каждой аллокации неэффективно; наиболее вероятно, что какой-либо сегмент памяти уже был освобожден (free()) , и мы можем повторно его использовать. malloc() реализует довольно сложные алгоритмы для повторного использования освобожденной памяти.

При этом для вас все происходит незаметно, так почему это должно вас волновать? А потому, что вызов free() не означает, что память обязательно возвращается сразу же операционной системе.

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

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

Выборочное применение hugepages

После прочтения статьи, вы определили, какие части вашей программы могут извлечь выгоду из применения hugepages, а какие – нет. Так следует ли вообще включать hugepages?

К счастью, вы можете использовать madvise() , чтобы включить hugepaging только для тех областей памяти, где это будет полезно.

Для начала, проверьте, что hugepages работают в режиме madvise(), с помощью инструкции в начале статьи.

Затем, используйте madvise() , чтобы указать ядру, где именно использовать hugepages.

Обратите внимание, что этот метод — просто рекомендации ядру по управлению памятью. Это не означает, что ядро будет автоматически использовать hugepages для заданной памяти.

Обратитесь к документации (manpage) madvise, чтобы узнать больше об управлении памятью и madvise() , у этой темы невероятно крутая кривая обучения. Поэтому, если вы намереваетесь действительно хорошо разобраться в ней, подготовьтесь к чтению и тестированию в течение нескольких недель, прежде чем рассчитывать на хоть какой-то положительный результат.

This chapter provides an overview of Hugepages and guides Linux system administrators to configure HugePages on Linux.

G.1 Overview of HugePages

HugePages is a feature integrated into the Linux kernel 2.6. Enabling HugePages makes it possible for the operating system to support memory pages greater than the default (usually 4 KB). Using very large page sizes can improve system performance by reducing the amount of system resources required to access page table entries. HugePages is useful for both 32-bit and 64-bit configurations. HugePage sizes vary from 2 MB to 256 MB, depending on the kernel version and the hardware architecture. For Oracle Databases, using HugePages reduces the operating system maintenance of page states, and increases Translation Lookaside Buffer (TLB) hit ratio.

Transparent Hugepages is currently not an alternative to manually configure HugePages.

This section includes the following topics:

G.1.1 Tuning SGA With HugePages

Without HugePages, the operating system keeps each 4 KB of memory as a page. When it allocates pages to the database System Global Area (SGA), the operating system kernel must continually update its page table with the page lifecycle (dirty, free, mapped to a process, and so on) for each 4 KB page allocated to the SGA.

With HugePages, the operating system page table (virtual memory to physical memory mapping) is smaller, because each page table entry is pointing to pages from 2 MB to 256 MB.

Also, the kernel has fewer pages whose lifecycle must be monitored. For example, if you use HugePages with 64-bit hardware, and you want to map 256 MB of memory, you may need one page table entry (PTE). If you do not use HugePages, and you want to map 256 MB of memory, then you must have 256 MB * 1024 KB/4 KB = 65536 PTEs.

HugePages provides the following advantages:

Increased performance through increased TLB hits

Pages are locked in memory and never swapped out, which provides RAM for shared memory structures such as SGA

Contiguous pages are preallocated and cannot be used for anything else but for System V shared memory (for example, SGA)

Less bookkeeping work for the kernel for that part of virtual memory because of larger page sizes

G.1.2 Configuring HugePages on Linux

Complete the following steps to configure HugePages on the computer:

Run the following command to determine if the kernel supports HugePages:

Some Linux systems do not support HugePages by default. For such systems, build the Linux kernel using the CONFIG_HUGETLBFS and CONFIG_HUGETLB_PAGE configuration options. CONFIG_HUGETLBFS is located under File Systems and CONFIG_HUGETLB_PAGE is selected when you select CONFIG_HUGETLBFS .

Edit the memlock setting in the /etc/security/limits.conf file. The memlock setting is specified in KB, and the maximum locked memory limit should be set to at least 90 percent of the current RAM when HugePages memory is enabled and at least 3145728 KB (3 GB) when HugePages memory is disabled. For example, if you have 64 GB RAM installed, then add the following entries to increase the maximum locked-in-memory address space:

You can also set the memlock value higher than your SGA requirements.

Log in as oracle user again and run the ulimit -l command to verify the new memlock setting:

Run the following command to display the value of Hugepagesize variable:

Complete the following procedure to create a script that computes recommended values for hugepages configuration for the current shared memory segments:

Create a text file named hugepages_settings.sh .

Add the following content in the file:

Run the following command to change the permission of the file:

Run the hugepages_settings.sh script to compute the values for hugepages configuration:

Before running this script, ensure that all the applications that use hugepages run.

Set the following kernel parameter, where value is the HugePages value that you determined in step 7:

To ensure that HugePages is allocated after system restarts, add the following entry to the /etc/sysctl.conf file, where value is the HugePages value that you determined in step 7:

Run the following command to check the available hugepages :

Restart the instance.

Run the following command to check the available hugepages (1 or 2 pages free):

If you cannot set your HugePages allocation using nr_hugepages , then your available memory may be fragmented. Restart your server for the Hugepages allocation to take effect.

G.1.3 Restrictions for HugePages Configurations

HugePages has the following limitations:

You must unset both the MEMORY_TARGET and MEMORY_MAX_TARGET initialization parameters. For example, to unset the parameters for the database instance, use the command ALTER SYSTEM RESET .

Automatic Memory Management (AMM) and HugePages are not compatible. When you use AMM, the entire SGA memory is allocated by creating files under /dev/shm . When Oracle Database allocates SGA with AMM, HugePages are not reserved. To use HugePages on Oracle Database 12 c , You must disable AMM.

If you are using VLM in a 32-bit environment, then you cannot use HugePages for the Database Buffer cache. You can use HugePages for other parts of the SGA, such as shared_pool , large_pool , and so on. Memory allocation for VLM (buffer cache) is done using shared memory file systems ( ramfs/tmpfs/shmfs ). Memory file systems do not reserve or use HugePages.

HugePages are not subject to allocation or release after system startup, unless a system administrator changes the HugePages configuration, either by modifying the number of pages available, or by modifying the pool size. If the space required is not reserved in memory during system startup, then HugePages allocation fails.

Ensure that HugePages is configured properly as the system may run out of memory if excess HugePages is not used by the application.

If there is insufficient HugePages when an instance starts and the initialization parameter use_large_pages is set to only , then the database fails to start and an alert log message provides the necessary information on Hugepages.

G.1.4 Disabling Transparent HugePages

Transparent HugePages memory is enabled by default with Red Hat Enterprise Linux 6, SUSE 11, and Oracle Linux 6 with earlier releases of Oracle Linux Unbreakable Enterprise Kernel 2 (UEK2) kernels. Transparent HugePages memory is disabled by default in later releases of UEK2 kernels.

Transparent HugePages can cause memory allocation delays at runtime. To avoid performance issues, Oracle recommends that you disable Transparent HugePages on all Oracle Database servers. Oracle recommends that you instead use standard HugePages for enhanced performance.

Transparent HugePages memory differs from standard HugePages memory because the kernel khugepaged thread allocates memory dynamically during runtime. Standard HugePages memory is pre-allocated at startup, and does not change during runtime.

To check if Transparent HugePages is enabled run one of the following commands as the root user:

Red Hat Enterprise Linux kernels:

The following is a sample output that shows Transparent HugePages is being used as the [always] flag is enabled.

If Transparent HugePages is removed from the kernel then the /sys/kernel/mm/transparent_hugepage or /sys/kernel/mm/redhat_transparent_hugepage files do not exist.

Читайте также: