[PATCH] realloc: Do not call madvise if oldsize >= THP size

Dev Jain dev.jain@arm.com
Mon Oct 6 05:53:16 GMT 2025


Linux handles virtual memory in Virtual Memory Areas (VMAs). The
madvise(MADV_HUGEPAGE) call works on a VMA granularity, which sets the
VM_HUGEPAGE flag on the VMA. If this VMA or a portion of it is mremapped
to a different location, Linux will create a new VMA, which will have
the same flags as the old one. This implies that the VM_HUGEPAGE flag
will be retained. Therefore, if we can guarantee that the old VMA was
marked with VM_HUGEPAGE, then there is no need to call madvise_thp() in
mremap_chunk().

The old chunk comes from an mmap allocation, which has already been
enlightened for THP. This implies that, if THP is on, and the size of the
old chunk is greater than or equal to thp_pagesize, the representative VMA
of this chunk has the VM_HUGEPAGE flag set. Hence in this case we can
avoid invoking the madvise() syscall.
---
 malloc/malloc.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/malloc/malloc.c b/malloc/malloc.c
index f46cfd5eac..7b666d5b2a 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -3065,7 +3065,10 @@ mremap_chunk (mchunkptr p, size_t new_size)
   if (cp == MAP_FAILED)
     return NULL;
 
-  madvise_thp (cp, new_size);
+  /* mremap preserves the region's flags - this means that if the old chunk
+     was marked with MADV_HUGEPAGE, the new chunk will retain that. */
+  if (total_size < mp_.thp_pagesize)
+    madvise_thp (cp, new_size);
 
   p = (mchunkptr) (cp + offset);
 
-- 
2.43.0



More information about the Libc-alpha mailing list