13de4cd12SGeorge Rokos //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===//
23de4cd12SGeorge Rokos //
357b08b09SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
457b08b09SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
557b08b09SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
63de4cd12SGeorge Rokos //
73de4cd12SGeorge Rokos //===----------------------------------------------------------------------===//
83de4cd12SGeorge Rokos //
93de4cd12SGeorge Rokos // RTL for CUDA machine
103de4cd12SGeorge Rokos //
113de4cd12SGeorge Rokos //===----------------------------------------------------------------------===//
123de4cd12SGeorge Rokos 
133de4cd12SGeorge Rokos #include <cassert>
143de4cd12SGeorge Rokos #include <cstddef>
153de4cd12SGeorge Rokos #include <cuda.h>
163de4cd12SGeorge Rokos #include <list>
17a5153dbcSJohannes Doerfert #include <memory>
18feed674dSShilei Tian #include <mutex>
193de4cd12SGeorge Rokos #include <string>
20a15f8589SJoseph Huber #include <unordered_map>
213de4cd12SGeorge Rokos #include <vector>
223de4cd12SGeorge Rokos 
23ae95ceebSJoseph Huber #include "Debug.h"
241546d319SGeorge Rokos #include "omptargetplugin.h"
253de4cd12SGeorge Rokos 
263de4cd12SGeorge Rokos #define TARGET_NAME CUDA
27ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
2878769ec4SMichael Kruse 
290871d6d5SShilei Tian #include "MemoryManager.h"
300871d6d5SShilei Tian 
3178769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
32ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3378769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3478769ec4SMichael Kruse   do {                                                                         \
35ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                 \
3603111e5eSYe Luo       const char *errStr = nullptr;                                            \
3703111e5eSYe Luo       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
3803111e5eSYe Luo       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
392ce16810SJoseph Huber         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
4003111e5eSYe Luo       else if (errStr_status == CUDA_SUCCESS)                                  \
412ce16810SJoseph Huber         REPORT("CUDA error is: %s\n", errStr);                                 \
4203111e5eSYe Luo       else {                                                                   \
432ce16810SJoseph Huber         REPORT("Unresolved CUDA error code: %d\n", err);                       \
442ce16810SJoseph Huber         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
4503111e5eSYe Luo                errStr_status);                                                 \
4603111e5eSYe Luo       }                                                                        \
472ce16810SJoseph Huber     } else {                                                                   \
482ce16810SJoseph Huber       const char *errStr = nullptr;                                            \
492ce16810SJoseph Huber       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
502ce16810SJoseph Huber       if (errStr_status == CUDA_SUCCESS)                                       \
512ce16810SJoseph Huber         REPORT("%s \n", errStr);                                               \
5278769ec4SMichael Kruse     }                                                                          \
5378769ec4SMichael Kruse   } while (false)
54b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
552ce16810SJoseph Huber #define CUDA_ERR_STRING(err)                                                   \
562ce16810SJoseph Huber   do {                                                                         \
572ce16810SJoseph Huber     const char *errStr = nullptr;                                              \
582ce16810SJoseph Huber     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
592ce16810SJoseph Huber     if (errStr_status == CUDA_SUCCESS)                                         \
602ce16810SJoseph Huber       REPORT("%s \n", errStr);                                                 \
612ce16810SJoseph Huber   } while (false)
62b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
633de4cd12SGeorge Rokos 
64d2f85d09SJose M Monsalve Diaz #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
65d2f85d09SJose M Monsalve Diaz 
66a81c68aeSShilei Tian #include "elf_common.h"
673de4cd12SGeorge Rokos 
683de4cd12SGeorge Rokos /// Keep entries table per device.
693de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
703de4cd12SGeorge Rokos   __tgt_target_table Table;
713de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
723de4cd12SGeorge Rokos };
733de4cd12SGeorge Rokos 
743de4cd12SGeorge Rokos enum ExecutionModeType {
75c13df8e5SGeorge Rokos   SPMD,         // constructors, destructors,
76c13df8e5SGeorge Rokos                 // combined constructs (`teams distribute parallel for [simd]`)
77c13df8e5SGeorge Rokos   GENERIC,      // everything else
787d576392SJoseph Huber   SPMD_GENERIC, // Generic kernel with SPMD execution
793de4cd12SGeorge Rokos   NONE
803de4cd12SGeorge Rokos };
813de4cd12SGeorge Rokos 
82dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
833de4cd12SGeorge Rokos struct KernelTy {
843de4cd12SGeorge Rokos   CUfunction Func;
853de4cd12SGeorge Rokos 
863de4cd12SGeorge Rokos   // execution mode of kernel
873de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
883de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
897d576392SJoseph Huber   // 2 - SPMD mode execution with Generic mode semantics.
903de4cd12SGeorge Rokos   int8_t ExecutionMode;
913de4cd12SGeorge Rokos 
92aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
93aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
94aa27cfc1SJohannes Doerfert 
953de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
963de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
973de4cd12SGeorge Rokos };
983de4cd12SGeorge Rokos 
994c6a098aSKazuaki Ishizaki /// Device environment data
100feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
101feed674dSShilei Tian /// file later.
102e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
103e1c7a46dSGuansong Zhang   int32_t debug_level;
104*ec02c34bSJoseph Huber   uint32_t num_devices;
105*ec02c34bSJoseph Huber   uint32_t device_num;
106e1c7a46dSGuansong Zhang };
107e1c7a46dSGuansong Zhang 
108feed674dSShilei Tian namespace {
109feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
110feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
111feed674dSShilei Tian     return true;
112feed674dSShilei Tian 
1132ce16810SJoseph Huber   REPORT("%s", ErrMsg);
114feed674dSShilei Tian   CUDA_ERR_STRING(Err);
115feed674dSShilei Tian   return false;
116feed674dSShilei Tian }
1174031bb98SShilei Tian 
118a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
119a014fbbcSShilei Tian                CUstream Stream) {
12095f0d1edSJon Chesterfield   CUresult Err =
12195f0d1edSJon Chesterfield       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
122a014fbbcSShilei Tian 
123a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
12429338459SJoseph Huber     DP("Error when copying data from device to device. Pointers: src "
125a014fbbcSShilei Tian        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
126a014fbbcSShilei Tian        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
127a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
128a014fbbcSShilei Tian     return OFFLOAD_FAIL;
129a014fbbcSShilei Tian   }
130a014fbbcSShilei Tian 
131a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
132a014fbbcSShilei Tian }
133a014fbbcSShilei Tian 
13429df4ab3SShilei Tian int createEvent(void **P) {
13529df4ab3SShilei Tian   CUevent Event = nullptr;
13629df4ab3SShilei Tian 
13729df4ab3SShilei Tian   CUresult Err = cuEventCreate(&Event, CU_EVENT_DEFAULT);
13829df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
13929df4ab3SShilei Tian     DP("Error when creating event event = " DPxMOD "\n", DPxPTR(Event));
14029df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
14129df4ab3SShilei Tian     return OFFLOAD_FAIL;
14229df4ab3SShilei Tian   }
14329df4ab3SShilei Tian 
14429df4ab3SShilei Tian   *P = Event;
14529df4ab3SShilei Tian 
14629df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
14729df4ab3SShilei Tian }
14829df4ab3SShilei Tian 
14929df4ab3SShilei Tian int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) {
15029df4ab3SShilei Tian   CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
15129df4ab3SShilei Tian   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
15229df4ab3SShilei Tian 
15329df4ab3SShilei Tian   CUresult Err = cuEventRecord(Event, Stream);
15429df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
15529df4ab3SShilei Tian     DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n",
15629df4ab3SShilei Tian        DPxPTR(Stream), DPxPTR(Event));
15729df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
15829df4ab3SShilei Tian     return OFFLOAD_FAIL;
15929df4ab3SShilei Tian   }
16029df4ab3SShilei Tian 
16129df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
16229df4ab3SShilei Tian }
16329df4ab3SShilei Tian 
16429df4ab3SShilei Tian int syncEvent(void *EventPtr) {
16529df4ab3SShilei Tian   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
16629df4ab3SShilei Tian 
16729df4ab3SShilei Tian   CUresult Err = cuEventSynchronize(Event);
16829df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
16929df4ab3SShilei Tian     DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event));
17029df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
17129df4ab3SShilei Tian     return OFFLOAD_FAIL;
17229df4ab3SShilei Tian   }
17329df4ab3SShilei Tian 
17429df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
17529df4ab3SShilei Tian }
17629df4ab3SShilei Tian 
17729df4ab3SShilei Tian int destroyEvent(void *EventPtr) {
17829df4ab3SShilei Tian   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
17929df4ab3SShilei Tian 
18029df4ab3SShilei Tian   CUresult Err = cuEventDestroy(Event);
18129df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
18229df4ab3SShilei Tian     DP("Error when destroying event = " DPxMOD "\n", DPxPTR(Event));
18329df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
18429df4ab3SShilei Tian     return OFFLOAD_FAIL;
18529df4ab3SShilei Tian   }
18629df4ab3SShilei Tian 
18729df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
18829df4ab3SShilei Tian }
18929df4ab3SShilei Tian 
1904031bb98SShilei Tian // Structure contains per-device data
1914031bb98SShilei Tian struct DeviceDataTy {
1925272d29eSJohannes Doerfert   /// List that contains all the kernels.
1935272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1945272d29eSJohannes Doerfert 
1954031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1965272d29eSJohannes Doerfert 
1974031bb98SShilei Tian   CUcontext Context = nullptr;
1984031bb98SShilei Tian   // Device properties
1994031bb98SShilei Tian   int ThreadsPerBlock = 0;
2004031bb98SShilei Tian   int BlocksPerGrid = 0;
2014031bb98SShilei Tian   int WarpSize = 0;
2024031bb98SShilei Tian   // OpenMP properties
2034031bb98SShilei Tian   int NumTeams = 0;
2044031bb98SShilei Tian   int NumThreads = 0;
2054031bb98SShilei Tian };
206feed674dSShilei Tian 
207feed674dSShilei Tian class StreamManagerTy {
208feed674dSShilei Tian   int NumberOfDevices;
2094031bb98SShilei Tian   // The initial size of stream pool
2104031bb98SShilei Tian   int EnvNumInitialStreams;
211feed674dSShilei Tian   // Per-device stream mutex
212feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
213feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
214feed674dSShilei Tian   std::vector<int> NextStreamId;
215feed674dSShilei Tian   // Per-device stream pool
216feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
2174031bb98SShilei Tian   // Reference to per-device data
2184031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
219feed674dSShilei Tian 
220feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
221feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
222feed674dSShilei Tian   // and we do not resize to smaller one.
223feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
224feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
225feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
226feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
227feed674dSShilei Tian 
2284031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
2294031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
230feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
231feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
232feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
233feed674dSShilei Tian       // nullptr.
234feed674dSShilei Tian       return;
235feed674dSShilei Tian     }
236feed674dSShilei Tian 
2374031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
2384031bb98SShilei Tian 
239feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
2404031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
2414031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
242feed674dSShilei Tian     }
243feed674dSShilei Tian   }
244feed674dSShilei Tian 
245feed674dSShilei Tian public:
2464031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
2474031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
2484031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
2494031bb98SShilei Tian         DeviceData(DeviceData) {
250feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
251feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
252feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
253feed674dSShilei Tian 
2544031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
2554031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
256feed674dSShilei Tian 
257feed674dSShilei Tian     // Initialize the next stream id
258feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
259feed674dSShilei Tian 
260feed674dSShilei Tian     // Initialize stream mutex
261feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
262feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
263feed674dSShilei Tian   }
264feed674dSShilei Tian 
265feed674dSShilei Tian   ~StreamManagerTy() {
266feed674dSShilei Tian     // Destroy streams
267feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
2684031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
2694031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
270feed674dSShilei Tian 
271feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
2724031bb98SShilei Tian         if (S)
27395f0d1edSJon Chesterfield           checkResult(cuStreamDestroy(S),
27495f0d1edSJon Chesterfield                       "Error returned from cuStreamDestroy\n");
275feed674dSShilei Tian       }
276feed674dSShilei Tian     }
277feed674dSShilei Tian   }
278feed674dSShilei Tian 
279feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
280feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
281feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
282feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
283feed674dSShilei Tian   // the id will increase one.
284feed674dSShilei Tian   // xxxxxs+++++++++
285feed674dSShilei Tian   //      ^
286feed674dSShilei Tian   //      id
287feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
288feed674dSShilei Tian   // xxxxxs+++++++++
289feed674dSShilei Tian   //       ^
290feed674dSShilei Tian   //       id
291feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
292feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
293feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
294feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
295ad94fce8SJohannes Doerfert     if (Id == static_cast<int>(StreamPool[DeviceId].size())) {
296feed674dSShilei Tian       // By default we double the stream pool every time
297feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
298feed674dSShilei Tian     }
299feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
300feed674dSShilei Tian   }
301feed674dSShilei Tian 
302feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
303feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
304feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
305feed674dSShilei Tian   // back.
306feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
307feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
308feed674dSShilei Tian   // two identical CUstreams.
309feed674dSShilei Tian   // xxax+a+++++
310feed674dSShilei Tian   //     ^
311feed674dSShilei Tian   //     id
312feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
313feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
314feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
315feed674dSShilei Tian   // from its initial state.
316feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
317feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
318feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
319feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
320feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
321feed674dSShilei Tian   }
322feed674dSShilei Tian 
3234031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
3244031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
3254031bb98SShilei Tian 
3264031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
3274031bb98SShilei Tian 
3284031bb98SShilei Tian     // Check the size of stream pool
329ad94fce8SJohannes Doerfert     if (static_cast<int>(StreamPool[DeviceId].size()) != EnvNumInitialStreams)
3304031bb98SShilei Tian       return false;
3314031bb98SShilei Tian 
3324031bb98SShilei Tian     // Check whether each stream is valid
3334031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
3344031bb98SShilei Tian       if (!S)
3354031bb98SShilei Tian         return false;
3364031bb98SShilei Tian 
3374031bb98SShilei Tian     return true;
338feed674dSShilei Tian   }
339feed674dSShilei Tian };
340feed674dSShilei Tian 
3414031bb98SShilei Tian class DeviceRTLTy {
3423de4cd12SGeorge Rokos   int NumberOfDevices;
3434031bb98SShilei Tian   // OpenMP environment properties
3443de4cd12SGeorge Rokos   int EnvNumTeams;
3453de4cd12SGeorge Rokos   int EnvTeamLimit;
346422adaa8SJoseph Huber   int EnvTeamThreadLimit;
3474031bb98SShilei Tian   // OpenMP requires flags
348c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
349c5fe030cSGheorghe-Teodor Bercea 
3504031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
3514031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
3524031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
3534031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
3543de4cd12SGeorge Rokos 
3554031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
3564031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
3574031bb98SShilei Tian   std::vector<CUmodule> Modules;
358feed674dSShilei Tian 
3590871d6d5SShilei Tian   /// A class responsible for interacting with device native runtime library to
3600871d6d5SShilei Tian   /// allocate and free memory.
3610871d6d5SShilei Tian   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
3620871d6d5SShilei Tian     const int DeviceId;
3630871d6d5SShilei Tian     const std::vector<DeviceDataTy> &DeviceData;
364a15f8589SJoseph Huber     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
3650871d6d5SShilei Tian 
3660871d6d5SShilei Tian   public:
3670871d6d5SShilei Tian     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
3680871d6d5SShilei Tian         : DeviceId(DeviceId), DeviceData(DeviceData) {}
3690871d6d5SShilei Tian 
370a15f8589SJoseph Huber     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
3710871d6d5SShilei Tian       if (Size == 0)
3720871d6d5SShilei Tian         return nullptr;
3730871d6d5SShilei Tian 
3740871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
3750871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
3760871d6d5SShilei Tian         return nullptr;
3770871d6d5SShilei Tian 
378a15f8589SJoseph Huber       void *MemAlloc = nullptr;
379a15f8589SJoseph Huber       switch (Kind) {
380a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
381a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
3820871d6d5SShilei Tian         CUdeviceptr DevicePtr;
38395f0d1edSJon Chesterfield         Err = cuMemAlloc(&DevicePtr, Size);
384a15f8589SJoseph Huber         MemAlloc = (void *)DevicePtr;
38595f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
3860871d6d5SShilei Tian           return nullptr;
387a15f8589SJoseph Huber         break;
388a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
389a15f8589SJoseph Huber         void *HostPtr;
390a15f8589SJoseph Huber         Err = cuMemAllocHost(&HostPtr, Size);
391a15f8589SJoseph Huber         MemAlloc = HostPtr;
392a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
393a15f8589SJoseph Huber           return nullptr;
394a15f8589SJoseph Huber         HostPinnedAllocs[MemAlloc] = Kind;
395a15f8589SJoseph Huber         break;
396a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
397a15f8589SJoseph Huber         CUdeviceptr SharedPtr;
398a15f8589SJoseph Huber         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
399a15f8589SJoseph Huber         MemAlloc = (void *)SharedPtr;
400a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
401a15f8589SJoseph Huber           return nullptr;
402a15f8589SJoseph Huber         break;
403a15f8589SJoseph Huber       }
4040871d6d5SShilei Tian 
405a15f8589SJoseph Huber       return MemAlloc;
4060871d6d5SShilei Tian     }
4070871d6d5SShilei Tian 
4080871d6d5SShilei Tian     int free(void *TgtPtr) override {
4090871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
4100871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
4110871d6d5SShilei Tian         return OFFLOAD_FAIL;
4120871d6d5SShilei Tian 
413a15f8589SJoseph Huber       // Host pinned memory must be freed differently.
414a15f8589SJoseph Huber       TargetAllocTy Kind =
415a15f8589SJoseph Huber           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
416a15f8589SJoseph Huber               ? TARGET_ALLOC_DEFAULT
417a15f8589SJoseph Huber               : TARGET_ALLOC_HOST;
418a15f8589SJoseph Huber       switch (Kind) {
419a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
420a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
421a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
42295f0d1edSJon Chesterfield         Err = cuMemFree((CUdeviceptr)TgtPtr);
42395f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemFree\n"))
4240871d6d5SShilei Tian           return OFFLOAD_FAIL;
425a15f8589SJoseph Huber         break;
426a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
427a15f8589SJoseph Huber         Err = cuMemFreeHost(TgtPtr);
428a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
429a15f8589SJoseph Huber           return OFFLOAD_FAIL;
430a15f8589SJoseph Huber         break;
431a15f8589SJoseph Huber       }
4320871d6d5SShilei Tian 
4330871d6d5SShilei Tian       return OFFLOAD_SUCCESS;
4340871d6d5SShilei Tian     }
4350871d6d5SShilei Tian   };
4360871d6d5SShilei Tian 
4370871d6d5SShilei Tian   /// A vector of device allocators
4380871d6d5SShilei Tian   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
4390871d6d5SShilei Tian 
4400871d6d5SShilei Tian   /// A vector of memory managers. Since the memory manager is non-copyable and
4410871d6d5SShilei Tian   // non-removable, we wrap them into std::unique_ptr.
4420871d6d5SShilei Tian   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
4430871d6d5SShilei Tian 
4440871d6d5SShilei Tian   /// Whether use memory manager
4450871d6d5SShilei Tian   bool UseMemoryManager = true;
4460871d6d5SShilei Tian 
4473de4cd12SGeorge Rokos   // Record entry point associated with device
4484031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
4494031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4503de4cd12SGeorge Rokos     E.Entries.push_back(entry);
4513de4cd12SGeorge Rokos   }
4523de4cd12SGeorge Rokos 
453ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
454ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
455ae209397SJoseph Huber                                              const void *Addr) const {
4564031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
4574031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
4584031bb98SShilei Tian       if (Itr.addr == Addr)
459ae209397SJoseph Huber         return &Itr;
4603de4cd12SGeorge Rokos 
461ae209397SJoseph Huber     return nullptr;
4623de4cd12SGeorge Rokos   }
4633de4cd12SGeorge Rokos 
4643de4cd12SGeorge Rokos   // Return the pointer to the target entries table
4654031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
4664031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4673de4cd12SGeorge Rokos 
4684031bb98SShilei Tian     if (E.Entries.empty())
4694031bb98SShilei Tian       return nullptr;
4703de4cd12SGeorge Rokos 
4713de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
4724031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
4734031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
4743de4cd12SGeorge Rokos 
4753de4cd12SGeorge Rokos     return &E.Table;
4763de4cd12SGeorge Rokos   }
4773de4cd12SGeorge Rokos 
4783de4cd12SGeorge Rokos   // Clear entries table for a device
4794031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
4804031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
4814031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4823de4cd12SGeorge Rokos     E.Entries.clear();
4834031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
4843de4cd12SGeorge Rokos   }
4853de4cd12SGeorge Rokos 
4865449fbb5SJohannes Doerfert   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
4875449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
4884031bb98SShilei Tian 
4895449fbb5SJohannes Doerfert     if (!AsyncInfo->Queue)
4905449fbb5SJohannes Doerfert       AsyncInfo->Queue = StreamManager->getStream(DeviceId);
4914031bb98SShilei Tian 
4925449fbb5SJohannes Doerfert     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
493b305d26bSSergey Dmitriev   }
4944031bb98SShilei Tian 
4954031bb98SShilei Tian public:
4964031bb98SShilei Tian   // This class should not be copied
4974031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
4984031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
4994031bb98SShilei Tian 
5004031bb98SShilei Tian   DeviceRTLTy()
5014031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
502422adaa8SJoseph Huber         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED) {
503b305d26bSSergey Dmitriev 
5043de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
5053de4cd12SGeorge Rokos 
5064031bb98SShilei Tian     CUresult Err = cuInit(0);
5077baff00eSJon Chesterfield     if (Err == CUDA_ERROR_INVALID_HANDLE) {
5087baff00eSJon Chesterfield       // Can't call cuGetErrorString if dlsym failed
5097baff00eSJon Chesterfield       DP("Failed to load CUDA shared library\n");
5107baff00eSJon Chesterfield       return;
5117baff00eSJon Chesterfield     }
5124031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
5133de4cd12SGeorge Rokos       return;
5143de4cd12SGeorge Rokos     }
5153de4cd12SGeorge Rokos 
5164031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
5174031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
5183de4cd12SGeorge Rokos       return;
5193de4cd12SGeorge Rokos 
5203de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
5213de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
5223de4cd12SGeorge Rokos       return;
5233de4cd12SGeorge Rokos     }
5243de4cd12SGeorge Rokos 
5254031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
5263de4cd12SGeorge Rokos 
5273de4cd12SGeorge Rokos     // Get environment variables regarding teams
5284031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
5293de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
5304031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
5313de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
5323de4cd12SGeorge Rokos     }
533422adaa8SJoseph Huber     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
534422adaa8SJoseph Huber       // OMP_TEAMS_THREAD_LIMIT has been set
535422adaa8SJoseph Huber       EnvTeamThreadLimit = std::stoi(EnvStr);
536422adaa8SJoseph Huber       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
537422adaa8SJoseph Huber     }
5384031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
5393de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
5404031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
5413de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
5423de4cd12SGeorge Rokos     }
543c5fe030cSGheorghe-Teodor Bercea 
544feed674dSShilei Tian     StreamManager =
5454031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
5460871d6d5SShilei Tian 
5470871d6d5SShilei Tian     for (int I = 0; I < NumberOfDevices; ++I)
5480871d6d5SShilei Tian       DeviceAllocators.emplace_back(I, DeviceData);
5490871d6d5SShilei Tian 
5500871d6d5SShilei Tian     // Get the size threshold from environment variable
5510871d6d5SShilei Tian     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
5520871d6d5SShilei Tian     UseMemoryManager = Res.second;
5530871d6d5SShilei Tian     size_t MemoryManagerThreshold = Res.first;
5540871d6d5SShilei Tian 
5550871d6d5SShilei Tian     if (UseMemoryManager)
5560871d6d5SShilei Tian       for (int I = 0; I < NumberOfDevices; ++I)
5570871d6d5SShilei Tian         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
5580871d6d5SShilei Tian             DeviceAllocators[I], MemoryManagerThreshold));
5593de4cd12SGeorge Rokos   }
5603de4cd12SGeorge Rokos 
5614031bb98SShilei Tian   ~DeviceRTLTy() {
5620871d6d5SShilei Tian     // We first destruct memory managers in case that its dependent data are
5630871d6d5SShilei Tian     // destroyed before it.
5640871d6d5SShilei Tian     for (auto &M : MemoryManagers)
5650871d6d5SShilei Tian       M.release();
5660871d6d5SShilei Tian 
567feed674dSShilei Tian     StreamManager = nullptr;
568feed674dSShilei Tian 
5694031bb98SShilei Tian     for (CUmodule &M : Modules)
5704031bb98SShilei Tian       // Close module
5714031bb98SShilei Tian       if (M)
5724031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
5734031bb98SShilei Tian 
5744031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
5754031bb98SShilei Tian       // Destroy context
576c5348aecSYe Luo       if (D.Context) {
577c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
578c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
579c5348aecSYe Luo         CUdevice Device;
580c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
581c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
58295f0d1edSJon Chesterfield         checkResult(cuDevicePrimaryCtxRelease(Device),
58395f0d1edSJon Chesterfield                     "Error returned from cuDevicePrimaryCtxRelease\n");
584c5348aecSYe Luo       }
5853de4cd12SGeorge Rokos     }
5863de4cd12SGeorge Rokos   }
5873de4cd12SGeorge Rokos 
5884031bb98SShilei Tian   // Check whether a given DeviceId is valid
5894031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
5904031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
59132ed2927SShilei Tian   }
59232ed2927SShilei Tian 
593cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
5944031bb98SShilei Tian 
5954031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
5964031bb98SShilei Tian 
5974031bb98SShilei Tian   int initDevice(const int DeviceId) {
5984031bb98SShilei Tian     CUdevice Device;
5994031bb98SShilei Tian 
6004031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
6014031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
6024031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
60332ed2927SShilei Tian       return OFFLOAD_FAIL;
6043de4cd12SGeorge Rokos 
605c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
606c5348aecSYe Luo     // it is inactive
607c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
608c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
609c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
610c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
611c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
612c5348aecSYe Luo       return OFFLOAD_FAIL;
613c5348aecSYe Luo 
614c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
615c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
616c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
617c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
618c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
619c5348aecSYe Luo     } else {
620c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
621c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
62295f0d1edSJon Chesterfield       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
62395f0d1edSJon Chesterfield       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
624c5348aecSYe Luo         return OFFLOAD_FAIL;
625c5348aecSYe Luo     }
626c5348aecSYe Luo 
627c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
628c5348aecSYe Luo     // device is selected.
629c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
630c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
6313de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
6323de4cd12SGeorge Rokos 
6334031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
6344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
6354031bb98SShilei Tian       return OFFLOAD_FAIL;
636a5153dbcSJohannes Doerfert 
637feed674dSShilei Tian     // Initialize stream pool
6384031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
6394031bb98SShilei Tian       return OFFLOAD_FAIL;
640a5153dbcSJohannes Doerfert 
641bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
6424031bb98SShilei Tian     int MaxGridDimX;
6434031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
6444031bb98SShilei Tian                                Device);
6454031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6464031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
6474031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
6484031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
6494031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
6504031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
6514031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
6523de4cd12SGeorge Rokos     } else {
6533de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
654bb51d398SJonas Hahnfeld          "at the hard limit\n",
6554031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
6564031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
6573de4cd12SGeorge Rokos     }
6583de4cd12SGeorge Rokos 
659bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
6604031bb98SShilei Tian     int MaxBlockDimX;
6614031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
6624031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
6634031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6644031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
6654031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
6664031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
667422adaa8SJoseph Huber     } else {
6684031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
6694031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
670422adaa8SJoseph Huber 
671422adaa8SJoseph Huber       if (EnvTeamThreadLimit > 0 &&
672422adaa8SJoseph Huber           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
673422adaa8SJoseph Huber         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
674422adaa8SJoseph Huber            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
675422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
676422adaa8SJoseph Huber         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
677422adaa8SJoseph Huber       }
678422adaa8SJoseph Huber       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
6794031bb98SShilei Tian         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
6804031bb98SShilei Tian            "capping at the hard limit\n",
681422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
6824031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
6833de4cd12SGeorge Rokos       }
684422adaa8SJoseph Huber     }
6853de4cd12SGeorge Rokos 
6864031bb98SShilei Tian     // Get and set warp size
6874031bb98SShilei Tian     int WarpSize;
6884031bb98SShilei Tian     Err =
6894031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
6904031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6914031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
6924031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
693bb51d398SJonas Hahnfeld     } else {
6944031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
6954031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
6963de4cd12SGeorge Rokos     }
6973de4cd12SGeorge Rokos 
6983de4cd12SGeorge Rokos     // Adjust teams to the env variables
6994031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
7003de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
7014031bb98SShilei Tian          EnvTeamLimit);
7024031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
7033de4cd12SGeorge Rokos     }
7043de4cd12SGeorge Rokos 
7053817ba13SJoseph Huber     size_t StackLimit;
7063817ba13SJoseph Huber     size_t HeapLimit;
7073817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
7083817ba13SJoseph Huber       StackLimit = std::stol(EnvStr);
7093817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
7103817ba13SJoseph Huber         return OFFLOAD_FAIL;
7113817ba13SJoseph Huber     } else {
7123817ba13SJoseph Huber       if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
7133817ba13SJoseph Huber         return OFFLOAD_FAIL;
7143817ba13SJoseph Huber     }
7153817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
7163817ba13SJoseph Huber       HeapLimit = std::stol(EnvStr);
7173817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
7183817ba13SJoseph Huber         return OFFLOAD_FAIL;
7193817ba13SJoseph Huber     } else {
7203817ba13SJoseph Huber       if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
7213817ba13SJoseph Huber         return OFFLOAD_FAIL;
7223817ba13SJoseph Huber     }
7233817ba13SJoseph Huber 
724119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
725ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
726ae209397SJoseph Huber          "warp size of %d\n",
727ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
728ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
7293817ba13SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
7303817ba13SJoseph Huber          "Device heap size is %d Bytes, device stack size is %d Bytes per "
7313817ba13SJoseph Huber          "thread\n",
7323817ba13SJoseph Huber          (int)HeapLimit, (int)StackLimit);
7333de4cd12SGeorge Rokos 
7343de4cd12SGeorge Rokos     // Set default number of teams
7354031bb98SShilei Tian     if (EnvNumTeams > 0) {
7363de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
7374031bb98SShilei Tian          EnvNumTeams);
7384031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
7393de4cd12SGeorge Rokos     } else {
7404031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
7413de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
7424031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
7433de4cd12SGeorge Rokos     }
7444031bb98SShilei Tian 
7454031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
7463de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
7474031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
7484031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
7493de4cd12SGeorge Rokos     }
7503de4cd12SGeorge Rokos 
7513de4cd12SGeorge Rokos     // Set default number of threads
7524031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
7533de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
7544031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
7554031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
7564031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
7573de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
7584031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
7594031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
7603de4cd12SGeorge Rokos     }
7613de4cd12SGeorge Rokos 
7623de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7633de4cd12SGeorge Rokos   }
7643de4cd12SGeorge Rokos 
7654031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
7664031bb98SShilei Tian                                  const __tgt_device_image *Image) {
7674031bb98SShilei Tian     // Set the context we are using
7684031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7694031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7704031bb98SShilei Tian       return nullptr;
7713de4cd12SGeorge Rokos 
7723de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
7734031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
7743de4cd12SGeorge Rokos 
7753de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
7764031bb98SShilei Tian     CUmodule Module;
7774031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
7784031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
7794031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
7804031bb98SShilei Tian       return nullptr;
7813de4cd12SGeorge Rokos 
7823de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
7834031bb98SShilei Tian 
7844031bb98SShilei Tian     Modules.push_back(Module);
7853de4cd12SGeorge Rokos 
7863de4cd12SGeorge Rokos     // Find the symbols in the module by name.
7874031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
7884031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
7893de4cd12SGeorge Rokos 
7905272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
7914031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
7924031bb98SShilei Tian       if (!E->addr) {
7934031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
7944031bb98SShilei Tian         // have always something in the address to uniquely identify the target
7954031bb98SShilei Tian         // region.
7964031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
7974031bb98SShilei Tian         return nullptr;
7983de4cd12SGeorge Rokos       }
7993de4cd12SGeorge Rokos 
8004031bb98SShilei Tian       if (E->size) {
8014031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
8024031bb98SShilei Tian         CUdeviceptr CUPtr;
8034031bb98SShilei Tian         size_t CUSize;
80495f0d1edSJon Chesterfield         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
8054031bb98SShilei Tian         // We keep this style here because we need the name
8064031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8072ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
8084031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8094031bb98SShilei Tian           return nullptr;
8103de4cd12SGeorge Rokos         }
8113de4cd12SGeorge Rokos 
8124031bb98SShilei Tian         if (CUSize != E->size) {
8134031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
8144031bb98SShilei Tian              CUSize, E->size);
8154031bb98SShilei Tian           return nullptr;
8163de4cd12SGeorge Rokos         }
8173de4cd12SGeorge Rokos 
8183de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
8194031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
8204031bb98SShilei Tian 
8214031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
8223de4cd12SGeorge Rokos 
823aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
824aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
825aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
826aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
827aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
8284c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
829aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
8304031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
8314031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
8324031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
833aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
834c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
835c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
83695f0d1edSJon Chesterfield           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
8374031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
8384031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
8394031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
840c5fe030cSGheorghe-Teodor Bercea         }
841c5fe030cSGheorghe-Teodor Bercea 
8424031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
8433de4cd12SGeorge Rokos 
8443de4cd12SGeorge Rokos         continue;
8453de4cd12SGeorge Rokos       }
8463de4cd12SGeorge Rokos 
8474031bb98SShilei Tian       CUfunction Func;
8484031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
8494031bb98SShilei Tian       // We keep this style here because we need the name
8504031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
8512ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
8524031bb98SShilei Tian         CUDA_ERR_STRING(Err);
8534031bb98SShilei Tian         return nullptr;
8543de4cd12SGeorge Rokos       }
8553de4cd12SGeorge Rokos 
8563de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
8574031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
8583de4cd12SGeorge Rokos 
8593de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
8603de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
8614031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
8623de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
8633de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
8643de4cd12SGeorge Rokos 
8653de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
8664031bb98SShilei Tian       size_t CUSize;
86795f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
8684031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
8694031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
8703de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
8714031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
8724031bb98SShilei Tian           return nullptr;
8733de4cd12SGeorge Rokos         }
8743de4cd12SGeorge Rokos 
87595f0d1edSJon Chesterfield         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
8764031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8772ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
8783de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
8794031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
8804031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8814031bb98SShilei Tian           return nullptr;
8823de4cd12SGeorge Rokos         }
8833de4cd12SGeorge Rokos 
8847d576392SJoseph Huber         if (ExecModeVal < 0 || ExecModeVal > 2) {
8853de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
8863de4cd12SGeorge Rokos              ExecModeVal);
8874031bb98SShilei Tian           return nullptr;
8883de4cd12SGeorge Rokos         }
8893de4cd12SGeorge Rokos       } else {
890edb8acdcSJoseph Huber         DP("Loading global exec_mode '%s' - symbol missing, using default "
8914031bb98SShilei Tian            "value GENERIC (1)\n",
8924031bb98SShilei Tian            ExecModeName);
8933de4cd12SGeorge Rokos       }
8943de4cd12SGeorge Rokos 
8954031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
8963de4cd12SGeorge Rokos 
8974031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
8984031bb98SShilei Tian       Entry.addr = &KernelsList.back();
8994031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
9003de4cd12SGeorge Rokos     }
9013de4cd12SGeorge Rokos 
902e1c7a46dSGuansong Zhang     // send device environment data to the device
903e1c7a46dSGuansong Zhang     {
904*ec02c34bSJoseph Huber       // TODO: The device ID used here is not the real device ID used by OpenMP.
905*ec02c34bSJoseph Huber       omptarget_device_environmentTy DeviceEnv{
906*ec02c34bSJoseph Huber           0, static_cast<uint32_t>(NumberOfDevices),
907*ec02c34bSJoseph Huber           static_cast<uint32_t>(DeviceId)};
908e1c7a46dSGuansong Zhang 
909e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
9104031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
9114031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
912e1c7a46dSGuansong Zhang #endif
913e1c7a46dSGuansong Zhang 
9144031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
9154031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
9164031bb98SShilei Tian       size_t CUSize;
917e1c7a46dSGuansong Zhang 
91895f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
9194031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
9204031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
9212ce16810SJoseph Huber           REPORT(
9222ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
9234031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
9244031bb98SShilei Tian           CUDA_ERR_STRING(Err);
9254031bb98SShilei Tian           return nullptr;
926e1c7a46dSGuansong Zhang         }
927e1c7a46dSGuansong Zhang 
92895f0d1edSJon Chesterfield         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
9294031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
9302ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
931e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
9324031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
9334031bb98SShilei Tian           CUDA_ERR_STRING(Err);
9344031bb98SShilei Tian           return nullptr;
935e1c7a46dSGuansong Zhang         }
936e1c7a46dSGuansong Zhang 
9374031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
938e1c7a46dSGuansong Zhang       } else {
9394031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
9404031bb98SShilei Tian            DeviceEnvName);
9414031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
9424031bb98SShilei Tian            "environment setting.\n");
943e1c7a46dSGuansong Zhang       }
944e1c7a46dSGuansong Zhang     }
945e1c7a46dSGuansong Zhang 
9464031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
9473de4cd12SGeorge Rokos   }
9483de4cd12SGeorge Rokos 
949a15f8589SJoseph Huber   void *dataAlloc(const int DeviceId, const int64_t Size,
950a15f8589SJoseph Huber                   const TargetAllocTy Kind) {
951a15f8589SJoseph Huber     switch (Kind) {
952a15f8589SJoseph Huber     case TARGET_ALLOC_DEFAULT:
953a15f8589SJoseph Huber     case TARGET_ALLOC_DEVICE:
9540871d6d5SShilei Tian       if (UseMemoryManager)
9550871d6d5SShilei Tian         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
956a15f8589SJoseph Huber       else
957a15f8589SJoseph Huber         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
958a15f8589SJoseph Huber     case TARGET_ALLOC_HOST:
959a15f8589SJoseph Huber     case TARGET_ALLOC_SHARED:
960a15f8589SJoseph Huber       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
961a15f8589SJoseph Huber     }
9624031bb98SShilei Tian 
963a15f8589SJoseph Huber     REPORT("Invalid target data allocation kind or requested allocator not "
964a15f8589SJoseph Huber            "implemented yet\n");
965a15f8589SJoseph Huber 
966a15f8589SJoseph Huber     return nullptr;
9673de4cd12SGeorge Rokos   }
9683de4cd12SGeorge Rokos 
9694031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
9705449fbb5SJohannes Doerfert                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
9715449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9723de4cd12SGeorge Rokos 
9734031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9744031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
9753de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9763de4cd12SGeorge Rokos 
9775449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
9783de4cd12SGeorge Rokos 
97995f0d1edSJon Chesterfield     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
9804031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
98129338459SJoseph Huber       DP("Error when copying data from host to device. Pointers: host "
9822ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9834031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9844031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9853de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9863de4cd12SGeorge Rokos     }
9873de4cd12SGeorge Rokos 
9883de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9893de4cd12SGeorge Rokos   }
9903de4cd12SGeorge Rokos 
9914031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
9925449fbb5SJohannes Doerfert                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
9935449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9944031bb98SShilei Tian 
9954031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9964031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
99703ff643dSShilei Tian       return OFFLOAD_FAIL;
99803ff643dSShilei Tian 
9995449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
100003ff643dSShilei Tian 
100195f0d1edSJon Chesterfield     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
10024031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
100329338459SJoseph Huber       DP("Error when copying data from device to host. Pointers: host "
10042ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
10054031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
10064031bb98SShilei Tian       CUDA_ERR_STRING(Err);
10073de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
10083de4cd12SGeorge Rokos     }
10093de4cd12SGeorge Rokos 
10104031bb98SShilei Tian     return OFFLOAD_SUCCESS;
10114031bb98SShilei Tian   }
10124031bb98SShilei Tian 
1013a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
10145449fbb5SJohannes Doerfert                    int64_t Size, __tgt_async_info *AsyncInfo) const {
10155449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
1016a014fbbcSShilei Tian 
1017a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
1018a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
1019a014fbbcSShilei Tian       return OFFLOAD_FAIL;
1020a014fbbcSShilei Tian 
10215449fbb5SJohannes Doerfert     CUstream Stream = getStream(SrcDevId, AsyncInfo);
1022a014fbbcSShilei Tian 
1023a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
1024a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
1025a014fbbcSShilei Tian       int CanAccessPeer = 0;
1026a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
1027a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
10282ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
1029a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
1030a014fbbcSShilei Tian                SrcDevId, DstDevId);
1031a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
1032a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1033a014fbbcSShilei Tian       }
1034a014fbbcSShilei Tian 
1035a014fbbcSShilei Tian       if (!CanAccessPeer) {
1036a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
1037a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1038a014fbbcSShilei Tian       }
1039a014fbbcSShilei Tian 
1040a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
1041a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
10422ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
1043a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
1044a014fbbcSShilei Tian                SrcDevId, DstDevId);
1045a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
1046a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1047a014fbbcSShilei Tian       }
1048a014fbbcSShilei Tian 
1049a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
1050a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
1051a014fbbcSShilei Tian                               Size, Stream);
1052a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
1053a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
1054a014fbbcSShilei Tian 
105529338459SJoseph Huber       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
105629338459SJoseph Huber          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
105745bb073dSYe Luo          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
1058a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
1059a014fbbcSShilei Tian     }
1060a014fbbcSShilei Tian 
1061a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1062a014fbbcSShilei Tian   }
1063a014fbbcSShilei Tian 
10640871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
10650871d6d5SShilei Tian     if (UseMemoryManager)
10660871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
10674031bb98SShilei Tian 
10680871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
10694031bb98SShilei Tian   }
10704031bb98SShilei Tian 
1071aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1072aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
1073aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
10744031bb98SShilei Tian                           const unsigned int LoopTripCount,
10754031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
10764031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
10774031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
10784031bb98SShilei Tian       return OFFLOAD_FAIL;
10794031bb98SShilei Tian 
10803de4cd12SGeorge Rokos     // All args are references.
10814031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
10824031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
10833de4cd12SGeorge Rokos 
10844031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
10854031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
10864031bb98SShilei Tian       Args[I] = &Ptrs[I];
10871546d319SGeorge Rokos     }
10883de4cd12SGeorge Rokos 
1089aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
10903de4cd12SGeorge Rokos 
1091aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
10924031bb98SShilei Tian     if (ThreadLimit > 0) {
10934031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
10944031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
10953de4cd12SGeorge Rokos       // Add master warp if necessary
10963de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
10974031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
10984031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
10993de4cd12SGeorge Rokos       }
1100c13df8e5SGeorge Rokos     } else {
1101c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
11024031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
11034031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1104c13df8e5SGeorge Rokos     }
11053de4cd12SGeorge Rokos 
11064031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
11073de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
11084031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
11094031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
11103de4cd12SGeorge Rokos     }
11113de4cd12SGeorge Rokos 
1112aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
1113aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
11144031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
11154031bb98SShilei Tian                                KernelInfo->Func);
1116aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1117aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
1118aa27cfc1SJohannes Doerfert     }
1119aa27cfc1SJohannes Doerfert 
1120aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1121aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
1122aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
1123aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
11243de4cd12SGeorge Rokos     }
11253de4cd12SGeorge Rokos 
11264031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
11274031bb98SShilei Tian     if (TeamNum <= 0) {
11284031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1129c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
11304031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
11314031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
11324031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
11334031bb98SShilei Tian           // integer
11344031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
11357d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == GENERIC) {
1136c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
1137c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
1138c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
1139c13df8e5SGeorge Rokos           //
1140c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
1141c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
1142c13df8e5SGeorge Rokos           //   #pragma omp parallel for
1143c13df8e5SGeorge Rokos           //   for(...) {}
1144c13df8e5SGeorge Rokos           // }
1145c13df8e5SGeorge Rokos           //
1146c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
1147c13df8e5SGeorge Rokos           // loop.
11484031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
11497d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == SPMD_GENERIC) {
11507d576392SJoseph Huber           // If we reach this point, then we are executing a kernel that was
11517d576392SJoseph Huber           // transformed from Generic-mode to SPMD-mode. This kernel has
11527d576392SJoseph Huber           // SPMD-mode execution, but needs its blocks to be scheduled
11537d576392SJoseph Huber           // differently because the current loop trip count only applies to the
11547d576392SJoseph Huber           // `teams distribute` region and will create var too few blocks using
11557d576392SJoseph Huber           // the regular SPMD-mode method.
11567d576392SJoseph Huber           CudaBlocksPerGrid = LoopTripCount;
1157a158d366SJoseph Huber         } else {
1158a158d366SJoseph Huber           REPORT("Unknown execution mode: %d\n", KernelInfo->ExecutionMode);
1159a158d366SJoseph Huber           return OFFLOAD_FAIL;
1160c13df8e5SGeorge Rokos         }
116145bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
11624031bb98SShilei Tian            " and number of threads per block %d\n",
11634031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
11643de4cd12SGeorge Rokos       } else {
11654031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
11664031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
11673de4cd12SGeorge Rokos       }
11684031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
11693de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
11704031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
11714031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
11723de4cd12SGeorge Rokos     } else {
11734031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
11744031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
11753de4cd12SGeorge Rokos     }
11763de4cd12SGeorge Rokos 
1177119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1178ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
1179ae209397SJoseph Huber          "mode\n",
1180ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1181ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1182ae209397SJoseph Huber              : "(null)",
1183ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
11847d576392SJoseph Huber          (KernelInfo->ExecutionMode != SPMD
118576c0c0caSJoseph Huber               ? (KernelInfo->ExecutionMode == GENERIC ? "Generic"
118676c0c0caSJoseph Huber                                                       : "SPMD-Generic")
11877d576392SJoseph Huber               : "SPMD"));
11883de4cd12SGeorge Rokos 
11894031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
11904031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
11914031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
11924031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
11934031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
11944031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
11954031bb98SShilei Tian       return OFFLOAD_FAIL;
11964031bb98SShilei Tian 
11974031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
11984031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
11994031bb98SShilei Tian 
12004031bb98SShilei Tian     return OFFLOAD_SUCCESS;
12014031bb98SShilei Tian   }
12024031bb98SShilei Tian 
12035449fbb5SJohannes Doerfert   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
12045449fbb5SJohannes Doerfert     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
12054031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
12063de4cd12SGeorge Rokos 
12074031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
12085449fbb5SJohannes Doerfert     // AsyncInfo. This is to make sure the synchronization only works for its
12094031bb98SShilei Tian     // own tasks.
12105449fbb5SJohannes Doerfert     StreamManager->returnStream(DeviceId,
12115449fbb5SJohannes Doerfert                                 reinterpret_cast<CUstream>(AsyncInfo->Queue));
12125449fbb5SJohannes Doerfert     AsyncInfo->Queue = nullptr;
12133de4cd12SGeorge Rokos 
121416064e71SJoseph Huber     if (Err != CUDA_SUCCESS) {
121529338459SJoseph Huber       DP("Error when synchronizing stream. stream = " DPxMOD
121616064e71SJoseph Huber          ", async info ptr = " DPxMOD "\n",
121716064e71SJoseph Huber          DPxPTR(Stream), DPxPTR(AsyncInfo));
121816064e71SJoseph Huber       CUDA_ERR_STRING(Err);
121916064e71SJoseph Huber     }
122016064e71SJoseph Huber     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
12213de4cd12SGeorge Rokos   }
1222d2f85d09SJose M Monsalve Diaz 
1223d2f85d09SJose M Monsalve Diaz   void printDeviceInfo(int32_t device_id) {
1224d2f85d09SJose M Monsalve Diaz     char TmpChar[1000];
1225d2f85d09SJose M Monsalve Diaz     std::string TmpStr;
1226d2f85d09SJose M Monsalve Diaz     size_t TmpSt;
1227d2f85d09SJose M Monsalve Diaz     int TmpInt, TmpInt2, TmpInt3;
1228d2f85d09SJose M Monsalve Diaz 
1229d2f85d09SJose M Monsalve Diaz     CUdevice Device;
1230d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGet(&Device, device_id),
1231d2f85d09SJose M Monsalve Diaz                 "Error returned from cuCtxGetDevice\n");
1232d2f85d09SJose M Monsalve Diaz 
1233d2f85d09SJose M Monsalve Diaz     cuDriverGetVersion(&TmpInt);
1234d2f85d09SJose M Monsalve Diaz     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1235d2f85d09SJose M Monsalve Diaz     printf("    CUDA Device Number: \t\t%d \n", device_id);
1236d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1237d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetName\n");
1238d2f85d09SJose M Monsalve Diaz     printf("    Device Name: \t\t\t%s \n", TmpChar);
1239d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1240d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceTotalMem\n");
1241d2f85d09SJose M Monsalve Diaz     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1242d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1243d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1244d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1245d2f85d09SJose M Monsalve Diaz     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1246d2f85d09SJose M Monsalve Diaz     checkResult(
1247d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1248d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1249d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1250d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1251d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1252d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1253d2f85d09SJose M Monsalve Diaz     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1254d2f85d09SJose M Monsalve Diaz     checkResult(
1255d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1256d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1257d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1258d2f85d09SJose M Monsalve Diaz     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
125928939b6aSShilei Tian     checkResult(
126028939b6aSShilei Tian         cuDeviceGetAttribute(
1261d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1262d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1263d2f85d09SJose M Monsalve Diaz     printf("    Registers per Block: \t\t%d \n", TmpInt);
1264d2f85d09SJose M Monsalve Diaz     checkResult(
1265d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1266d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1267d2f85d09SJose M Monsalve Diaz     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1268d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1269d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1270d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1271d2f85d09SJose M Monsalve Diaz     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
127228939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
127328939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1274d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
127528939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
127628939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1277d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
127828939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
127928939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1280d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1281d2f85d09SJose M Monsalve Diaz     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1282d2f85d09SJose M Monsalve Diaz            TmpInt3);
128328939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
128428939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1285d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
128628939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
128728939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1288d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
128928939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
129028939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1291d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1292d2f85d09SJose M Monsalve Diaz     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1293d2f85d09SJose M Monsalve Diaz            TmpInt3);
1294d2f85d09SJose M Monsalve Diaz     checkResult(
1295d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1296d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1297d2f85d09SJose M Monsalve Diaz     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1298d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1299d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1300d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1301d2f85d09SJose M Monsalve Diaz     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1302d2f85d09SJose M Monsalve Diaz     checkResult(
1303d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1304d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1305d2f85d09SJose M Monsalve Diaz     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1306d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1307d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1308d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1309d2f85d09SJose M Monsalve Diaz     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1310d2f85d09SJose M Monsalve Diaz     checkResult(
1311d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1312d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1313d2f85d09SJose M Monsalve Diaz     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1314d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1315d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1316d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1317d2f85d09SJose M Monsalve Diaz     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1318d2f85d09SJose M Monsalve Diaz     checkResult(
1319d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1320d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1321d2f85d09SJose M Monsalve Diaz     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1322d2f85d09SJose M Monsalve Diaz       TmpStr = "DEFAULT";
1323d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1324d2f85d09SJose M Monsalve Diaz       TmpStr = "PROHIBITED";
1325d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1326d2f85d09SJose M Monsalve Diaz       TmpStr = "EXCLUSIVE PROCESS";
1327d2f85d09SJose M Monsalve Diaz     else
1328d2f85d09SJose M Monsalve Diaz       TmpStr = "unknown";
1329d2f85d09SJose M Monsalve Diaz     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1330d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1331d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1332d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1333d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1334d2f85d09SJose M Monsalve Diaz     checkResult(
1335d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1336d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1337d2f85d09SJose M Monsalve Diaz     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1338d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1339d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1340d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1341d2f85d09SJose M Monsalve Diaz     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
134228939b6aSShilei Tian     checkResult(
134328939b6aSShilei Tian         cuDeviceGetAttribute(
1344d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1345d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1346d2f85d09SJose M Monsalve Diaz     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
134728939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
134828939b6aSShilei Tian                                      Device),
1349d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1350d2f85d09SJose M Monsalve Diaz     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
135128939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
135228939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
135328939b6aSShilei Tian                     Device),
1354d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1355d2f85d09SJose M Monsalve Diaz     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1356d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1357d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1358d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1359d2f85d09SJose M Monsalve Diaz     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1360d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1361d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1362d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1363d2f85d09SJose M Monsalve Diaz     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
136428939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
136528939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1366d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1367d2f85d09SJose M Monsalve Diaz     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1368d2f85d09SJose M Monsalve Diaz     checkResult(
1369d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1370d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1371d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1372d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1373d2f85d09SJose M Monsalve Diaz     checkResult(
1374d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1375d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1376d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1377d2f85d09SJose M Monsalve Diaz     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1378d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1379d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1380d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1381d2f85d09SJose M Monsalve Diaz     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
138228939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
138328939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1384d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1385d2f85d09SJose M Monsalve Diaz     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
138628939b6aSShilei Tian     checkResult(
138728939b6aSShilei Tian         cuDeviceGetAttribute(
138828939b6aSShilei Tian             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1389d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
139028939b6aSShilei Tian     checkResult(
139128939b6aSShilei Tian         cuDeviceGetAttribute(
139228939b6aSShilei Tian             &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1393d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1394d2f85d09SJose M Monsalve Diaz     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1395d2f85d09SJose M Monsalve Diaz   }
139629df4ab3SShilei Tian 
139729df4ab3SShilei Tian   int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo,
139829df4ab3SShilei Tian                 void *EventPtr) const {
139929df4ab3SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
140029df4ab3SShilei Tian     CUevent Event = reinterpret_cast<CUevent>(EventPtr);
140129df4ab3SShilei Tian 
140229df4ab3SShilei Tian     // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from
140329df4ab3SShilei Tian     // specific CUDA version, and defined as 0x0. In previous version, per CUDA
140429df4ab3SShilei Tian     // API document, that argument has to be 0x0.
140529df4ab3SShilei Tian     CUresult Err = cuStreamWaitEvent(Stream, Event, 0);
140629df4ab3SShilei Tian     if (Err != CUDA_SUCCESS) {
140729df4ab3SShilei Tian       DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n",
140829df4ab3SShilei Tian          DPxPTR(Stream), DPxPTR(Event));
140929df4ab3SShilei Tian       CUDA_ERR_STRING(Err);
141029df4ab3SShilei Tian       return OFFLOAD_FAIL;
141129df4ab3SShilei Tian     }
141229df4ab3SShilei Tian 
141329df4ab3SShilei Tian     return OFFLOAD_SUCCESS;
141429df4ab3SShilei Tian   }
14154031bb98SShilei Tian };
14164031bb98SShilei Tian 
14174031bb98SShilei Tian DeviceRTLTy DeviceRTL;
14184031bb98SShilei Tian } // namespace
14194031bb98SShilei Tian 
14204031bb98SShilei Tian // Exposed library API function
14214031bb98SShilei Tian #ifdef __cplusplus
14224031bb98SShilei Tian extern "C" {
14234031bb98SShilei Tian #endif
14244031bb98SShilei Tian 
14254031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
14264031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
14274031bb98SShilei Tian }
14284031bb98SShilei Tian 
14294031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
14304031bb98SShilei Tian 
14314031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
143240470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
14334031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
14344031bb98SShilei Tian   return RequiresFlags;
14354031bb98SShilei Tian }
14364031bb98SShilei Tian 
1437a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1438a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1439a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1440a014fbbcSShilei Tian     return 1;
1441a014fbbcSShilei Tian 
1442a014fbbcSShilei Tian   return 0;
1443a014fbbcSShilei Tian }
1444a014fbbcSShilei Tian 
14454031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
14464031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14474031bb98SShilei Tian 
14484031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
14494031bb98SShilei Tian }
14504031bb98SShilei Tian 
14514031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
14524031bb98SShilei Tian                                           __tgt_device_image *image) {
14534031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14544031bb98SShilei Tian 
14554031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
14564031bb98SShilei Tian }
14574031bb98SShilei Tian 
14582468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
14592468fdd9SGeorge Rokos                            int32_t kind) {
14604031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14614031bb98SShilei Tian 
1462a15f8589SJoseph Huber   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
14634031bb98SShilei Tian }
14644031bb98SShilei Tian 
14654031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
14664031bb98SShilei Tian                               int64_t size) {
14674031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14684031bb98SShilei Tian 
14695449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14704031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
14715449fbb5SJohannes Doerfert                                                  size, &AsyncInfo);
14724031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14734031bb98SShilei Tian     return OFFLOAD_FAIL;
14744031bb98SShilei Tian 
14755449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14764031bb98SShilei Tian }
14774031bb98SShilei Tian 
14784031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
14794031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
14804031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
14814031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14824031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
14834031bb98SShilei Tian 
14844031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
14854031bb98SShilei Tian                               async_info_ptr);
14864031bb98SShilei Tian }
14874031bb98SShilei Tian 
14884031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
14894031bb98SShilei Tian                                 int64_t size) {
14904031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14914031bb98SShilei Tian 
14925449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14934031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
14945449fbb5SJohannes Doerfert                                                    size, &AsyncInfo);
14954031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14964031bb98SShilei Tian     return OFFLOAD_FAIL;
14974031bb98SShilei Tian 
14985449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14994031bb98SShilei Tian }
15004031bb98SShilei Tian 
15014031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
15024031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
15034031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
15044031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15054031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
15064031bb98SShilei Tian 
15074031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
15084031bb98SShilei Tian                                 async_info_ptr);
15094031bb98SShilei Tian }
15104031bb98SShilei Tian 
1511a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1512a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1513a014fbbcSShilei Tian                                       int64_t size,
15145449fbb5SJohannes Doerfert                                       __tgt_async_info *AsyncInfo) {
1515a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1516a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
15175449fbb5SJohannes Doerfert   assert(AsyncInfo && "AsyncInfo is nullptr");
1518a014fbbcSShilei Tian 
1519a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
15205449fbb5SJohannes Doerfert                                 AsyncInfo);
1521a014fbbcSShilei Tian }
1522a014fbbcSShilei Tian 
1523a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1524a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1525a014fbbcSShilei Tian                                 int64_t size) {
1526a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1527a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1528a014fbbcSShilei Tian 
15295449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1530a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
15315449fbb5SJohannes Doerfert       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1532a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1533a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1534a014fbbcSShilei Tian 
15355449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1536a014fbbcSShilei Tian }
1537a014fbbcSShilei Tian 
15384031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
15394031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15404031bb98SShilei Tian 
15414031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
15424031bb98SShilei Tian }
15434031bb98SShilei Tian 
15444031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
15454031bb98SShilei Tian                                          void **tgt_args,
15464031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
15474031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
15484031bb98SShilei Tian                                          int32_t thread_limit,
15494031bb98SShilei Tian                                          uint64_t loop_tripcount) {
15504031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15514031bb98SShilei Tian 
15525449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
15534031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
15544031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
15555449fbb5SJohannes Doerfert       thread_limit, loop_tripcount, &AsyncInfo);
15564031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
15574031bb98SShilei Tian     return OFFLOAD_FAIL;
15584031bb98SShilei Tian 
15595449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
15604031bb98SShilei Tian }
15614031bb98SShilei Tian 
15624031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
15634031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
15644031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
15654031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
15664031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
15674031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15684031bb98SShilei Tian 
15694031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
15704031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
15714031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
15724031bb98SShilei Tian }
15733de4cd12SGeorge Rokos 
15743de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
157532ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
157603ff643dSShilei Tian                                     int32_t arg_num) {
15774031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15784031bb98SShilei Tian 
15795449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
15804031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
15815449fbb5SJohannes Doerfert       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
158203ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
158303ff643dSShilei Tian     return OFFLOAD_FAIL;
158403ff643dSShilei Tian 
15855449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
158603ff643dSShilei Tian }
158703ff643dSShilei Tian 
158803ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
158903ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
159003ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
159132ed2927SShilei Tian                                           int32_t arg_num,
15924031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
15934031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15944031bb98SShilei Tian 
159503ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
15964031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
15974031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
15984031bb98SShilei Tian       async_info_ptr);
159932ed2927SShilei Tian }
160032ed2927SShilei Tian 
16014031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
16024031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
16034031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
16044031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
16054031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
160632ed2927SShilei Tian 
16074031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
16083de4cd12SGeorge Rokos }
16093de4cd12SGeorge Rokos 
16102b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
161159b68490SJoseph Huber   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
16122b6f2008SJoseph Huber   InfoLevel.store(NewInfoLevel);
16132b6f2008SJoseph Huber }
16142b6f2008SJoseph Huber 
1615d2f85d09SJose M Monsalve Diaz void __tgt_rtl_print_device_info(int32_t device_id) {
1616d2f85d09SJose M Monsalve Diaz   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1617d2f85d09SJose M Monsalve Diaz   DeviceRTL.printDeviceInfo(device_id);
1618d2f85d09SJose M Monsalve Diaz }
1619d2f85d09SJose M Monsalve Diaz 
162029df4ab3SShilei Tian int32_t __tgt_rtl_create_event(int32_t device_id, void **event) {
162129df4ab3SShilei Tian   assert(event && "event is nullptr");
162229df4ab3SShilei Tian   return createEvent(event);
162329df4ab3SShilei Tian }
162429df4ab3SShilei Tian 
162529df4ab3SShilei Tian int32_t __tgt_rtl_record_event(int32_t device_id, void *event_ptr,
162629df4ab3SShilei Tian                                __tgt_async_info *async_info_ptr) {
162729df4ab3SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
162829df4ab3SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
162929df4ab3SShilei Tian   assert(event_ptr && "event_ptr is nullptr");
163029df4ab3SShilei Tian 
163129df4ab3SShilei Tian   return recordEvent(event_ptr, async_info_ptr);
163229df4ab3SShilei Tian }
163329df4ab3SShilei Tian 
163429df4ab3SShilei Tian int32_t __tgt_rtl_wait_event(int32_t device_id, void *event_ptr,
163529df4ab3SShilei Tian                              __tgt_async_info *async_info_ptr) {
163629df4ab3SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
163729df4ab3SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
163829df4ab3SShilei Tian   assert(event_ptr && "event is nullptr");
163929df4ab3SShilei Tian 
164029df4ab3SShilei Tian   return DeviceRTL.waitEvent(device_id, async_info_ptr, event_ptr);
164129df4ab3SShilei Tian }
164229df4ab3SShilei Tian 
164329df4ab3SShilei Tian int32_t __tgt_rtl_sync_event(int32_t device_id, void *event_ptr) {
164429df4ab3SShilei Tian   assert(event_ptr && "event is nullptr");
164529df4ab3SShilei Tian 
164629df4ab3SShilei Tian   return syncEvent(event_ptr);
164729df4ab3SShilei Tian }
164829df4ab3SShilei Tian 
164929df4ab3SShilei Tian int32_t __tgt_rtl_destroy_event(int32_t device_id, void *event_ptr) {
165029df4ab3SShilei Tian   assert(event_ptr && "event is nullptr");
165129df4ab3SShilei Tian 
165229df4ab3SShilei Tian   return destroyEvent(event_ptr);
165329df4ab3SShilei Tian }
165429df4ab3SShilei Tian 
16553de4cd12SGeorge Rokos #ifdef __cplusplus
16563de4cd12SGeorge Rokos }
16573de4cd12SGeorge Rokos #endif
1658