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