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;
104e1c7a46dSGuansong Zhang };
105e1c7a46dSGuansong Zhang 
106feed674dSShilei Tian namespace {
107feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
108feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
109feed674dSShilei Tian     return true;
110feed674dSShilei Tian 
1112ce16810SJoseph Huber   REPORT("%s", ErrMsg);
112feed674dSShilei Tian   CUDA_ERR_STRING(Err);
113feed674dSShilei Tian   return false;
114feed674dSShilei Tian }
1154031bb98SShilei Tian 
116a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
117a014fbbcSShilei Tian                CUstream Stream) {
11895f0d1edSJon Chesterfield   CUresult Err =
11995f0d1edSJon Chesterfield       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
120a014fbbcSShilei Tian 
121a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
12229338459SJoseph Huber     DP("Error when copying data from device to device. Pointers: src "
123a014fbbcSShilei Tian        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
124a014fbbcSShilei Tian        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
125a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
126a014fbbcSShilei Tian     return OFFLOAD_FAIL;
127a014fbbcSShilei Tian   }
128a014fbbcSShilei Tian 
129a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
130a014fbbcSShilei Tian }
131a014fbbcSShilei Tian 
1324031bb98SShilei Tian // Structure contains per-device data
1334031bb98SShilei Tian struct DeviceDataTy {
1345272d29eSJohannes Doerfert   /// List that contains all the kernels.
1355272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1365272d29eSJohannes Doerfert 
1374031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1385272d29eSJohannes Doerfert 
1394031bb98SShilei Tian   CUcontext Context = nullptr;
1404031bb98SShilei Tian   // Device properties
1414031bb98SShilei Tian   int ThreadsPerBlock = 0;
1424031bb98SShilei Tian   int BlocksPerGrid = 0;
1434031bb98SShilei Tian   int WarpSize = 0;
1444031bb98SShilei Tian   // OpenMP properties
1454031bb98SShilei Tian   int NumTeams = 0;
1464031bb98SShilei Tian   int NumThreads = 0;
1474031bb98SShilei Tian };
148feed674dSShilei Tian 
149feed674dSShilei Tian class StreamManagerTy {
150feed674dSShilei Tian   int NumberOfDevices;
1514031bb98SShilei Tian   // The initial size of stream pool
1524031bb98SShilei Tian   int EnvNumInitialStreams;
153feed674dSShilei Tian   // Per-device stream mutex
154feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
155feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
156feed674dSShilei Tian   std::vector<int> NextStreamId;
157feed674dSShilei Tian   // Per-device stream pool
158feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
1594031bb98SShilei Tian   // Reference to per-device data
1604031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
161feed674dSShilei Tian 
162feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
163feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
164feed674dSShilei Tian   // and we do not resize to smaller one.
165feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
166feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
167feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
168feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
169feed674dSShilei Tian 
1704031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1714031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
172feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
173feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
174feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
175feed674dSShilei Tian       // nullptr.
176feed674dSShilei Tian       return;
177feed674dSShilei Tian     }
178feed674dSShilei Tian 
1794031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
1804031bb98SShilei Tian 
181feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
1824031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
1834031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
184feed674dSShilei Tian     }
185feed674dSShilei Tian   }
186feed674dSShilei Tian 
187feed674dSShilei Tian public:
1884031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
1894031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
1904031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
1914031bb98SShilei Tian         DeviceData(DeviceData) {
192feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
193feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
194feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
195feed674dSShilei Tian 
1964031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
1974031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
198feed674dSShilei Tian 
199feed674dSShilei Tian     // Initialize the next stream id
200feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
201feed674dSShilei Tian 
202feed674dSShilei Tian     // Initialize stream mutex
203feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
204feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
205feed674dSShilei Tian   }
206feed674dSShilei Tian 
207feed674dSShilei Tian   ~StreamManagerTy() {
208feed674dSShilei Tian     // Destroy streams
209feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
2104031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
2114031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
212feed674dSShilei Tian 
213feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
2144031bb98SShilei Tian         if (S)
21595f0d1edSJon Chesterfield           checkResult(cuStreamDestroy(S),
21695f0d1edSJon Chesterfield                       "Error returned from cuStreamDestroy\n");
217feed674dSShilei Tian       }
218feed674dSShilei Tian     }
219feed674dSShilei Tian   }
220feed674dSShilei Tian 
221feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
222feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
223feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
224feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
225feed674dSShilei Tian   // the id will increase one.
226feed674dSShilei Tian   // xxxxxs+++++++++
227feed674dSShilei Tian   //      ^
228feed674dSShilei Tian   //      id
229feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
230feed674dSShilei Tian   // xxxxxs+++++++++
231feed674dSShilei Tian   //       ^
232feed674dSShilei Tian   //       id
233feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
234feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
235feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
236feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
237ad94fce8SJohannes Doerfert     if (Id == static_cast<int>(StreamPool[DeviceId].size())) {
238feed674dSShilei Tian       // By default we double the stream pool every time
239feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
240feed674dSShilei Tian     }
241feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
242feed674dSShilei Tian   }
243feed674dSShilei Tian 
244feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
245feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
246feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
247feed674dSShilei Tian   // back.
248feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
249feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
250feed674dSShilei Tian   // two identical CUstreams.
251feed674dSShilei Tian   // xxax+a+++++
252feed674dSShilei Tian   //     ^
253feed674dSShilei Tian   //     id
254feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
255feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
256feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
257feed674dSShilei Tian   // from its initial state.
258feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
259feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
260feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
261feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
262feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
263feed674dSShilei Tian   }
264feed674dSShilei Tian 
2654031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
2664031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
2674031bb98SShilei Tian 
2684031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
2694031bb98SShilei Tian 
2704031bb98SShilei Tian     // Check the size of stream pool
271ad94fce8SJohannes Doerfert     if (static_cast<int>(StreamPool[DeviceId].size()) != EnvNumInitialStreams)
2724031bb98SShilei Tian       return false;
2734031bb98SShilei Tian 
2744031bb98SShilei Tian     // Check whether each stream is valid
2754031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
2764031bb98SShilei Tian       if (!S)
2774031bb98SShilei Tian         return false;
2784031bb98SShilei Tian 
2794031bb98SShilei Tian     return true;
280feed674dSShilei Tian   }
281feed674dSShilei Tian };
282feed674dSShilei Tian 
2834031bb98SShilei Tian class DeviceRTLTy {
2843de4cd12SGeorge Rokos   int NumberOfDevices;
2854031bb98SShilei Tian   // OpenMP environment properties
2863de4cd12SGeorge Rokos   int EnvNumTeams;
2873de4cd12SGeorge Rokos   int EnvTeamLimit;
288422adaa8SJoseph Huber   int EnvTeamThreadLimit;
2894031bb98SShilei Tian   // OpenMP requires flags
290c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
291c5fe030cSGheorghe-Teodor Bercea 
2924031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
2934031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
2944031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
2954031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2963de4cd12SGeorge Rokos 
2974031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
2984031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
2994031bb98SShilei Tian   std::vector<CUmodule> Modules;
300feed674dSShilei Tian 
3010871d6d5SShilei Tian   /// A class responsible for interacting with device native runtime library to
3020871d6d5SShilei Tian   /// allocate and free memory.
3030871d6d5SShilei Tian   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
3040871d6d5SShilei Tian     const int DeviceId;
3050871d6d5SShilei Tian     const std::vector<DeviceDataTy> &DeviceData;
306a15f8589SJoseph Huber     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
3070871d6d5SShilei Tian 
3080871d6d5SShilei Tian   public:
3090871d6d5SShilei Tian     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
3100871d6d5SShilei Tian         : DeviceId(DeviceId), DeviceData(DeviceData) {}
3110871d6d5SShilei Tian 
312a15f8589SJoseph Huber     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
3130871d6d5SShilei Tian       if (Size == 0)
3140871d6d5SShilei Tian         return nullptr;
3150871d6d5SShilei Tian 
3160871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
3170871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
3180871d6d5SShilei Tian         return nullptr;
3190871d6d5SShilei Tian 
320a15f8589SJoseph Huber       void *MemAlloc = nullptr;
321a15f8589SJoseph Huber       switch (Kind) {
322a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
323a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
3240871d6d5SShilei Tian         CUdeviceptr DevicePtr;
32595f0d1edSJon Chesterfield         Err = cuMemAlloc(&DevicePtr, Size);
326a15f8589SJoseph Huber         MemAlloc = (void *)DevicePtr;
32795f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
3280871d6d5SShilei Tian           return nullptr;
329a15f8589SJoseph Huber         break;
330a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
331a15f8589SJoseph Huber         void *HostPtr;
332a15f8589SJoseph Huber         Err = cuMemAllocHost(&HostPtr, Size);
333a15f8589SJoseph Huber         MemAlloc = HostPtr;
334a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
335a15f8589SJoseph Huber           return nullptr;
336a15f8589SJoseph Huber         HostPinnedAllocs[MemAlloc] = Kind;
337a15f8589SJoseph Huber         break;
338a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
339a15f8589SJoseph Huber         CUdeviceptr SharedPtr;
340a15f8589SJoseph Huber         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
341a15f8589SJoseph Huber         MemAlloc = (void *)SharedPtr;
342a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
343a15f8589SJoseph Huber           return nullptr;
344a15f8589SJoseph Huber         break;
345a15f8589SJoseph Huber       }
3460871d6d5SShilei Tian 
347a15f8589SJoseph Huber       return MemAlloc;
3480871d6d5SShilei Tian     }
3490871d6d5SShilei Tian 
3500871d6d5SShilei Tian     int free(void *TgtPtr) override {
3510871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
3520871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
3530871d6d5SShilei Tian         return OFFLOAD_FAIL;
3540871d6d5SShilei Tian 
355a15f8589SJoseph Huber       // Host pinned memory must be freed differently.
356a15f8589SJoseph Huber       TargetAllocTy Kind =
357a15f8589SJoseph Huber           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
358a15f8589SJoseph Huber               ? TARGET_ALLOC_DEFAULT
359a15f8589SJoseph Huber               : TARGET_ALLOC_HOST;
360a15f8589SJoseph Huber       switch (Kind) {
361a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
362a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
363a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
36495f0d1edSJon Chesterfield         Err = cuMemFree((CUdeviceptr)TgtPtr);
36595f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemFree\n"))
3660871d6d5SShilei Tian           return OFFLOAD_FAIL;
367a15f8589SJoseph Huber         break;
368a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
369a15f8589SJoseph Huber         Err = cuMemFreeHost(TgtPtr);
370a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
371a15f8589SJoseph Huber           return OFFLOAD_FAIL;
372a15f8589SJoseph Huber         break;
373a15f8589SJoseph Huber       }
3740871d6d5SShilei Tian 
3750871d6d5SShilei Tian       return OFFLOAD_SUCCESS;
3760871d6d5SShilei Tian     }
3770871d6d5SShilei Tian   };
3780871d6d5SShilei Tian 
3790871d6d5SShilei Tian   /// A vector of device allocators
3800871d6d5SShilei Tian   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
3810871d6d5SShilei Tian 
3820871d6d5SShilei Tian   /// A vector of memory managers. Since the memory manager is non-copyable and
3830871d6d5SShilei Tian   // non-removable, we wrap them into std::unique_ptr.
3840871d6d5SShilei Tian   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
3850871d6d5SShilei Tian 
3860871d6d5SShilei Tian   /// Whether use memory manager
3870871d6d5SShilei Tian   bool UseMemoryManager = true;
3880871d6d5SShilei Tian 
3893de4cd12SGeorge Rokos   // Record entry point associated with device
3904031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
3914031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3923de4cd12SGeorge Rokos     E.Entries.push_back(entry);
3933de4cd12SGeorge Rokos   }
3943de4cd12SGeorge Rokos 
395ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
396ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
397ae209397SJoseph Huber                                              const void *Addr) const {
3984031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
3994031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
4004031bb98SShilei Tian       if (Itr.addr == Addr)
401ae209397SJoseph Huber         return &Itr;
4023de4cd12SGeorge Rokos 
403ae209397SJoseph Huber     return nullptr;
4043de4cd12SGeorge Rokos   }
4053de4cd12SGeorge Rokos 
4063de4cd12SGeorge Rokos   // Return the pointer to the target entries table
4074031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
4084031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4093de4cd12SGeorge Rokos 
4104031bb98SShilei Tian     if (E.Entries.empty())
4114031bb98SShilei Tian       return nullptr;
4123de4cd12SGeorge Rokos 
4133de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
4144031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
4154031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
4163de4cd12SGeorge Rokos 
4173de4cd12SGeorge Rokos     return &E.Table;
4183de4cd12SGeorge Rokos   }
4193de4cd12SGeorge Rokos 
4203de4cd12SGeorge Rokos   // Clear entries table for a device
4214031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
4224031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
4234031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4243de4cd12SGeorge Rokos     E.Entries.clear();
4254031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
4263de4cd12SGeorge Rokos   }
4273de4cd12SGeorge Rokos 
4285449fbb5SJohannes Doerfert   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
4295449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
4304031bb98SShilei Tian 
4315449fbb5SJohannes Doerfert     if (!AsyncInfo->Queue)
4325449fbb5SJohannes Doerfert       AsyncInfo->Queue = StreamManager->getStream(DeviceId);
4334031bb98SShilei Tian 
4345449fbb5SJohannes Doerfert     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
435b305d26bSSergey Dmitriev   }
4364031bb98SShilei Tian 
4374031bb98SShilei Tian public:
4384031bb98SShilei Tian   // This class should not be copied
4394031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
4404031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
4414031bb98SShilei Tian 
4424031bb98SShilei Tian   DeviceRTLTy()
4434031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
444422adaa8SJoseph Huber         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED) {
445b305d26bSSergey Dmitriev 
4463de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
4473de4cd12SGeorge Rokos 
4484031bb98SShilei Tian     CUresult Err = cuInit(0);
4497baff00eSJon Chesterfield     if (Err == CUDA_ERROR_INVALID_HANDLE) {
4507baff00eSJon Chesterfield       // Can't call cuGetErrorString if dlsym failed
4517baff00eSJon Chesterfield       DP("Failed to load CUDA shared library\n");
4527baff00eSJon Chesterfield       return;
4537baff00eSJon Chesterfield     }
4544031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
4553de4cd12SGeorge Rokos       return;
4563de4cd12SGeorge Rokos     }
4573de4cd12SGeorge Rokos 
4584031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
4594031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
4603de4cd12SGeorge Rokos       return;
4613de4cd12SGeorge Rokos 
4623de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
4633de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
4643de4cd12SGeorge Rokos       return;
4653de4cd12SGeorge Rokos     }
4663de4cd12SGeorge Rokos 
4674031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
4683de4cd12SGeorge Rokos 
4693de4cd12SGeorge Rokos     // Get environment variables regarding teams
4704031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
4713de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
4724031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
4733de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
4743de4cd12SGeorge Rokos     }
475422adaa8SJoseph Huber     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
476422adaa8SJoseph Huber       // OMP_TEAMS_THREAD_LIMIT has been set
477422adaa8SJoseph Huber       EnvTeamThreadLimit = std::stoi(EnvStr);
478422adaa8SJoseph Huber       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
479422adaa8SJoseph Huber     }
4804031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
4813de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
4824031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
4833de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
4843de4cd12SGeorge Rokos     }
485c5fe030cSGheorghe-Teodor Bercea 
486feed674dSShilei Tian     StreamManager =
4874031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
4880871d6d5SShilei Tian 
4890871d6d5SShilei Tian     for (int I = 0; I < NumberOfDevices; ++I)
4900871d6d5SShilei Tian       DeviceAllocators.emplace_back(I, DeviceData);
4910871d6d5SShilei Tian 
4920871d6d5SShilei Tian     // Get the size threshold from environment variable
4930871d6d5SShilei Tian     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
4940871d6d5SShilei Tian     UseMemoryManager = Res.second;
4950871d6d5SShilei Tian     size_t MemoryManagerThreshold = Res.first;
4960871d6d5SShilei Tian 
4970871d6d5SShilei Tian     if (UseMemoryManager)
4980871d6d5SShilei Tian       for (int I = 0; I < NumberOfDevices; ++I)
4990871d6d5SShilei Tian         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
5000871d6d5SShilei Tian             DeviceAllocators[I], MemoryManagerThreshold));
5013de4cd12SGeorge Rokos   }
5023de4cd12SGeorge Rokos 
5034031bb98SShilei Tian   ~DeviceRTLTy() {
5040871d6d5SShilei Tian     // We first destruct memory managers in case that its dependent data are
5050871d6d5SShilei Tian     // destroyed before it.
5060871d6d5SShilei Tian     for (auto &M : MemoryManagers)
5070871d6d5SShilei Tian       M.release();
5080871d6d5SShilei Tian 
509feed674dSShilei Tian     StreamManager = nullptr;
510feed674dSShilei Tian 
5114031bb98SShilei Tian     for (CUmodule &M : Modules)
5124031bb98SShilei Tian       // Close module
5134031bb98SShilei Tian       if (M)
5144031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
5154031bb98SShilei Tian 
5164031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
5174031bb98SShilei Tian       // Destroy context
518c5348aecSYe Luo       if (D.Context) {
519c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
520c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
521c5348aecSYe Luo         CUdevice Device;
522c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
523c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
52495f0d1edSJon Chesterfield         checkResult(cuDevicePrimaryCtxRelease(Device),
52595f0d1edSJon Chesterfield                     "Error returned from cuDevicePrimaryCtxRelease\n");
526c5348aecSYe Luo       }
5273de4cd12SGeorge Rokos     }
5283de4cd12SGeorge Rokos   }
5293de4cd12SGeorge Rokos 
5304031bb98SShilei Tian   // Check whether a given DeviceId is valid
5314031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
5324031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
53332ed2927SShilei Tian   }
53432ed2927SShilei Tian 
535cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
5364031bb98SShilei Tian 
5374031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
5384031bb98SShilei Tian 
5394031bb98SShilei Tian   int initDevice(const int DeviceId) {
5404031bb98SShilei Tian     CUdevice Device;
5414031bb98SShilei Tian 
5424031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
5434031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
5444031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
54532ed2927SShilei Tian       return OFFLOAD_FAIL;
5463de4cd12SGeorge Rokos 
547c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
548c5348aecSYe Luo     // it is inactive
549c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
550c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
551c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
552c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
553c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
554c5348aecSYe Luo       return OFFLOAD_FAIL;
555c5348aecSYe Luo 
556c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
557c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
558c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
559c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
560c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
561c5348aecSYe Luo     } else {
562c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
563c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
56495f0d1edSJon Chesterfield       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
56595f0d1edSJon Chesterfield       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
566c5348aecSYe Luo         return OFFLOAD_FAIL;
567c5348aecSYe Luo     }
568c5348aecSYe Luo 
569c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
570c5348aecSYe Luo     // device is selected.
571c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
572c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
5733de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
5743de4cd12SGeorge Rokos 
5754031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
5764031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
5774031bb98SShilei Tian       return OFFLOAD_FAIL;
578a5153dbcSJohannes Doerfert 
579feed674dSShilei Tian     // Initialize stream pool
5804031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
5814031bb98SShilei Tian       return OFFLOAD_FAIL;
582a5153dbcSJohannes Doerfert 
583bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
5844031bb98SShilei Tian     int MaxGridDimX;
5854031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
5864031bb98SShilei Tian                                Device);
5874031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5884031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
5894031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5904031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
5914031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
5924031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
5934031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
5943de4cd12SGeorge Rokos     } else {
5953de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
596bb51d398SJonas Hahnfeld          "at the hard limit\n",
5974031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
5984031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
5993de4cd12SGeorge Rokos     }
6003de4cd12SGeorge Rokos 
601bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
6024031bb98SShilei Tian     int MaxBlockDimX;
6034031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
6044031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
6054031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6064031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
6074031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
6084031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
609422adaa8SJoseph Huber     } else {
6104031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
6114031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
612422adaa8SJoseph Huber 
613422adaa8SJoseph Huber       if (EnvTeamThreadLimit > 0 &&
614422adaa8SJoseph Huber           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
615422adaa8SJoseph Huber         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
616422adaa8SJoseph Huber            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
617422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
618422adaa8SJoseph Huber         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
619422adaa8SJoseph Huber       }
620422adaa8SJoseph Huber       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
6214031bb98SShilei Tian         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
6224031bb98SShilei Tian            "capping at the hard limit\n",
623422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
6244031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
6253de4cd12SGeorge Rokos       }
626422adaa8SJoseph Huber     }
6273de4cd12SGeorge Rokos 
6284031bb98SShilei Tian     // Get and set warp size
6294031bb98SShilei Tian     int WarpSize;
6304031bb98SShilei Tian     Err =
6314031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
6324031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6334031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
6344031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
635bb51d398SJonas Hahnfeld     } else {
6364031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
6374031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
6383de4cd12SGeorge Rokos     }
6393de4cd12SGeorge Rokos 
6403de4cd12SGeorge Rokos     // Adjust teams to the env variables
6414031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
6423de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
6434031bb98SShilei Tian          EnvTeamLimit);
6444031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
6453de4cd12SGeorge Rokos     }
6463de4cd12SGeorge Rokos 
6473817ba13SJoseph Huber     size_t StackLimit;
6483817ba13SJoseph Huber     size_t HeapLimit;
6493817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
6503817ba13SJoseph Huber       StackLimit = std::stol(EnvStr);
6513817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
6523817ba13SJoseph Huber         return OFFLOAD_FAIL;
6533817ba13SJoseph Huber     } else {
6543817ba13SJoseph Huber       if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
6553817ba13SJoseph Huber         return OFFLOAD_FAIL;
6563817ba13SJoseph Huber     }
6573817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
6583817ba13SJoseph Huber       HeapLimit = std::stol(EnvStr);
6593817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
6603817ba13SJoseph Huber         return OFFLOAD_FAIL;
6613817ba13SJoseph Huber     } else {
6623817ba13SJoseph Huber       if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
6633817ba13SJoseph Huber         return OFFLOAD_FAIL;
6643817ba13SJoseph Huber     }
6653817ba13SJoseph Huber 
666119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
667ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
668ae209397SJoseph Huber          "warp size of %d\n",
669ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
670ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
6713817ba13SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
6723817ba13SJoseph Huber          "Device heap size is %d Bytes, device stack size is %d Bytes per "
6733817ba13SJoseph Huber          "thread\n",
6743817ba13SJoseph Huber          (int)HeapLimit, (int)StackLimit);
6753de4cd12SGeorge Rokos 
6763de4cd12SGeorge Rokos     // Set default number of teams
6774031bb98SShilei Tian     if (EnvNumTeams > 0) {
6783de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
6794031bb98SShilei Tian          EnvNumTeams);
6804031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
6813de4cd12SGeorge Rokos     } else {
6824031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
6833de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
6844031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
6853de4cd12SGeorge Rokos     }
6864031bb98SShilei Tian 
6874031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
6883de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
6894031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
6904031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
6913de4cd12SGeorge Rokos     }
6923de4cd12SGeorge Rokos 
6933de4cd12SGeorge Rokos     // Set default number of threads
6944031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
6953de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
6964031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
6974031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
6984031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
6993de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
7004031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
7014031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
7023de4cd12SGeorge Rokos     }
7033de4cd12SGeorge Rokos 
7043de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7053de4cd12SGeorge Rokos   }
7063de4cd12SGeorge Rokos 
7074031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
7084031bb98SShilei Tian                                  const __tgt_device_image *Image) {
7094031bb98SShilei Tian     // Set the context we are using
7104031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7114031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7124031bb98SShilei Tian       return nullptr;
7133de4cd12SGeorge Rokos 
7143de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
7154031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
7163de4cd12SGeorge Rokos 
7173de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
7184031bb98SShilei Tian     CUmodule Module;
7194031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
7204031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
7214031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
7224031bb98SShilei Tian       return nullptr;
7233de4cd12SGeorge Rokos 
7243de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
7254031bb98SShilei Tian 
7264031bb98SShilei Tian     Modules.push_back(Module);
7273de4cd12SGeorge Rokos 
7283de4cd12SGeorge Rokos     // Find the symbols in the module by name.
7294031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
7304031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
7313de4cd12SGeorge Rokos 
7325272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
7334031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
7344031bb98SShilei Tian       if (!E->addr) {
7354031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
7364031bb98SShilei Tian         // have always something in the address to uniquely identify the target
7374031bb98SShilei Tian         // region.
7384031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
7394031bb98SShilei Tian         return nullptr;
7403de4cd12SGeorge Rokos       }
7413de4cd12SGeorge Rokos 
7424031bb98SShilei Tian       if (E->size) {
7434031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
7444031bb98SShilei Tian         CUdeviceptr CUPtr;
7454031bb98SShilei Tian         size_t CUSize;
74695f0d1edSJon Chesterfield         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
7474031bb98SShilei Tian         // We keep this style here because we need the name
7484031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
7492ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
7504031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7514031bb98SShilei Tian           return nullptr;
7523de4cd12SGeorge Rokos         }
7533de4cd12SGeorge Rokos 
7544031bb98SShilei Tian         if (CUSize != E->size) {
7554031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
7564031bb98SShilei Tian              CUSize, E->size);
7574031bb98SShilei Tian           return nullptr;
7583de4cd12SGeorge Rokos         }
7593de4cd12SGeorge Rokos 
7603de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
7614031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
7624031bb98SShilei Tian 
7634031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
7643de4cd12SGeorge Rokos 
765aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
766aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
767aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
768aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
769aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
7704c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
771aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
7724031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
7734031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
7744031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
775aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
776c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
777c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
77895f0d1edSJon Chesterfield           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
7794031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
7804031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
7814031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
782c5fe030cSGheorghe-Teodor Bercea         }
783c5fe030cSGheorghe-Teodor Bercea 
7844031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
7853de4cd12SGeorge Rokos 
7863de4cd12SGeorge Rokos         continue;
7873de4cd12SGeorge Rokos       }
7883de4cd12SGeorge Rokos 
7894031bb98SShilei Tian       CUfunction Func;
7904031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
7914031bb98SShilei Tian       // We keep this style here because we need the name
7924031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
7932ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
7944031bb98SShilei Tian         CUDA_ERR_STRING(Err);
7954031bb98SShilei Tian         return nullptr;
7963de4cd12SGeorge Rokos       }
7973de4cd12SGeorge Rokos 
7983de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
7994031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
8003de4cd12SGeorge Rokos 
8013de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
8023de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
8034031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
8043de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
8053de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
8063de4cd12SGeorge Rokos 
8073de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
8084031bb98SShilei Tian       size_t CUSize;
80995f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
8104031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
8114031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
8123de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
8134031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
8144031bb98SShilei Tian           return nullptr;
8153de4cd12SGeorge Rokos         }
8163de4cd12SGeorge Rokos 
81795f0d1edSJon Chesterfield         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
8184031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8192ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
8203de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
8214031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
8224031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8234031bb98SShilei Tian           return nullptr;
8243de4cd12SGeorge Rokos         }
8253de4cd12SGeorge Rokos 
8267d576392SJoseph Huber         if (ExecModeVal < 0 || ExecModeVal > 2) {
8273de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
8283de4cd12SGeorge Rokos              ExecModeVal);
8294031bb98SShilei Tian           return nullptr;
8303de4cd12SGeorge Rokos         }
8313de4cd12SGeorge Rokos       } else {
832*edb8acdcSJoseph Huber         DP("Loading global exec_mode '%s' - symbol missing, using default "
8334031bb98SShilei Tian            "value GENERIC (1)\n",
8344031bb98SShilei Tian            ExecModeName);
8353de4cd12SGeorge Rokos       }
8363de4cd12SGeorge Rokos 
8374031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
8383de4cd12SGeorge Rokos 
8394031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
8404031bb98SShilei Tian       Entry.addr = &KernelsList.back();
8414031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
8423de4cd12SGeorge Rokos     }
8433de4cd12SGeorge Rokos 
844e1c7a46dSGuansong Zhang     // send device environment data to the device
845e1c7a46dSGuansong Zhang     {
8464031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
847e1c7a46dSGuansong Zhang 
848e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
8494031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
8504031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
851e1c7a46dSGuansong Zhang #endif
852e1c7a46dSGuansong Zhang 
8534031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
8544031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
8554031bb98SShilei Tian       size_t CUSize;
856e1c7a46dSGuansong Zhang 
85795f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
8584031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
8594031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
8602ce16810SJoseph Huber           REPORT(
8612ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
8624031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
8634031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8644031bb98SShilei Tian           return nullptr;
865e1c7a46dSGuansong Zhang         }
866e1c7a46dSGuansong Zhang 
86795f0d1edSJon Chesterfield         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
8684031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8692ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
870e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
8714031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
8724031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8734031bb98SShilei Tian           return nullptr;
874e1c7a46dSGuansong Zhang         }
875e1c7a46dSGuansong Zhang 
8764031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
877e1c7a46dSGuansong Zhang       } else {
8784031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
8794031bb98SShilei Tian            DeviceEnvName);
8804031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
8814031bb98SShilei Tian            "environment setting.\n");
882e1c7a46dSGuansong Zhang       }
883e1c7a46dSGuansong Zhang     }
884e1c7a46dSGuansong Zhang 
8854031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
8863de4cd12SGeorge Rokos   }
8873de4cd12SGeorge Rokos 
888a15f8589SJoseph Huber   void *dataAlloc(const int DeviceId, const int64_t Size,
889a15f8589SJoseph Huber                   const TargetAllocTy Kind) {
890a15f8589SJoseph Huber     switch (Kind) {
891a15f8589SJoseph Huber     case TARGET_ALLOC_DEFAULT:
892a15f8589SJoseph Huber     case TARGET_ALLOC_DEVICE:
8930871d6d5SShilei Tian       if (UseMemoryManager)
8940871d6d5SShilei Tian         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
895a15f8589SJoseph Huber       else
896a15f8589SJoseph Huber         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
897a15f8589SJoseph Huber     case TARGET_ALLOC_HOST:
898a15f8589SJoseph Huber     case TARGET_ALLOC_SHARED:
899a15f8589SJoseph Huber       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
900a15f8589SJoseph Huber     }
9014031bb98SShilei Tian 
902a15f8589SJoseph Huber     REPORT("Invalid target data allocation kind or requested allocator not "
903a15f8589SJoseph Huber            "implemented yet\n");
904a15f8589SJoseph Huber 
905a15f8589SJoseph Huber     return nullptr;
9063de4cd12SGeorge Rokos   }
9073de4cd12SGeorge Rokos 
9084031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
9095449fbb5SJohannes Doerfert                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
9105449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9113de4cd12SGeorge Rokos 
9124031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9134031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
9143de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9153de4cd12SGeorge Rokos 
9165449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
9173de4cd12SGeorge Rokos 
91895f0d1edSJon Chesterfield     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
9194031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
92029338459SJoseph Huber       DP("Error when copying data from host to device. Pointers: host "
9212ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9224031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9234031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9243de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9253de4cd12SGeorge Rokos     }
9263de4cd12SGeorge Rokos 
9273de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9283de4cd12SGeorge Rokos   }
9293de4cd12SGeorge Rokos 
9304031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
9315449fbb5SJohannes Doerfert                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
9325449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9334031bb98SShilei Tian 
9344031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9354031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
93603ff643dSShilei Tian       return OFFLOAD_FAIL;
93703ff643dSShilei Tian 
9385449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
93903ff643dSShilei Tian 
94095f0d1edSJon Chesterfield     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
9414031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
94229338459SJoseph Huber       DP("Error when copying data from device to host. Pointers: host "
9432ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9444031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9454031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9463de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9473de4cd12SGeorge Rokos     }
9483de4cd12SGeorge Rokos 
9494031bb98SShilei Tian     return OFFLOAD_SUCCESS;
9504031bb98SShilei Tian   }
9514031bb98SShilei Tian 
952a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
9535449fbb5SJohannes Doerfert                    int64_t Size, __tgt_async_info *AsyncInfo) const {
9545449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
955a014fbbcSShilei Tian 
956a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
957a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
958a014fbbcSShilei Tian       return OFFLOAD_FAIL;
959a014fbbcSShilei Tian 
9605449fbb5SJohannes Doerfert     CUstream Stream = getStream(SrcDevId, AsyncInfo);
961a014fbbcSShilei Tian 
962a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
963a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
964a014fbbcSShilei Tian       int CanAccessPeer = 0;
965a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
966a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9672ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
968a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
969a014fbbcSShilei Tian                SrcDevId, DstDevId);
970a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
971a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
972a014fbbcSShilei Tian       }
973a014fbbcSShilei Tian 
974a014fbbcSShilei Tian       if (!CanAccessPeer) {
975a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
976a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
977a014fbbcSShilei Tian       }
978a014fbbcSShilei Tian 
979a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
980a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9812ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
982a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
983a014fbbcSShilei Tian                SrcDevId, DstDevId);
984a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
985a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
986a014fbbcSShilei Tian       }
987a014fbbcSShilei Tian 
988a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
989a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
990a014fbbcSShilei Tian                               Size, Stream);
991a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
992a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
993a014fbbcSShilei Tian 
99429338459SJoseph Huber       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
99529338459SJoseph Huber          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
99645bb073dSYe Luo          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
997a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
998a014fbbcSShilei Tian     }
999a014fbbcSShilei Tian 
1000a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1001a014fbbcSShilei Tian   }
1002a014fbbcSShilei Tian 
10030871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
10040871d6d5SShilei Tian     if (UseMemoryManager)
10050871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
10064031bb98SShilei Tian 
10070871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
10084031bb98SShilei Tian   }
10094031bb98SShilei Tian 
1010aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1011aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
1012aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
10134031bb98SShilei Tian                           const unsigned int LoopTripCount,
10144031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
10154031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
10164031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
10174031bb98SShilei Tian       return OFFLOAD_FAIL;
10184031bb98SShilei Tian 
10193de4cd12SGeorge Rokos     // All args are references.
10204031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
10214031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
10223de4cd12SGeorge Rokos 
10234031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
10244031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
10254031bb98SShilei Tian       Args[I] = &Ptrs[I];
10261546d319SGeorge Rokos     }
10273de4cd12SGeorge Rokos 
1028aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
10293de4cd12SGeorge Rokos 
1030aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
10314031bb98SShilei Tian     if (ThreadLimit > 0) {
10324031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
10334031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
10343de4cd12SGeorge Rokos       // Add master warp if necessary
10353de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
10364031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
10374031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
10383de4cd12SGeorge Rokos       }
1039c13df8e5SGeorge Rokos     } else {
1040c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
10414031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
10424031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1043c13df8e5SGeorge Rokos     }
10443de4cd12SGeorge Rokos 
10454031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
10463de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
10474031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
10484031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
10493de4cd12SGeorge Rokos     }
10503de4cd12SGeorge Rokos 
1051aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
1052aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
10534031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
10544031bb98SShilei Tian                                KernelInfo->Func);
1055aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1056aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
1057aa27cfc1SJohannes Doerfert     }
1058aa27cfc1SJohannes Doerfert 
1059aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1060aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
1061aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
1062aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
10633de4cd12SGeorge Rokos     }
10643de4cd12SGeorge Rokos 
10654031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
10664031bb98SShilei Tian     if (TeamNum <= 0) {
10674031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1068c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
10694031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
10704031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
10714031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
10724031bb98SShilei Tian           // integer
10734031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
10747d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == GENERIC) {
1075c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
1076c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
1077c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
1078c13df8e5SGeorge Rokos           //
1079c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
1080c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
1081c13df8e5SGeorge Rokos           //   #pragma omp parallel for
1082c13df8e5SGeorge Rokos           //   for(...) {}
1083c13df8e5SGeorge Rokos           // }
1084c13df8e5SGeorge Rokos           //
1085c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
1086c13df8e5SGeorge Rokos           // loop.
10874031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
10887d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == SPMD_GENERIC) {
10897d576392SJoseph Huber           // If we reach this point, then we are executing a kernel that was
10907d576392SJoseph Huber           // transformed from Generic-mode to SPMD-mode. This kernel has
10917d576392SJoseph Huber           // SPMD-mode execution, but needs its blocks to be scheduled
10927d576392SJoseph Huber           // differently because the current loop trip count only applies to the
10937d576392SJoseph Huber           // `teams distribute` region and will create var too few blocks using
10947d576392SJoseph Huber           // the regular SPMD-mode method.
10957d576392SJoseph Huber           CudaBlocksPerGrid = LoopTripCount;
1096a158d366SJoseph Huber         } else {
1097a158d366SJoseph Huber           REPORT("Unknown execution mode: %d\n", KernelInfo->ExecutionMode);
1098a158d366SJoseph Huber           return OFFLOAD_FAIL;
1099c13df8e5SGeorge Rokos         }
110045bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
11014031bb98SShilei Tian            " and number of threads per block %d\n",
11024031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
11033de4cd12SGeorge Rokos       } else {
11044031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
11054031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
11063de4cd12SGeorge Rokos       }
11074031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
11083de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
11094031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
11104031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
11113de4cd12SGeorge Rokos     } else {
11124031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
11134031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
11143de4cd12SGeorge Rokos     }
11153de4cd12SGeorge Rokos 
1116119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1117ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
1118ae209397SJoseph Huber          "mode\n",
1119ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1120ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1121ae209397SJoseph Huber              : "(null)",
1122ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
11237d576392SJoseph Huber          (KernelInfo->ExecutionMode != SPMD
112476c0c0caSJoseph Huber               ? (KernelInfo->ExecutionMode == GENERIC ? "Generic"
112576c0c0caSJoseph Huber                                                       : "SPMD-Generic")
11267d576392SJoseph Huber               : "SPMD"));
11273de4cd12SGeorge Rokos 
11284031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
11294031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
11304031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
11314031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
11324031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
11334031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
11344031bb98SShilei Tian       return OFFLOAD_FAIL;
11354031bb98SShilei Tian 
11364031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
11374031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
11384031bb98SShilei Tian 
11394031bb98SShilei Tian     return OFFLOAD_SUCCESS;
11404031bb98SShilei Tian   }
11414031bb98SShilei Tian 
11425449fbb5SJohannes Doerfert   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
11435449fbb5SJohannes Doerfert     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
11444031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
11453de4cd12SGeorge Rokos 
11464031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
11475449fbb5SJohannes Doerfert     // AsyncInfo. This is to make sure the synchronization only works for its
11484031bb98SShilei Tian     // own tasks.
11495449fbb5SJohannes Doerfert     StreamManager->returnStream(DeviceId,
11505449fbb5SJohannes Doerfert                                 reinterpret_cast<CUstream>(AsyncInfo->Queue));
11515449fbb5SJohannes Doerfert     AsyncInfo->Queue = nullptr;
11523de4cd12SGeorge Rokos 
115316064e71SJoseph Huber     if (Err != CUDA_SUCCESS) {
115429338459SJoseph Huber       DP("Error when synchronizing stream. stream = " DPxMOD
115516064e71SJoseph Huber          ", async info ptr = " DPxMOD "\n",
115616064e71SJoseph Huber          DPxPTR(Stream), DPxPTR(AsyncInfo));
115716064e71SJoseph Huber       CUDA_ERR_STRING(Err);
115816064e71SJoseph Huber     }
115916064e71SJoseph Huber     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
11603de4cd12SGeorge Rokos   }
1161d2f85d09SJose M Monsalve Diaz 
1162d2f85d09SJose M Monsalve Diaz   void printDeviceInfo(int32_t device_id) {
1163d2f85d09SJose M Monsalve Diaz     char TmpChar[1000];
1164d2f85d09SJose M Monsalve Diaz     std::string TmpStr;
1165d2f85d09SJose M Monsalve Diaz     size_t TmpSt;
1166d2f85d09SJose M Monsalve Diaz     int TmpInt, TmpInt2, TmpInt3;
1167d2f85d09SJose M Monsalve Diaz 
1168d2f85d09SJose M Monsalve Diaz     CUdevice Device;
1169d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGet(&Device, device_id),
1170d2f85d09SJose M Monsalve Diaz                 "Error returned from cuCtxGetDevice\n");
1171d2f85d09SJose M Monsalve Diaz 
1172d2f85d09SJose M Monsalve Diaz     cuDriverGetVersion(&TmpInt);
1173d2f85d09SJose M Monsalve Diaz     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1174d2f85d09SJose M Monsalve Diaz     printf("    CUDA Device Number: \t\t%d \n", device_id);
1175d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1176d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetName\n");
1177d2f85d09SJose M Monsalve Diaz     printf("    Device Name: \t\t\t%s \n", TmpChar);
1178d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1179d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceTotalMem\n");
1180d2f85d09SJose M Monsalve Diaz     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1181d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1182d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1183d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1184d2f85d09SJose M Monsalve Diaz     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1185d2f85d09SJose M Monsalve Diaz     checkResult(
1186d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1187d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1188d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1189d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1190d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1191d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1192d2f85d09SJose M Monsalve Diaz     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1193d2f85d09SJose M Monsalve Diaz     checkResult(
1194d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1195d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1196d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1197d2f85d09SJose M Monsalve Diaz     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
119828939b6aSShilei Tian     checkResult(
119928939b6aSShilei Tian         cuDeviceGetAttribute(
1200d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1201d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1202d2f85d09SJose M Monsalve Diaz     printf("    Registers per Block: \t\t%d \n", TmpInt);
1203d2f85d09SJose M Monsalve Diaz     checkResult(
1204d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1205d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1206d2f85d09SJose M Monsalve Diaz     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1207d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1208d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1209d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1210d2f85d09SJose M Monsalve Diaz     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
121128939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
121228939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1213d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
121428939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
121528939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1216d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
121728939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
121828939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1219d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1220d2f85d09SJose M Monsalve Diaz     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1221d2f85d09SJose M Monsalve Diaz            TmpInt3);
122228939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
122328939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1224d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
122528939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
122628939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1227d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
122828939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
122928939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1230d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1231d2f85d09SJose M Monsalve Diaz     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1232d2f85d09SJose M Monsalve Diaz            TmpInt3);
1233d2f85d09SJose M Monsalve Diaz     checkResult(
1234d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1235d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1236d2f85d09SJose M Monsalve Diaz     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1237d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1238d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1239d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1240d2f85d09SJose M Monsalve Diaz     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1241d2f85d09SJose M Monsalve Diaz     checkResult(
1242d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1243d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1244d2f85d09SJose M Monsalve Diaz     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1245d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1246d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1247d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1248d2f85d09SJose M Monsalve Diaz     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1249d2f85d09SJose M Monsalve Diaz     checkResult(
1250d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1251d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1252d2f85d09SJose M Monsalve Diaz     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1253d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1254d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1255d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1256d2f85d09SJose M Monsalve Diaz     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1257d2f85d09SJose M Monsalve Diaz     checkResult(
1258d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1259d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1260d2f85d09SJose M Monsalve Diaz     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1261d2f85d09SJose M Monsalve Diaz       TmpStr = "DEFAULT";
1262d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1263d2f85d09SJose M Monsalve Diaz       TmpStr = "PROHIBITED";
1264d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1265d2f85d09SJose M Monsalve Diaz       TmpStr = "EXCLUSIVE PROCESS";
1266d2f85d09SJose M Monsalve Diaz     else
1267d2f85d09SJose M Monsalve Diaz       TmpStr = "unknown";
1268d2f85d09SJose M Monsalve Diaz     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1269d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1270d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1271d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1272d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1273d2f85d09SJose M Monsalve Diaz     checkResult(
1274d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1275d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1276d2f85d09SJose M Monsalve Diaz     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1277d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1278d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1279d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1280d2f85d09SJose M Monsalve Diaz     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
128128939b6aSShilei Tian     checkResult(
128228939b6aSShilei Tian         cuDeviceGetAttribute(
1283d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1284d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1285d2f85d09SJose M Monsalve Diaz     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
128628939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
128728939b6aSShilei Tian                                      Device),
1288d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1289d2f85d09SJose M Monsalve Diaz     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
129028939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
129128939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
129228939b6aSShilei Tian                     Device),
1293d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1294d2f85d09SJose M Monsalve Diaz     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1295d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1296d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1297d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1298d2f85d09SJose M Monsalve Diaz     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1299d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1300d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1301d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1302d2f85d09SJose M Monsalve Diaz     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
130328939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
130428939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1305d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1306d2f85d09SJose M Monsalve Diaz     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1307d2f85d09SJose M Monsalve Diaz     checkResult(
1308d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1309d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1310d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1311d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1312d2f85d09SJose M Monsalve Diaz     checkResult(
1313d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1314d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1315d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1316d2f85d09SJose M Monsalve Diaz     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1317d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1318d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1319d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1320d2f85d09SJose M Monsalve Diaz     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
132128939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
132228939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1323d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1324d2f85d09SJose M Monsalve Diaz     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
132528939b6aSShilei Tian     checkResult(
132628939b6aSShilei Tian         cuDeviceGetAttribute(
132728939b6aSShilei Tian             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1328d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
132928939b6aSShilei Tian     checkResult(
133028939b6aSShilei Tian         cuDeviceGetAttribute(
133128939b6aSShilei Tian             &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1332d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1333d2f85d09SJose M Monsalve Diaz     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1334d2f85d09SJose M Monsalve Diaz   }
13354031bb98SShilei Tian };
13364031bb98SShilei Tian 
13374031bb98SShilei Tian DeviceRTLTy DeviceRTL;
13384031bb98SShilei Tian } // namespace
13394031bb98SShilei Tian 
13404031bb98SShilei Tian // Exposed library API function
13414031bb98SShilei Tian #ifdef __cplusplus
13424031bb98SShilei Tian extern "C" {
13434031bb98SShilei Tian #endif
13444031bb98SShilei Tian 
13454031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
13464031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
13474031bb98SShilei Tian }
13484031bb98SShilei Tian 
13494031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
13504031bb98SShilei Tian 
13514031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
135240470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
13534031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
13544031bb98SShilei Tian   return RequiresFlags;
13554031bb98SShilei Tian }
13564031bb98SShilei Tian 
1357a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1358a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1359a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1360a014fbbcSShilei Tian     return 1;
1361a014fbbcSShilei Tian 
1362a014fbbcSShilei Tian   return 0;
1363a014fbbcSShilei Tian }
1364a014fbbcSShilei Tian 
13654031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
13664031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13674031bb98SShilei Tian 
13684031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
13694031bb98SShilei Tian }
13704031bb98SShilei Tian 
13714031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
13724031bb98SShilei Tian                                           __tgt_device_image *image) {
13734031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13744031bb98SShilei Tian 
13754031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
13764031bb98SShilei Tian }
13774031bb98SShilei Tian 
13782468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
13792468fdd9SGeorge Rokos                            int32_t kind) {
13804031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13814031bb98SShilei Tian 
1382a15f8589SJoseph Huber   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
13834031bb98SShilei Tian }
13844031bb98SShilei Tian 
13854031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
13864031bb98SShilei Tian                               int64_t size) {
13874031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13884031bb98SShilei Tian 
13895449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
13904031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
13915449fbb5SJohannes Doerfert                                                  size, &AsyncInfo);
13924031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
13934031bb98SShilei Tian     return OFFLOAD_FAIL;
13944031bb98SShilei Tian 
13955449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
13964031bb98SShilei Tian }
13974031bb98SShilei Tian 
13984031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
13994031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
14004031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
14014031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14024031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
14034031bb98SShilei Tian 
14044031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
14054031bb98SShilei Tian                               async_info_ptr);
14064031bb98SShilei Tian }
14074031bb98SShilei Tian 
14084031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
14094031bb98SShilei Tian                                 int64_t size) {
14104031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14114031bb98SShilei Tian 
14125449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14134031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
14145449fbb5SJohannes Doerfert                                                    size, &AsyncInfo);
14154031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14164031bb98SShilei Tian     return OFFLOAD_FAIL;
14174031bb98SShilei Tian 
14185449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14194031bb98SShilei Tian }
14204031bb98SShilei Tian 
14214031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
14224031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
14234031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
14244031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14254031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
14264031bb98SShilei Tian 
14274031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
14284031bb98SShilei Tian                                 async_info_ptr);
14294031bb98SShilei Tian }
14304031bb98SShilei Tian 
1431a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1432a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1433a014fbbcSShilei Tian                                       int64_t size,
14345449fbb5SJohannes Doerfert                                       __tgt_async_info *AsyncInfo) {
1435a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1436a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
14375449fbb5SJohannes Doerfert   assert(AsyncInfo && "AsyncInfo is nullptr");
1438a014fbbcSShilei Tian 
1439a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
14405449fbb5SJohannes Doerfert                                 AsyncInfo);
1441a014fbbcSShilei Tian }
1442a014fbbcSShilei Tian 
1443a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1444a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1445a014fbbcSShilei Tian                                 int64_t size) {
1446a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1447a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1448a014fbbcSShilei Tian 
14495449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1450a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
14515449fbb5SJohannes Doerfert       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1452a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1453a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1454a014fbbcSShilei Tian 
14555449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1456a014fbbcSShilei Tian }
1457a014fbbcSShilei Tian 
14584031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
14594031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14604031bb98SShilei Tian 
14614031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
14624031bb98SShilei Tian }
14634031bb98SShilei Tian 
14644031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
14654031bb98SShilei Tian                                          void **tgt_args,
14664031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
14674031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
14684031bb98SShilei Tian                                          int32_t thread_limit,
14694031bb98SShilei Tian                                          uint64_t loop_tripcount) {
14704031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14714031bb98SShilei Tian 
14725449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14734031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
14744031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
14755449fbb5SJohannes Doerfert       thread_limit, loop_tripcount, &AsyncInfo);
14764031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14774031bb98SShilei Tian     return OFFLOAD_FAIL;
14784031bb98SShilei Tian 
14795449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14804031bb98SShilei Tian }
14814031bb98SShilei Tian 
14824031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
14834031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
14844031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
14854031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
14864031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
14874031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14884031bb98SShilei Tian 
14894031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
14904031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
14914031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
14924031bb98SShilei Tian }
14933de4cd12SGeorge Rokos 
14943de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
149532ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
149603ff643dSShilei Tian                                     int32_t arg_num) {
14974031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14984031bb98SShilei Tian 
14995449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
15004031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
15015449fbb5SJohannes Doerfert       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
150203ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
150303ff643dSShilei Tian     return OFFLOAD_FAIL;
150403ff643dSShilei Tian 
15055449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
150603ff643dSShilei Tian }
150703ff643dSShilei Tian 
150803ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
150903ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
151003ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
151132ed2927SShilei Tian                                           int32_t arg_num,
15124031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
15134031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15144031bb98SShilei Tian 
151503ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
15164031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
15174031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
15184031bb98SShilei Tian       async_info_ptr);
151932ed2927SShilei Tian }
152032ed2927SShilei Tian 
15214031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
15224031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
15234031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15244031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
15254031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
152632ed2927SShilei Tian 
15274031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
15283de4cd12SGeorge Rokos }
15293de4cd12SGeorge Rokos 
15302b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
153159b68490SJoseph Huber   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
15322b6f2008SJoseph Huber   InfoLevel.store(NewInfoLevel);
15332b6f2008SJoseph Huber }
15342b6f2008SJoseph Huber 
1535d2f85d09SJose M Monsalve Diaz void __tgt_rtl_print_device_info(int32_t device_id) {
1536d2f85d09SJose M Monsalve Diaz   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1537d2f85d09SJose M Monsalve Diaz   DeviceRTL.printDeviceInfo(device_id);
1538d2f85d09SJose M Monsalve Diaz }
1539d2f85d09SJose M Monsalve Diaz 
15403de4cd12SGeorge Rokos #ifdef __cplusplus
15413de4cd12SGeorge Rokos }
15423de4cd12SGeorge Rokos #endif
1543