[PATCH] malloc: Avoid accessing /sys/kernel/mm files

Wilco Dijkstra Wilco.Dijkstra@arm.com
Fri Feb 27 21:03:05 GMT 2026


On AArch64 malloc always checks /sys/kernel/mm/transparent_hugepage/enabled to set
the THP mode. However this check is quite expensive and the file may not be accessible
in containers. If DEFAULT_THP_PAGESIZE is non-zero, use malloc_thp_mode_madvise so that
we take advantage of THP in all cases. Since madvise is a fast systemcall, it adds only
a small overhead compared to the cost of mmap and populating the pages.

Passes regress, OK for commit?

---

diff --git a/malloc/arena.c b/malloc/arena.c
index cabeb0d8ce1783121af3327ccd3371ab516b8722..988182c25f022783cb6b97d0c8d5ba3b5a718335 100644
--- a/malloc/arena.c
+++ b/malloc/arena.c
@@ -275,6 +275,15 @@ __ptmalloc_init (void)
     __always_fail_morecore = true;
 #endif
 
+  /* Enable THP if DEFAULT_THP_PAGESIZE is non-zero.  Avoid quering the THP
+     page size or mode since accessing /sys/kernel/mm is relatively slow and
+     might not be accessible in containers.  */
+  if (DEFAULT_THP_PAGESIZE > 0)
+    {
+      mp_.thp_mode = malloc_thp_mode_madvise;
+      mp_.thp_pagesize = DEFAULT_THP_PAGESIZE;
+    }
+
   thread_arena = &main_arena;
 
   malloc_init_state (&main_arena);
diff --git a/malloc/malloc.c b/malloc/malloc.c
index d3bf2b9b7687b721cd157e5688ad83944c780e92..b87280228a0b6e07f5a38e6b45af842fa29c34ac 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -1898,26 +1898,11 @@ free_perturb (char *p, size_t n)
 
 /* ----------- Routines dealing with transparent huge pages ----------- */
 
-static __always_inline void
-thp_init (void)
-{
-  /* Initialize only once if DEFAULT_THP_PAGESIZE is defined.  */
-  if (DEFAULT_THP_PAGESIZE == 0 || mp_.thp_mode != malloc_thp_mode_not_supported)
-    return;
-
-  /* Set thp_pagesize even if thp_mode is never.  This reduces frequency
-     of MORECORE () invocation.  */
-  mp_.thp_mode = __malloc_thp_mode ();
-  mp_.thp_pagesize = DEFAULT_THP_PAGESIZE;
-}
-
 static inline void
 madvise_thp (void *p, INTERNAL_SIZE_T size)
 {
 #ifdef MADV_HUGEPAGE
 
-  thp_init ();
-
   /* Only use __madvise if the system is using 'madvise' mode and the size
      is at least a huge page, otherwise the call is wasteful. */
   if (mp_.thp_mode != malloc_thp_mode_madvise || size < mp_.thp_pagesize)
@@ -2468,9 +2453,6 @@ sysmalloc (INTERNAL_SIZE_T nb, mstate av)
          previous calls. Otherwise, we correct to page-align below.
        */
 
-      /* Ensure thp_pagesize is initialized.  */
-      thp_init ();
-
       if (__glibc_unlikely (mp_.thp_pagesize != 0))
 	{
 	  uintptr_t lastbrk = (uintptr_t) MORECORE (0);



More information about the Libc-alpha mailing list