util/os_misc: add os_get_available_system_memory()
authorJonathan Gray <jsg@jsg.id.au>
Thu, 5 Dec 2019 14:01:29 +0000 (01:01 +1100)
committerJonathan Gray <jsg@jsg.id.au>
Wed, 2 Sep 2020 02:14:56 +0000 (12:14 +1000)
Add os_get_available_system_memory() derived from
src/intel/vulkan/anv_device.c get_available_system_memory()

Fixes: b80930a6fea ("anv: add support for VK_EXT_memory_budget")
Signed-off-by: Jonathan Gray <jsg@jsg.id.au>
Reviewed-by: Jason Ekstrand <jason@jlekstrand.net>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/6517>

src/util/os_misc.c
src/util/os_misc.h

index e6894731b635b754e028b4ac49b2da8769607a0c..954900e3c5d7dd4ceaf5497c2d7e9eb5c15db755 100644 (file)
@@ -27,6 +27,7 @@
 
 
 #include "os_misc.h"
+#include "os_file.h"
 
 #include <stdarg.h>
 
@@ -44,6 +45,8 @@
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
 
 #endif
 
@@ -182,3 +185,31 @@ os_get_total_physical_memory(uint64_t *size)
    return false;
 #endif
 }
+
+bool
+os_get_available_system_memory(uint64_t *size)
+{
+#if DETECT_OS_LINUX
+   char *meminfo = os_read_file("/proc/meminfo", NULL);
+   if (!meminfo)
+      return false;
+
+   char *str = strstr(meminfo, "MemAvailable:");
+   if (!str) {
+      free(meminfo);
+      return false;
+   }
+
+   uint64_t kb_mem_available;
+   if (sscanf(str, "MemAvailable: %" PRIx64, &kb_mem_available) == 1) {
+      free(meminfo);
+      *size = kb_mem_available << 10;
+      return true;
+   }
+
+   free(meminfo);
+   return false;
+#else
+   return false;
+#endif
+}
index 19c8962d5d8fb3516df5dc1caca889fb6bb46935..60811faf5a4658877fb8fcd502d35762da4ab6b2 100644 (file)
@@ -95,6 +95,12 @@ os_get_option(const char *name);
 bool
 os_get_total_physical_memory(uint64_t *size);
 
+/*
+ * Amount of physical memory available to a process
+ */
+bool
+os_get_available_system_memory(uint64_t *size);
+
 
 #ifdef __cplusplus
 }