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 
64*d2f85d09SJose M Monsalve Diaz #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
65*d2f85d09SJose 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 {
8322ce16810SJoseph Huber         REPORT("Loading global exec_mode '%s' - symbol missing, using default "
8334031bb98SShilei Tian                "value GENERIC (1)\n",
8344031bb98SShilei Tian                ExecModeName);
8354031bb98SShilei Tian         CUDA_ERR_STRING(Err);
8363de4cd12SGeorge Rokos       }
8373de4cd12SGeorge Rokos 
8384031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
8393de4cd12SGeorge Rokos 
8404031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
8414031bb98SShilei Tian       Entry.addr = &KernelsList.back();
8424031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
8433de4cd12SGeorge Rokos     }
8443de4cd12SGeorge Rokos 
845e1c7a46dSGuansong Zhang     // send device environment data to the device
846e1c7a46dSGuansong Zhang     {
8474031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
848e1c7a46dSGuansong Zhang 
849e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
8504031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
8514031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
852e1c7a46dSGuansong Zhang #endif
853e1c7a46dSGuansong Zhang 
8544031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
8554031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
8564031bb98SShilei Tian       size_t CUSize;
857e1c7a46dSGuansong Zhang 
85895f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
8594031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
8604031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
8612ce16810SJoseph Huber           REPORT(
8622ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
8634031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
8644031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8654031bb98SShilei Tian           return nullptr;
866e1c7a46dSGuansong Zhang         }
867e1c7a46dSGuansong Zhang 
86895f0d1edSJon Chesterfield         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
8694031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8702ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
871e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
8724031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
8734031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8744031bb98SShilei Tian           return nullptr;
875e1c7a46dSGuansong Zhang         }
876e1c7a46dSGuansong Zhang 
8774031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
878e1c7a46dSGuansong Zhang       } else {
8794031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
8804031bb98SShilei Tian            DeviceEnvName);
8814031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
8824031bb98SShilei Tian            "environment setting.\n");
883e1c7a46dSGuansong Zhang       }
884e1c7a46dSGuansong Zhang     }
885e1c7a46dSGuansong Zhang 
8864031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
8873de4cd12SGeorge Rokos   }
8883de4cd12SGeorge Rokos 
889a15f8589SJoseph Huber   void *dataAlloc(const int DeviceId, const int64_t Size,
890a15f8589SJoseph Huber                   const TargetAllocTy Kind) {
891a15f8589SJoseph Huber     switch (Kind) {
892a15f8589SJoseph Huber     case TARGET_ALLOC_DEFAULT:
893a15f8589SJoseph Huber     case TARGET_ALLOC_DEVICE:
8940871d6d5SShilei Tian       if (UseMemoryManager)
8950871d6d5SShilei Tian         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
896a15f8589SJoseph Huber       else
897a15f8589SJoseph Huber         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
898a15f8589SJoseph Huber     case TARGET_ALLOC_HOST:
899a15f8589SJoseph Huber     case TARGET_ALLOC_SHARED:
900a15f8589SJoseph Huber       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
901a15f8589SJoseph Huber     }
9024031bb98SShilei Tian 
903a15f8589SJoseph Huber     REPORT("Invalid target data allocation kind or requested allocator not "
904a15f8589SJoseph Huber            "implemented yet\n");
905a15f8589SJoseph Huber 
906a15f8589SJoseph Huber     return nullptr;
9073de4cd12SGeorge Rokos   }
9083de4cd12SGeorge Rokos 
9094031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
9105449fbb5SJohannes Doerfert                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
9115449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9123de4cd12SGeorge Rokos 
9134031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9144031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
9153de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9163de4cd12SGeorge Rokos 
9175449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
9183de4cd12SGeorge Rokos 
91995f0d1edSJon Chesterfield     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
9204031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
92129338459SJoseph Huber       DP("Error when copying data from host to device. Pointers: host "
9222ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9234031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9244031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9253de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9263de4cd12SGeorge Rokos     }
9273de4cd12SGeorge Rokos 
9283de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9293de4cd12SGeorge Rokos   }
9303de4cd12SGeorge Rokos 
9314031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
9325449fbb5SJohannes Doerfert                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
9335449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9344031bb98SShilei Tian 
9354031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9364031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
93703ff643dSShilei Tian       return OFFLOAD_FAIL;
93803ff643dSShilei Tian 
9395449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
94003ff643dSShilei Tian 
94195f0d1edSJon Chesterfield     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
9424031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
94329338459SJoseph Huber       DP("Error when copying data from device to host. Pointers: host "
9442ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
9454031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
9464031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9473de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9483de4cd12SGeorge Rokos     }
9493de4cd12SGeorge Rokos 
9504031bb98SShilei Tian     return OFFLOAD_SUCCESS;
9514031bb98SShilei Tian   }
9524031bb98SShilei Tian 
953a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
9545449fbb5SJohannes Doerfert                    int64_t Size, __tgt_async_info *AsyncInfo) const {
9555449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
956a014fbbcSShilei Tian 
957a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
958a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
959a014fbbcSShilei Tian       return OFFLOAD_FAIL;
960a014fbbcSShilei Tian 
9615449fbb5SJohannes Doerfert     CUstream Stream = getStream(SrcDevId, AsyncInfo);
962a014fbbcSShilei Tian 
963a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
964a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
965a014fbbcSShilei Tian       int CanAccessPeer = 0;
966a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
967a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9682ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
969a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
970a014fbbcSShilei Tian                SrcDevId, DstDevId);
971a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
972a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
973a014fbbcSShilei Tian       }
974a014fbbcSShilei Tian 
975a014fbbcSShilei Tian       if (!CanAccessPeer) {
976a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
977a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
978a014fbbcSShilei Tian       }
979a014fbbcSShilei Tian 
980a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
981a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
9822ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
983a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
984a014fbbcSShilei Tian                SrcDevId, DstDevId);
985a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
986a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
987a014fbbcSShilei Tian       }
988a014fbbcSShilei Tian 
989a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
990a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
991a014fbbcSShilei Tian                               Size, Stream);
992a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
993a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
994a014fbbcSShilei Tian 
99529338459SJoseph Huber       DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
99629338459SJoseph Huber          ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n",
99745bb073dSYe Luo          DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
998a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
999a014fbbcSShilei Tian     }
1000a014fbbcSShilei Tian 
1001a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1002a014fbbcSShilei Tian   }
1003a014fbbcSShilei Tian 
10040871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
10050871d6d5SShilei Tian     if (UseMemoryManager)
10060871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
10074031bb98SShilei Tian 
10080871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
10094031bb98SShilei Tian   }
10104031bb98SShilei Tian 
1011aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1012aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
1013aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
10144031bb98SShilei Tian                           const unsigned int LoopTripCount,
10154031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
10164031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
10174031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
10184031bb98SShilei Tian       return OFFLOAD_FAIL;
10194031bb98SShilei Tian 
10203de4cd12SGeorge Rokos     // All args are references.
10214031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
10224031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
10233de4cd12SGeorge Rokos 
10244031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
10254031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
10264031bb98SShilei Tian       Args[I] = &Ptrs[I];
10271546d319SGeorge Rokos     }
10283de4cd12SGeorge Rokos 
1029aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
10303de4cd12SGeorge Rokos 
1031aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
10324031bb98SShilei Tian     if (ThreadLimit > 0) {
10334031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
10344031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
10353de4cd12SGeorge Rokos       // Add master warp if necessary
10363de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
10374031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
10384031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
10393de4cd12SGeorge Rokos       }
1040c13df8e5SGeorge Rokos     } else {
1041c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
10424031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
10434031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1044c13df8e5SGeorge Rokos     }
10453de4cd12SGeorge Rokos 
10464031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
10473de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
10484031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
10494031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
10503de4cd12SGeorge Rokos     }
10513de4cd12SGeorge Rokos 
1052aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
1053aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
10544031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
10554031bb98SShilei Tian                                KernelInfo->Func);
1056aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1057aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
1058aa27cfc1SJohannes Doerfert     }
1059aa27cfc1SJohannes Doerfert 
1060aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1061aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
1062aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
1063aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
10643de4cd12SGeorge Rokos     }
10653de4cd12SGeorge Rokos 
10664031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
10674031bb98SShilei Tian     if (TeamNum <= 0) {
10684031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1069c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
10704031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
10714031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
10724031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
10734031bb98SShilei Tian           // integer
10744031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
10757d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == GENERIC) {
1076c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
1077c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
1078c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
1079c13df8e5SGeorge Rokos           //
1080c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
1081c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
1082c13df8e5SGeorge Rokos           //   #pragma omp parallel for
1083c13df8e5SGeorge Rokos           //   for(...) {}
1084c13df8e5SGeorge Rokos           // }
1085c13df8e5SGeorge Rokos           //
1086c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
1087c13df8e5SGeorge Rokos           // loop.
10884031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
10897d576392SJoseph Huber         } else if (KernelInfo->ExecutionMode == SPMD_GENERIC) {
10907d576392SJoseph Huber           // If we reach this point, then we are executing a kernel that was
10917d576392SJoseph Huber           // transformed from Generic-mode to SPMD-mode. This kernel has
10927d576392SJoseph Huber           // SPMD-mode execution, but needs its blocks to be scheduled
10937d576392SJoseph Huber           // differently because the current loop trip count only applies to the
10947d576392SJoseph Huber           // `teams distribute` region and will create var too few blocks using
10957d576392SJoseph Huber           // the regular SPMD-mode method.
10967d576392SJoseph Huber           CudaBlocksPerGrid = LoopTripCount;
1097a158d366SJoseph Huber         } else {
1098a158d366SJoseph Huber           REPORT("Unknown execution mode: %d\n", KernelInfo->ExecutionMode);
1099a158d366SJoseph Huber           return OFFLOAD_FAIL;
1100c13df8e5SGeorge Rokos         }
110145bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
11024031bb98SShilei Tian            " and number of threads per block %d\n",
11034031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
11043de4cd12SGeorge Rokos       } else {
11054031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
11064031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
11073de4cd12SGeorge Rokos       }
11084031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
11093de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
11104031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
11114031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
11123de4cd12SGeorge Rokos     } else {
11134031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
11144031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
11153de4cd12SGeorge Rokos     }
11163de4cd12SGeorge Rokos 
1117119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1118ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
1119ae209397SJoseph Huber          "mode\n",
1120ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1121ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1122ae209397SJoseph Huber              : "(null)",
1123ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
11247d576392SJoseph Huber          (KernelInfo->ExecutionMode != SPMD
112576c0c0caSJoseph Huber               ? (KernelInfo->ExecutionMode == GENERIC ? "Generic"
112676c0c0caSJoseph Huber                                                       : "SPMD-Generic")
11277d576392SJoseph Huber               : "SPMD"));
11283de4cd12SGeorge Rokos 
11294031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
11304031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
11314031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
11324031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
11334031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
11344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
11354031bb98SShilei Tian       return OFFLOAD_FAIL;
11364031bb98SShilei Tian 
11374031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
11384031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
11394031bb98SShilei Tian 
11404031bb98SShilei Tian     return OFFLOAD_SUCCESS;
11414031bb98SShilei Tian   }
11424031bb98SShilei Tian 
11435449fbb5SJohannes Doerfert   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
11445449fbb5SJohannes Doerfert     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
11454031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
11463de4cd12SGeorge Rokos 
11474031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
11485449fbb5SJohannes Doerfert     // AsyncInfo. This is to make sure the synchronization only works for its
11494031bb98SShilei Tian     // own tasks.
11505449fbb5SJohannes Doerfert     StreamManager->returnStream(DeviceId,
11515449fbb5SJohannes Doerfert                                 reinterpret_cast<CUstream>(AsyncInfo->Queue));
11525449fbb5SJohannes Doerfert     AsyncInfo->Queue = nullptr;
11533de4cd12SGeorge Rokos 
115416064e71SJoseph Huber     if (Err != CUDA_SUCCESS) {
115529338459SJoseph Huber       DP("Error when synchronizing stream. stream = " DPxMOD
115616064e71SJoseph Huber          ", async info ptr = " DPxMOD "\n",
115716064e71SJoseph Huber          DPxPTR(Stream), DPxPTR(AsyncInfo));
115816064e71SJoseph Huber       CUDA_ERR_STRING(Err);
115916064e71SJoseph Huber     }
116016064e71SJoseph Huber     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
11613de4cd12SGeorge Rokos   }
1162*d2f85d09SJose M Monsalve Diaz 
1163*d2f85d09SJose M Monsalve Diaz   void printDeviceInfo(int32_t device_id) {
1164*d2f85d09SJose M Monsalve Diaz     char TmpChar[1000];
1165*d2f85d09SJose M Monsalve Diaz     std::string TmpStr;
1166*d2f85d09SJose M Monsalve Diaz     size_t TmpSt;
1167*d2f85d09SJose M Monsalve Diaz     int TmpInt, TmpInt2, TmpInt3;
1168*d2f85d09SJose M Monsalve Diaz 
1169*d2f85d09SJose M Monsalve Diaz     CUdevice Device;
1170*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGet(&Device, device_id),
1171*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuCtxGetDevice\n");
1172*d2f85d09SJose M Monsalve Diaz 
1173*d2f85d09SJose M Monsalve Diaz     cuDriverGetVersion(&TmpInt);
1174*d2f85d09SJose M Monsalve Diaz     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1175*d2f85d09SJose M Monsalve Diaz     printf("    CUDA Device Number: \t\t%d \n", device_id);
1176*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1177*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetName\n");
1178*d2f85d09SJose M Monsalve Diaz     printf("    Device Name: \t\t\t%s \n", TmpChar);
1179*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1180*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceTotalMem\n");
1181*d2f85d09SJose M Monsalve Diaz     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1182*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1183*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1184*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1185*d2f85d09SJose M Monsalve Diaz     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1186*d2f85d09SJose M Monsalve Diaz     checkResult(
1187*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1188*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1189*d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1190*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1191*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1192*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1193*d2f85d09SJose M Monsalve Diaz     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1194*d2f85d09SJose M Monsalve Diaz     checkResult(
1195*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1196*d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1197*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1198*d2f85d09SJose M Monsalve Diaz     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
1199*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1200*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1201*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1202*d2f85d09SJose M Monsalve Diaz     printf("    Registers per Block: \t\t%d \n", TmpInt);
1203*d2f85d09SJose M Monsalve Diaz     checkResult(
1204*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1205*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1206*d2f85d09SJose M Monsalve Diaz     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1207*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1208*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1209*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1210*d2f85d09SJose M Monsalve Diaz     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
1211*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X,
1212*d2f85d09SJose M Monsalve Diaz                                     Device),
1213*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1214*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt2,
1215*d2f85d09SJose M Monsalve Diaz                                     CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1216*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1217*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt3,
1218*d2f85d09SJose M Monsalve Diaz                                     CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1219*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1220*d2f85d09SJose M Monsalve Diaz     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1221*d2f85d09SJose M Monsalve Diaz           TmpInt3);
1222*d2f85d09SJose M Monsalve Diaz     checkResult(
1223*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1224*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1225*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y,
1226*d2f85d09SJose M Monsalve Diaz                                     Device),
1227*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1228*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z,
1229*d2f85d09SJose M Monsalve Diaz                                     Device),
1230*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1231*d2f85d09SJose M Monsalve Diaz     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1232*d2f85d09SJose M Monsalve Diaz           TmpInt3);
1233*d2f85d09SJose M Monsalve Diaz     checkResult(
1234*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1235*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1236*d2f85d09SJose M Monsalve Diaz     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1237*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1238*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1239*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1240*d2f85d09SJose M Monsalve Diaz     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1241*d2f85d09SJose M Monsalve Diaz     checkResult(
1242*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1243*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1244*d2f85d09SJose M Monsalve Diaz     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1245*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1246*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1247*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1248*d2f85d09SJose M Monsalve Diaz     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1249*d2f85d09SJose M Monsalve Diaz     checkResult(
1250*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1251*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1252*d2f85d09SJose M Monsalve Diaz     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1253*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1254*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1255*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1256*d2f85d09SJose M Monsalve Diaz     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1257*d2f85d09SJose M Monsalve Diaz     checkResult(
1258*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1259*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1260*d2f85d09SJose M Monsalve Diaz     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1261*d2f85d09SJose M Monsalve Diaz       TmpStr = "DEFAULT";
1262*d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1263*d2f85d09SJose M Monsalve Diaz       TmpStr = "PROHIBITED";
1264*d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1265*d2f85d09SJose M Monsalve Diaz       TmpStr = "EXCLUSIVE PROCESS";
1266*d2f85d09SJose M Monsalve Diaz     else
1267*d2f85d09SJose M Monsalve Diaz       TmpStr = "unknown";
1268*d2f85d09SJose M Monsalve Diaz     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1269*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1270*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1271*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1272*d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1273*d2f85d09SJose M Monsalve Diaz     checkResult(
1274*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1275*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1276*d2f85d09SJose M Monsalve Diaz     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1277*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1278*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1279*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1280*d2f85d09SJose M Monsalve Diaz     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
1281*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1282*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1283*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1284*d2f85d09SJose M Monsalve Diaz     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
1285*d2f85d09SJose M Monsalve Diaz     checkResult(
1286*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, Device),
1287*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1288*d2f85d09SJose M Monsalve Diaz     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
1289*d2f85d09SJose M Monsalve Diaz     checkResult(
1290*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1291*d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, Device),
1292*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1293*d2f85d09SJose M Monsalve Diaz     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1294*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1295*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1296*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1297*d2f85d09SJose M Monsalve Diaz     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1298*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1299*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1300*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1301*d2f85d09SJose M Monsalve Diaz     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
1302*d2f85d09SJose M Monsalve Diaz     checkResult(
1303*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1304*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1305*d2f85d09SJose M Monsalve Diaz     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1306*d2f85d09SJose M Monsalve Diaz     checkResult(
1307*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1308*d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1309*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1310*d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1311*d2f85d09SJose M Monsalve Diaz     checkResult(
1312*d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1313*d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1314*d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1315*d2f85d09SJose M Monsalve Diaz     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1316*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1317*d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1318*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1319*d2f85d09SJose M Monsalve Diaz     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
1320*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD,
1321*d2f85d09SJose M Monsalve Diaz                                     Device),
1322*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1323*d2f85d09SJose M Monsalve Diaz     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
1324*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt,
1325*d2f85d09SJose M Monsalve Diaz                                     CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,
1326*d2f85d09SJose M Monsalve Diaz                                     Device),
1327*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1328*d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(&TmpInt2,
1329*d2f85d09SJose M Monsalve Diaz                                     CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,
1330*d2f85d09SJose M Monsalve Diaz                                     Device),
1331*d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1332*d2f85d09SJose M Monsalve Diaz     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1333*d2f85d09SJose M Monsalve Diaz   }
13344031bb98SShilei Tian };
13354031bb98SShilei Tian 
13364031bb98SShilei Tian DeviceRTLTy DeviceRTL;
13374031bb98SShilei Tian } // namespace
13384031bb98SShilei Tian 
13394031bb98SShilei Tian // Exposed library API function
13404031bb98SShilei Tian #ifdef __cplusplus
13414031bb98SShilei Tian extern "C" {
13424031bb98SShilei Tian #endif
13434031bb98SShilei Tian 
13444031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
13454031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
13464031bb98SShilei Tian }
13474031bb98SShilei Tian 
13484031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
13494031bb98SShilei Tian 
13504031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
135140470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
13524031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
13534031bb98SShilei Tian   return RequiresFlags;
13544031bb98SShilei Tian }
13554031bb98SShilei Tian 
1356a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1357a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1358a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1359a014fbbcSShilei Tian     return 1;
1360a014fbbcSShilei Tian 
1361a014fbbcSShilei Tian   return 0;
1362a014fbbcSShilei Tian }
1363a014fbbcSShilei Tian 
13644031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
13654031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13664031bb98SShilei Tian 
13674031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
13684031bb98SShilei Tian }
13694031bb98SShilei Tian 
13704031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
13714031bb98SShilei Tian                                           __tgt_device_image *image) {
13724031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13734031bb98SShilei Tian 
13744031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
13754031bb98SShilei Tian }
13764031bb98SShilei Tian 
13772468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *,
13782468fdd9SGeorge Rokos                            int32_t kind) {
13794031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13804031bb98SShilei Tian 
1381a15f8589SJoseph Huber   return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind);
13824031bb98SShilei Tian }
13834031bb98SShilei Tian 
13844031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
13854031bb98SShilei Tian                               int64_t size) {
13864031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
13874031bb98SShilei Tian 
13885449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
13894031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
13905449fbb5SJohannes Doerfert                                                  size, &AsyncInfo);
13914031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
13924031bb98SShilei Tian     return OFFLOAD_FAIL;
13934031bb98SShilei Tian 
13945449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
13954031bb98SShilei Tian }
13964031bb98SShilei Tian 
13974031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
13984031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
13994031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
14004031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14014031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
14024031bb98SShilei Tian 
14034031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
14044031bb98SShilei Tian                               async_info_ptr);
14054031bb98SShilei Tian }
14064031bb98SShilei Tian 
14074031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
14084031bb98SShilei Tian                                 int64_t size) {
14094031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14104031bb98SShilei Tian 
14115449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14124031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
14135449fbb5SJohannes Doerfert                                                    size, &AsyncInfo);
14144031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14154031bb98SShilei Tian     return OFFLOAD_FAIL;
14164031bb98SShilei Tian 
14175449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14184031bb98SShilei Tian }
14194031bb98SShilei Tian 
14204031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
14214031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
14224031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
14234031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14244031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
14254031bb98SShilei Tian 
14264031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
14274031bb98SShilei Tian                                 async_info_ptr);
14284031bb98SShilei Tian }
14294031bb98SShilei Tian 
1430a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1431a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1432a014fbbcSShilei Tian                                       int64_t size,
14335449fbb5SJohannes Doerfert                                       __tgt_async_info *AsyncInfo) {
1434a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1435a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
14365449fbb5SJohannes Doerfert   assert(AsyncInfo && "AsyncInfo is nullptr");
1437a014fbbcSShilei Tian 
1438a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
14395449fbb5SJohannes Doerfert                                 AsyncInfo);
1440a014fbbcSShilei Tian }
1441a014fbbcSShilei Tian 
1442a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1443a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1444a014fbbcSShilei Tian                                 int64_t size) {
1445a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1446a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1447a014fbbcSShilei Tian 
14485449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1449a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
14505449fbb5SJohannes Doerfert       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo);
1451a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1452a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1453a014fbbcSShilei Tian 
14545449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo);
1455a014fbbcSShilei Tian }
1456a014fbbcSShilei Tian 
14574031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
14584031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14594031bb98SShilei Tian 
14604031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
14614031bb98SShilei Tian }
14624031bb98SShilei Tian 
14634031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
14644031bb98SShilei Tian                                          void **tgt_args,
14654031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
14664031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
14674031bb98SShilei Tian                                          int32_t thread_limit,
14684031bb98SShilei Tian                                          uint64_t loop_tripcount) {
14694031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14704031bb98SShilei Tian 
14715449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14724031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
14734031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
14745449fbb5SJohannes Doerfert       thread_limit, loop_tripcount, &AsyncInfo);
14754031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
14764031bb98SShilei Tian     return OFFLOAD_FAIL;
14774031bb98SShilei Tian 
14785449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
14794031bb98SShilei Tian }
14804031bb98SShilei Tian 
14814031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
14824031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
14834031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
14844031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
14854031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
14864031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14874031bb98SShilei Tian 
14884031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
14894031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
14904031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
14914031bb98SShilei Tian }
14923de4cd12SGeorge Rokos 
14933de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
149432ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
149503ff643dSShilei Tian                                     int32_t arg_num) {
14964031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
14974031bb98SShilei Tian 
14985449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
14994031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
15005449fbb5SJohannes Doerfert       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo);
150103ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
150203ff643dSShilei Tian     return OFFLOAD_FAIL;
150303ff643dSShilei Tian 
15045449fbb5SJohannes Doerfert   return __tgt_rtl_synchronize(device_id, &AsyncInfo);
150503ff643dSShilei Tian }
150603ff643dSShilei Tian 
150703ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
150803ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
150903ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
151032ed2927SShilei Tian                                           int32_t arg_num,
15114031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
15124031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15134031bb98SShilei Tian 
151403ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
15154031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
15164031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
15174031bb98SShilei Tian       async_info_ptr);
151832ed2927SShilei Tian }
151932ed2927SShilei Tian 
15204031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
15214031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
15224031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
15234031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
15244031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
152532ed2927SShilei Tian 
15264031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
15273de4cd12SGeorge Rokos }
15283de4cd12SGeorge Rokos 
15292b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
153059b68490SJoseph Huber   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
15312b6f2008SJoseph Huber   InfoLevel.store(NewInfoLevel);
15322b6f2008SJoseph Huber }
15332b6f2008SJoseph Huber 
1534*d2f85d09SJose M Monsalve Diaz void __tgt_rtl_print_device_info(int32_t device_id) {
1535*d2f85d09SJose M Monsalve Diaz   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
1536*d2f85d09SJose M Monsalve Diaz   DeviceRTL.printDeviceInfo(device_id);
1537*d2f85d09SJose M Monsalve Diaz }
1538*d2f85d09SJose M Monsalve Diaz 
15393de4cd12SGeorge Rokos #ifdef __cplusplus
15403de4cd12SGeorge Rokos }
15413de4cd12SGeorge Rokos #endif
1542