From 5518b489d823bac40cacc7f28aeb70d2c3113eb7 Mon Sep 17 00:00:00 2001 From: "Neil R. Spruit" Date: Thu, 7 Mar 2024 16:05:36 -0800 Subject: [PATCH] Remove error return for adapter and change get to create temp adapter - To handle the customer usecases, don't return uinit when the adapter is used after the adapter library has already closed. - Given the global adapter is gone, but get adapter is called, then a temp adapter struct is allocated and an ondemand atexit cleanup of this memory is registered. Signed-off-by: Neil R. Spruit --- source/adapters/level_zero/adapter.cpp | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/source/adapters/level_zero/adapter.cpp b/source/adapters/level_zero/adapter.cpp index 9d5b1038a2..39a0934b4f 100644 --- a/source/adapters/level_zero/adapter.cpp +++ b/source/adapters/level_zero/adapter.cpp @@ -105,13 +105,11 @@ ur_adapter_handle_t_::ur_adapter_handle_t_() { }; } -#if defined(_WIN32) -void globalAdapterWindowsCleanup() { +void globalAdapterOnDemandCleanup() { if (GlobalAdapter) { delete GlobalAdapter; } } -#endif ur_result_t adapterStateTeardown() { bool LeakFound = false; @@ -201,7 +199,7 @@ ur_result_t adapterStateTeardown() { // Due to multiple DLLMain definitions with SYCL, register to cleanup the // Global Adapter after refcnt is 0 #if defined(_WIN32) - std::atexit(globalAdapterWindowsCleanup); + std::atexit(globalAdapterOnDemandCleanup); #endif return UR_RESULT_SUCCESS; @@ -227,10 +225,18 @@ UR_APIEXPORT ur_result_t UR_APICALL urAdapterGet( if (GlobalAdapter->RefCount++ == 0) { adapterStateInit(); } - *Adapters = GlobalAdapter; } else { - return UR_RESULT_ERROR_UNINITIALIZED; + // If the GetAdapter is called after the Library began or was torndown, + // then temporarily create a new Adapter handle and register a new + // cleanup. + GlobalAdapter = new ur_adapter_handle_t_(); + std::lock_guard Lock{GlobalAdapter->Mutex}; + if (GlobalAdapter->RefCount++ == 0) { + adapterStateInit(); + } + std::atexit(globalAdapterOnDemandCleanup); } + *Adapters = GlobalAdapter; } if (NumAdapters) { @@ -256,8 +262,6 @@ UR_APIEXPORT ur_result_t UR_APICALL urAdapterRetain(ur_adapter_handle_t) { if (GlobalAdapter) { std::lock_guard Lock{GlobalAdapter->Mutex}; GlobalAdapter->RefCount++; - } else { - return UR_RESULT_ERROR_UNINITIALIZED; } return UR_RESULT_SUCCESS;