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