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     INFO(OMP_INFOTYPE_MAPPING_EXISTS, DeviceID,
220          "Mapping exists%s with HstPtrBegin=" DPxMOD ", TgtPtrBegin=" DPxMOD
221          ", "
222          "Size=%" PRId64 ",%s RefCount=%s, Name=%s\n",
223          (IsImplicit ? " (implicit)" : ""), DPxPTR(HstPtrBegin), DPxPTR(tp),
224          Size, (UpdateRefCount ? " updated" : ""),
225          HT.isRefCountInf() ? "INF" : std::to_string(HT.getRefCount()).c_str(),
226          (HstPtrName) ? getNameFromMapping(HstPtrName).c_str() : "unknown");
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, HstPtrName));
272     rc = (void *)tp;
273   }
274 
275   DataMapMtx.unlock();
276   return rc;
277 }
278 
279 // Used by targetDataBegin, targetDataEnd, targetDataUpdate 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   IsInit = true;
377 }
378 
379 /// Thread-safe method to initialize the device only once.
380 int32_t DeviceTy::initOnce() {
381   std::call_once(InitFlag, &DeviceTy::init, this);
382 
383   // At this point, if IsInit is true, then either this thread or some other
384   // thread in the past successfully initialized the device, so we can return
385   // OFFLOAD_SUCCESS. If this thread executed init() via call_once() and it
386   // failed, return OFFLOAD_FAIL. If call_once did not invoke init(), it means
387   // that some other thread already attempted to execute init() and if IsInit
388   // is still false, return OFFLOAD_FAIL.
389   if (IsInit)
390     return OFFLOAD_SUCCESS;
391   else
392     return OFFLOAD_FAIL;
393 }
394 
395 // Load binary to device.
396 __tgt_target_table *DeviceTy::load_binary(void *Img) {
397   RTL->Mtx.lock();
398   __tgt_target_table *rc = RTL->load_binary(RTLDeviceID, Img);
399   RTL->Mtx.unlock();
400   return rc;
401 }
402 
403 void *DeviceTy::allocData(int64_t Size, void *HstPtr) {
404   return RTL->data_alloc(RTLDeviceID, Size, HstPtr);
405 }
406 
407 int32_t DeviceTy::deleteData(void *TgtPtrBegin) {
408   return RTL->data_delete(RTLDeviceID, TgtPtrBegin);
409 }
410 
411 // Submit data to device
412 int32_t DeviceTy::submitData(void *TgtPtrBegin, void *HstPtrBegin, int64_t Size,
413                              __tgt_async_info *AsyncInfoPtr) {
414   if (!AsyncInfoPtr || !RTL->data_submit_async || !RTL->synchronize)
415     return RTL->data_submit(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size);
416   else
417     return RTL->data_submit_async(RTLDeviceID, TgtPtrBegin, HstPtrBegin, Size,
418                                   AsyncInfoPtr);
419 }
420 
421 // Retrieve data from device
422 int32_t DeviceTy::retrieveData(void *HstPtrBegin, void *TgtPtrBegin,
423                                int64_t Size, __tgt_async_info *AsyncInfoPtr) {
424   if (!AsyncInfoPtr || !RTL->data_retrieve_async || !RTL->synchronize)
425     return RTL->data_retrieve(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size);
426   else
427     return RTL->data_retrieve_async(RTLDeviceID, HstPtrBegin, TgtPtrBegin, Size,
428                                     AsyncInfoPtr);
429 }
430 
431 // Copy data from current device to destination device directly
432 int32_t DeviceTy::dataExchange(void *SrcPtr, DeviceTy &DstDev, void *DstPtr,
433                                int64_t Size, __tgt_async_info *AsyncInfo) {
434   if (!AsyncInfo || !RTL->data_exchange_async || !RTL->synchronize) {
435     assert(RTL->data_exchange && "RTL->data_exchange is nullptr");
436     return RTL->data_exchange(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID, DstPtr,
437                               Size);
438   } else
439     return RTL->data_exchange_async(RTLDeviceID, SrcPtr, DstDev.RTLDeviceID,
440                                     DstPtr, Size, AsyncInfo);
441 }
442 
443 // Run region on device
444 int32_t DeviceTy::runRegion(void *TgtEntryPtr, void **TgtVarsPtr,
445                             ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
446                             __tgt_async_info *AsyncInfoPtr) {
447   if (!AsyncInfoPtr || !RTL->run_region || !RTL->synchronize)
448     return RTL->run_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr, TgtOffsets,
449                            TgtVarsSize);
450   else
451     return RTL->run_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
452                                  TgtOffsets, TgtVarsSize, AsyncInfoPtr);
453 }
454 
455 // Run team region on device.
456 int32_t DeviceTy::runTeamRegion(void *TgtEntryPtr, void **TgtVarsPtr,
457                                 ptrdiff_t *TgtOffsets, int32_t TgtVarsSize,
458                                 int32_t NumTeams, int32_t ThreadLimit,
459                                 uint64_t LoopTripCount,
460                                 __tgt_async_info *AsyncInfoPtr) {
461   if (!AsyncInfoPtr || !RTL->run_team_region_async || !RTL->synchronize)
462     return RTL->run_team_region(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
463                                 TgtOffsets, TgtVarsSize, NumTeams, ThreadLimit,
464                                 LoopTripCount);
465   else
466     return RTL->run_team_region_async(RTLDeviceID, TgtEntryPtr, TgtVarsPtr,
467                                       TgtOffsets, TgtVarsSize, NumTeams,
468                                       ThreadLimit, LoopTripCount, AsyncInfoPtr);
469 }
470 
471 // Whether data can be copied to DstDevice directly
472 bool DeviceTy::isDataExchangable(const DeviceTy &DstDevice) {
473   if (RTL != DstDevice.RTL || !RTL->is_data_exchangable)
474     return false;
475 
476   if (RTL->is_data_exchangable(RTLDeviceID, DstDevice.RTLDeviceID))
477     return (RTL->data_exchange != nullptr) ||
478            (RTL->data_exchange_async != nullptr);
479 
480   return false;
481 }
482 
483 int32_t DeviceTy::synchronize(__tgt_async_info *AsyncInfoPtr) {
484   if (RTL->synchronize)
485     return RTL->synchronize(RTLDeviceID, AsyncInfoPtr);
486   return OFFLOAD_SUCCESS;
487 }
488 
489 /// Check whether a device has an associated RTL and initialize it if it's not
490 /// already initialized.
491 bool device_is_ready(int device_num) {
492   DP("Checking whether device %d is ready.\n", device_num);
493   // Devices.size() can only change while registering a new
494   // library, so try to acquire the lock of RTLs' mutex.
495   PM->RTLsMtx.lock();
496   size_t DevicesSize = PM->Devices.size();
497   PM->RTLsMtx.unlock();
498   if (DevicesSize <= (size_t)device_num) {
499     DP("Device ID  %d does not have a matching RTL\n", device_num);
500     return false;
501   }
502 
503   // Get device info
504   DeviceTy &Device = PM->Devices[device_num];
505 
506   DP("Is the device %d (local ID %d) initialized? %d\n", device_num,
507        Device.RTLDeviceID, Device.IsInit);
508 
509   // Init the device if not done before
510   if (!Device.IsInit && Device.initOnce() != OFFLOAD_SUCCESS) {
511     DP("Failed to init device %d\n", device_num);
512     return false;
513   }
514 
515   DP("Device %d is ready to use.\n", device_num);
516 
517   return true;
518 }
519