diff --git a/src/sys/posix/posix_main.cpp b/src/sys/posix/posix_main.cpp index c1e923ac8..4e0b656f3 100644 --- a/src/sys/posix/posix_main.cpp +++ b/src/sys/posix/posix_main.cpp @@ -1226,6 +1226,16 @@ Posix_EarlyInit =============== */ void Posix_EarlyInit( void ) { +#if defined( __GLIBC__ ) + // glibc gives every thread that allocates a malloc arena of its own. The + // job workers allocate during level loads and the main thread frees, so + // each arena keeps its pages and RSS climbs from map to map even after + // Sys_ReleaseFreeHeapMemory. Two arenas keep that in check; set + // MALLOC_ARENA_MAX to choose another number. + if ( getenv( "MALLOC_ARENA_MAX" ) == NULL ) { + mallopt( M_ARENA_MAX, 2 ); + } +#endif posix_mainThread = pthread_self(); posix_mainThreadRecorded = true; memset( &asyncThread, 0, sizeof( asyncThread ) ); diff --git a/tools/tests/posix_memory_management.py b/tools/tests/posix_memory_management.py index 70e3ec4a5..9d58571ce 100644 --- a/tools/tests/posix_memory_management.py +++ b/tools/tests/posix_memory_management.py @@ -98,10 +98,23 @@ def validate_level_load_heap_release() -> None: raise AssertionError("level load must release free heap memory after the settle frames") +def validate_malloc_arena_cap() -> None: + posix = read("src/sys/posix/posix_main.cpp") + body = function_body(posix, "void Posix_EarlyInit( void ) {") + require(body, "#if defined( __GLIBC__ )", "glibc malloc arena cap") + require(body, 'if ( getenv( "MALLOC_ARENA_MAX" ) == NULL ) {', "user MALLOC_ARENA_MAX wins") + require(body, "mallopt( M_ARENA_MAX, 2 );", "glibc malloc arena cap") + cap = body.find("mallopt( M_ARENA_MAX, 2 );") + thread = body.find("posix_mainThread = pthread_self();") + if cap == -1 or thread == -1 or cap > thread: + raise AssertionError("the malloc arena cap must be set before Posix_EarlyInit does anything else") + + def main() -> None: validate_posix_page_locking() validate_ram_total_helpers() validate_level_load_heap_release() + validate_malloc_arena_cap() print("posix_memory_management: ok")