@@ -97,6 +97,7 @@ struct AllocInfo {
97
97
// Global shared state for liboffload
98
98
struct OffloadContext ;
99
99
static OffloadContext *OffloadContextVal;
100
+ std::mutex OffloadContextValMutex;
100
101
struct OffloadContext {
101
102
OffloadContext (OffloadContext &) = delete ;
102
103
OffloadContext (OffloadContext &&) = delete ;
@@ -107,6 +108,7 @@ struct OffloadContext {
107
108
bool ValidationEnabled = true ;
108
109
DenseMap<void *, AllocInfo> AllocInfoMap{};
109
110
SmallVector<ol_platform_impl_t , 4 > Platforms{};
111
+ size_t RefCount;
110
112
111
113
ol_device_handle_t HostDevice () {
112
114
// The host platform is always inserted last
@@ -191,18 +193,41 @@ Error initPlugins() {
191
193
return Plugin::success ();
192
194
}
193
195
194
- // TODO: We can properly reference count here and manage the resources in a more
195
- // clever way
196
196
Error olInit_impl () {
197
- static std::once_flag InitFlag;
198
- std::optional<Error> InitResult{};
199
- std::call_once (InitFlag, [&] { InitResult = initPlugins (); });
197
+ std::lock_guard<std::mutex> Lock{OffloadContextValMutex};
198
+
199
+ std::optional<Error> InitResult;
200
+ if (!isOffloadInitialized ())
201
+ InitResult = initPlugins ();
202
+
203
+ OffloadContext::get ().RefCount ++;
200
204
201
205
if (InitResult)
202
206
return std::move (*InitResult);
203
207
return Error::success ();
204
208
}
205
- Error olShutDown_impl () { return Error::success (); }
209
+
210
+ Error olShutDown_impl () {
211
+ std::lock_guard<std::mutex> Lock{OffloadContextValMutex};
212
+
213
+ if (--OffloadContext::get ().RefCount != 0 )
214
+ return Error::success ();
215
+
216
+ llvm::Error Result = Error::success ();
217
+
218
+ for (auto &P : OffloadContext::get ().Platforms ) {
219
+ // Host plugin is nullptr and has no deinit
220
+ if (!P.Plugin )
221
+ continue ;
222
+
223
+ if (auto Res = P.Plugin ->deinit ())
224
+ Result = llvm::joinErrors (std::move (Result), std::move (Res));
225
+ }
226
+ delete OffloadContextVal;
227
+ OffloadContextVal = nullptr ;
228
+
229
+ return Result;
230
+ }
206
231
207
232
Error olGetPlatformInfoImplDetail (ol_platform_handle_t Platform,
208
233
ol_platform_info_t PropName, size_t PropSize,
0 commit comments