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 <vector>
21 
22 #include "Debug.h"
23 #include "omptargetplugin.h"
24 
25 #define TARGET_NAME CUDA
26 #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
27 
28 #include "MemoryManager.h"
29 
30 // Utility for retrieving and printing CUDA error string.
31 #ifdef OMPTARGET_DEBUG
32 #define CUDA_ERR_STRING(err)                                                   \
33   do {                                                                         \
34     if (getDebugLevel() > 0) {                                                 \
35       const char *errStr = nullptr;                                            \
36       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
37       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
38         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
39       else if (errStr_status == CUDA_SUCCESS)                                  \
40         REPORT("CUDA error is: %s\n", errStr);                                 \
41       else {                                                                   \
42         REPORT("Unresolved CUDA error code: %d\n", err);                       \
43         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
44                errStr_status);                                                 \
45       }                                                                        \
46     } else {                                                                   \
47       const char *errStr = nullptr;                                            \
48       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
49       if (errStr_status == CUDA_SUCCESS)                                       \
50         REPORT("%s \n", errStr);                                               \
51     }                                                                          \
52   } while (false)
53 #else // OMPTARGET_DEBUG
54 #define CUDA_ERR_STRING(err)                                                   \
55   do {                                                                         \
56     const char *errStr = nullptr;                                              \
57     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
58     if (errStr_status == CUDA_SUCCESS)                                         \
59       REPORT("%s \n", errStr);                                                 \
60   } while (false)
61 #endif // OMPTARGET_DEBUG
62 
63 #include "elf_common.h"
64 
65 /// Keep entries table per device.
66 struct FuncOrGblEntryTy {
67   __tgt_target_table Table;
68   std::vector<__tgt_offload_entry> Entries;
69 };
70 
71 enum ExecutionModeType {
72   SPMD, // constructors, destructors,
73   // combined constructs (`teams distribute parallel for [simd]`)
74   GENERIC, // everything else
75   NONE
76 };
77 
78 /// Use a single entity to encode a kernel and a set of flags.
79 struct KernelTy {
80   CUfunction Func;
81 
82   // execution mode of kernel
83   // 0 - SPMD mode (without master warp)
84   // 1 - Generic mode (with master warp)
85   int8_t ExecutionMode;
86 
87   /// Maximal number of threads per block for this kernel.
88   int MaxThreadsPerBlock = 0;
89 
90   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
91       : Func(_Func), ExecutionMode(_ExecutionMode) {}
92 };
93 
94 /// Device environment data
95 /// Manually sync with the deviceRTL side for now, move to a dedicated header
96 /// file later.
97 struct omptarget_device_environmentTy {
98   int32_t debug_level;
99 };
100 
101 namespace {
102 bool checkResult(CUresult Err, const char *ErrMsg) {
103   if (Err == CUDA_SUCCESS)
104     return true;
105 
106   REPORT("%s", ErrMsg);
107   CUDA_ERR_STRING(Err);
108   return false;
109 }
110 
111 int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
112                CUstream Stream) {
113   CUresult Err = cuMemcpyDtoDAsync_v2((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr,
114                                       Size, Stream);
115 
116   if (Err != CUDA_SUCCESS) {
117     REPORT("Error when copying data from device to device. Pointers: src "
118            "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
119            DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
120     CUDA_ERR_STRING(Err);
121     return OFFLOAD_FAIL;
122   }
123 
124   return OFFLOAD_SUCCESS;
125 }
126 
127 // Structure contains per-device data
128 struct DeviceDataTy {
129   /// List that contains all the kernels.
130   std::list<KernelTy> KernelsList;
131 
132   std::list<FuncOrGblEntryTy> FuncGblEntries;
133 
134   CUcontext Context = nullptr;
135   // Device properties
136   int ThreadsPerBlock = 0;
137   int BlocksPerGrid = 0;
138   int WarpSize = 0;
139   // OpenMP properties
140   int NumTeams = 0;
141   int NumThreads = 0;
142 };
143 
144 class StreamManagerTy {
145   int NumberOfDevices;
146   // The initial size of stream pool
147   int EnvNumInitialStreams;
148   // Per-device stream mutex
149   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
150   // Per-device stream Id indicates the next available stream in the pool
151   std::vector<int> NextStreamId;
152   // Per-device stream pool
153   std::vector<std::vector<CUstream>> StreamPool;
154   // Reference to per-device data
155   std::vector<DeviceDataTy> &DeviceData;
156 
157   // If there is no CUstream left in the pool, we will resize the pool to
158   // allocate more CUstream. This function should be called with device mutex,
159   // and we do not resize to smaller one.
160   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
161     std::vector<CUstream> &Pool = StreamPool[DeviceId];
162     const size_t CurrentSize = Pool.size();
163     assert(NewSize > CurrentSize && "new size is not larger than current size");
164 
165     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
166     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
167       // We will return if cannot switch to the right context in case of
168       // creating bunch of streams that are not corresponding to the right
169       // device. The offloading will fail later because selected CUstream is
170       // nullptr.
171       return;
172     }
173 
174     Pool.resize(NewSize, nullptr);
175 
176     for (size_t I = CurrentSize; I < NewSize; ++I) {
177       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
178                   "Error returned from cuStreamCreate\n");
179     }
180   }
181 
182 public:
183   StreamManagerTy(const int NumberOfDevices,
184                   std::vector<DeviceDataTy> &DeviceData)
185       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
186         DeviceData(DeviceData) {
187     StreamPool.resize(NumberOfDevices);
188     NextStreamId.resize(NumberOfDevices);
189     StreamMtx.resize(NumberOfDevices);
190 
191     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
192       EnvNumInitialStreams = std::stoi(EnvStr);
193 
194     // Initialize the next stream id
195     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
196 
197     // Initialize stream mutex
198     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
199       Ptr = std::make_unique<std::mutex>();
200   }
201 
202   ~StreamManagerTy() {
203     // Destroy streams
204     for (int I = 0; I < NumberOfDevices; ++I) {
205       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
206                   "Error returned from cuCtxSetCurrent\n");
207 
208       for (CUstream &S : StreamPool[I]) {
209         if (S)
210           checkResult(cuStreamDestroy_v2(S),
211                       "Error returned from cuStreamDestroy_v2\n");
212       }
213     }
214   }
215 
216   // Get a CUstream from pool. Per-device next stream id always points to the
217   // next available CUstream. That means, CUstreams [0, id-1] have been
218   // assigned, and [id,] are still available. If there is no CUstream left, we
219   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
220   // the id will increase one.
221   // xxxxxs+++++++++
222   //      ^
223   //      id
224   // After assignment, the pool becomes the following and s is assigned.
225   // xxxxxs+++++++++
226   //       ^
227   //       id
228   CUstream getStream(const int DeviceId) {
229     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
230     int &Id = NextStreamId[DeviceId];
231     // No CUstream left in the pool, we need to request from CUDA RT
232     if (Id == StreamPool[DeviceId].size()) {
233       // By default we double the stream pool every time
234       resizeStreamPool(DeviceId, Id * 2);
235     }
236     return StreamPool[DeviceId][Id++];
237   }
238 
239   // Return a CUstream back to pool. As mentioned above, per-device next
240   // stream is always points to the next available CUstream, so when we return
241   // a CUstream, we need to first decrease the id, and then copy the CUstream
242   // back.
243   // It is worth noting that, the order of streams return might be different
244   // from that they're assigned, that saying, at some point, there might be
245   // two identical CUstreams.
246   // xxax+a+++++
247   //     ^
248   //     id
249   // However, it doesn't matter, because they're always on the two sides of
250   // id. The left one will in the end be overwritten by another CUstream.
251   // Therefore, after several execution, the order of pool might be different
252   // from its initial state.
253   void returnStream(const int DeviceId, CUstream Stream) {
254     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
255     int &Id = NextStreamId[DeviceId];
256     assert(Id > 0 && "Wrong stream ID");
257     StreamPool[DeviceId][--Id] = Stream;
258   }
259 
260   bool initializeDeviceStreamPool(const int DeviceId) {
261     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
262 
263     resizeStreamPool(DeviceId, EnvNumInitialStreams);
264 
265     // Check the size of stream pool
266     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
267       return false;
268 
269     // Check whether each stream is valid
270     for (CUstream &S : StreamPool[DeviceId])
271       if (!S)
272         return false;
273 
274     return true;
275   }
276 };
277 
278 class DeviceRTLTy {
279   int NumberOfDevices;
280   // OpenMP environment properties
281   int EnvNumTeams;
282   int EnvTeamLimit;
283   // OpenMP requires flags
284   int64_t RequiresFlags;
285 
286   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
287   static constexpr const int HardThreadLimit = 1024;
288   static constexpr const int DefaultNumTeams = 128;
289   static constexpr const int DefaultNumThreads = 128;
290 
291   std::unique_ptr<StreamManagerTy> StreamManager;
292   std::vector<DeviceDataTy> DeviceData;
293   std::vector<CUmodule> Modules;
294 
295   /// A class responsible for interacting with device native runtime library to
296   /// allocate and free memory.
297   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
298     const int DeviceId;
299     const std::vector<DeviceDataTy> &DeviceData;
300 
301   public:
302     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
303         : DeviceId(DeviceId), DeviceData(DeviceData) {}
304 
305     void *allocate(size_t Size, void *) override {
306       if (Size == 0)
307         return nullptr;
308 
309       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
310       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
311         return nullptr;
312 
313       CUdeviceptr DevicePtr;
314       Err = cuMemAlloc_v2(&DevicePtr, Size);
315       if (!checkResult(Err, "Error returned from cuMemAlloc_v2\n"))
316         return nullptr;
317 
318       return (void *)DevicePtr;
319     }
320 
321     int free(void *TgtPtr) override {
322       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
323       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
324         return OFFLOAD_FAIL;
325 
326       Err = cuMemFree_v2((CUdeviceptr)TgtPtr);
327       if (!checkResult(Err, "Error returned from cuMemFree_v2\n"))
328         return OFFLOAD_FAIL;
329 
330       return OFFLOAD_SUCCESS;
331     }
332   };
333 
334   /// A vector of device allocators
335   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
336 
337   /// A vector of memory managers. Since the memory manager is non-copyable and
338   // non-removable, we wrap them into std::unique_ptr.
339   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
340 
341   /// Whether use memory manager
342   bool UseMemoryManager = true;
343 
344   // Record entry point associated with device
345   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
346     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
347     E.Entries.push_back(entry);
348   }
349 
350   // Return a pointer to the entry associated with the pointer
351   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
352                                              const void *Addr) const {
353     for (const __tgt_offload_entry &Itr :
354          DeviceData[DeviceId].FuncGblEntries.back().Entries)
355       if (Itr.addr == Addr)
356         return &Itr;
357 
358     return nullptr;
359   }
360 
361   // Return the pointer to the target entries table
362   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
363     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
364 
365     if (E.Entries.empty())
366       return nullptr;
367 
368     // Update table info according to the entries and return the pointer
369     E.Table.EntriesBegin = E.Entries.data();
370     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
371 
372     return &E.Table;
373   }
374 
375   // Clear entries table for a device
376   void clearOffloadEntriesTable(const int DeviceId) {
377     DeviceData[DeviceId].FuncGblEntries.emplace_back();
378     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
379     E.Entries.clear();
380     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
381   }
382 
383   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
384     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
385 
386     if (!AsyncInfoPtr->Queue)
387       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
388 
389     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
390   }
391 
392 public:
393   // This class should not be copied
394   DeviceRTLTy(const DeviceRTLTy &) = delete;
395   DeviceRTLTy(DeviceRTLTy &&) = delete;
396 
397   DeviceRTLTy()
398       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
399         RequiresFlags(OMP_REQ_UNDEFINED) {
400 
401     DP("Start initializing CUDA\n");
402 
403     CUresult Err = cuInit(0);
404     if (!checkResult(Err, "Error returned from cuInit\n")) {
405       return;
406     }
407 
408     Err = cuDeviceGetCount(&NumberOfDevices);
409     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
410       return;
411 
412     if (NumberOfDevices == 0) {
413       DP("There are no devices supporting CUDA.\n");
414       return;
415     }
416 
417     DeviceData.resize(NumberOfDevices);
418 
419     // Get environment variables regarding teams
420     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
421       // OMP_TEAM_LIMIT has been set
422       EnvTeamLimit = std::stoi(EnvStr);
423       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
424     }
425     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
426       // OMP_NUM_TEAMS has been set
427       EnvNumTeams = std::stoi(EnvStr);
428       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
429     }
430 
431     StreamManager =
432         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
433 
434     for (int I = 0; I < NumberOfDevices; ++I)
435       DeviceAllocators.emplace_back(I, DeviceData);
436 
437     // Get the size threshold from environment variable
438     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
439     UseMemoryManager = Res.second;
440     size_t MemoryManagerThreshold = Res.first;
441 
442     if (UseMemoryManager)
443       for (int I = 0; I < NumberOfDevices; ++I)
444         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
445             DeviceAllocators[I], MemoryManagerThreshold));
446   }
447 
448   ~DeviceRTLTy() {
449     // We first destruct memory managers in case that its dependent data are
450     // destroyed before it.
451     for (auto &M : MemoryManagers)
452       M.release();
453 
454     StreamManager = nullptr;
455 
456     for (CUmodule &M : Modules)
457       // Close module
458       if (M)
459         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
460 
461     for (DeviceDataTy &D : DeviceData) {
462       // Destroy context
463       if (D.Context) {
464         checkResult(cuCtxSetCurrent(D.Context),
465                     "Error returned from cuCtxSetCurrent\n");
466         CUdevice Device;
467         checkResult(cuCtxGetDevice(&Device),
468                     "Error returned from cuCtxGetDevice\n");
469         checkResult(cuDevicePrimaryCtxRelease_v2(Device),
470                     "Error returned from cuDevicePrimaryCtxRelease_v2\n");
471       }
472     }
473   }
474 
475   // Check whether a given DeviceId is valid
476   bool isValidDeviceId(const int DeviceId) const {
477     return DeviceId >= 0 && DeviceId < NumberOfDevices;
478   }
479 
480   int getNumOfDevices() const { return NumberOfDevices; }
481 
482   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
483 
484   int initDevice(const int DeviceId) {
485     CUdevice Device;
486 
487     DP("Getting device %d\n", DeviceId);
488     CUresult Err = cuDeviceGet(&Device, DeviceId);
489     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
490       return OFFLOAD_FAIL;
491 
492     // Query the current flags of the primary context and set its flags if
493     // it is inactive
494     unsigned int FormerPrimaryCtxFlags = 0;
495     int FormerPrimaryCtxIsActive = 0;
496     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
497                                      &FormerPrimaryCtxIsActive);
498     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
499       return OFFLOAD_FAIL;
500 
501     if (FormerPrimaryCtxIsActive) {
502       DP("The primary context is active, no change to its flags\n");
503       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
504           CU_CTX_SCHED_BLOCKING_SYNC)
505         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
506     } else {
507       DP("The primary context is inactive, set its flags to "
508          "CU_CTX_SCHED_BLOCKING_SYNC\n");
509       Err = cuDevicePrimaryCtxSetFlags_v2(Device, CU_CTX_SCHED_BLOCKING_SYNC);
510       if (!checkResult(Err,
511                        "Error returned from cuDevicePrimaryCtxSetFlags_v2\n"))
512         return OFFLOAD_FAIL;
513     }
514 
515     // Retain the per device primary context and save it to use whenever this
516     // device is selected.
517     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
518     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
519       return OFFLOAD_FAIL;
520 
521     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
522     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
523       return OFFLOAD_FAIL;
524 
525     // Initialize stream pool
526     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
527       return OFFLOAD_FAIL;
528 
529     // Query attributes to determine number of threads/block and blocks/grid.
530     int MaxGridDimX;
531     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
532                                Device);
533     if (Err != CUDA_SUCCESS) {
534       DP("Error getting max grid dimension, use default value %d\n",
535          DeviceRTLTy::DefaultNumTeams);
536       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
537     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
538       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
539       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
540     } else {
541       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
542          "at the hard limit\n",
543          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
544       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
545     }
546 
547     // We are only exploiting threads along the x axis.
548     int MaxBlockDimX;
549     Err = cuDeviceGetAttribute(&MaxBlockDimX,
550                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
551     if (Err != CUDA_SUCCESS) {
552       DP("Error getting max block dimension, use default value %d\n",
553          DeviceRTLTy::DefaultNumThreads);
554       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
555     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
556       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
557       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
558     } else {
559       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
560          "capping at the hard limit\n",
561          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
562       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
563     }
564 
565     // Get and set warp size
566     int WarpSize;
567     Err =
568         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
569     if (Err != CUDA_SUCCESS) {
570       DP("Error getting warp size, assume default value 32\n");
571       DeviceData[DeviceId].WarpSize = 32;
572     } else {
573       DP("Using warp size %d\n", WarpSize);
574       DeviceData[DeviceId].WarpSize = WarpSize;
575     }
576 
577     // Adjust teams to the env variables
578     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
579       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
580          EnvTeamLimit);
581       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
582     }
583 
584     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
585          "Device supports up to %d CUDA blocks and %d threads with a "
586          "warp size of %d\n",
587          DeviceData[DeviceId].BlocksPerGrid,
588          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
589 
590     // Set default number of teams
591     if (EnvNumTeams > 0) {
592       DP("Default number of teams set according to environment %d\n",
593          EnvNumTeams);
594       DeviceData[DeviceId].NumTeams = EnvNumTeams;
595     } else {
596       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
597       DP("Default number of teams set according to library's default %d\n",
598          DeviceRTLTy::DefaultNumTeams);
599     }
600 
601     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
602       DP("Default number of teams exceeds device limit, capping at %d\n",
603          DeviceData[DeviceId].BlocksPerGrid);
604       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
605     }
606 
607     // Set default number of threads
608     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
609     DP("Default number of threads set according to library's default %d\n",
610        DeviceRTLTy::DefaultNumThreads);
611     if (DeviceData[DeviceId].NumThreads >
612         DeviceData[DeviceId].ThreadsPerBlock) {
613       DP("Default number of threads exceeds device limit, capping at %d\n",
614          DeviceData[DeviceId].ThreadsPerBlock);
615       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
616     }
617 
618     return OFFLOAD_SUCCESS;
619   }
620 
621   __tgt_target_table *loadBinary(const int DeviceId,
622                                  const __tgt_device_image *Image) {
623     // Set the context we are using
624     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
625     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
626       return nullptr;
627 
628     // Clear the offload table as we are going to create a new one.
629     clearOffloadEntriesTable(DeviceId);
630 
631     // Create the module and extract the function pointers.
632     CUmodule Module;
633     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
634     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
635     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
636       return nullptr;
637 
638     DP("CUDA module successfully loaded!\n");
639 
640     Modules.push_back(Module);
641 
642     // Find the symbols in the module by name.
643     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
644     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
645 
646     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
647     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
648       if (!E->addr) {
649         // We return nullptr when something like this happens, the host should
650         // have always something in the address to uniquely identify the target
651         // region.
652         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
653         return nullptr;
654       }
655 
656       if (E->size) {
657         __tgt_offload_entry Entry = *E;
658         CUdeviceptr CUPtr;
659         size_t CUSize;
660         Err = cuModuleGetGlobal_v2(&CUPtr, &CUSize, Module, E->name);
661         // We keep this style here because we need the name
662         if (Err != CUDA_SUCCESS) {
663           REPORT("Loading global '%s' Failed\n", E->name);
664           CUDA_ERR_STRING(Err);
665           return nullptr;
666         }
667 
668         if (CUSize != E->size) {
669           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
670              CUSize, E->size);
671           return nullptr;
672         }
673 
674         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
675            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
676 
677         Entry.addr = (void *)(CUPtr);
678 
679         // Note: In the current implementation declare target variables
680         // can either be link or to. This means that once unified
681         // memory is activated via the requires directive, the variable
682         // can be used directly from the host in both cases.
683         // TODO: when variables types other than to or link are added,
684         // the below condition should be changed to explicitly
685         // check for to and link variables types:
686         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
687         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
688         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
689           // If unified memory is present any target link or to variables
690           // can access host addresses directly. There is no longer a
691           // need for device copies.
692           cuMemcpyHtoD_v2(CUPtr, E->addr, sizeof(void *));
693           DP("Copy linked variable host address (" DPxMOD
694              ") to device address (" DPxMOD ")\n",
695              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
696         }
697 
698         addOffloadEntry(DeviceId, Entry);
699 
700         continue;
701       }
702 
703       CUfunction Func;
704       Err = cuModuleGetFunction(&Func, Module, E->name);
705       // We keep this style here because we need the name
706       if (Err != CUDA_SUCCESS) {
707         REPORT("Loading '%s' Failed\n", E->name);
708         CUDA_ERR_STRING(Err);
709         return nullptr;
710       }
711 
712       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
713          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
714 
715       // default value GENERIC (in case symbol is missing from cubin file)
716       int8_t ExecModeVal = ExecutionModeType::GENERIC;
717       std::string ExecModeNameStr(E->name);
718       ExecModeNameStr += "_exec_mode";
719       const char *ExecModeName = ExecModeNameStr.c_str();
720 
721       CUdeviceptr ExecModePtr;
722       size_t CUSize;
723       Err = cuModuleGetGlobal_v2(&ExecModePtr, &CUSize, Module, ExecModeName);
724       if (Err == CUDA_SUCCESS) {
725         if (CUSize != sizeof(int8_t)) {
726           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
727              ExecModeName, CUSize, sizeof(int8_t));
728           return nullptr;
729         }
730 
731         Err = cuMemcpyDtoH_v2(&ExecModeVal, ExecModePtr, CUSize);
732         if (Err != CUDA_SUCCESS) {
733           REPORT("Error when copying data from device to host. Pointers: "
734                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
735                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
736           CUDA_ERR_STRING(Err);
737           return nullptr;
738         }
739 
740         if (ExecModeVal < 0 || ExecModeVal > 1) {
741           DP("Error wrong exec_mode value specified in cubin file: %d\n",
742              ExecModeVal);
743           return nullptr;
744         }
745       } else {
746         REPORT("Loading global exec_mode '%s' - symbol missing, using default "
747                "value GENERIC (1)\n",
748                ExecModeName);
749         CUDA_ERR_STRING(Err);
750       }
751 
752       KernelsList.emplace_back(Func, ExecModeVal);
753 
754       __tgt_offload_entry Entry = *E;
755       Entry.addr = &KernelsList.back();
756       addOffloadEntry(DeviceId, Entry);
757     }
758 
759     // send device environment data to the device
760     {
761       omptarget_device_environmentTy DeviceEnv{0};
762 
763 #ifdef OMPTARGET_DEBUG
764       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
765         DeviceEnv.debug_level = std::stoi(EnvStr);
766 #endif
767 
768       const char *DeviceEnvName = "omptarget_device_environment";
769       CUdeviceptr DeviceEnvPtr;
770       size_t CUSize;
771 
772       Err = cuModuleGetGlobal_v2(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
773       if (Err == CUDA_SUCCESS) {
774         if (CUSize != sizeof(DeviceEnv)) {
775           REPORT(
776               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
777               DeviceEnvName, CUSize, sizeof(int32_t));
778           CUDA_ERR_STRING(Err);
779           return nullptr;
780         }
781 
782         Err = cuMemcpyHtoD_v2(DeviceEnvPtr, &DeviceEnv, CUSize);
783         if (Err != CUDA_SUCCESS) {
784           REPORT("Error when copying data from host to device. Pointers: "
785                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
786                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
787           CUDA_ERR_STRING(Err);
788           return nullptr;
789         }
790 
791         DP("Sending global device environment data %zu bytes\n", CUSize);
792       } else {
793         DP("Finding global device environment '%s' - symbol missing.\n",
794            DeviceEnvName);
795         DP("Continue, considering this is a device RTL which does not accept "
796            "environment setting.\n");
797       }
798     }
799 
800     return getOffloadEntriesTable(DeviceId);
801   }
802 
803   void *dataAlloc(const int DeviceId, const int64_t Size) {
804     if (UseMemoryManager)
805       return MemoryManagers[DeviceId]->allocate(Size, nullptr);
806 
807     return DeviceAllocators[DeviceId].allocate(Size, nullptr);
808   }
809 
810   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
811                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
812     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
813 
814     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
815     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
816       return OFFLOAD_FAIL;
817 
818     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
819 
820     Err = cuMemcpyHtoDAsync_v2((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
821     if (Err != CUDA_SUCCESS) {
822       REPORT("Error when copying data from host to device. Pointers: host "
823              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
824              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
825       CUDA_ERR_STRING(Err);
826       return OFFLOAD_FAIL;
827     }
828 
829     return OFFLOAD_SUCCESS;
830   }
831 
832   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
833                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
834     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
835 
836     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
837     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
838       return OFFLOAD_FAIL;
839 
840     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
841 
842     Err = cuMemcpyDtoHAsync_v2(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
843     if (Err != CUDA_SUCCESS) {
844       REPORT("Error when copying data from device to host. Pointers: host "
845              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
846              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
847       CUDA_ERR_STRING(Err);
848       return OFFLOAD_FAIL;
849     }
850 
851     return OFFLOAD_SUCCESS;
852   }
853 
854   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
855                    int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
856     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
857 
858     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
859     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
860       return OFFLOAD_FAIL;
861 
862     CUstream Stream = getStream(SrcDevId, AsyncInfoPtr);
863 
864     // If they are two devices, we try peer to peer copy first
865     if (SrcDevId != DstDevId) {
866       int CanAccessPeer = 0;
867       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
868       if (Err != CUDA_SUCCESS) {
869         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
870                ", dst = %" PRId32 "\n",
871                SrcDevId, DstDevId);
872         CUDA_ERR_STRING(Err);
873         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
874       }
875 
876       if (!CanAccessPeer) {
877         DP("P2P memcpy not supported so fall back to D2D memcpy");
878         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
879       }
880 
881       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
882       if (Err != CUDA_SUCCESS) {
883         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
884                ", dst = %" PRId32 "\n",
885                SrcDevId, DstDevId);
886         CUDA_ERR_STRING(Err);
887         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
888       }
889 
890       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
891                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
892                               Size, Stream);
893       if (Err == CUDA_SUCCESS)
894         return OFFLOAD_SUCCESS;
895 
896       REPORT("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
897              ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32
898              "\n",
899              DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
900       CUDA_ERR_STRING(Err);
901     }
902 
903     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
904   }
905 
906   int dataDelete(const int DeviceId, void *TgtPtr) {
907     if (UseMemoryManager)
908       return MemoryManagers[DeviceId]->free(TgtPtr);
909 
910     return DeviceAllocators[DeviceId].free(TgtPtr);
911   }
912 
913   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
914                           ptrdiff_t *TgtOffsets, const int ArgNum,
915                           const int TeamNum, const int ThreadLimit,
916                           const unsigned int LoopTripCount,
917                           __tgt_async_info *AsyncInfo) const {
918     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
919     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
920       return OFFLOAD_FAIL;
921 
922     // All args are references.
923     std::vector<void *> Args(ArgNum);
924     std::vector<void *> Ptrs(ArgNum);
925 
926     for (int I = 0; I < ArgNum; ++I) {
927       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
928       Args[I] = &Ptrs[I];
929     }
930 
931     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
932 
933     int CudaThreadsPerBlock;
934     if (ThreadLimit > 0) {
935       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
936       CudaThreadsPerBlock = ThreadLimit;
937       // Add master warp if necessary
938       if (KernelInfo->ExecutionMode == GENERIC) {
939         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
940         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
941       }
942     } else {
943       DP("Setting CUDA threads per block to default %d\n",
944          DeviceData[DeviceId].NumThreads);
945       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
946     }
947 
948     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
949       DP("Threads per block capped at device limit %d\n",
950          DeviceData[DeviceId].ThreadsPerBlock);
951       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
952     }
953 
954     if (!KernelInfo->MaxThreadsPerBlock) {
955       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
956                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
957                                KernelInfo->Func);
958       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
959         return OFFLOAD_FAIL;
960     }
961 
962     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
963       DP("Threads per block capped at kernel limit %d\n",
964          KernelInfo->MaxThreadsPerBlock);
965       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
966     }
967 
968     unsigned int CudaBlocksPerGrid;
969     if (TeamNum <= 0) {
970       if (LoopTripCount > 0 && EnvNumTeams < 0) {
971         if (KernelInfo->ExecutionMode == SPMD) {
972           // We have a combined construct, i.e. `target teams distribute
973           // parallel for [simd]`. We launch so many teams so that each thread
974           // will execute one iteration of the loop. round up to the nearest
975           // integer
976           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
977         } else {
978           // If we reach this point, then we have a non-combined construct, i.e.
979           // `teams distribute` with a nested `parallel for` and each team is
980           // assigned one iteration of the `distribute` loop. E.g.:
981           //
982           // #pragma omp target teams distribute
983           // for(...loop_tripcount...) {
984           //   #pragma omp parallel for
985           //   for(...) {}
986           // }
987           //
988           // Threads within a team will execute the iterations of the `parallel`
989           // loop.
990           CudaBlocksPerGrid = LoopTripCount;
991         }
992         DP("Using %d teams due to loop trip count %" PRIu32
993            " and number of threads per block %d\n",
994            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
995       } else {
996         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
997         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
998       }
999     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
1000       DP("Capping number of teams to team limit %d\n",
1001          DeviceData[DeviceId].BlocksPerGrid);
1002       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
1003     } else {
1004       DP("Using requested number of teams %d\n", TeamNum);
1005       CudaBlocksPerGrid = TeamNum;
1006     }
1007 
1008     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1009          "Launching kernel %s with %d blocks and %d threads in %s "
1010          "mode\n",
1011          (getOffloadEntry(DeviceId, TgtEntryPtr))
1012              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1013              : "(null)",
1014          CudaBlocksPerGrid, CudaThreadsPerBlock,
1015          (KernelInfo->ExecutionMode == SPMD) ? "SPMD" : "Generic");
1016 
1017     CUstream Stream = getStream(DeviceId, AsyncInfo);
1018     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
1019                          /* gridDimZ */ 1, CudaThreadsPerBlock,
1020                          /* blockDimY */ 1, /* blockDimZ */ 1,
1021                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
1022     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
1023       return OFFLOAD_FAIL;
1024 
1025     DP("Launch of entry point at " DPxMOD " successful!\n",
1026        DPxPTR(TgtEntryPtr));
1027 
1028     return OFFLOAD_SUCCESS;
1029   }
1030 
1031   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
1032     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
1033     CUresult Err = cuStreamSynchronize(Stream);
1034     if (Err != CUDA_SUCCESS) {
1035       REPORT("Error when synchronizing stream. stream = " DPxMOD
1036              ", async info ptr = " DPxMOD "\n",
1037              DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
1038       CUDA_ERR_STRING(Err);
1039       return OFFLOAD_FAIL;
1040     }
1041 
1042     // Once the stream is synchronized, return it to stream pool and reset
1043     // async_info. This is to make sure the synchronization only works for its
1044     // own tasks.
1045     StreamManager->returnStream(
1046         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
1047     AsyncInfoPtr->Queue = nullptr;
1048 
1049     return OFFLOAD_SUCCESS;
1050   }
1051 };
1052 
1053 DeviceRTLTy DeviceRTL;
1054 } // namespace
1055 
1056 // Exposed library API function
1057 #ifdef __cplusplus
1058 extern "C" {
1059 #endif
1060 
1061 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
1062   return elf_check_machine(image, /* EM_CUDA */ 190);
1063 }
1064 
1065 int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
1066 
1067 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
1068   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
1069   DeviceRTL.setRequiresFlag(RequiresFlags);
1070   return RequiresFlags;
1071 }
1072 
1073 int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1074   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1075       DeviceRTL.isValidDeviceId(dst_dev_id))
1076     return 1;
1077 
1078   return 0;
1079 }
1080 
1081 int32_t __tgt_rtl_init_device(int32_t device_id) {
1082   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1083 
1084   return DeviceRTL.initDevice(device_id);
1085 }
1086 
1087 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
1088                                           __tgt_device_image *image) {
1089   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1090 
1091   return DeviceRTL.loadBinary(device_id, image);
1092 }
1093 
1094 void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
1095   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1096 
1097   return DeviceRTL.dataAlloc(device_id, size);
1098 }
1099 
1100 int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
1101                               int64_t size) {
1102   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1103 
1104   __tgt_async_info async_info;
1105   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
1106                                                  size, &async_info);
1107   if (rc != OFFLOAD_SUCCESS)
1108     return OFFLOAD_FAIL;
1109 
1110   return __tgt_rtl_synchronize(device_id, &async_info);
1111 }
1112 
1113 int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
1114                                     void *hst_ptr, int64_t size,
1115                                     __tgt_async_info *async_info_ptr) {
1116   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1117   assert(async_info_ptr && "async_info_ptr is nullptr");
1118 
1119   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
1120                               async_info_ptr);
1121 }
1122 
1123 int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
1124                                 int64_t size) {
1125   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1126 
1127   __tgt_async_info async_info;
1128   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
1129                                                    size, &async_info);
1130   if (rc != OFFLOAD_SUCCESS)
1131     return OFFLOAD_FAIL;
1132 
1133   return __tgt_rtl_synchronize(device_id, &async_info);
1134 }
1135 
1136 int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
1137                                       void *tgt_ptr, int64_t size,
1138                                       __tgt_async_info *async_info_ptr) {
1139   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1140   assert(async_info_ptr && "async_info_ptr is nullptr");
1141 
1142   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
1143                                 async_info_ptr);
1144 }
1145 
1146 int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1147                                       int dst_dev_id, void *dst_ptr,
1148                                       int64_t size,
1149                                       __tgt_async_info *async_info_ptr) {
1150   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1151   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1152   assert(async_info_ptr && "async_info_ptr is nullptr");
1153 
1154   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1155                                 async_info_ptr);
1156 }
1157 
1158 int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1159                                 int32_t dst_dev_id, void *dst_ptr,
1160                                 int64_t size) {
1161   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1162   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1163 
1164   __tgt_async_info async_info;
1165   const int32_t rc = __tgt_rtl_data_exchange_async(
1166       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &async_info);
1167   if (rc != OFFLOAD_SUCCESS)
1168     return OFFLOAD_FAIL;
1169 
1170   return __tgt_rtl_synchronize(src_dev_id, &async_info);
1171 }
1172 
1173 int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
1174   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1175 
1176   return DeviceRTL.dataDelete(device_id, tgt_ptr);
1177 }
1178 
1179 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
1180                                          void **tgt_args,
1181                                          ptrdiff_t *tgt_offsets,
1182                                          int32_t arg_num, int32_t team_num,
1183                                          int32_t thread_limit,
1184                                          uint64_t loop_tripcount) {
1185   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1186 
1187   __tgt_async_info async_info;
1188   const int32_t rc = __tgt_rtl_run_target_team_region_async(
1189       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1190       thread_limit, loop_tripcount, &async_info);
1191   if (rc != OFFLOAD_SUCCESS)
1192     return OFFLOAD_FAIL;
1193 
1194   return __tgt_rtl_synchronize(device_id, &async_info);
1195 }
1196 
1197 int32_t __tgt_rtl_run_target_team_region_async(
1198     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
1199     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
1200     int32_t thread_limit, uint64_t loop_tripcount,
1201     __tgt_async_info *async_info_ptr) {
1202   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1203 
1204   return DeviceRTL.runTargetTeamRegion(
1205       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
1206       thread_limit, loop_tripcount, async_info_ptr);
1207 }
1208 
1209 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
1210                                     void **tgt_args, ptrdiff_t *tgt_offsets,
1211                                     int32_t arg_num) {
1212   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1213 
1214   __tgt_async_info async_info;
1215   const int32_t rc = __tgt_rtl_run_target_region_async(
1216       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
1217   if (rc != OFFLOAD_SUCCESS)
1218     return OFFLOAD_FAIL;
1219 
1220   return __tgt_rtl_synchronize(device_id, &async_info);
1221 }
1222 
1223 int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
1224                                           void *tgt_entry_ptr, void **tgt_args,
1225                                           ptrdiff_t *tgt_offsets,
1226                                           int32_t arg_num,
1227                                           __tgt_async_info *async_info_ptr) {
1228   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1229 
1230   return __tgt_rtl_run_target_team_region_async(
1231       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
1232       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1233       async_info_ptr);
1234 }
1235 
1236 int32_t __tgt_rtl_synchronize(int32_t device_id,
1237                               __tgt_async_info *async_info_ptr) {
1238   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1239   assert(async_info_ptr && "async_info_ptr is nullptr");
1240   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
1241 
1242   return DeviceRTL.synchronize(device_id, async_info_ptr);
1243 }
1244 
1245 #ifdef __cplusplus
1246 }
1247 #endif
1248