@@ -32,6 +32,7 @@ terms of the MIT license. A copy of the license can be found in the file
3232#if defined(__linux__ )
3333 #include <features.h>
3434 #include <sys/prctl.h> // THP disable, PR_SET_VMA
35+ #include <sys/sysinfo.h> // sysinfo
3536 #if defined(__GLIBC__ ) && !defined(PR_SET_VMA )
3637 #include <linux/prctl.h>
3738 #endif
@@ -156,18 +157,25 @@ static void unix_detect_physical_memory( size_t page_size, size_t* physical_memo
156157 int mib [2 ] = { CTL_HW , HW_MEMSIZE };
157158 #endif
158159 const int err = sysctl (mib , 2 , & physical_memory , & length , NULL , 0 );
159- if (err == 0 && physical_memory > 0 ) {
160+ if (err == 0 && physical_memory > 0 ) {
160161 const int64_t phys_in_kib = physical_memory / MI_KiB ;
161162 if (phys_in_kib > 0 && (uint64_t )phys_in_kib <= SIZE_MAX ) {
162163 * physical_memory_in_kib = (size_t )phys_in_kib ;
163- }
164+ }
165+ }
166+ #elif defined(__linux__ )
167+ MI_UNUSED (page_size );
168+ struct sysinfo info ; _mi_memzero_var (info );
169+ const int err = sysinfo (& info );
170+ if (err == 0 && info .totalram > 0 && info .totalram <= SIZE_MAX ) {
171+ * physical_memory_in_kib = (size_t )info .totalram / MI_KiB ;
164172 }
165- #elif defined(_SC_PHYS_PAGES ) // linux
173+ #elif defined(_SC_PHYS_PAGES ) // do not use by default as it might cause allocation (by using `fopen` to parse /proc/meminfo) (issue #1100)
166174 const long pphys = sysconf (_SC_PHYS_PAGES );
167175 const size_t psize_in_kib = page_size / MI_KiB ;
168- if (psize_in_kib > 0 && pphys > 0 && (unsigned long )pphys < SIZE_MAX && (size_t )pphys <= (SIZE_MAX /psize_in_kib )) {
176+ if (psize_in_kib > 0 && pphys > 0 && (unsigned long )pphys <= SIZE_MAX && (size_t )pphys <= (SIZE_MAX /psize_in_kib )) {
169177 * physical_memory_in_kib = (size_t )pphys * psize_in_kib ;
170- }
178+ }
171179 #endif
172180}
173181
@@ -472,7 +480,7 @@ int _mi_prim_decommit(void* start, size_t size, bool* needs_recommit) {
472480 #else
473481 // decommit: use MADV_DONTNEED as it decreases rss immediately (unlike MADV_FREE)
474482 err = unix_madvise (start , size , MADV_DONTNEED );
475- #endif
483+ #endif
476484 #if !MI_DEBUG && MI_SECURE <=2
477485 * needs_recommit = false;
478486 #else
@@ -493,8 +501,8 @@ int _mi_prim_reset(void* start, size_t size) {
493501 int err = 0 ;
494502
495503 // on macOS can use MADV_FREE_REUSABLE (but we disable this for now as it seems slower)
496- #if 0 && defined(__APPLE__ ) && defined(MADV_FREE_REUSABLE )
497- err = unix_madvise (start , size , MADV_FREE_REUSABLE );
504+ #if 0 && defined(__APPLE__ ) && defined(MADV_FREE_REUSABLE )
505+ err = unix_madvise (start , size , MADV_FREE_REUSABLE );
498506 if (err == 0 ) return 0 ;
499507 // fall through
500508 #endif
0 commit comments