1 //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===//
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 // RTL for CUDA machine
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include <cassert>
14 #include <cstddef>
15 #include <cuda.h>
16 #include <list>
17 #include <memory>
18 #include <mutex>
19 #include <string>
20 #include <unordered_map>
21 #include <vector>
22 
23 #include "Debug.h"
24 #include "DeviceEnvironment.h"
25 #include "omptargetplugin.h"
26 
27 #define TARGET_NAME CUDA
28 #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
29 
30 #include "MemoryManager.h"
31 
32 #include "llvm/Frontend/OpenMP/OMPConstants.h"
33 
34 // Utility for retrieving and printing CUDA error string.
35 #ifdef OMPTARGET_DEBUG
36 #define CUDA_ERR_STRING(err)                                                   \
37   do {                                                                         \
38     if (getDebugLevel() > 0) {                                                 \
39       const char *errStr = nullptr;                                            \
40       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
41       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
42         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
43       else if (errStr_status == CUDA_SUCCESS)                                  \
44         REPORT("CUDA error is: %s\n", errStr);                                 \
45       else {                                                                   \
46         REPORT("Unresolved CUDA error code: %d\n", err);                       \
47         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
48                errStr_status);                                                 \
49       }                                                                        \
50     } else {                                                                   \
51       const char *errStr = nullptr;                                            \
52       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
53       if (errStr_status == CUDA_SUCCESS)                                       \
54         REPORT("%s \n", errStr);                                               \
55     }                                                                          \
56   } while (false)
57 #else // OMPTARGET_DEBUG
58 #define CUDA_ERR_STRING(err)                                                   \
59   do {                                                                         \
60     const char *errStr = nullptr;                                              \
61     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
62     if (errStr_status == CUDA_SUCCESS)                                         \
63       REPORT("%s \n", errStr);                                                 \
64   } while (false)
65 #endif // OMPTARGET_DEBUG
66 
67 #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
68 
69 #include "elf_common.h"
70 
71 /// Keep entries table per device.
72 struct FuncOrGblEntryTy {
73   __tgt_target_table Table;
74   std::vector<__tgt_offload_entry> Entries;
75 };
76 
77 /// Use a single entity to encode a kernel and a set of flags.
78 struct KernelTy {
79   CUfunction Func;
80 
81   // execution mode of kernel
82   llvm::omp::OMPTgtExecModeFlags ExecutionMode;
83 
84   /// Maximal number of threads per block for this kernel.
85   int MaxThreadsPerBlock = 0;
86 
87   KernelTy(CUfunction _Func, llvm::omp::OMPTgtExecModeFlags _ExecutionMode)
88       : Func(_Func), ExecutionMode(_ExecutionMode) {}
89 };
90 
91 namespace {
92 bool checkResult(CUresult Err, const char *ErrMsg) {
93   if (Err == CUDA_SUCCESS)
94     return true;
95 
96   REPORT("%s", ErrMsg);
97   CUDA_ERR_STRING(Err);
98   return false;
99 }
100 
101 int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
102                CUstream Stream) {
103   CUresult Err =
104       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
105 
106   if (Err != CUDA_SUCCESS) {
107     DP("Error when copying data from device to device. Pointers: src "
108        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
109        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
110     CUDA_ERR_STRING(Err);
111     return OFFLOAD_FAIL;
112   }
113 
114   return OFFLOAD_SUCCESS;
115 }
116 
117 int createEvent(void **P) {
118   CUevent Event = nullptr;
119 
120   CUresult Err = cuEventCreate(&Event, CU_EVENT_DEFAULT);
121   if (Err != CUDA_SUCCESS) {
122     DP("Error when creating event event = " DPxMOD "\n", DPxPTR(Event));
123     CUDA_ERR_STRING(Err);
124     return OFFLOAD_FAIL;
125   }
126 
127   *P = Event;
128 
129   return OFFLOAD_SUCCESS;
130 }
131 
132 int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) {
133   CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
134   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
135 
136   CUresult Err = cuEventRecord(Event, Stream);
137   if (Err != CUDA_SUCCESS) {
138     DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n",
139        DPxPTR(Stream), DPxPTR(Event));
140     CUDA_ERR_STRING(Err);
141     return OFFLOAD_FAIL;
142   }
143 
144   return OFFLOAD_SUCCESS;
145 }
146 
147 int syncEvent(void *EventPtr) {
148   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
149 
150   CUresult Err = cuEventSynchronize(Event);
151   if (Err != CUDA_SUCCESS) {
152     DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event));
153     CUDA_ERR_STRING(Err);
154     return OFFLOAD_FAIL;
155   }
156 
157   return OFFLOAD_SUCCESS;
158 }
159 
160 int destroyEvent(void *EventPtr) {
161   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
162 
163   CUresult Err = cuEventDestroy(Event);
164   if (Err != CUDA_SUCCESS) {
165     DP("Error when destroying event = " DPxMOD "\n", DPxPTR(Event));
166     CUDA_ERR_STRING(Err);
167     return OFFLOAD_FAIL;
168   }
169 
170   return OFFLOAD_SUCCESS;
171 }
172 
173 // Structure contains per-device data
174 struct DeviceDataTy {
175   /// List that contains all the kernels.
176   std::list<KernelTy> KernelsList;
177 
178   std::list<FuncOrGblEntryTy> FuncGblEntries;
179 
180   CUcontext Context = nullptr;
181   // Device properties
182   int ThreadsPerBlock = 0;
183   int BlocksPerGrid = 0;
184   int WarpSize = 0;
185   // OpenMP properties
186   int NumTeams = 0;
187   int NumThreads = 0;
188 };
189 
190 class StreamManagerTy {
191   int NumberOfDevices;
192   // The initial size of stream pool
193   int EnvNumInitialStreams;
194   // Per-device stream mutex
195   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
196   // Per-device stream Id indicates the next available stream in the pool
197   std::vector<int> NextStreamId;
198   // Per-device stream pool
199   std::vector<std::vector<CUstream>> StreamPool;
200   // Reference to per-device data
201   std::vector<DeviceDataTy> &DeviceData;
202 
203   // If there is no CUstream left in the pool, we will resize the pool to
204   // allocate more CUstream. This function should be called with device mutex,
205   // and we do not resize to smaller one.
206   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
207     std::vector<CUstream> &Pool = StreamPool[DeviceId];
208     const size_t CurrentSize = Pool.size();
209     assert(NewSize > CurrentSize && "new size is not larger than current size");
210 
211     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
212     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
213       // We will return if cannot switch to the right context in case of
214       // creating bunch of streams that are not corresponding to the right
215       // device. The offloading will fail later because selected CUstream is
216       // nullptr.
217       return;
218     }
219 
220     Pool.resize(NewSize, nullptr);
221 
222     for (size_t I = CurrentSize; I < NewSize; ++I) {
223       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
224                   "Error returned from cuStreamCreate\n");
225     }
226   }
227 
228 public:
229   StreamManagerTy(const int NumberOfDevices,
230                   std::vector<DeviceDataTy> &DeviceData)
231       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
232         DeviceData(DeviceData) {
233     StreamPool.resize(NumberOfDevices);
234     NextStreamId.resize(NumberOfDevices);
235     StreamMtx.resize(NumberOfDevices);
236 
237     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
238       EnvNumInitialStreams = std::stoi(EnvStr);
239 
240     // Initialize the next stream id
241     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
242 
243     // Initialize stream mutex
244     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
245       Ptr = std::make_unique<std::mutex>();
246   }
247 
248   ~StreamManagerTy() {
249     // Destroy streams
250     for (int I = 0; I < NumberOfDevices; ++I) {
251       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
252                   "Error returned from cuCtxSetCurrent\n");
253 
254       for (CUstream &S : StreamPool[I]) {
255         if (S)
256           checkResult(cuStreamDestroy(S),
257                       "Error returned from cuStreamDestroy\n");
258       }
259     }
260   }
261 
262   // Get a CUstream from pool. Per-device next stream id always points to the
263   // next available CUstream. That means, CUstreams [0, id-1] have been
264   // assigned, and [id,] are still available. If there is no CUstream left, we
265   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
266   // the id will increase one.
267   // xxxxxs+++++++++
268   //      ^
269   //      id
270   // After assignment, the pool becomes the following and s is assigned.
271   // xxxxxs+++++++++
272   //       ^
273   //       id
274   CUstream getStream(const int DeviceId) {
275     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
276     int &Id = NextStreamId[DeviceId];
277     // No CUstream left in the pool, we need to request from CUDA RT
278     if (Id == static_cast<int>(StreamPool[DeviceId].size())) {
279       // By default we double the stream pool every time
280       resizeStreamPool(DeviceId, Id * 2);
281     }
282     return StreamPool[DeviceId][Id++];
283   }
284 
285   // Return a CUstream back to pool. As mentioned above, per-device next
286   // stream is always points to the next available CUstream, so when we return
287   // a CUstream, we need to first decrease the id, and then copy the CUstream
288   // back.
289   // It is worth noting that, the order of streams return might be different
290   // from that they're assigned, that saying, at some point, there might be
291   // two identical CUstreams.
292   // xxax+a+++++
293   //     ^
294   //     id
295   // However, it doesn't matter, because they're always on the two sides of
296   // id. The left one will in the end be overwritten by another CUstream.
297   // Therefore, after several execution, the order of pool might be different
298   // from its initial state.
299   void returnStream(const int DeviceId, CUstream Stream) {
300     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
301     int &Id = NextStreamId[DeviceId];
302     assert(Id > 0 && "Wrong stream ID");
303     StreamPool[DeviceId][--Id] = Stream;
304   }
305 
306   bool initializeDeviceStreamPool(const int DeviceId) {
307     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
308 
309     resizeStreamPool(DeviceId, EnvNumInitialStreams);
310 
311     // Check the size of stream pool
312     if (static_cast<int>(StreamPool[DeviceId].size()) != EnvNumInitialStreams)
313       return false;
314 
315     // Check whether each stream is valid
316     for (CUstream &S : StreamPool[DeviceId])
317       if (!S)
318         return false;
319 
320     return true;
321   }
322 };
323 
324 class DeviceRTLTy {
325   int NumberOfDevices;
326   // OpenMP environment properties
327   int EnvNumTeams;
328   int EnvTeamLimit;
329   int EnvTeamThreadLimit;
330   // OpenMP requires flags
331   int64_t RequiresFlags;
332   // Amount of dynamic shared memory to use at launch.
333   uint64_t DynamicMemorySize;
334 
335   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
336   static constexpr const int HardThreadLimit = 1024;
337   static constexpr const int DefaultNumTeams = 128;
338   static constexpr const int DefaultNumThreads = 128;
339 
340   std::unique_ptr<StreamManagerTy> StreamManager;
341   std::vector<DeviceDataTy> DeviceData;
342   std::vector<CUmodule> Modules;
343 
344   /// A class responsible for interacting with device native runtime library to
345   /// allocate and free memory.
346   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
347     const int DeviceId;
348     const std::vector<DeviceDataTy> &DeviceData;
349     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
350 
351   public:
352     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
353         : DeviceId(DeviceId), DeviceData(DeviceData) {}
354 
355     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
356       if (Size == 0)
357         return nullptr;
358 
359       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
360       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
361         return nullptr;
362 
363       void *MemAlloc = nullptr;
364       switch (Kind) {
365       case TARGET_ALLOC_DEFAULT:
366       case TARGET_ALLOC_DEVICE:
367         CUdeviceptr DevicePtr;
368         Err = cuMemAlloc(&DevicePtr, Size);
369         MemAlloc = (void *)DevicePtr;
370         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
371           return nullptr;
372         break;
373       case TARGET_ALLOC_HOST:
374         void *HostPtr;
375         Err = cuMemAllocHost(&HostPtr, Size);
376         MemAlloc = HostPtr;
377         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
378           return nullptr;
379         HostPinnedAllocs[MemAlloc] = Kind;
380         break;
381       case TARGET_ALLOC_SHARED:
382         CUdeviceptr SharedPtr;
383         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
384         MemAlloc = (void *)SharedPtr;
385         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
386           return nullptr;
387         break;
388       }
389 
390       return MemAlloc;
391     }
392 
393     int free(void *TgtPtr) override {
394       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
395       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
396         return OFFLOAD_FAIL;
397 
398       // Host pinned memory must be freed differently.
399       TargetAllocTy Kind =
400           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
401               ? TARGET_ALLOC_DEFAULT
402               : TARGET_ALLOC_HOST;
403       switch (Kind) {
404       case TARGET_ALLOC_DEFAULT:
405       case TARGET_ALLOC_DEVICE:
406       case TARGET_ALLOC_SHARED:
407         Err = cuMemFree((CUdeviceptr)TgtPtr);
408         if (!checkResult(Err, "Error returned from cuMemFree\n"))
409           return OFFLOAD_FAIL;
410         break;
411       case TARGET_ALLOC_HOST:
412         Err = cuMemFreeHost(TgtPtr);
413         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
414           return OFFLOAD_FAIL;
415         break;
416       }
417 
418       return OFFLOAD_SUCCESS;
419     }
420   };
421 
422   /// A vector of device allocators
423   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
424 
425   /// A vector of memory managers. Since the memory manager is non-copyable and
426   // non-removable, we wrap them into std::unique_ptr.
427   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
428 
429   /// Whether use memory manager
430   bool UseMemoryManager = true;
431 
432   // Record entry point associated with device
433   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
434     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
435     E.Entries.push_back(entry);
436   }
437 
438   // Return a pointer to the entry associated with the pointer
439   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
440                                              const void *Addr) const {
441     for (const __tgt_offload_entry &Itr :
442          DeviceData[DeviceId].FuncGblEntries.back().Entries)
443       if (Itr.addr == Addr)
444         return &Itr;
445 
446     return nullptr;
447   }
448 
449   // Return the pointer to the target entries table
450   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
451     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
452 
453     if (E.Entries.empty())
454       return nullptr;
455 
456     // Update table info according to the entries and return the pointer
457     E.Table.EntriesBegin = E.Entries.data();
458     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
459 
460     return &E.Table;
461   }
462 
463   // Clear entries table for a device
464   void clearOffloadEntriesTable(const int DeviceId) {
465     DeviceData[DeviceId].FuncGblEntries.emplace_back();
466     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
467     E.Entries.clear();
468     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
469   }
470 
471   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
472     assert(AsyncInfo && "AsyncInfo is nullptr");
473 
474     if (!AsyncInfo->Queue)
475       AsyncInfo->Queue = StreamManager->getStream(DeviceId);
476 
477     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
478   }
479 
480 public:
481   // This class should not be copied
482   DeviceRTLTy(const DeviceRTLTy &) = delete;
483   DeviceRTLTy(DeviceRTLTy &&) = delete;
484 
485   DeviceRTLTy()
486       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
487         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED),
488         DynamicMemorySize(0) {
489 
490     DP("Start initializing CUDA\n");
491 
492     CUresult Err = cuInit(0);
493     if (Err == CUDA_ERROR_INVALID_HANDLE) {
494       // Can't call cuGetErrorString if dlsym failed
495       DP("Failed to load CUDA shared library\n");
496       return;
497     }
498     if (!checkResult(Err, "Error returned from cuInit\n")) {
499       return;
500     }
501 
502     Err = cuDeviceGetCount(&NumberOfDevices);
503     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
504       return;
505 
506     if (NumberOfDevices == 0) {
507       DP("There are no devices supporting CUDA.\n");
508       return;
509     }
510 
511     DeviceData.resize(NumberOfDevices);
512 
513     // Get environment variables regarding teams
514     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
515       // OMP_TEAM_LIMIT has been set
516       EnvTeamLimit = std::stoi(EnvStr);
517       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
518     }
519     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
520       // OMP_TEAMS_THREAD_LIMIT has been set
521       EnvTeamThreadLimit = std::stoi(EnvStr);
522       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
523     }
524     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
525       // OMP_NUM_TEAMS has been set
526       EnvNumTeams = std::stoi(EnvStr);
527       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
528     }
529     if (const char *EnvStr = getenv("LIBOMPTARGET_SHARED_MEMORY_SIZE")) {
530       // LIBOMPTARGET_SHARED_MEMORY_SIZE has been set
531       DynamicMemorySize = std::stoi(EnvStr);
532       DP("Parsed LIBOMPTARGET_SHARED_MEMORY_SIZE = %" PRIu64 "\n",
533          DynamicMemorySize);
534     }
535 
536     StreamManager =
537         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
538 
539     for (int I = 0; I < NumberOfDevices; ++I)
540       DeviceAllocators.emplace_back(I, DeviceData);
541 
542     // Get the size threshold from environment variable
543     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
544     UseMemoryManager = Res.second;
545     size_t MemoryManagerThreshold = Res.first;
546 
547     if (UseMemoryManager)
548       for (int I = 0; I < NumberOfDevices; ++I)
549         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
550             DeviceAllocators[I], MemoryManagerThreshold));
551   }
552 
553   ~DeviceRTLTy() {
554     // We first destruct memory managers in case that its dependent data are
555     // destroyed before it.
556     for (auto &M : MemoryManagers)
557       M.release();
558 
559     StreamManager = nullptr;
560 
561     for (CUmodule &M : Modules)
562       // Close module
563       if (M)
564         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
565 
566     for (DeviceDataTy &D : DeviceData) {
567       // Destroy context
568       if (D.Context) {
569         checkResult(cuCtxSetCurrent(D.Context),
570                     "Error returned from cuCtxSetCurrent\n");
571         CUdevice Device;
572         checkResult(cuCtxGetDevice(&Device),
573                     "Error returned from cuCtxGetDevice\n");
574         checkResult(cuDevicePrimaryCtxRelease(Device),
575                     "Error returned from cuDevicePrimaryCtxRelease\n");
576       }
577     }
578   }
579 
580   // Check whether a given DeviceId is valid
581   bool isValidDeviceId(const int DeviceId) const {
582     return DeviceId >= 0 && DeviceId < NumberOfDevices;
583   }
584 
585   int getNumOfDevices() const { return NumberOfDevices; }
586 
587   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
588 
589   int initDevice(const int DeviceId) {
590     CUdevice Device;
591 
592     DP("Getting device %d\n", DeviceId);
593     CUresult Err = cuDeviceGet(&Device, DeviceId);
594     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
595       return OFFLOAD_FAIL;
596 
597     // Query the current flags of the primary context and set its flags if
598     // it is inactive
599     unsigned int FormerPrimaryCtxFlags = 0;
600     int FormerPrimaryCtxIsActive = 0;
601     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
602                                      &FormerPrimaryCtxIsActive);
603     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
604       return OFFLOAD_FAIL;
605 
606     if (FormerPrimaryCtxIsActive) {
607       DP("The primary context is active, no change to its flags\n");
608       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
609           CU_CTX_SCHED_BLOCKING_SYNC)
610         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
611     } else {
612       DP("The primary context is inactive, set its flags to "
613          "CU_CTX_SCHED_BLOCKING_SYNC\n");
614       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
615       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
616         return OFFLOAD_FAIL;
617     }
618 
619     // Retain the per device primary context and save it to use whenever this
620     // device is selected.
621     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
622     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
623       return OFFLOAD_FAIL;
624 
625     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
626     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
627       return OFFLOAD_FAIL;
628 
629     // Initialize stream pool
630     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
631       return OFFLOAD_FAIL;
632 
633     // Query attributes to determine number of threads/block and blocks/grid.
634     int MaxGridDimX;
635     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
636                                Device);
637     if (Err != CUDA_SUCCESS) {
638       DP("Error getting max grid dimension, use default value %d\n",
639          DeviceRTLTy::DefaultNumTeams);
640       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
641     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
642       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
643       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
644     } else {
645       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
646          "at the hard limit\n",
647          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
648       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
649     }
650 
651     // We are only exploiting threads along the x axis.
652     int MaxBlockDimX;
653     Err = cuDeviceGetAttribute(&MaxBlockDimX,
654                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
655     if (Err != CUDA_SUCCESS) {
656       DP("Error getting max block dimension, use default value %d\n",
657          DeviceRTLTy::DefaultNumThreads);
658       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
659     } else {
660       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
661       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
662 
663       if (EnvTeamThreadLimit > 0 &&
664           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
665         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
666            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
667            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
668         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
669       }
670       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
671         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
672            "capping at the hard limit\n",
673            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
674         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
675       }
676     }
677 
678     // Get and set warp size
679     int WarpSize;
680     Err =
681         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
682     if (Err != CUDA_SUCCESS) {
683       DP("Error getting warp size, assume default value 32\n");
684       DeviceData[DeviceId].WarpSize = 32;
685     } else {
686       DP("Using warp size %d\n", WarpSize);
687       DeviceData[DeviceId].WarpSize = WarpSize;
688     }
689 
690     // Adjust teams to the env variables
691     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
692       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
693          EnvTeamLimit);
694       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
695     }
696 
697     size_t StackLimit;
698     size_t HeapLimit;
699     if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
700       StackLimit = std::stol(EnvStr);
701       if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
702         return OFFLOAD_FAIL;
703     } else {
704       if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
705         return OFFLOAD_FAIL;
706     }
707     if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
708       HeapLimit = std::stol(EnvStr);
709       if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
710         return OFFLOAD_FAIL;
711     } else {
712       if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
713         return OFFLOAD_FAIL;
714     }
715 
716     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
717          "Device supports up to %d CUDA blocks and %d threads with a "
718          "warp size of %d\n",
719          DeviceData[DeviceId].BlocksPerGrid,
720          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
721     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
722          "Device heap size is %d Bytes, device stack size is %d Bytes per "
723          "thread\n",
724          (int)HeapLimit, (int)StackLimit);
725 
726     // Set default number of teams
727     if (EnvNumTeams > 0) {
728       DP("Default number of teams set according to environment %d\n",
729          EnvNumTeams);
730       DeviceData[DeviceId].NumTeams = EnvNumTeams;
731     } else {
732       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
733       DP("Default number of teams set according to library's default %d\n",
734          DeviceRTLTy::DefaultNumTeams);
735     }
736 
737     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
738       DP("Default number of teams exceeds device limit, capping at %d\n",
739          DeviceData[DeviceId].BlocksPerGrid);
740       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
741     }
742 
743     // Set default number of threads
744     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
745     DP("Default number of threads set according to library's default %d\n",
746        DeviceRTLTy::DefaultNumThreads);
747     if (DeviceData[DeviceId].NumThreads >
748         DeviceData[DeviceId].ThreadsPerBlock) {
749       DP("Default number of threads exceeds device limit, capping at %d\n",
750          DeviceData[DeviceId].ThreadsPerBlock);
751       DeviceData[DeviceId].NumThreads = DeviceData[DeviceId].ThreadsPerBlock;
752     }
753 
754     return OFFLOAD_SUCCESS;
755   }
756 
757   __tgt_target_table *loadBinary(const int DeviceId,
758                                  const __tgt_device_image *Image) {
759     // Set the context we are using
760     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
761     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
762       return nullptr;
763 
764     // Clear the offload table as we are going to create a new one.
765     clearOffloadEntriesTable(DeviceId);
766 
767     // Create the module and extract the function pointers.
768     CUmodule Module;
769     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
770     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
771     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
772       return nullptr;
773 
774     DP("CUDA module successfully loaded!\n");
775 
776     Modules.push_back(Module);
777 
778     // Find the symbols in the module by name.
779     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
780     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
781 
782     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
783     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
784       if (!E->addr) {
785         // We return nullptr when something like this happens, the host should
786         // have always something in the address to uniquely identify the target
787         // region.
788         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
789         return nullptr;
790       }
791 
792       if (E->size) {
793         __tgt_offload_entry Entry = *E;
794         CUdeviceptr CUPtr;
795         size_t CUSize;
796         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
797         // We keep this style here because we need the name
798         if (Err != CUDA_SUCCESS) {
799           REPORT("Loading global '%s' Failed\n", E->name);
800           CUDA_ERR_STRING(Err);
801           return nullptr;
802         }
803 
804         if (CUSize != E->size) {
805           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
806              CUSize, E->size);
807           return nullptr;
808         }
809 
810         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
811            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
812 
813         Entry.addr = (void *)(CUPtr);
814 
815         // Note: In the current implementation declare target variables
816         // can either be link or to. This means that once unified
817         // memory is activated via the requires directive, the variable
818         // can be used directly from the host in both cases.
819         // TODO: when variables types other than to or link are added,
820         // the below condition should be changed to explicitly
821         // check for to and link variables types:
822         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
823         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
824         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
825           // If unified memory is present any target link or to variables
826           // can access host addresses directly. There is no longer a
827           // need for device copies.
828           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
829           DP("Copy linked variable host address (" DPxMOD
830              ") to device address (" DPxMOD ")\n",
831              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
832         }
833 
834         addOffloadEntry(DeviceId, Entry);
835 
836         continue;
837       }
838 
839       CUfunction Func;
840       Err = cuModuleGetFunction(&Func, Module, E->name);
841       // We keep this style here because we need the name
842       if (Err != CUDA_SUCCESS) {
843         REPORT("Loading '%s' Failed\n", E->name);
844         CUDA_ERR_STRING(Err);
845         return nullptr;
846       }
847 
848       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
849          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
850 
851       // default value GENERIC (in case symbol is missing from cubin file)
852       llvm::omp::OMPTgtExecModeFlags ExecModeVal;
853       std::string ExecModeNameStr(E->name);
854       ExecModeNameStr += "_exec_mode";
855       const char *ExecModeName = ExecModeNameStr.c_str();
856 
857       CUdeviceptr ExecModePtr;
858       size_t CUSize;
859       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
860       if (Err == CUDA_SUCCESS) {
861         if (CUSize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
862           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
863              ExecModeName, CUSize, sizeof(llvm::omp::OMPTgtExecModeFlags));
864           return nullptr;
865         }
866 
867         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
868         if (Err != CUDA_SUCCESS) {
869           REPORT("Error when copying data from device to host. Pointers: "
870                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
871                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
872           CUDA_ERR_STRING(Err);
873           return nullptr;
874         }
875       } else {
876         DP("Loading global exec_mode '%s' - symbol missing, using default "
877            "value GENERIC (1)\n",
878            ExecModeName);
879       }
880 
881       KernelsList.emplace_back(Func, ExecModeVal);
882 
883       __tgt_offload_entry Entry = *E;
884       Entry.addr = &KernelsList.back();
885       addOffloadEntry(DeviceId, Entry);
886     }
887 
888     // send device environment data to the device
889     {
890       // TODO: The device ID used here is not the real device ID used by OpenMP.
891       DeviceEnvironmentTy DeviceEnv{0, static_cast<uint32_t>(NumberOfDevices),
892                                     static_cast<uint32_t>(DeviceId),
893                                     static_cast<uint32_t>(DynamicMemorySize)};
894 
895       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
896         DeviceEnv.DebugKind = std::stoi(EnvStr);
897 
898       const char *DeviceEnvName = "omptarget_device_environment";
899       CUdeviceptr DeviceEnvPtr;
900       size_t CUSize;
901 
902       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
903       if (Err == CUDA_SUCCESS) {
904         if (CUSize != sizeof(DeviceEnv)) {
905           REPORT(
906               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
907               DeviceEnvName, CUSize, sizeof(int32_t));
908           CUDA_ERR_STRING(Err);
909           return nullptr;
910         }
911 
912         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
913         if (Err != CUDA_SUCCESS) {
914           REPORT("Error when copying data from host to device. Pointers: "
915                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
916                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
917           CUDA_ERR_STRING(Err);
918           return nullptr;
919         }
920 
921         DP("Sending global device environment data %zu bytes\n", CUSize);
922       } else {
923         DP("Finding global device environment '%s' - symbol missing.\n",
924            DeviceEnvName);
925         DP("Continue, considering this is a device RTL which does not accept "
926            "environment setting.\n");
927       }
928     }
929 
930     return getOffloadEntriesTable(DeviceId);
931   }
932 
933   void *dataAlloc(const int DeviceId, const int64_t Size,
934                   const TargetAllocTy Kind) {
935     switch (Kind) {
936     case TARGET_ALLOC_DEFAULT:
937     case TARGET_ALLOC_DEVICE:
938       if (UseMemoryManager)
939         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
940       else
941         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
942     case TARGET_ALLOC_HOST:
943     case TARGET_ALLOC_SHARED:
944       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
945     }
946 
947     REPORT("Invalid target data allocation kind or requested allocator not "
948            "implemented yet\n");
949 
950     return nullptr;
951   }
952 
953   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
954                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
955     assert(AsyncInfo && "AsyncInfo is nullptr");
956 
957     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
958     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
959       return OFFLOAD_FAIL;
960 
961     CUstream Stream = getStream(DeviceId, AsyncInfo);
962 
963     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
964     if (Err != CUDA_SUCCESS) {
965       DP("Error when copying data from host to device. Pointers: host "
966          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
967          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
968       CUDA_ERR_STRING(Err);
969       return OFFLOAD_FAIL;
970     }
971 
972     return OFFLOAD_SUCCESS;
973   }
974 
975   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
976                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
977     assert(AsyncInfo && "AsyncInfo is nullptr");
978 
979     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
980     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
981       return OFFLOAD_FAIL;
982 
983     CUstream Stream = getStream(DeviceId, AsyncInfo);
984 
985     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
986     if (Err != CUDA_SUCCESS) {
987       DP("Error when copying data from device to host. Pointers: host "
988          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
989          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
990       CUDA_ERR_STRING(Err);
991       return OFFLOAD_FAIL;
992     }
993 
994     return OFFLOAD_SUCCESS;
995   }
996 
997   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
998                    int64_t Size, __tgt_async_info *AsyncInfo) const {
999     assert(AsyncInfo && "AsyncInfo is nullptr");
1000 
1001     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
1002     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
1003       return OFFLOAD_FAIL;
1004 
1005     CUstream Stream = getStream(SrcDevId, AsyncInfo);
1006 
1007     // If they are two devices, we try peer to peer copy first
1008     if (SrcDevId != DstDevId) {
1009       int CanAccessPeer = 0;
1010       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
1011       if (Err != CUDA_SUCCESS) {
1012         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
1013                ", dst = %" PRId32 "\n",
1014                SrcDevId, DstDevId);
1015         CUDA_ERR_STRING(Err);
1016         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1017       }
1018 
1019       if (!CanAccessPeer) {
1020         DP("P2P memcpy not supported so fall back to D2D memcpy");
1021         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1022       }
1023 
1024       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
1025       if (Err != CUDA_SUCCESS) {
1026         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
1027                ", dst = %" PRId32 "\n",
1028                SrcDevId, DstDevId);
1029         CUDA_ERR_STRING(Err);
1030         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1031       }
1032 
1033       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
1034                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
1035                               Size, Stream);
1036       if (Err == CUDA_SUCCESS)
1037         return OFFLOAD_SUCCESS;
1038 
1039       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
1040          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
1041          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
1042       CUDA_ERR_STRING(Err);
1043     }
1044 
1045     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1046   }
1047 
1048   int dataDelete(const int DeviceId, void *TgtPtr) {
1049     if (UseMemoryManager)
1050       return MemoryManagers[DeviceId]->free(TgtPtr);
1051 
1052     return DeviceAllocators[DeviceId].free(TgtPtr);
1053   }
1054 
1055   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1056                           ptrdiff_t *TgtOffsets, const int ArgNum,
1057                           const int TeamNum, const int ThreadLimit,
1058                           const unsigned int LoopTripCount,
1059                           __tgt_async_info *AsyncInfo) const {
1060     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1061     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
1062       return OFFLOAD_FAIL;
1063 
1064     // All args are references.
1065     std::vector<void *> Args(ArgNum);
1066     std::vector<void *> Ptrs(ArgNum);
1067 
1068     for (int I = 0; I < ArgNum; ++I) {
1069       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
1070       Args[I] = &Ptrs[I];
1071     }
1072 
1073     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
1074 
1075     const bool IsSPMDGenericMode =
1076         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD;
1077     const bool IsSPMDMode =
1078         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
1079     const bool IsGenericMode =
1080         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
1081 
1082     int CudaThreadsPerBlock;
1083     if (ThreadLimit > 0) {
1084       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
1085       CudaThreadsPerBlock = ThreadLimit;
1086       // Add master warp if necessary
1087       if (IsGenericMode) {
1088         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
1089         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
1090       }
1091     } else {
1092       DP("Setting CUDA threads per block to default %d\n",
1093          DeviceData[DeviceId].NumThreads);
1094       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1095     }
1096 
1097     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
1098       DP("Threads per block capped at device limit %d\n",
1099          DeviceData[DeviceId].ThreadsPerBlock);
1100       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
1101     }
1102 
1103     if (!KernelInfo->MaxThreadsPerBlock) {
1104       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
1105                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
1106                                KernelInfo->Func);
1107       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1108         return OFFLOAD_FAIL;
1109     }
1110 
1111     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1112       DP("Threads per block capped at kernel limit %d\n",
1113          KernelInfo->MaxThreadsPerBlock);
1114       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
1115     }
1116 
1117     unsigned int CudaBlocksPerGrid;
1118     if (TeamNum <= 0) {
1119       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1120         if (IsSPMDGenericMode) {
1121           // If we reach this point, then we are executing a kernel that was
1122           // transformed from Generic-mode to SPMD-mode. This kernel has
1123           // SPMD-mode execution, but needs its blocks to be scheduled
1124           // differently because the current loop trip count only applies to the
1125           // `teams distribute` region and will create var too few blocks using
1126           // the regular SPMD-mode method.
1127           CudaBlocksPerGrid = LoopTripCount;
1128         } else if (IsSPMDMode) {
1129           // We have a combined construct, i.e. `target teams distribute
1130           // parallel for [simd]`. We launch so many teams so that each thread
1131           // will execute one iteration of the loop. round up to the nearest
1132           // integer
1133           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
1134         } else if (IsGenericMode) {
1135           // If we reach this point, then we have a non-combined construct, i.e.
1136           // `teams distribute` with a nested `parallel for` and each team is
1137           // assigned one iteration of the `distribute` loop. E.g.:
1138           //
1139           // #pragma omp target teams distribute
1140           // for(...loop_tripcount...) {
1141           //   #pragma omp parallel for
1142           //   for(...) {}
1143           // }
1144           //
1145           // Threads within a team will execute the iterations of the `parallel`
1146           // loop.
1147           CudaBlocksPerGrid = LoopTripCount;
1148         } else {
1149           REPORT("Unknown execution mode: %d\n",
1150                  static_cast<int8_t>(KernelInfo->ExecutionMode));
1151           return OFFLOAD_FAIL;
1152         }
1153         DP("Using %d teams due to loop trip count %" PRIu32
1154            " and number of threads per block %d\n",
1155            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
1156       } else {
1157         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
1158         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
1159       }
1160     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
1161       DP("Capping number of teams to team limit %d\n",
1162          DeviceData[DeviceId].BlocksPerGrid);
1163       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
1164     } else {
1165       DP("Using requested number of teams %d\n", TeamNum);
1166       CudaBlocksPerGrid = TeamNum;
1167     }
1168 
1169     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1170          "Launching kernel %s with %d blocks and %d threads in %s mode\n",
1171          (getOffloadEntry(DeviceId, TgtEntryPtr))
1172              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1173              : "(null)",
1174          CudaBlocksPerGrid, CudaThreadsPerBlock,
1175          (!IsSPMDMode ? (IsGenericMode ? "Generic" : "SPMD-Generic") : "SPMD"));
1176 
1177     CUstream Stream = getStream(DeviceId, AsyncInfo);
1178     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
1179                          /* gridDimZ */ 1, CudaThreadsPerBlock,
1180                          /* blockDimY */ 1, /* blockDimZ */ 1,
1181                          DynamicMemorySize, Stream, &Args[0], nullptr);
1182     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
1183       return OFFLOAD_FAIL;
1184 
1185     DP("Launch of entry point at " DPxMOD " successful!\n",
1186        DPxPTR(TgtEntryPtr));
1187 
1188     return OFFLOAD_SUCCESS;
1189   }
1190 
1191   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
1192     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
1193     CUresult Err = cuStreamSynchronize(Stream);
1194 
1195     // Once the stream is synchronized, return it to stream pool and reset
1196     // AsyncInfo. This is to make sure the synchronization only works for its
1197     // own tasks.
1198     StreamManager->returnStream(DeviceId,
1199                                 reinterpret_cast<CUstream>(AsyncInfo->Queue));
1200     AsyncInfo->Queue = nullptr;
1201 
1202     if (Err != CUDA_SUCCESS) {
1203       DP("Error when synchronizing stream. stream = " DPxMOD
1204          ", async info ptr = " DPxMOD "\n",
1205          DPxPTR(Stream), DPxPTR(AsyncInfo));
1206       CUDA_ERR_STRING(Err);
1207     }
1208     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
1209   }
1210 
1211   void printDeviceInfo(int32_t device_id) {
1212     char TmpChar[1000];
1213     std::string TmpStr;
1214     size_t TmpSt;
1215     int TmpInt, TmpInt2, TmpInt3;
1216 
1217     CUdevice Device;
1218     checkResult(cuDeviceGet(&Device, device_id),
1219                 "Error returned from cuCtxGetDevice\n");
1220 
1221     cuDriverGetVersion(&TmpInt);
1222     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1223     printf("    CUDA Device Number: \t\t%d \n", device_id);
1224     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1225                 "Error returned from cuDeviceGetName\n");
1226     printf("    Device Name: \t\t\t%s \n", TmpChar);
1227     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1228                 "Error returned from cuDeviceTotalMem\n");
1229     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1230     checkResult(cuDeviceGetAttribute(
1231                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1232                 "Error returned from cuDeviceGetAttribute\n");
1233     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1234     checkResult(
1235         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1236         "Error returned from cuDeviceGetAttribute\n");
1237     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1238     checkResult(cuDeviceGetAttribute(
1239                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1240                 "Error returned from cuDeviceGetAttribute\n");
1241     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1242     checkResult(
1243         cuDeviceGetAttribute(
1244             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1245         "Error returned from cuDeviceGetAttribute\n");
1246     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
1247     checkResult(
1248         cuDeviceGetAttribute(
1249             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1250         "Error returned from cuDeviceGetAttribute\n");
1251     printf("    Registers per Block: \t\t%d \n", TmpInt);
1252     checkResult(
1253         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1254         "Error returned from cuDeviceGetAttribute\n");
1255     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1256     checkResult(cuDeviceGetAttribute(
1257                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1258                 "Error returned from cuDeviceGetAttribute\n");
1259     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
1260     checkResult(cuDeviceGetAttribute(
1261                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1262                 "Error returned from cuDeviceGetAttribute\n");
1263     checkResult(cuDeviceGetAttribute(
1264                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1265                 "Error returned from cuDeviceGetAttribute\n");
1266     checkResult(cuDeviceGetAttribute(
1267                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1268                 "Error returned from cuDeviceGetAttribute\n");
1269     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1270            TmpInt3);
1271     checkResult(cuDeviceGetAttribute(
1272                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1273                 "Error returned from cuDeviceGetAttribute\n");
1274     checkResult(cuDeviceGetAttribute(
1275                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1276                 "Error returned from cuDeviceGetAttribute\n");
1277     checkResult(cuDeviceGetAttribute(
1278                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1279                 "Error returned from cuDeviceGetAttribute\n");
1280     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1281            TmpInt3);
1282     checkResult(
1283         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1284         "Error returned from cuDeviceGetAttribute\n");
1285     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1286     checkResult(cuDeviceGetAttribute(
1287                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1288                 "Error returned from cuDeviceGetAttribute\n");
1289     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1290     checkResult(
1291         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1292         "Error returned from cuDeviceGetAttribute\n");
1293     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1294     checkResult(cuDeviceGetAttribute(
1295                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1296                 "Error returned from cuDeviceGetAttribute\n");
1297     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1298     checkResult(
1299         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1300         "Error returned from cuDeviceGetAttribute\n");
1301     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1302     checkResult(cuDeviceGetAttribute(
1303                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1304                 "Error returned from cuDeviceGetAttribute\n");
1305     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1306     checkResult(
1307         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1308         "Error returned from cuDeviceGetAttribute\n");
1309     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1310       TmpStr = "DEFAULT";
1311     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1312       TmpStr = "PROHIBITED";
1313     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1314       TmpStr = "EXCLUSIVE PROCESS";
1315     else
1316       TmpStr = "unknown";
1317     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1318     checkResult(cuDeviceGetAttribute(
1319                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1320                 "Error returned from cuDeviceGetAttribute\n");
1321     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1322     checkResult(
1323         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1324         "Error returned from cuDeviceGetAttribute\n");
1325     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1326     checkResult(cuDeviceGetAttribute(
1327                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1328                 "Error returned from cuDeviceGetAttribute\n");
1329     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
1330     checkResult(
1331         cuDeviceGetAttribute(
1332             &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1333         "Error returned from cuDeviceGetAttribute\n");
1334     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
1335     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
1336                                      Device),
1337                 "Error returned from cuDeviceGetAttribute\n");
1338     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
1339     checkResult(cuDeviceGetAttribute(
1340                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
1341                     Device),
1342                 "Error returned from cuDeviceGetAttribute\n");
1343     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1344     checkResult(cuDeviceGetAttribute(
1345                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1346                 "Error returned from cuDeviceGetAttribute\n");
1347     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1348     checkResult(cuDeviceGetAttribute(
1349                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1350                 "Error returned from cuDeviceGetAttribute\n");
1351     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
1352     checkResult(cuDeviceGetAttribute(
1353                     &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1354                 "Error returned from cuDeviceGetAttribute\n");
1355     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1356     checkResult(
1357         cuDeviceGetAttribute(
1358             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1359         "Error returned from cuDeviceGetAttribute\n");
1360     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1361     checkResult(
1362         cuDeviceGetAttribute(
1363             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1364         "Error returned from cuDeviceGetAttribute\n");
1365     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1366     checkResult(cuDeviceGetAttribute(
1367                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1368                 "Error returned from cuDeviceGetAttribute\n");
1369     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
1370     checkResult(cuDeviceGetAttribute(
1371                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1372                 "Error returned from cuDeviceGetAttribute\n");
1373     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
1374     checkResult(
1375         cuDeviceGetAttribute(
1376             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1377         "Error returned from cuDeviceGetAttribute\n");
1378     checkResult(
1379         cuDeviceGetAttribute(
1380             &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1381         "Error returned from cuDeviceGetAttribute\n");
1382     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1383   }
1384 
1385   int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo,
1386                 void *EventPtr) const {
1387     CUstream Stream = getStream(DeviceId, AsyncInfo);
1388     CUevent Event = reinterpret_cast<CUevent>(EventPtr);
1389 
1390     // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from
1391     // specific CUDA version, and defined as 0x0. In previous version, per CUDA
1392     // API document, that argument has to be 0x0.
1393     CUresult Err = cuStreamWaitEvent(Stream, Event, 0);
1394     if (Err != CUDA_SUCCESS) {
1395       DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n",
1396          DPxPTR(Stream), DPxPTR(Event));
1397       CUDA_ERR_STRING(Err);
1398       return OFFLOAD_FAIL;
1399     }
1400 
1401     return OFFLOAD_SUCCESS;
1402   }
1403 };
1404 
1405 DeviceRTLTy DeviceRTL;
1406 } // namespace
1407 
1408 // Exposed library API function
1409 #ifdef __cplusplus
1410 extern "C" {
1411 #endif
1412 
1413 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
1414   return elf_check_machine(image, /* EM_CUDA */ 190);
1415 }
1416 
1417 int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
1418 
1419 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
1420   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
1421   DeviceRTL.setRequiresFlag(RequiresFlags);
1422   return RequiresFlags;
1423 }
1424 
1425 int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1426   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1427       DeviceRTL.isValidDeviceId(dst_dev_id))
1428     return 1;
1429 
1430   return 0;
1431 }
1432 
1433 int32_t __tgt_rtl_init_device(int32_t device_id) {
1434   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1435 
1436   return DeviceRTL.initDevice(device_id);
1437 }
1438 
1439 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1440                                           __tgt_device_image *image) {
1441   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1442 
1443   return DeviceRTL.loadBinary(device_id, image);
1444 }
1445 
1446 void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
1447                            int32_t kind) {
1448   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1449 
1450   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
1451 }
1452 
1453 int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
1454                               int64_t size) {
1455   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1456 
1457   __tgt_async_info AsyncInfo;
1458   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
1459                                                  size, &AsyncInfo);
1460   if (rc != OFFLOAD_SUCCESS)
1461     return OFFLOAD_FAIL;
1462 
1463   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1464 }
1465 
1466 int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
1467                                     void *hst_ptr, int64_t size,
1468                                     __tgt_async_info *async_info_ptr) {
1469   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1470   assert(async_info_ptr && "async_info_ptr is nullptr");
1471 
1472   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
1473                               async_info_ptr);
1474 }
1475 
1476 int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
1477                                 int64_t size) {
1478   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1479 
1480   __tgt_async_info AsyncInfo;
1481   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
1482                                                    size, &AsyncInfo);
1483   if (rc != OFFLOAD_SUCCESS)
1484     return OFFLOAD_FAIL;
1485 
1486   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1487 }
1488 
1489 int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
1490                                       void *tgt_ptr, int64_t size,
1491                                       __tgt_async_info *async_info_ptr) {
1492   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1493   assert(async_info_ptr && "async_info_ptr is nullptr");
1494 
1495   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
1496                                 async_info_ptr);
1497 }
1498 
1499 int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1500                                       int dst_dev_id, void *dst_ptr,
1501                                       int64_t size,
1502                                       __tgt_async_info *AsyncInfo) {
1503   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1504   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1505   assert(AsyncInfo && "AsyncInfo is nullptr");
1506 
1507   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1508                                 AsyncInfo);
1509 }
1510 
1511 int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1512                                 int32_t dst_dev_id, void *dst_ptr,
1513                                 int64_t size) {
1514   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1515   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1516 
1517   __tgt_async_info AsyncInfo;
1518   const int32_t rc = __tgt_rtl_data_exchange_async(
1519       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1520   if (rc != OFFLOAD_SUCCESS)
1521     return OFFLOAD_FAIL;
1522 
1523   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1524 }
1525 
1526 int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
1527   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1528 
1529   return DeviceRTL.dataDelete(device_id, tgt_ptr);
1530 }
1531 
1532 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
1533                                          void **tgt_args,
1534                                          ptrdiff_t *tgt_offsets,
1535                                          int32_t arg_num, int32_t team_num,
1536                                          int32_t thread_limit,
1537                                          uint64_t loop_tripcount) {
1538   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1539 
1540   __tgt_async_info AsyncInfo;
1541   const int32_t rc = __tgt_rtl_run_target_team_region_async(
1542       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1543       thread_limit, loop_tripcount, &AsyncInfo);
1544   if (rc != OFFLOAD_SUCCESS)
1545     return OFFLOAD_FAIL;
1546 
1547   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1548 }
1549 
1550 int32_t __tgt_rtl_run_target_team_region_async(
1551     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1552     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
1553     int32_t thread_limit, uint64_t loop_tripcount,
1554     __tgt_async_info *async_info_ptr) {
1555   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1556 
1557   return DeviceRTL.runTargetTeamRegion(
1558       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1559       thread_limit, loop_tripcount, async_info_ptr);
1560 }
1561 
1562 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
1563                                     void **tgt_args, ptrdiff_t *tgt_offsets,
1564                                     int32_t arg_num) {
1565   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1566 
1567   __tgt_async_info AsyncInfo;
1568   const int32_t rc = __tgt_rtl_run_target_region_async(
1569       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
1570   if (rc != OFFLOAD_SUCCESS)
1571     return OFFLOAD_FAIL;
1572 
1573   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
1574 }
1575 
1576 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
1577                                           void *tgt_entry_ptr, void **tgt_args,
1578                                           ptrdiff_t *tgt_offsets,
1579                                           int32_t arg_num,
1580                                           __tgt_async_info *async_info_ptr) {
1581   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1582 
1583   return __tgt_rtl_run_target_team_region_async(
1584       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
1585       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1586       async_info_ptr);
1587 }
1588 
1589 int32_t __tgt_rtl_synchronize(int32_t device_id,
1590                               __tgt_async_info *async_info_ptr) {
1591   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1592   assert(async_info_ptr && "async_info_ptr is nullptr");
1593   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1594 
1595   return DeviceRTL.synchronize(device_id, async_info_ptr);
1596 }
1597 
1598 void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
1599   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
1600   InfoLevel.store(NewInfoLevel);
1601 }
1602 
1603 void __tgt_rtl_print_device_info(int32_t device_id) {
1604   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1605   DeviceRTL.printDeviceInfo(device_id);
1606 }
1607 
1608 int32_t __tgt_rtl_create_event(int32_t device_id, void **event) {
1609   assert(event && "event is nullptr");
1610   return createEvent(event);
1611 }
1612 
1613 int32_t __tgt_rtl_record_event(int32_t device_id, void *event_ptr,
1614                                __tgt_async_info *async_info_ptr) {
1615   assert(async_info_ptr && "async_info_ptr is nullptr");
1616   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1617   assert(event_ptr && "event_ptr is nullptr");
1618 
1619   return recordEvent(event_ptr, async_info_ptr);
1620 }
1621 
1622 int32_t __tgt_rtl_wait_event(int32_t device_id, void *event_ptr,
1623                              __tgt_async_info *async_info_ptr) {
1624   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1625   assert(async_info_ptr && "async_info_ptr is nullptr");
1626   assert(event_ptr && "event is nullptr");
1627 
1628   return DeviceRTL.waitEvent(device_id, async_info_ptr, event_ptr);
1629 }
1630 
1631 int32_t __tgt_rtl_sync_event(int32_t device_id, void *event_ptr) {
1632   assert(event_ptr && "event is nullptr");
1633 
1634   return syncEvent(event_ptr);
1635 }
1636 
1637 int32_t __tgt_rtl_destroy_event(int32_t device_id, void *event_ptr) {
1638   assert(event_ptr && "event is nullptr");
1639 
1640   return destroyEvent(event_ptr);
1641 }
1642 
1643 #ifdef __cplusplus
1644 }
1645 #endif
1646