1 //===--------- device.cpp - Target independent OpenMP target RTL ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Functionality for managing devices that are handled by RTL plugins.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "device.h"
14 #include "private.h"
15 #include "rtl.h"
16 
17 #include <cassert>
18 #include <climits>
19 #include <cstdio>
20 #include <string>
21 
22 DeviceTy::DeviceTy(const DeviceTy &D)
23     : DeviceID(D.DeviceID), RTL(D.RTL), RTLDeviceID(D.RTLDeviceID),
24       IsInit(D.IsInit), InitFlag(), HasPendingGlobals(D.HasPendingGlobals),
25       HostDataToTargetMap(D.HostDataToTargetMap),
26       PendingCtorsDtors(D.PendingCtorsDtors), ShadowPtrMap(D.ShadowPtrMap),
27       DataMapMtx(), PendingGlobalsMtx(), ShadowMtx(),
28       LoopTripCnt(D.LoopTripCnt) {}
29 
30 DeviceTy &DeviceTy::operator=(const DeviceTy &D) {
31   DeviceID = D.DeviceID;
32   RTL = D.RTL;
33   RTLDeviceID = D.RTLDeviceID;
34   IsInit = D.IsInit;
35   HasPendingGlobals = D.HasPendingGlobals;
36   HostDataToTargetMap = D.HostDataToTargetMap;
37   PendingCtorsDtors = D.PendingCtorsDtors;
38   ShadowPtrMap = D.ShadowPtrMap;
39   LoopTripCnt = D.LoopTripCnt;
40 
41   return *this;
42 }
43 
44 DeviceTy::DeviceTy(RTLInfoTy *RTL)
45     : DeviceID(-1), RTL(RTL), RTLDeviceID(-1), IsInit(false), InitFlag(),
46       HasPendingGlobals(false), HostDataToTargetMap(), PendingCtorsDtors(),
47       ShadowPtrMap(), DataMapMtx(), PendingGlobalsMtx(), ShadowMtx() {}
48 
49 DeviceTy::~DeviceTy() {
50   if (DeviceID == -1 || !(getInfoLevel() & OMP_INFOTYPE_DUMP_TABLE))
51     return;
52 
53   ident_t loc = {0, 0, 0, 0, ";libomptarget;libomptarget;0;0;;"};
54   dumpTargetPointerMappings(&loc, *this);
55 }
56 
57 int DeviceTy::associatePtr(void *HstPtrBegin, void *TgtPtrBegin, int64_t Size) {
58   DataMapMtx.lock();
59 
60   // Check if entry exists
61   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
62   if (search != HostDataToTargetMap.end()) {
63     // Mapping already exists
64     bool isValid = search->HstPtrEnd == (uintptr_t)HstPtrBegin + Size &&
65                    search->TgtPtrBegin == (uintptr_t)TgtPtrBegin;
66     DataMapMtx.unlock();
67     if (isValid) {
68       DP("Attempt to re-associate the same device ptr+offset with the same "
69          "host ptr, nothing to do\n");
70       return OFFLOAD_SUCCESS;
71     } else {
72       REPORT("Not allowed to re-associate a different device ptr+offset with "
73              "the same host ptr\n");
74       return OFFLOAD_FAIL;
75     }
76   }
77 
78   // Mapping does not exist, allocate it with refCount=INF
79   HostDataToTargetTy newEntry((uintptr_t)HstPtrBegin /*HstPtrBase*/,
80                               (uintptr_t)HstPtrBegin /*HstPtrBegin*/,
81                               (uintptr_t)HstPtrBegin + Size /*HstPtrEnd*/,
82                               (uintptr_t)TgtPtrBegin /*TgtPtrBegin*/, nullptr,
83                               true /*IsRefCountINF*/);
84 
85   DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", HstEnd="
86       DPxMOD ", TgtBegin=" DPxMOD "\n", DPxPTR(newEntry.HstPtrBase),
87       DPxPTR(newEntry.HstPtrBegin), DPxPTR(newEntry.HstPtrEnd),
88       DPxPTR(newEntry.TgtPtrBegin));
89   HostDataToTargetMap.insert(newEntry);
90 
91   DataMapMtx.unlock();
92 
93   return OFFLOAD_SUCCESS;
94 }
95 
96 int DeviceTy::disassociatePtr(void *HstPtrBegin) {
97   DataMapMtx.lock();
98 
99   auto search = HostDataToTargetMap.find(HstPtrBeginTy{(uintptr_t)HstPtrBegin});
100   if (search != HostDataToTargetMap.end()) {
101     // Mapping exists
102     if (search->isRefCountInf()) {
103       DP("Association found, removing it\n");
104       HostDataToTargetMap.erase(search);
105       DataMapMtx.unlock();
106       return OFFLOAD_SUCCESS;
107     } else {
108       REPORT("Trying to disassociate a pointer which was not mapped via "
109              "omp_target_associate_ptr\n");
110     }
111   }
112 
113   // Mapping not found
114   DataMapMtx.unlock();
115   REPORT("Association not found\n");
116   return OFFLOAD_FAIL;
117 }
118 
119 // Get ref count of map entry containing HstPtrBegin
120 uint64_t DeviceTy::getMapEntryRefCnt(void *HstPtrBegin) {
121   uintptr_t hp = (uintptr_t)HstPtrBegin;
122   uint64_t RefCnt = 0;
123 
124   DataMapMtx.lock();
125   if (!HostDataToTargetMap.empty()) {
126     auto upper = HostDataToTargetMap.upper_bound(hp);
127     if (upper != HostDataToTargetMap.begin()) {
128       upper--;
129       if (hp >= upper->HstPtrBegin && hp < upper->HstPtrEnd) {
130         DP("DeviceTy::getMapEntry: requested entry found\n");
131         RefCnt = upper->getRefCount();
132       }
133     }
134   }
135   DataMapMtx.unlock();
136 
137   if (RefCnt == 0) {
138     DP("DeviceTy::getMapEntry: requested entry not found\n");
139   }
140 
141   return RefCnt;
142 }
143 
144 LookupResult DeviceTy::lookupMapping(void *HstPtrBegin, int64_t Size) {
145   uintptr_t hp = (uintptr_t)HstPtrBegin;
146   LookupResult lr;
147 
148   DP("Looking up mapping(HstPtrBegin=" DPxMOD ", Size=%" PRId64 ")...\n",
149       DPxPTR(hp), Size);
150 
151   if (HostDataToTargetMap.empty())
152     return lr;
153 
154   auto upper = HostDataToTargetMap.upper_bound(hp);
155   // check the left bin
156   if (upper != HostDataToTargetMap.begin()) {
157     lr.Entry = std::prev(upper);
158     auto &HT = *lr.Entry;
159     // Is it contained?
160     lr.Flags.IsContained = hp >= HT.HstPtrBegin && hp < HT.HstPtrEnd &&
161         (hp+Size) <= HT.HstPtrEnd;
162     // Does it extend beyond the mapped region?
163     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp + Size) > HT.HstPtrEnd;
164   }
165 
166   // check the right bin
167   if (!(lr.Flags.IsContained || lr.Flags.ExtendsAfter) &&
168       upper != HostDataToTargetMap.end()) {
169     lr.Entry = upper;
170     auto &HT = *lr.Entry;
171     // Does it extend into an already mapped region?
172     lr.Flags.ExtendsBefore = hp < HT.HstPtrBegin && (hp+Size) > HT.HstPtrBegin;
173     // Does it extend beyond the mapped region?
174     lr.Flags.ExtendsAfter = hp < HT.HstPtrEnd && (hp+Size) > HT.HstPtrEnd;
175   }
176 
177   if (lr.Flags.ExtendsBefore) {
178     DP("WARNING: Pointer is not mapped but section extends into already "
179         "mapped data\n");
180   }
181   if (lr.Flags.ExtendsAfter) {
182     DP("WARNING: Pointer is already mapped but section extends beyond mapped "
183         "region\n");
184   }
185 
186   return lr;
187 }
188 
189 // Used by targetDataBegin
190 // Return the target pointer begin (where the data will be moved).
191 // Allocate memory if this is the first occurrence of this mapping.
192 // Increment the reference counter.
193 // If NULL is returned, then either data allocation failed or the user tried
194 // to do an illegal mapping.
195 void *DeviceTy::getOrAllocTgtPtr(void *HstPtrBegin, void *HstPtrBase,
196                                  int64_t Size, map_var_info_t HstPtrName,
197                                  bool &IsNew, bool &IsHostPtr, bool IsImplicit,
198                                  bool UpdateRefCount, bool HasCloseModifier,
199                                  bool HasPresentModifier) {
200   void *rc = NULL;
201   IsHostPtr = false;
202   IsNew = false;
203   DataMapMtx.lock();
204   LookupResult lr = lookupMapping(HstPtrBegin, Size);
205 
206   // Check if the pointer is contained.
207   // If a variable is mapped to the device manually by the user - which would
208   // lead to the IsContained flag to be true - then we must ensure that the
209   // device address is returned even under unified memory conditions.
210   if (lr.Flags.IsContained ||
211       ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && IsImplicit)) {
212     auto &HT = *lr.Entry;
213     IsNew = false;
214 
215     if (UpdateRefCount)
216       HT.incRefCount();
217 
218     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
219     if (getDebugLevel() || getInfoLevel() & OMP_INFOTYPE_MAPPING_EXISTS)
220       INFO(DeviceID,
221            "Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
222            ", "
223            "Size=%" PRId64 ",%s RefCount=%s, Name=%s\n",
224            (IsImplicit ? " (implicit)" : ""), DPxPTR(HstPtrBegin), DPxPTR(tp),
225            Size, (UpdateRefCount ? " updated" : ""),
226            HT.isRefCountInf() ? "INF"
227                               : std::to_string(HT.getRefCount()).c_str(),
228            (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
229     rc = (void *)tp;
230   } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
231     // Explicit extension of mapped data - not allowed.
232     MESSAGE("explicit extension not allowed: host address specified is " DPxMOD
233             " (%" PRId64 " bytes), but device allocation maps to host at "
234             DPxMOD " (%" PRId64 " bytes)",
235             DPxPTR(HstPtrBegin), Size, DPxPTR(lr.Entry->HstPtrBegin),
236             lr.Entry->HstPtrEnd - lr.Entry->HstPtrBegin);
237     if (HasPresentModifier)
238       MESSAGE("device mapping required by 'present' map type modifier does not "
239               "exist for host address " DPxMOD " (%" PRId64 " bytes)",
240               DPxPTR(HstPtrBegin), Size);
241   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
242              !HasCloseModifier) {
243     // If unified shared memory is active, implicitly mapped variables that are
244     // not privatized use host address. Any explicitly mapped variables also use
245     // host address where correctness is not impeded. In all other cases maps
246     // are respected.
247     // In addition to the mapping rules above, the close map modifier forces the
248     // mapping of the variable to the device.
249     if (Size) {
250       DP("Return HstPtrBegin " DPxMOD " Size=%" PRId64 " RefCount=%s\n",
251          DPxPTR((uintptr_t)HstPtrBegin), Size,
252          (UpdateRefCount ? " updated" : ""));
253       IsHostPtr = true;
254       rc = HstPtrBegin;
255     }
256   } else if (HasPresentModifier) {
257     DP("Mapping required by 'present' map type modifier does not exist for "
258        "HstPtrBegin=" DPxMOD ", Size=%" PRId64 "\n",
259        DPxPTR(HstPtrBegin), Size);
260     MESSAGE("device mapping required by 'present' map type modifier does not "
261             "exist for host address " DPxMOD " (%" PRId64 " bytes)",
262             DPxPTR(HstPtrBegin), Size);
263   } else if (Size) {
264     // If it is not contained and Size > 0, we should create a new entry for it.
265     IsNew = true;
266     uintptr_t tp = (uintptr_t)allocData(Size, HstPtrBegin);
267     DP("Creating new map entry: HstBase=" DPxMOD ", HstBegin=" DPxMOD ", "
268        "HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n",
269        DPxPTR(HstPtrBase), DPxPTR(HstPtrBegin),
270        DPxPTR((uintptr_t)HstPtrBegin + Size), DPxPTR(tp));
271     HostDataToTargetMap.emplace(
272         HostDataToTargetTy((uintptr_t)HstPtrBase, (uintptr_t)HstPtrBegin,
273                            (uintptr_t)HstPtrBegin + Size, tp, HstPtrName));
274     rc = (void *)tp;
275   }
276 
277   DataMapMtx.unlock();
278   return rc;
279 }
280 
281 // Used by targetDataBegin, targetDataEnd, targetDataUpdate and target.
282 // Return the target pointer begin (where the data will be moved).
283 // Decrement the reference counter if called from targetDataEnd.
284 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size, bool &IsLast,
285                                bool UpdateRefCount, bool &IsHostPtr,
286                                bool MustContain) {
287   void *rc = NULL;
288   IsHostPtr = false;
289   IsLast = false;
290   DataMapMtx.lock();
291   LookupResult lr = lookupMapping(HstPtrBegin, Size);
292 
293   if (lr.Flags.IsContained ||
294       (!MustContain && (lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter))) {
295     auto &HT = *lr.Entry;
296     IsLast = HT.getRefCount() == 1;
297 
298     if (!IsLast && UpdateRefCount)
299       HT.decRefCount();
300 
301     uintptr_t tp = HT.TgtPtrBegin + ((uintptr_t)HstPtrBegin - HT.HstPtrBegin);
302     DP("Mapping exists with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD ", "
303         "Size=%" PRId64 ",%s RefCount=%s\n", DPxPTR(HstPtrBegin), DPxPTR(tp),
304         Size, (UpdateRefCount ? " updated" : ""),
305         HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str());
306     rc = (void *)tp;
307   } else if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
308     // If the value isn't found in the mapping and unified shared memory
309     // is on then it means we have stumbled upon a value which we need to
310     // use directly from the host.
311     DP("Get HstPtrBegin " DPxMOD " Size=%" PRId64 " RefCount=%s\n",
312        DPxPTR((uintptr_t)HstPtrBegin), Size, (UpdateRefCount ? " updated" : ""));
313     IsHostPtr = true;
314     rc = HstPtrBegin;
315   }
316 
317   DataMapMtx.unlock();
318   return rc;
319 }
320 
321 // Return the target pointer begin (where the data will be moved).
322 // Lock-free version called when loading global symbols from the fat binary.
323 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
324   uintptr_t hp = (uintptr_t)HstPtrBegin;
325   LookupResult lr = lookupMapping(HstPtrBegin, Size);
326   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
327     auto &HT = *lr.Entry;
328     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
329     return (void *)tp;
330   }
331 
332   return NULL;
333 }
334 
335 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete,
336                             bool HasCloseModifier) {
337   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
338       !HasCloseModifier)
339     return OFFLOAD_SUCCESS;
340   // Check if the pointer is contained in any sub-nodes.
341   int rc;
342   DataMapMtx.lock();
343   LookupResult lr = lookupMapping(HstPtrBegin, Size);
344   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
345     auto &HT = *lr.Entry;
346     if (ForceDelete)
347       HT.resetRefCount();
348     if (HT.decRefCount() == 0) {
349       DP("Deleting tgt data " DPxMOD " of size %" PRId64 "\n",
350           DPxPTR(HT.TgtPtrBegin), Size);
351       deleteData((void *)HT.TgtPtrBegin);
352       DP("Removing%s mapping with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
353           ", Size=%" PRId64 "\n", (ForceDelete ? " (forced)" : ""),
354           DPxPTR(HT.HstPtrBegin), DPxPTR(HT.TgtPtrBegin), Size);
355       HostDataToTargetMap.erase(lr.Entry);
356     }
357     rc = OFFLOAD_SUCCESS;
358   } else {
359     REPORT("Section to delete (hst addr " DPxMOD ") does not exist in the"
360            " allocated memory\n",
361            DPxPTR(HstPtrBegin));
362     rc = OFFLOAD_FAIL;
363   }
364 
365   DataMapMtx.unlock();
366   return rc;
367 }
368 
369 /// Init device, should not be called directly.
370 void DeviceTy::init() {
371   // Make call to init_requires if it exists for this plugin.
372   if (RTL->init_requires)
373     RTL->init_requires(PM->RTLs.RequiresFlags);
374   int32_t Ret = RTL->init_device(RTLDeviceID);
375   if (Ret != OFFLOAD_SUCCESS)
376     return;
377 
378   IsInit = true;
379 }
380 
381 /// Thread-safe method to initialize the device only once.
382 int32_t DeviceTy::initOnce() {
383   std::call_once(InitFlag, &DeviceTy::init, this);
384 
385   // At this point, if IsInit is true, then either this thread or some other
386   // thread in the past successfully initialized the device, so we can return
387   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
388   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
389   // that some other thread already attempted to execute init() and if IsInit
390   // is still false, return OFFLOAD_FAIL.
391   if (IsInit)
392     return OFFLOAD_SUCCESS;
393   else
394     return OFFLOAD_FAIL;
395 }
396 
397 // Load binary to device.
398 __tgt_target_table *DeviceTy::load_binary(void *Img) {
399   RTL->Mtx.lock();
400   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
401   RTL->Mtx.unlock();
402   return rc;
403 }
404 
405 void *DeviceTy::allocData(int64_t Size, void *HstPtr) {
406   return RTL->data_alloc(RTLDeviceID, Size, HstPtr);
407 }
408 
409 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
410   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
411 }
412 
413 // Submit data to device
414 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
415                              __tgt_async_info *AsyncInfoPtr) {
416   if (!AsyncInfoPtr || !RTL->data_submit_async || !RTL->synchronize)
417     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
418   else
419     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
420                                   AsyncInfoPtr);
421 }
422 
423 // Retrieve data from device
424 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
425                                int64_t Size, __tgt_async_info *AsyncInfoPtr) {
426   if (!AsyncInfoPtr || !RTL->data_retrieve_async || !RTL->synchronize)
427     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
428   else
429     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
430                                     AsyncInfoPtr);
431 }
432 
433 // Copy data from current device to destination device directly
434 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
435                                int64_t Size, __tgt_async_info *AsyncInfo) {
436   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
437     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
438     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
439                               Size);
440   } else
441     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
442                                     DstPtr, Size, AsyncInfo);
443 }
444 
445 // Run region on device
446 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
447                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
448                             __tgt_async_info *AsyncInfoPtr) {
449   if (!AsyncInfoPtr || !RTL->run_region || !RTL->synchronize)
450     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
451                            TgtVarsSize);
452   else
453     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
454                                  TgtOffsets, TgtVarsSize, AsyncInfoPtr);
455 }
456 
457 // Run team region on device.
458 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
459                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
460                                 int32_t NumTeams, int32_t ThreadLimit,
461                                 uint64_t LoopTripCount,
462                                 __tgt_async_info *AsyncInfoPtr) {
463   if (!AsyncInfoPtr || !RTL->run_team_region_async || !RTL->synchronize)
464     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
465                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
466                                 LoopTripCount);
467   else
468     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
469                                       TgtOffsets, TgtVarsSize, NumTeams,
470                                       ThreadLimit, LoopTripCount, AsyncInfoPtr);
471 }
472 
473 // Whether data can be copied to DstDevice directly
474 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
475   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
476     return false;
477 
478   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
479     return (RTL->data_exchange != nullptr) ||
480            (RTL->data_exchange_async != nullptr);
481 
482   return false;
483 }
484 
485 int32_t DeviceTy::synchronize(__tgt_async_info *AsyncInfoPtr) {
486   if (RTL->synchronize)
487     return RTL->synchronize(RTLDeviceID, AsyncInfoPtr);
488   return OFFLOAD_SUCCESS;
489 }
490 
491 /// Check whether a device has an associated RTL and initialize it if it's not
492 /// already initialized.
493 bool device_is_ready(int device_num) {
494   DP("Checking whether device %d is ready.\n", device_num);
495   // Devices.size() can only change while registering a new
496   // library, so try to acquire the lock of RTLs' mutex.
497   PM->RTLsMtx.lock();
498   size_t DevicesSize = PM->Devices.size();
499   PM->RTLsMtx.unlock();
500   if (DevicesSize <= (size_t)device_num) {
501     DP("Device ID  %d does not have a matching RTL\n", device_num);
502     return false;
503   }
504 
505   // Get device info
506   DeviceTy &Device = PM->Devices[device_num];
507 
508   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
509        Device.RTLDeviceID, Device.IsInit);
510 
511   // Init the device if not done before
512   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
513     DP("Failed to init device %d\n", device_num);
514     return false;
515   }
516 
517   DP("Device %d is ready to use.\n", device_num);
518 
519   return true;
520 }
521