From 97f56c04a1883982f4dbdc041369fd047c3d4d66 Mon Sep 17 00:00:00 2001 From: Matthew Dillon Date: Thu, 23 Jul 2015 14:22:32 -0700 Subject: [PATCH] nmalloc - Improve incremental reallocs() * Fix realloc() issue that caused unnecessary unmap/remap operations due to the page coloring optimization. * In addition, scale large reallocations by allowing more wiggle room as the allocation becomes larger so overhead isn't quite as geometrically bad for programs which do incremental realloc()s to huge sizes. Initial-patch-by: vadaszi Bug #2832 --- lib/libc/stdlib/nmalloc.c | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/lib/libc/stdlib/nmalloc.c b/lib/libc/stdlib/nmalloc.c index 0e46e3d312..cc076a02df 100644 --- a/lib/libc/stdlib/nmalloc.c +++ b/lib/libc/stdlib/nmalloc.c @@ -1058,10 +1058,33 @@ _slabrealloc(void *ptr, size_t size) if (big->base == ptr) { size = (size + PAGE_MASK) & ~(size_t)PAGE_MASK; bigbytes = big->bytes; - if (bigbytes == size) { + + /* + * If it already fits determine if it makes + * sense to shrink/reallocate. Try to optimize + * programs which stupidly make incremental + * reallocations larger or smaller by scaling + * the allocation. Also deal with potential + * coloring. + */ + if (size <= bigbytes && + (size + 4096 == bigbytes || + size >= bigbytes - (size >> 2))) { bigalloc_unlock(ptr); return(ptr); } + + /* + * For large allocations, allocate more space + * than we need to try to avoid excessive + * reallocations later on. + */ + if (size > PAGE_SIZE * 16) { + size += size >> 3; + size = (size + PAGE_MASK) & + ~(size_t)PAGE_MASK; + } + *bigp = big->next; bigalloc_unlock(ptr); if ((nptr = _slaballoc(size, 0)) == NULL) { -- 2.41.0