From dd22d6ed11ba38f4d61011aaeeb4200741b934a7 Mon Sep 17 00:00:00 2001 From: Roman Arutyunyan Date: Fri, 13 Jun 2025 17:25:20 +0400 Subject: [PATCH] Core: trim malloc memory after configuration unload. When using dynamic configurations, multiple malloc arens could be created because of using threads. Also, a worker process may persist through multiple dynamic cycles which increases memory fragmentation. Both these factors contribute to malloc not being able to effectively free its memory to the kernel, which increases overall system memory consumption despite only a small amount of memory being allocated from malloc(). To enfoce memory release, malloc_trim() is now called after cycle unload. --- auto/unix | 10 ++++++++++ src/core/ngx_dynamic_conf.c | 4 ++++ 2 files changed, 14 insertions(+) diff --git a/auto/unix b/auto/unix index 6087e04fd..2f9ac4555 100644 --- a/auto/unix +++ b/auto/unix @@ -833,6 +833,16 @@ ngx_feature_test="void *p; p = memalign(4096, 4096); . auto/feature +ngx_feature="malloc_trim()" +ngx_feature_name="NGX_HAVE_MALLOC_TRIM" +ngx_feature_run=no +ngx_feature_incs="#include " +ngx_feature_path= +ngx_feature_libs= +ngx_feature_test="malloc_trim(0)" +. auto/feature + + ngx_feature="mmap(MAP_ANON|MAP_SHARED)" ngx_feature_name="NGX_HAVE_MAP_ANON" ngx_feature_run=yes diff --git a/src/core/ngx_dynamic_conf.c b/src/core/ngx_dynamic_conf.c index 7e10ca845..0e11a9ca6 100644 --- a/src/core/ngx_dynamic_conf.c +++ b/src/core/ngx_dynamic_conf.c @@ -864,6 +864,10 @@ ngx_dynamic_conf_unload(ngx_dynamic_conf_ctx_t *ctx) ctx->cycle, ctx->id); ngx_destroy_pool(ctx->pool); + +#if (NGX_HAVE_MALLOC_TRIM) + malloc_trim(0); +#endif }