From c8981042286d6b53085095876b12cc07324736ca Mon Sep 17 00:00:00 2001 From: lyndonli Date: Fri, 27 Sep 2024 10:47:23 +0800 Subject: [PATCH] wsl/hsakmt: Introduce WSL_CHECK_AVAIL_SYSRAM environment variable By default, this variable is 0. Set it to 1 to compare available system memory with the requested amount before allocation. It helps identify system hangs caused by excessive memory allocation. Signed-off-by: lyndonli Reviewed-by: Flora Cui Part-of: --- globals.cpp | 2 ++ libhsakmt.h | 1 + memory.cpp | 10 ++++++++++ openclose.cpp | 5 +++++ 4 files changed, 18 insertions(+) diff --git a/globals.cpp b/globals.cpp index a75100201f..f7ac58e59c 100644 --- a/globals.cpp +++ b/globals.cpp @@ -47,5 +47,7 @@ int zfb_support; int vendor_packet_support; /* enable vendor packet in hsa-runtime*/ int enable_vendor_packet; +/* check available system memory before allocation */ +bool check_avail_sysram = false; size_t max_single_alloc_size = 0; \ No newline at end of file diff --git a/libhsakmt.h b/libhsakmt.h index fb8e8b0a37..61e49d0105 100644 --- a/libhsakmt.h +++ b/libhsakmt.h @@ -45,6 +45,7 @@ extern bool is_svm_api_supported; extern int zfb_support; extern int vendor_packet_support; extern int enable_vendor_packet; +extern bool check_avail_sysram; extern size_t max_single_alloc_size; #undef HSAKMTAPI diff --git a/memory.cpp b/memory.cpp index 8c47bfb282..260d0b0a30 100644 --- a/memory.cpp +++ b/memory.cpp @@ -105,6 +105,13 @@ HSAKMT_STATUS HSAKMTAPI hsaKmtAllocMemory(HSAuint32 PreferredNode, #define POWER_OF_2(x) ((x && (!(x & (x - 1)))) ? 1 : 0) +bool isSystemMemoryAvailable(HSAuint64 SizeInBytes) { + struct sysinfo info; + if (sysinfo(&info) != 0) + return false; + return SizeInBytes <= info.freeram; +} + HSAKMT_STATUS HSAKMTAPI hsaKmtAllocMemoryAlign(HSAuint32 PreferredNode, HSAuint64 SizeInBytes, HSAuint64 Alignment, @@ -140,6 +147,9 @@ HSAKMT_STATUS HSAKMTAPI hsaKmtAllocMemoryAlign(HSAuint32 PreferredNode, if (SizeInBytes > max_single_alloc_size) return HSAKMT_STATUS_NO_MEMORY; + if (check_avail_sysram && !isSystemMemoryAvailable(SizeInBytes)) + return HSAKMT_STATUS_NO_MEMORY; + /* If allocate VRAM under ZFB mode */ if (zfb_support && MemFlags.ui32.NonPaged == 1) MemFlags.ui32.CoarseGrain = 1; diff --git a/openclose.cpp b/openclose.cpp index 2aa917f97b..11181e10ac 100644 --- a/openclose.cpp +++ b/openclose.cpp @@ -129,6 +129,11 @@ static HSAKMT_STATUS init_vars_from_env(void) { if (envvar) enable_vendor_packet = atoi(envvar); + /* Decide whether to check available system memory before allocation */ + envvar = getenv("WSL_CHECK_AVAIL_SYSRAM"); + if (envvar) + check_avail_sysram = !strcmp(envvar, "1"); + return HSAKMT_STATUS_SUCCESS; }