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