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
86      ", HstEnd=" DPxMOD ", TgtBegin=" DPxMOD "\n",
87      DPxPTR(newEntry.HstPtrBase), DPxPTR(newEntry.HstPtrBegin),
88      DPxPTR(newEntry.HstPtrEnd), 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 =
173         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, map_var_info_t HstPtrName,
198                                  bool &IsNew, bool &IsHostPtr, bool IsImplicit,
199                                  bool UpdateRefCount, 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(OMP_INFOTYPE_MAPPING_EXISTS, 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" : std::to_string(HT.getRefCount()).c_str(),
227          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
228     rc = (void *)tp;
229   } else if ((lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) && !IsImplicit) {
230     // Explicit extension of mapped data - not allowed.
231     MESSAGE("explicit extension not allowed: host address specified is " DPxMOD
232             " (%" PRId64
233             " bytes), but device allocation maps to host at " DPxMOD
234             " (%" 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",
304        DPxPTR(HstPtrBegin), DPxPTR(tp), Size,
305        (UpdateRefCount ? " updated" : ""),
306        HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str());
307     rc = (void *)tp;
308   } else if (PM->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,
314        (UpdateRefCount ? " updated" : ""));
315     IsHostPtr = true;
316     rc = HstPtrBegin;
317   }
318 
319   DataMapMtx.unlock();
320   return rc;
321 }
322 
323 // Return the target pointer begin (where the data will be moved).
324 // Lock-free version called when loading global symbols from the fat binary.
325 void *DeviceTy::getTgtPtrBegin(void *HstPtrBegin, int64_t Size) {
326   uintptr_t hp = (uintptr_t)HstPtrBegin;
327   LookupResult lr = lookupMapping(HstPtrBegin, Size);
328   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
329     auto &HT = *lr.Entry;
330     uintptr_t tp = HT.TgtPtrBegin + (hp - HT.HstPtrBegin);
331     return (void *)tp;
332   }
333 
334   return NULL;
335 }
336 
337 int DeviceTy::deallocTgtPtr(void *HstPtrBegin, int64_t Size, bool ForceDelete,
338                             bool HasCloseModifier) {
339   if (PM->RTLs.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY &&
340       !HasCloseModifier)
341     return OFFLOAD_SUCCESS;
342   // Check if the pointer is contained in any sub-nodes.
343   int rc;
344   DataMapMtx.lock();
345   LookupResult lr = lookupMapping(HstPtrBegin, Size);
346   if (lr.Flags.IsContained || lr.Flags.ExtendsBefore || lr.Flags.ExtendsAfter) {
347     auto &HT = *lr.Entry;
348     if (ForceDelete)
349       HT.resetRefCount();
350     if (HT.decRefCount() == 0) {
351       DP("Deleting tgt data " DPxMOD " of size %" PRId64 "\n",
352          DPxPTR(HT.TgtPtrBegin), Size);
353       deleteData((void *)HT.TgtPtrBegin);
354       DP("Removing%s mapping with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
355          ", Size=%" PRId64 "\n",
356          (ForceDelete ? " (forced)" : ""), DPxPTR(HT.HstPtrBegin),
357          DPxPTR(HT.TgtPtrBegin), Size);
358       HostDataToTargetMap.erase(lr.Entry);
359     }
360     rc = OFFLOAD_SUCCESS;
361   } else {
362     REPORT("Section to delete (hst addr " DPxMOD ") does not exist in the"
363            " allocated memory\n",
364            DPxPTR(HstPtrBegin));
365     rc = OFFLOAD_FAIL;
366   }
367 
368   DataMapMtx.unlock();
369   return rc;
370 }
371 
372 /// Init device, should not be called directly.
373 void DeviceTy::init() {
374   // Make call to init_requires if it exists for this plugin.
375   if (RTL->init_requires)
376     RTL->init_requires(PM->RTLs.RequiresFlags);
377   int32_t Ret = RTL->init_device(RTLDeviceID);
378   if (Ret != OFFLOAD_SUCCESS)
379     return;
380 
381   IsInit = true;
382 }
383 
384 /// Thread-safe method to initialize the device only once.
385 int32_t DeviceTy::initOnce() {
386   std::call_once(InitFlag, &DeviceTy::init, this);
387 
388   // At this point, if IsInit is true, then either this thread or some other
389   // thread in the past successfully initialized the device, so we can return
390   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
391   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
392   // that some other thread already attempted to execute init() and if IsInit
393   // is still false, return OFFLOAD_FAIL.
394   if (IsInit)
395     return OFFLOAD_SUCCESS;
396   else
397     return OFFLOAD_FAIL;
398 }
399 
400 // Load binary to device.
401 __tgt_target_table *DeviceTy::load_binary(void *Img) {
402   RTL->Mtx.lock();
403   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
404   RTL->Mtx.unlock();
405   return rc;
406 }
407 
408 void *DeviceTy::allocData(int64_t Size, void *HstPtr, int32_t Kind) {
409   return RTL->data_alloc(RTLDeviceID, Size, HstPtr, Kind);
410 }
411 
412 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
413   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
414 }
415 
416 // Submit data to device
417 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
418                              AsyncInfoTy &AsyncInfo) {
419   if (!AsyncInfo || !RTL->data_submit_async || !RTL->synchronize)
420     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
421   else
422     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
423                                   AsyncInfo);
424 }
425 
426 // Retrieve data from device
427 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
428                                int64_t Size, AsyncInfoTy &AsyncInfo) {
429   if (!RTL->data_retrieve_async || !RTL->synchronize)
430     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
431   else
432     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
433                                     AsyncInfo);
434 }
435 
436 // Copy data from current device to destination device directly
437 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
438                                int64_t Size, AsyncInfoTy &AsyncInfo) {
439   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
440     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
441     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
442                               Size);
443   } else
444     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
445                                     DstPtr, Size, AsyncInfo);
446 }
447 
448 // Run region on device
449 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
450                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
451                             AsyncInfoTy &AsyncInfo) {
452   if (!RTL->run_region || !RTL->synchronize)
453     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
454                            TgtVarsSize);
455   else
456     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
457                                  TgtOffsets, TgtVarsSize, AsyncInfo);
458 }
459 
460 // Run team region on device.
461 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
462                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
463                                 int32_t NumTeams, int32_t ThreadLimit,
464                                 uint64_t LoopTripCount,
465                                 AsyncInfoTy &AsyncInfo) {
466   if (!RTL->run_team_region_async || !RTL->synchronize)
467     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
468                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
469                                 LoopTripCount);
470   else
471     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
472                                       TgtOffsets, TgtVarsSize, NumTeams,
473                                       ThreadLimit, LoopTripCount, AsyncInfo);
474 }
475 
476 // Whether data can be copied to DstDevice directly
477 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
478   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
479     return false;
480 
481   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
482     return (RTL->data_exchange != nullptr) ||
483            (RTL->data_exchange_async != nullptr);
484 
485   return false;
486 }
487 
488 int32_t DeviceTy::synchronize(AsyncInfoTy &AsyncInfo) {
489   if (RTL->synchronize)
490     return RTL->synchronize(RTLDeviceID, AsyncInfo);
491   return OFFLOAD_SUCCESS;
492 }
493 
494 /// Check whether a device has an associated RTL and initialize it if it's not
495 /// already initialized.
496 bool device_is_ready(int device_num) {
497   DP("Checking whether device %d is ready.\n", device_num);
498   // Devices.size() can only change while registering a new
499   // library, so try to acquire the lock of RTLs' mutex.
500   PM->RTLsMtx.lock();
501   size_t DevicesSize = PM->Devices.size();
502   PM->RTLsMtx.unlock();
503   if (DevicesSize <= (size_t)device_num) {
504     DP("Device ID  %d does not have a matching RTL\n", device_num);
505     return false;
506   }
507 
508   // Get device info
509   DeviceTy &Device = PM->Devices[device_num];
510 
511   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
512      Device.RTLDeviceID, Device.IsInit);
513 
514   // Init the device if not done before
515   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
516     DP("Failed to init device %d\n", device_num);
517     return false;
518   }
519 
520   DP("Device %d is ready to use.\n", device_num);
521 
522   return true;
523 }
524