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>
203de4cd12SGeorge Rokos #include <vector>
213de4cd12SGeorge Rokos 
22ae95ceebSJoseph Huber #include "Debug.h"
231546d319SGeorge Rokos #include "omptargetplugin.h"
243de4cd12SGeorge Rokos 
253de4cd12SGeorge Rokos #define TARGET_NAME CUDA
26ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
2778769ec4SMichael Kruse 
2878769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
29ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3078769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3178769ec4SMichael Kruse   do {                                                                         \
32ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                 \
3303111e5eSYe Luo       const char *errStr = nullptr;                                            \
3403111e5eSYe Luo       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
3503111e5eSYe Luo       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
36*2ce16810SJoseph Huber         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
3703111e5eSYe Luo       else if (errStr_status == CUDA_SUCCESS)                                  \
38*2ce16810SJoseph Huber         REPORT("CUDA error is: %s\n", errStr);                                 \
3903111e5eSYe Luo       else {                                                                   \
40*2ce16810SJoseph Huber         REPORT("Unresolved CUDA error code: %d\n", err);                       \
41*2ce16810SJoseph Huber         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
4203111e5eSYe Luo                errStr_status);                                                 \
4303111e5eSYe Luo       }                                                                        \
44*2ce16810SJoseph Huber     } else {                                                                   \
45*2ce16810SJoseph Huber       const char *errStr = nullptr;                                            \
46*2ce16810SJoseph Huber       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
47*2ce16810SJoseph Huber       if (errStr_status == CUDA_SUCCESS)                                       \
48*2ce16810SJoseph Huber         REPORT("%s \n", errStr);                                               \
4978769ec4SMichael Kruse     }                                                                          \
5078769ec4SMichael Kruse   } while (false)
51b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
52*2ce16810SJoseph Huber #define CUDA_ERR_STRING(err)                                                   \
53*2ce16810SJoseph Huber   do {                                                                         \
54*2ce16810SJoseph Huber     const char *errStr = nullptr;                                              \
55*2ce16810SJoseph Huber     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
56*2ce16810SJoseph Huber     if (errStr_status == CUDA_SUCCESS)                                         \
57*2ce16810SJoseph Huber       REPORT("%s \n", errStr);                                                 \
58*2ce16810SJoseph Huber   } while (false)
59b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
603de4cd12SGeorge Rokos 
613de4cd12SGeorge Rokos #include "../../common/elf_common.c"
623de4cd12SGeorge Rokos 
633de4cd12SGeorge Rokos /// Keep entries table per device.
643de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
653de4cd12SGeorge Rokos   __tgt_target_table Table;
663de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
673de4cd12SGeorge Rokos };
683de4cd12SGeorge Rokos 
693de4cd12SGeorge Rokos enum ExecutionModeType {
70c13df8e5SGeorge Rokos   SPMD, // constructors, destructors,
71c13df8e5SGeorge Rokos   // combined constructs (`teams distribute parallel for [simd]`)
72c13df8e5SGeorge Rokos   GENERIC, // everything else
733de4cd12SGeorge Rokos   NONE
743de4cd12SGeorge Rokos };
753de4cd12SGeorge Rokos 
76dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
773de4cd12SGeorge Rokos struct KernelTy {
783de4cd12SGeorge Rokos   CUfunction Func;
793de4cd12SGeorge Rokos 
803de4cd12SGeorge Rokos   // execution mode of kernel
813de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
823de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
833de4cd12SGeorge Rokos   int8_t ExecutionMode;
843de4cd12SGeorge Rokos 
85aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
86aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
87aa27cfc1SJohannes Doerfert 
883de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
893de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
903de4cd12SGeorge Rokos };
913de4cd12SGeorge Rokos 
924c6a098aSKazuaki Ishizaki /// Device environment data
93feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
94feed674dSShilei Tian /// file later.
95e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
96e1c7a46dSGuansong Zhang   int32_t debug_level;
97e1c7a46dSGuansong Zhang };
98e1c7a46dSGuansong Zhang 
99feed674dSShilei Tian namespace {
100feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
101feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
102feed674dSShilei Tian     return true;
103feed674dSShilei Tian 
104*2ce16810SJoseph Huber   REPORT("%s", ErrMsg);
105feed674dSShilei Tian   CUDA_ERR_STRING(Err);
106feed674dSShilei Tian   return false;
107feed674dSShilei Tian }
1084031bb98SShilei Tian 
109a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
110a014fbbcSShilei Tian                CUstream Stream) {
111a014fbbcSShilei Tian   CUresult Err =
112a014fbbcSShilei Tian       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
113a014fbbcSShilei Tian 
114a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
115*2ce16810SJoseph Huber     REPORT("Error when copying data from device to device. Pointers: src "
116a014fbbcSShilei Tian            "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
117a014fbbcSShilei Tian            DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
118a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
119a014fbbcSShilei Tian     return OFFLOAD_FAIL;
120a014fbbcSShilei Tian   }
121a014fbbcSShilei Tian 
122a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
123a014fbbcSShilei Tian }
124a014fbbcSShilei Tian 
1254031bb98SShilei Tian // Structure contains per-device data
1264031bb98SShilei Tian struct DeviceDataTy {
1275272d29eSJohannes Doerfert   /// List that contains all the kernels.
1285272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1295272d29eSJohannes Doerfert 
1304031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1315272d29eSJohannes Doerfert 
1324031bb98SShilei Tian   CUcontext Context = nullptr;
1334031bb98SShilei Tian   // Device properties
1344031bb98SShilei Tian   int ThreadsPerBlock = 0;
1354031bb98SShilei Tian   int BlocksPerGrid = 0;
1364031bb98SShilei Tian   int WarpSize = 0;
1374031bb98SShilei Tian   // OpenMP properties
1384031bb98SShilei Tian   int NumTeams = 0;
1394031bb98SShilei Tian   int NumThreads = 0;
1404031bb98SShilei Tian };
141feed674dSShilei Tian 
142feed674dSShilei Tian class StreamManagerTy {
143feed674dSShilei Tian   int NumberOfDevices;
1444031bb98SShilei Tian   // The initial size of stream pool
1454031bb98SShilei Tian   int EnvNumInitialStreams;
146feed674dSShilei Tian   // Per-device stream mutex
147feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
148feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
149feed674dSShilei Tian   std::vector<int> NextStreamId;
150feed674dSShilei Tian   // Per-device stream pool
151feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
1524031bb98SShilei Tian   // Reference to per-device data
1534031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
154feed674dSShilei Tian 
155feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
156feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
157feed674dSShilei Tian   // and we do not resize to smaller one.
158feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
159feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
160feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
161feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
162feed674dSShilei Tian 
1634031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1644031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
165feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
166feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
167feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
168feed674dSShilei Tian       // nullptr.
169feed674dSShilei Tian       return;
170feed674dSShilei Tian     }
171feed674dSShilei Tian 
1724031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
1734031bb98SShilei Tian 
174feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
1754031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
1764031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
177feed674dSShilei Tian     }
178feed674dSShilei Tian   }
179feed674dSShilei Tian 
180feed674dSShilei Tian public:
1814031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
1824031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
1834031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
1844031bb98SShilei Tian         DeviceData(DeviceData) {
185feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
186feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
187feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
188feed674dSShilei Tian 
1894031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
1904031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
191feed674dSShilei Tian 
192feed674dSShilei Tian     // Initialize the next stream id
193feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
194feed674dSShilei Tian 
195feed674dSShilei Tian     // Initialize stream mutex
196feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
197feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
198feed674dSShilei Tian   }
199feed674dSShilei Tian 
200feed674dSShilei Tian   ~StreamManagerTy() {
201feed674dSShilei Tian     // Destroy streams
202feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
2034031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
2044031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
205feed674dSShilei Tian 
206feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
2074031bb98SShilei Tian         if (S)
2084031bb98SShilei Tian           checkResult(cuStreamDestroy(S),
2094031bb98SShilei Tian                       "Error returned from cuStreamDestroy\n");
210feed674dSShilei Tian       }
211feed674dSShilei Tian     }
212feed674dSShilei Tian   }
213feed674dSShilei Tian 
214feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
215feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
216feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
217feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
218feed674dSShilei Tian   // the id will increase one.
219feed674dSShilei Tian   // xxxxxs+++++++++
220feed674dSShilei Tian   //      ^
221feed674dSShilei Tian   //      id
222feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
223feed674dSShilei Tian   // xxxxxs+++++++++
224feed674dSShilei Tian   //       ^
225feed674dSShilei Tian   //       id
226feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
227feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
228feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
229feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
230feed674dSShilei Tian     if (Id == StreamPool[DeviceId].size()) {
231feed674dSShilei Tian       // By default we double the stream pool every time
232feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
233feed674dSShilei Tian     }
234feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
235feed674dSShilei Tian   }
236feed674dSShilei Tian 
237feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
238feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
239feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
240feed674dSShilei Tian   // back.
241feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
242feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
243feed674dSShilei Tian   // two identical CUstreams.
244feed674dSShilei Tian   // xxax+a+++++
245feed674dSShilei Tian   //     ^
246feed674dSShilei Tian   //     id
247feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
248feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
249feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
250feed674dSShilei Tian   // from its initial state.
251feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
252feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
253feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
254feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
255feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
256feed674dSShilei Tian   }
257feed674dSShilei Tian 
2584031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
2594031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
2604031bb98SShilei Tian 
2614031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
2624031bb98SShilei Tian 
2634031bb98SShilei Tian     // Check the size of stream pool
2644031bb98SShilei Tian     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
2654031bb98SShilei Tian       return false;
2664031bb98SShilei Tian 
2674031bb98SShilei Tian     // Check whether each stream is valid
2684031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
2694031bb98SShilei Tian       if (!S)
2704031bb98SShilei Tian         return false;
2714031bb98SShilei Tian 
2724031bb98SShilei Tian     return true;
273feed674dSShilei Tian   }
274feed674dSShilei Tian };
275feed674dSShilei Tian 
2764031bb98SShilei Tian class DeviceRTLTy {
2773de4cd12SGeorge Rokos   int NumberOfDevices;
2784031bb98SShilei Tian   // OpenMP environment properties
2793de4cd12SGeorge Rokos   int EnvNumTeams;
2803de4cd12SGeorge Rokos   int EnvTeamLimit;
2814031bb98SShilei Tian   // OpenMP requires flags
282c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
283c5fe030cSGheorghe-Teodor Bercea 
2844031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
2854031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
2864031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
2874031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2883de4cd12SGeorge Rokos 
2894031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
2904031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
2914031bb98SShilei Tian   std::vector<CUmodule> Modules;
292feed674dSShilei Tian 
2933de4cd12SGeorge Rokos   // Record entry point associated with device
2944031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
2954031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
2963de4cd12SGeorge Rokos     E.Entries.push_back(entry);
2973de4cd12SGeorge Rokos   }
2983de4cd12SGeorge Rokos 
299ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
300ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
301ae209397SJoseph Huber                                              const void *Addr) const {
3024031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
3034031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
3044031bb98SShilei Tian       if (Itr.addr == Addr)
305ae209397SJoseph Huber         return &Itr;
3063de4cd12SGeorge Rokos 
307ae209397SJoseph Huber     return nullptr;
3083de4cd12SGeorge Rokos   }
3093de4cd12SGeorge Rokos 
3103de4cd12SGeorge Rokos   // Return the pointer to the target entries table
3114031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
3124031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3133de4cd12SGeorge Rokos 
3144031bb98SShilei Tian     if (E.Entries.empty())
3154031bb98SShilei Tian       return nullptr;
3163de4cd12SGeorge Rokos 
3173de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
3184031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
3194031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
3203de4cd12SGeorge Rokos 
3213de4cd12SGeorge Rokos     return &E.Table;
3223de4cd12SGeorge Rokos   }
3233de4cd12SGeorge Rokos 
3243de4cd12SGeorge Rokos   // Clear entries table for a device
3254031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
3264031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
3274031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3283de4cd12SGeorge Rokos     E.Entries.clear();
3294031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
3303de4cd12SGeorge Rokos   }
3313de4cd12SGeorge Rokos 
3324031bb98SShilei Tian   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
3334031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
3344031bb98SShilei Tian 
3354031bb98SShilei Tian     if (!AsyncInfoPtr->Queue)
3364031bb98SShilei Tian       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
3374031bb98SShilei Tian 
3384031bb98SShilei Tian     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
339b305d26bSSergey Dmitriev   }
3404031bb98SShilei Tian 
3414031bb98SShilei Tian public:
3424031bb98SShilei Tian   // This class should not be copied
3434031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
3444031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
3454031bb98SShilei Tian 
3464031bb98SShilei Tian   DeviceRTLTy()
3474031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
3484031bb98SShilei Tian         RequiresFlags(OMP_REQ_UNDEFINED) {
349b305d26bSSergey Dmitriev 
3503de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
3513de4cd12SGeorge Rokos 
3524031bb98SShilei Tian     CUresult Err = cuInit(0);
3534031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
3543de4cd12SGeorge Rokos       return;
3553de4cd12SGeorge Rokos     }
3563de4cd12SGeorge Rokos 
3574031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
3584031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
3593de4cd12SGeorge Rokos       return;
3603de4cd12SGeorge Rokos 
3613de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
3623de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
3633de4cd12SGeorge Rokos       return;
3643de4cd12SGeorge Rokos     }
3653de4cd12SGeorge Rokos 
3664031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
3673de4cd12SGeorge Rokos 
3683de4cd12SGeorge Rokos     // Get environment variables regarding teams
3694031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
3703de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
3714031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
3723de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
3733de4cd12SGeorge Rokos     }
3744031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
3753de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
3764031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
3773de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
3783de4cd12SGeorge Rokos     }
379c5fe030cSGheorghe-Teodor Bercea 
380feed674dSShilei Tian     StreamManager =
3814031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
3823de4cd12SGeorge Rokos   }
3833de4cd12SGeorge Rokos 
3844031bb98SShilei Tian   ~DeviceRTLTy() {
385feed674dSShilei Tian     // First destruct stream manager in case of Contexts is destructed before it
386feed674dSShilei Tian     StreamManager = nullptr;
387feed674dSShilei Tian 
3884031bb98SShilei Tian     for (CUmodule &M : Modules)
3894031bb98SShilei Tian       // Close module
3904031bb98SShilei Tian       if (M)
3914031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
3924031bb98SShilei Tian 
3934031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
3944031bb98SShilei Tian       // Destroy context
395c5348aecSYe Luo       if (D.Context) {
396c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
397c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
398c5348aecSYe Luo         CUdevice Device;
399c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
400c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
401c5348aecSYe Luo         checkResult(cuDevicePrimaryCtxRelease(Device),
402c5348aecSYe Luo                     "Error returned from cuDevicePrimaryCtxRelease\n");
403c5348aecSYe Luo       }
4043de4cd12SGeorge Rokos     }
4053de4cd12SGeorge Rokos   }
4063de4cd12SGeorge Rokos 
4074031bb98SShilei Tian   // Check whether a given DeviceId is valid
4084031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
4094031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
41032ed2927SShilei Tian   }
41132ed2927SShilei Tian 
412cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
4134031bb98SShilei Tian 
4144031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
4154031bb98SShilei Tian 
4164031bb98SShilei Tian   int initDevice(const int DeviceId) {
4174031bb98SShilei Tian     CUdevice Device;
4184031bb98SShilei Tian 
4194031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
4204031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
4214031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
42232ed2927SShilei Tian       return OFFLOAD_FAIL;
4233de4cd12SGeorge Rokos 
424c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
425c5348aecSYe Luo     // it is inactive
426c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
427c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
428c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
429c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
430c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
431c5348aecSYe Luo       return OFFLOAD_FAIL;
432c5348aecSYe Luo 
433c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
434c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
435c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
436c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
437c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
438c5348aecSYe Luo     } else {
439c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
440c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
441c5348aecSYe Luo       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
442c5348aecSYe Luo       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
443c5348aecSYe Luo         return OFFLOAD_FAIL;
444c5348aecSYe Luo     }
445c5348aecSYe Luo 
446c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
447c5348aecSYe Luo     // device is selected.
448c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
449c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
4503de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
4513de4cd12SGeorge Rokos 
4524031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
4534031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
4544031bb98SShilei Tian       return OFFLOAD_FAIL;
455a5153dbcSJohannes Doerfert 
456feed674dSShilei Tian     // Initialize stream pool
4574031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
4584031bb98SShilei Tian       return OFFLOAD_FAIL;
459a5153dbcSJohannes Doerfert 
460bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
4614031bb98SShilei Tian     int MaxGridDimX;
4624031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
4634031bb98SShilei Tian                                Device);
4644031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
4654031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
4664031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
4674031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
4684031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
4694031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
4704031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
4713de4cd12SGeorge Rokos     } else {
4723de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
473bb51d398SJonas Hahnfeld          "at the hard limit\n",
4744031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
4754031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
4763de4cd12SGeorge Rokos     }
4773de4cd12SGeorge Rokos 
478bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
4794031bb98SShilei Tian     int MaxBlockDimX;
4804031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
4814031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
4824031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
4834031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
4844031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
4854031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
4864031bb98SShilei Tian     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
4874031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
4884031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
4893de4cd12SGeorge Rokos     } else {
4904031bb98SShilei Tian       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
4914031bb98SShilei Tian          "capping at the hard limit\n",
4924031bb98SShilei Tian          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
4934031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
4943de4cd12SGeorge Rokos     }
4953de4cd12SGeorge Rokos 
4964031bb98SShilei Tian     // Get and set warp size
4974031bb98SShilei Tian     int WarpSize;
4984031bb98SShilei Tian     Err =
4994031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
5004031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5014031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
5024031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
503bb51d398SJonas Hahnfeld     } else {
5044031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
5054031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
5063de4cd12SGeorge Rokos     }
5073de4cd12SGeorge Rokos 
5083de4cd12SGeorge Rokos     // Adjust teams to the env variables
5094031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
5103de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
5114031bb98SShilei Tian          EnvTeamLimit);
5124031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
5133de4cd12SGeorge Rokos     }
5143de4cd12SGeorge Rokos 
515ae209397SJoseph Huber     INFO(DeviceId,
516ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
517ae209397SJoseph Huber          "warp size of %d\n",
518ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
519ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
5203de4cd12SGeorge Rokos 
5213de4cd12SGeorge Rokos     // Set default number of teams
5224031bb98SShilei Tian     if (EnvNumTeams > 0) {
5233de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
5244031bb98SShilei Tian          EnvNumTeams);
5254031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
5263de4cd12SGeorge Rokos     } else {
5274031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
5283de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
5294031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5303de4cd12SGeorge Rokos     }
5314031bb98SShilei Tian 
5324031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
5333de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
5344031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
5354031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
5363de4cd12SGeorge Rokos     }
5373de4cd12SGeorge Rokos 
5383de4cd12SGeorge Rokos     // Set default number of threads
5394031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
5403de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
5414031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
5424031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
5434031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
5443de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
5454031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
5464031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
5473de4cd12SGeorge Rokos     }
5483de4cd12SGeorge Rokos 
5493de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
5503de4cd12SGeorge Rokos   }
5513de4cd12SGeorge Rokos 
5524031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
5534031bb98SShilei Tian                                  const __tgt_device_image *Image) {
5544031bb98SShilei Tian     // Set the context we are using
5554031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
5564031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
5574031bb98SShilei Tian       return nullptr;
5583de4cd12SGeorge Rokos 
5593de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
5604031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
5613de4cd12SGeorge Rokos 
5623de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
5634031bb98SShilei Tian     CUmodule Module;
5644031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
5654031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
5664031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
5674031bb98SShilei Tian       return nullptr;
5683de4cd12SGeorge Rokos 
5693de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
5704031bb98SShilei Tian 
5714031bb98SShilei Tian     Modules.push_back(Module);
5723de4cd12SGeorge Rokos 
5733de4cd12SGeorge Rokos     // Find the symbols in the module by name.
5744031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
5754031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
5763de4cd12SGeorge Rokos 
5775272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
5784031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
5794031bb98SShilei Tian       if (!E->addr) {
5804031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
5814031bb98SShilei Tian         // have always something in the address to uniquely identify the target
5824031bb98SShilei Tian         // region.
5834031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
5844031bb98SShilei Tian         return nullptr;
5853de4cd12SGeorge Rokos       }
5863de4cd12SGeorge Rokos 
5874031bb98SShilei Tian       if (E->size) {
5884031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
5894031bb98SShilei Tian         CUdeviceptr CUPtr;
5904031bb98SShilei Tian         size_t CUSize;
5914031bb98SShilei Tian         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
5924031bb98SShilei Tian         // We keep this style here because we need the name
5934031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
594*2ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
5954031bb98SShilei Tian           CUDA_ERR_STRING(Err);
5964031bb98SShilei Tian           return nullptr;
5973de4cd12SGeorge Rokos         }
5983de4cd12SGeorge Rokos 
5994031bb98SShilei Tian         if (CUSize != E->size) {
6004031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
6014031bb98SShilei Tian              CUSize, E->size);
6024031bb98SShilei Tian           return nullptr;
6033de4cd12SGeorge Rokos         }
6043de4cd12SGeorge Rokos 
6053de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
6064031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
6074031bb98SShilei Tian 
6084031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
6093de4cd12SGeorge Rokos 
610aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
611aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
612aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
613aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
614aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
6154c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
616aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
6174031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
6184031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
6194031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
620aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
621c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
622c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
6234031bb98SShilei Tian           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
6244031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
6254031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
6264031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
627c5fe030cSGheorghe-Teodor Bercea         }
628c5fe030cSGheorghe-Teodor Bercea 
6294031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
6303de4cd12SGeorge Rokos 
6313de4cd12SGeorge Rokos         continue;
6323de4cd12SGeorge Rokos       }
6333de4cd12SGeorge Rokos 
6344031bb98SShilei Tian       CUfunction Func;
6354031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
6364031bb98SShilei Tian       // We keep this style here because we need the name
6374031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
638*2ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
6394031bb98SShilei Tian         CUDA_ERR_STRING(Err);
6404031bb98SShilei Tian         return nullptr;
6413de4cd12SGeorge Rokos       }
6423de4cd12SGeorge Rokos 
6433de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
6444031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
6453de4cd12SGeorge Rokos 
6463de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
6473de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
6484031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
6493de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
6503de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
6513de4cd12SGeorge Rokos 
6523de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
6534031bb98SShilei Tian       size_t CUSize;
6544031bb98SShilei Tian       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
6554031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
6564031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
6573de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
6584031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
6594031bb98SShilei Tian           return nullptr;
6603de4cd12SGeorge Rokos         }
6613de4cd12SGeorge Rokos 
6624031bb98SShilei Tian         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
6634031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
664*2ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
6653de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
6664031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
6674031bb98SShilei Tian           CUDA_ERR_STRING(Err);
6684031bb98SShilei Tian           return nullptr;
6693de4cd12SGeorge Rokos         }
6703de4cd12SGeorge Rokos 
6713de4cd12SGeorge Rokos         if (ExecModeVal < 0 || ExecModeVal > 1) {
6723de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
6733de4cd12SGeorge Rokos              ExecModeVal);
6744031bb98SShilei Tian           return nullptr;
6753de4cd12SGeorge Rokos         }
6763de4cd12SGeorge Rokos       } else {
677*2ce16810SJoseph Huber         REPORT("Loading global exec_mode '%s' - symbol missing, using default "
6784031bb98SShilei Tian                "value GENERIC (1)\n",
6794031bb98SShilei Tian                ExecModeName);
6804031bb98SShilei Tian         CUDA_ERR_STRING(Err);
6813de4cd12SGeorge Rokos       }
6823de4cd12SGeorge Rokos 
6834031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
6843de4cd12SGeorge Rokos 
6854031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
6864031bb98SShilei Tian       Entry.addr = &KernelsList.back();
6874031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
6883de4cd12SGeorge Rokos     }
6893de4cd12SGeorge Rokos 
690e1c7a46dSGuansong Zhang     // send device environment data to the device
691e1c7a46dSGuansong Zhang     {
6924031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
693e1c7a46dSGuansong Zhang 
694e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
6954031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
6964031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
697e1c7a46dSGuansong Zhang #endif
698e1c7a46dSGuansong Zhang 
6994031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
7004031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
7014031bb98SShilei Tian       size_t CUSize;
702e1c7a46dSGuansong Zhang 
7034031bb98SShilei Tian       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
7044031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
7054031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
706*2ce16810SJoseph Huber           REPORT(
707*2ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
7084031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
7094031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7104031bb98SShilei Tian           return nullptr;
711e1c7a46dSGuansong Zhang         }
712e1c7a46dSGuansong Zhang 
7134031bb98SShilei Tian         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
7144031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
715*2ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
716e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
7174031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
7184031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7194031bb98SShilei Tian           return nullptr;
720e1c7a46dSGuansong Zhang         }
721e1c7a46dSGuansong Zhang 
7224031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
723e1c7a46dSGuansong Zhang       } else {
7244031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
7254031bb98SShilei Tian            DeviceEnvName);
7264031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
7274031bb98SShilei Tian            "environment setting.\n");
728e1c7a46dSGuansong Zhang       }
729e1c7a46dSGuansong Zhang     }
730e1c7a46dSGuansong Zhang 
7314031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
7323de4cd12SGeorge Rokos   }
7333de4cd12SGeorge Rokos 
7344031bb98SShilei Tian   void *dataAlloc(const int DeviceId, const int64_t Size) const {
7354031bb98SShilei Tian     if (Size == 0)
7364031bb98SShilei Tian       return nullptr;
7374031bb98SShilei Tian 
7384031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7394031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7404031bb98SShilei Tian       return nullptr;
7414031bb98SShilei Tian 
7424031bb98SShilei Tian     CUdeviceptr DevicePtr;
7434031bb98SShilei Tian     Err = cuMemAlloc(&DevicePtr, Size);
7444031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
7454031bb98SShilei Tian       return nullptr;
7464031bb98SShilei Tian 
7474031bb98SShilei Tian     return (void *)DevicePtr;
7483de4cd12SGeorge Rokos   }
7493de4cd12SGeorge Rokos 
7504031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
7514031bb98SShilei Tian                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
7524031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
7533de4cd12SGeorge Rokos 
7544031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7554031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
7563de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7573de4cd12SGeorge Rokos 
7584031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
7593de4cd12SGeorge Rokos 
7604031bb98SShilei Tian     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
7614031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
762*2ce16810SJoseph Huber       REPORT("Error when copying data from host to device. Pointers: host "
763*2ce16810SJoseph Huber              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
7644031bb98SShilei Tian              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
7654031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7663de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7673de4cd12SGeorge Rokos     }
7683de4cd12SGeorge Rokos 
7693de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7703de4cd12SGeorge Rokos   }
7713de4cd12SGeorge Rokos 
7724031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
7734031bb98SShilei Tian                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
7744031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
7754031bb98SShilei Tian 
7764031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
7774031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
77803ff643dSShilei Tian       return OFFLOAD_FAIL;
77903ff643dSShilei Tian 
7804031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
78103ff643dSShilei Tian 
7824031bb98SShilei Tian     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
7834031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
784*2ce16810SJoseph Huber       REPORT("Error when copying data from device to host. Pointers: host "
785*2ce16810SJoseph Huber              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
7864031bb98SShilei Tian              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
7874031bb98SShilei Tian       CUDA_ERR_STRING(Err);
7883de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
7893de4cd12SGeorge Rokos     }
7903de4cd12SGeorge Rokos 
7914031bb98SShilei Tian     return OFFLOAD_SUCCESS;
7924031bb98SShilei Tian   }
7934031bb98SShilei Tian 
794a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
795a014fbbcSShilei Tian                    int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
796a014fbbcSShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
797a014fbbcSShilei Tian 
798a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
799a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
800a014fbbcSShilei Tian       return OFFLOAD_FAIL;
801a014fbbcSShilei Tian 
802a014fbbcSShilei Tian     CUstream Stream = getStream(SrcDevId, AsyncInfoPtr);
803a014fbbcSShilei Tian 
804a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
805a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
806a014fbbcSShilei Tian       int CanAccessPeer = 0;
807a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
808a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
809*2ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
810a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
811a014fbbcSShilei Tian                SrcDevId, DstDevId);
812a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
813a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
814a014fbbcSShilei Tian       }
815a014fbbcSShilei Tian 
816a014fbbcSShilei Tian       if (!CanAccessPeer) {
817a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
818a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
819a014fbbcSShilei Tian       }
820a014fbbcSShilei Tian 
821a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
822a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
823*2ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
824a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
825a014fbbcSShilei Tian                SrcDevId, DstDevId);
826a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
827a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
828a014fbbcSShilei Tian       }
829a014fbbcSShilei Tian 
830a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
831a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
832a014fbbcSShilei Tian                               Size, Stream);
833a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
834a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
835a014fbbcSShilei Tian 
836*2ce16810SJoseph Huber       REPORT("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
837*2ce16810SJoseph Huber              ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32
838*2ce16810SJoseph Huber              "\n",
83945bb073dSYe Luo              DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
840a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
841a014fbbcSShilei Tian     }
842a014fbbcSShilei Tian 
843a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
844a014fbbcSShilei Tian   }
845a014fbbcSShilei Tian 
8464031bb98SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) const {
8474031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8484031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8494031bb98SShilei Tian       return OFFLOAD_FAIL;
8504031bb98SShilei Tian 
8514031bb98SShilei Tian     Err = cuMemFree((CUdeviceptr)TgtPtr);
8524031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuMemFree\n"))
8534031bb98SShilei Tian       return OFFLOAD_FAIL;
8544031bb98SShilei Tian 
8554031bb98SShilei Tian     return OFFLOAD_SUCCESS;
8564031bb98SShilei Tian   }
8574031bb98SShilei Tian 
858aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
859aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
860aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
8614031bb98SShilei Tian                           const unsigned int LoopTripCount,
8624031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
8634031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8644031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8654031bb98SShilei Tian       return OFFLOAD_FAIL;
8664031bb98SShilei Tian 
8673de4cd12SGeorge Rokos     // All args are references.
8684031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
8694031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
8703de4cd12SGeorge Rokos 
8714031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
8724031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
8734031bb98SShilei Tian       Args[I] = &Ptrs[I];
8741546d319SGeorge Rokos     }
8753de4cd12SGeorge Rokos 
876aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
8773de4cd12SGeorge Rokos 
878aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
8794031bb98SShilei Tian     if (ThreadLimit > 0) {
8804031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
8814031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
8823de4cd12SGeorge Rokos       // Add master warp if necessary
8833de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
8844031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
8854031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
8863de4cd12SGeorge Rokos       }
887c13df8e5SGeorge Rokos     } else {
888c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
8894031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
8904031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
891c13df8e5SGeorge Rokos     }
8923de4cd12SGeorge Rokos 
8934031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
8943de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
8954031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
8964031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
8973de4cd12SGeorge Rokos     }
8983de4cd12SGeorge Rokos 
899aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
900aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
9014031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
9024031bb98SShilei Tian                                KernelInfo->Func);
903aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
904aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
905aa27cfc1SJohannes Doerfert     }
906aa27cfc1SJohannes Doerfert 
907aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
908aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
909aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
910aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
9113de4cd12SGeorge Rokos     }
9123de4cd12SGeorge Rokos 
9134031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
9144031bb98SShilei Tian     if (TeamNum <= 0) {
9154031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
916c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
9174031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
9184031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
9194031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
9204031bb98SShilei Tian           // integer
9214031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
922c13df8e5SGeorge Rokos         } else {
923c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
924c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
925c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
926c13df8e5SGeorge Rokos           //
927c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
928c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
929c13df8e5SGeorge Rokos           //   #pragma omp parallel for
930c13df8e5SGeorge Rokos           //   for(...) {}
931c13df8e5SGeorge Rokos           // }
932c13df8e5SGeorge Rokos           //
933c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
934c13df8e5SGeorge Rokos           // loop.
9354031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
936c13df8e5SGeorge Rokos         }
93745bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
9384031bb98SShilei Tian            " and number of threads per block %d\n",
9394031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
9403de4cd12SGeorge Rokos       } else {
9414031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
9424031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
9433de4cd12SGeorge Rokos       }
9444031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
9453de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
9464031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
9474031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
9483de4cd12SGeorge Rokos     } else {
9494031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
9504031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
9513de4cd12SGeorge Rokos     }
9523de4cd12SGeorge Rokos 
953ae209397SJoseph Huber     INFO(DeviceId,
954ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
955ae209397SJoseph Huber          "mode\n",
956ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
957ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
958ae209397SJoseph Huber              : "(null)",
959ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
960ae209397SJoseph Huber          (KernelInfo->ExecutionMode == SPMD) ? "SPMD" : "Generic");
9613de4cd12SGeorge Rokos 
9624031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
9634031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
9644031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
9654031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
9664031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
9674031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
9684031bb98SShilei Tian       return OFFLOAD_FAIL;
9694031bb98SShilei Tian 
9704031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
9714031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
9724031bb98SShilei Tian 
9734031bb98SShilei Tian     return OFFLOAD_SUCCESS;
9744031bb98SShilei Tian   }
9754031bb98SShilei Tian 
9764031bb98SShilei Tian   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
9774031bb98SShilei Tian     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
9784031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
9794031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
980*2ce16810SJoseph Huber       REPORT("Error when synchronizing stream. stream = " DPxMOD
9814031bb98SShilei Tian              ", async info ptr = " DPxMOD "\n",
9824031bb98SShilei Tian              DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
9834031bb98SShilei Tian       CUDA_ERR_STRING(Err);
9843de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
9853de4cd12SGeorge Rokos     }
9863de4cd12SGeorge Rokos 
9874031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
9884031bb98SShilei Tian     // async_info. This is to make sure the synchronization only works for its
9894031bb98SShilei Tian     // own tasks.
9904031bb98SShilei Tian     StreamManager->returnStream(
9914031bb98SShilei Tian         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
9924031bb98SShilei Tian     AsyncInfoPtr->Queue = nullptr;
9933de4cd12SGeorge Rokos 
9943de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
9953de4cd12SGeorge Rokos   }
9964031bb98SShilei Tian };
9974031bb98SShilei Tian 
9984031bb98SShilei Tian DeviceRTLTy DeviceRTL;
9994031bb98SShilei Tian } // namespace
10004031bb98SShilei Tian 
10014031bb98SShilei Tian // Exposed library API function
10024031bb98SShilei Tian #ifdef __cplusplus
10034031bb98SShilei Tian extern "C" {
10044031bb98SShilei Tian #endif
10054031bb98SShilei Tian 
10064031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
10074031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
10084031bb98SShilei Tian }
10094031bb98SShilei Tian 
10104031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
10114031bb98SShilei Tian 
10124031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
101340470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
10144031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
10154031bb98SShilei Tian   return RequiresFlags;
10164031bb98SShilei Tian }
10174031bb98SShilei Tian 
1018a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1019a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1020a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1021a014fbbcSShilei Tian     return 1;
1022a014fbbcSShilei Tian 
1023a014fbbcSShilei Tian   return 0;
1024a014fbbcSShilei Tian }
1025a014fbbcSShilei Tian 
10264031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
10274031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10284031bb98SShilei Tian 
10294031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
10304031bb98SShilei Tian }
10314031bb98SShilei Tian 
10324031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
10334031bb98SShilei Tian                                           __tgt_device_image *image) {
10344031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10354031bb98SShilei Tian 
10364031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
10374031bb98SShilei Tian }
10384031bb98SShilei Tian 
10394031bb98SShilei Tian void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
10404031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10414031bb98SShilei Tian 
10424031bb98SShilei Tian   return DeviceRTL.dataAlloc(device_id, size);
10434031bb98SShilei Tian }
10444031bb98SShilei Tian 
10454031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
10464031bb98SShilei Tian                               int64_t size) {
10474031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10484031bb98SShilei Tian 
10494031bb98SShilei Tian   __tgt_async_info async_info;
10504031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
10514031bb98SShilei Tian                                                  size, &async_info);
10524031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
10534031bb98SShilei Tian     return OFFLOAD_FAIL;
10544031bb98SShilei Tian 
10554031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
10564031bb98SShilei Tian }
10574031bb98SShilei Tian 
10584031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
10594031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
10604031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
10614031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10624031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
10634031bb98SShilei Tian 
10644031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
10654031bb98SShilei Tian                               async_info_ptr);
10664031bb98SShilei Tian }
10674031bb98SShilei Tian 
10684031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
10694031bb98SShilei Tian                                 int64_t size) {
10704031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10714031bb98SShilei Tian 
10724031bb98SShilei Tian   __tgt_async_info async_info;
10734031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
10744031bb98SShilei Tian                                                    size, &async_info);
10754031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
10764031bb98SShilei Tian     return OFFLOAD_FAIL;
10774031bb98SShilei Tian 
10784031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
10794031bb98SShilei Tian }
10804031bb98SShilei Tian 
10814031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
10824031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
10834031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
10844031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10854031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
10864031bb98SShilei Tian 
10874031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
10884031bb98SShilei Tian                                 async_info_ptr);
10894031bb98SShilei Tian }
10904031bb98SShilei Tian 
1091a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1092a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1093a014fbbcSShilei Tian                                       int64_t size,
1094a014fbbcSShilei Tian                                       __tgt_async_info *async_info_ptr) {
1095a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1096a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1097a014fbbcSShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
1098a014fbbcSShilei Tian 
1099a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1100a014fbbcSShilei Tian                                 async_info_ptr);
1101a014fbbcSShilei Tian }
1102a014fbbcSShilei Tian 
1103a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1104a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1105a014fbbcSShilei Tian                                 int64_t size) {
1106a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1107a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1108a014fbbcSShilei Tian 
1109a014fbbcSShilei Tian   __tgt_async_info async_info;
1110a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
1111a014fbbcSShilei Tian       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &async_info);
1112a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1113a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1114a014fbbcSShilei Tian 
1115a014fbbcSShilei Tian   return __tgt_rtl_synchronize(src_dev_id, &async_info);
1116a014fbbcSShilei Tian }
1117a014fbbcSShilei Tian 
11184031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
11194031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11204031bb98SShilei Tian 
11214031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
11224031bb98SShilei Tian }
11234031bb98SShilei Tian 
11244031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
11254031bb98SShilei Tian                                          void **tgt_args,
11264031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
11274031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
11284031bb98SShilei Tian                                          int32_t thread_limit,
11294031bb98SShilei Tian                                          uint64_t loop_tripcount) {
11304031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11314031bb98SShilei Tian 
11324031bb98SShilei Tian   __tgt_async_info async_info;
11334031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
11344031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
11354031bb98SShilei Tian       thread_limit, loop_tripcount, &async_info);
11364031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11374031bb98SShilei Tian     return OFFLOAD_FAIL;
11384031bb98SShilei Tian 
11394031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
11404031bb98SShilei Tian }
11414031bb98SShilei Tian 
11424031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
11434031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
11444031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
11454031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
11464031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
11474031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11484031bb98SShilei Tian 
11494031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
11504031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
11514031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
11524031bb98SShilei Tian }
11533de4cd12SGeorge Rokos 
11543de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
115532ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
115603ff643dSShilei Tian                                     int32_t arg_num) {
11574031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11584031bb98SShilei Tian 
115903ff643dSShilei Tian   __tgt_async_info async_info;
11604031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
116103ff643dSShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
116203ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
116303ff643dSShilei Tian     return OFFLOAD_FAIL;
116403ff643dSShilei Tian 
116503ff643dSShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
116603ff643dSShilei Tian }
116703ff643dSShilei Tian 
116803ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
116903ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
117003ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
117132ed2927SShilei Tian                                           int32_t arg_num,
11724031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
11734031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11744031bb98SShilei Tian 
117503ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
11764031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
11774031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
11784031bb98SShilei Tian       async_info_ptr);
117932ed2927SShilei Tian }
118032ed2927SShilei Tian 
11814031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
11824031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
11834031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11844031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
11854031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
118632ed2927SShilei Tian 
11874031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
11883de4cd12SGeorge Rokos }
11893de4cd12SGeorge Rokos 
11903de4cd12SGeorge Rokos #ifdef __cplusplus
11913de4cd12SGeorge Rokos }
11923de4cd12SGeorge Rokos #endif
1193