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 
28*0871d6d5SShilei Tian #include "MemoryManager.h"
29*0871d6d5SShilei Tian 
3078769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
31ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3278769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3378769ec4SMichael Kruse   do {                                                                         \
34ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                 \
3503111e5eSYe Luo       const char *errStr = nullptr;                                            \
3603111e5eSYe Luo       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
3703111e5eSYe Luo       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
382ce16810SJoseph Huber         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
3903111e5eSYe Luo       else if (errStr_status == CUDA_SUCCESS)                                  \
402ce16810SJoseph Huber         REPORT("CUDA error is: %s\n", errStr);                                 \
4103111e5eSYe Luo       else {                                                                   \
422ce16810SJoseph Huber         REPORT("Unresolved CUDA error code: %d\n", err);                       \
432ce16810SJoseph Huber         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
4403111e5eSYe Luo                errStr_status);                                                 \
4503111e5eSYe Luo       }                                                                        \
462ce16810SJoseph Huber     } else {                                                                   \
472ce16810SJoseph Huber       const char *errStr = nullptr;                                            \
482ce16810SJoseph Huber       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
492ce16810SJoseph Huber       if (errStr_status == CUDA_SUCCESS)                                       \
502ce16810SJoseph Huber         REPORT("%s \n", errStr);                                               \
5178769ec4SMichael Kruse     }                                                                          \
5278769ec4SMichael Kruse   } while (false)
53b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
542ce16810SJoseph Huber #define CUDA_ERR_STRING(err)                                                   \
552ce16810SJoseph Huber   do {                                                                         \
562ce16810SJoseph Huber     const char *errStr = nullptr;                                              \
572ce16810SJoseph Huber     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
582ce16810SJoseph Huber     if (errStr_status == CUDA_SUCCESS)                                         \
592ce16810SJoseph Huber       REPORT("%s \n", errStr);                                                 \
602ce16810SJoseph Huber   } while (false)
61b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
623de4cd12SGeorge Rokos 
63a81c68aeSShilei Tian #include "elf_common.h"
643de4cd12SGeorge Rokos 
653de4cd12SGeorge Rokos /// Keep entries table per device.
663de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
673de4cd12SGeorge Rokos   __tgt_target_table Table;
683de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
693de4cd12SGeorge Rokos };
703de4cd12SGeorge Rokos 
713de4cd12SGeorge Rokos enum ExecutionModeType {
72c13df8e5SGeorge Rokos   SPMD, // constructors, destructors,
73c13df8e5SGeorge Rokos   // combined constructs (`teams distribute parallel for [simd]`)
74c13df8e5SGeorge Rokos   GENERIC, // everything else
753de4cd12SGeorge Rokos   NONE
763de4cd12SGeorge Rokos };
773de4cd12SGeorge Rokos 
78dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
793de4cd12SGeorge Rokos struct KernelTy {
803de4cd12SGeorge Rokos   CUfunction Func;
813de4cd12SGeorge Rokos 
823de4cd12SGeorge Rokos   // execution mode of kernel
833de4cd12SGeorge Rokos   // 0 - SPMD mode (without master warp)
843de4cd12SGeorge Rokos   // 1 - Generic mode (with master warp)
853de4cd12SGeorge Rokos   int8_t ExecutionMode;
863de4cd12SGeorge Rokos 
87aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
88aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
89aa27cfc1SJohannes Doerfert 
903de4cd12SGeorge Rokos   KernelTy(CUfunction _Func, int8_t _ExecutionMode)
913de4cd12SGeorge Rokos       : Func(_Func), ExecutionMode(_ExecutionMode) {}
923de4cd12SGeorge Rokos };
933de4cd12SGeorge Rokos 
944c6a098aSKazuaki Ishizaki /// Device environment data
95feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header
96feed674dSShilei Tian /// file later.
97e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy {
98e1c7a46dSGuansong Zhang   int32_t debug_level;
99e1c7a46dSGuansong Zhang };
100e1c7a46dSGuansong Zhang 
101feed674dSShilei Tian namespace {
102feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
103feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
104feed674dSShilei Tian     return true;
105feed674dSShilei Tian 
1062ce16810SJoseph Huber   REPORT("%s", ErrMsg);
107feed674dSShilei Tian   CUDA_ERR_STRING(Err);
108feed674dSShilei Tian   return false;
109feed674dSShilei Tian }
1104031bb98SShilei Tian 
111a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
112a014fbbcSShilei Tian                CUstream Stream) {
113a014fbbcSShilei Tian   CUresult Err =
114a014fbbcSShilei Tian       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
115a014fbbcSShilei Tian 
116a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
1172ce16810SJoseph Huber     REPORT("Error when copying data from device to device. Pointers: src "
118a014fbbcSShilei Tian            "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
119a014fbbcSShilei Tian            DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
120a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
121a014fbbcSShilei Tian     return OFFLOAD_FAIL;
122a014fbbcSShilei Tian   }
123a014fbbcSShilei Tian 
124a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
125a014fbbcSShilei Tian }
126a014fbbcSShilei Tian 
1274031bb98SShilei Tian // Structure contains per-device data
1284031bb98SShilei Tian struct DeviceDataTy {
1295272d29eSJohannes Doerfert   /// List that contains all the kernels.
1305272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1315272d29eSJohannes Doerfert 
1324031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1335272d29eSJohannes Doerfert 
1344031bb98SShilei Tian   CUcontext Context = nullptr;
1354031bb98SShilei Tian   // Device properties
1364031bb98SShilei Tian   int ThreadsPerBlock = 0;
1374031bb98SShilei Tian   int BlocksPerGrid = 0;
1384031bb98SShilei Tian   int WarpSize = 0;
1394031bb98SShilei Tian   // OpenMP properties
1404031bb98SShilei Tian   int NumTeams = 0;
1414031bb98SShilei Tian   int NumThreads = 0;
1424031bb98SShilei Tian };
143feed674dSShilei Tian 
144feed674dSShilei Tian class StreamManagerTy {
145feed674dSShilei Tian   int NumberOfDevices;
1464031bb98SShilei Tian   // The initial size of stream pool
1474031bb98SShilei Tian   int EnvNumInitialStreams;
148feed674dSShilei Tian   // Per-device stream mutex
149feed674dSShilei Tian   std::vector<std::unique_ptr<std::mutex>> StreamMtx;
150feed674dSShilei Tian   // Per-device stream Id indicates the next available stream in the pool
151feed674dSShilei Tian   std::vector<int> NextStreamId;
152feed674dSShilei Tian   // Per-device stream pool
153feed674dSShilei Tian   std::vector<std::vector<CUstream>> StreamPool;
1544031bb98SShilei Tian   // Reference to per-device data
1554031bb98SShilei Tian   std::vector<DeviceDataTy> &DeviceData;
156feed674dSShilei Tian 
157feed674dSShilei Tian   // If there is no CUstream left in the pool, we will resize the pool to
158feed674dSShilei Tian   // allocate more CUstream. This function should be called with device mutex,
159feed674dSShilei Tian   // and we do not resize to smaller one.
160feed674dSShilei Tian   void resizeStreamPool(const int DeviceId, const size_t NewSize) {
161feed674dSShilei Tian     std::vector<CUstream> &Pool = StreamPool[DeviceId];
162feed674dSShilei Tian     const size_t CurrentSize = Pool.size();
163feed674dSShilei Tian     assert(NewSize > CurrentSize && "new size is not larger than current size");
164feed674dSShilei Tian 
1654031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
1664031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) {
167feed674dSShilei Tian       // We will return if cannot switch to the right context in case of
168feed674dSShilei Tian       // creating bunch of streams that are not corresponding to the right
169feed674dSShilei Tian       // device. The offloading will fail later because selected CUstream is
170feed674dSShilei Tian       // nullptr.
171feed674dSShilei Tian       return;
172feed674dSShilei Tian     }
173feed674dSShilei Tian 
1744031bb98SShilei Tian     Pool.resize(NewSize, nullptr);
1754031bb98SShilei Tian 
176feed674dSShilei Tian     for (size_t I = CurrentSize; I < NewSize; ++I) {
1774031bb98SShilei Tian       checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING),
1784031bb98SShilei Tian                   "Error returned from cuStreamCreate\n");
179feed674dSShilei Tian     }
180feed674dSShilei Tian   }
181feed674dSShilei Tian 
182feed674dSShilei Tian public:
1834031bb98SShilei Tian   StreamManagerTy(const int NumberOfDevices,
1844031bb98SShilei Tian                   std::vector<DeviceDataTy> &DeviceData)
1854031bb98SShilei Tian       : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32),
1864031bb98SShilei Tian         DeviceData(DeviceData) {
187feed674dSShilei Tian     StreamPool.resize(NumberOfDevices);
188feed674dSShilei Tian     NextStreamId.resize(NumberOfDevices);
189feed674dSShilei Tian     StreamMtx.resize(NumberOfDevices);
190feed674dSShilei Tian 
1914031bb98SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS"))
1924031bb98SShilei Tian       EnvNumInitialStreams = std::stoi(EnvStr);
193feed674dSShilei Tian 
194feed674dSShilei Tian     // Initialize the next stream id
195feed674dSShilei Tian     std::fill(NextStreamId.begin(), NextStreamId.end(), 0);
196feed674dSShilei Tian 
197feed674dSShilei Tian     // Initialize stream mutex
198feed674dSShilei Tian     for (std::unique_ptr<std::mutex> &Ptr : StreamMtx)
199feed674dSShilei Tian       Ptr = std::make_unique<std::mutex>();
200feed674dSShilei Tian   }
201feed674dSShilei Tian 
202feed674dSShilei Tian   ~StreamManagerTy() {
203feed674dSShilei Tian     // Destroy streams
204feed674dSShilei Tian     for (int I = 0; I < NumberOfDevices; ++I) {
2054031bb98SShilei Tian       checkResult(cuCtxSetCurrent(DeviceData[I].Context),
2064031bb98SShilei Tian                   "Error returned from cuCtxSetCurrent\n");
207feed674dSShilei Tian 
208feed674dSShilei Tian       for (CUstream &S : StreamPool[I]) {
2094031bb98SShilei Tian         if (S)
2104031bb98SShilei Tian           checkResult(cuStreamDestroy(S),
2114031bb98SShilei Tian                       "Error returned from cuStreamDestroy\n");
212feed674dSShilei Tian       }
213feed674dSShilei Tian     }
214feed674dSShilei Tian   }
215feed674dSShilei Tian 
216feed674dSShilei Tian   // Get a CUstream from pool. Per-device next stream id always points to the
217feed674dSShilei Tian   // next available CUstream. That means, CUstreams [0, id-1] have been
218feed674dSShilei Tian   // assigned, and [id,] are still available. If there is no CUstream left, we
219feed674dSShilei Tian   // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned,
220feed674dSShilei Tian   // the id will increase one.
221feed674dSShilei Tian   // xxxxxs+++++++++
222feed674dSShilei Tian   //      ^
223feed674dSShilei Tian   //      id
224feed674dSShilei Tian   // After assignment, the pool becomes the following and s is assigned.
225feed674dSShilei Tian   // xxxxxs+++++++++
226feed674dSShilei Tian   //       ^
227feed674dSShilei Tian   //       id
228feed674dSShilei Tian   CUstream getStream(const int DeviceId) {
229feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
230feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
231feed674dSShilei Tian     // No CUstream left in the pool, we need to request from CUDA RT
232feed674dSShilei Tian     if (Id == StreamPool[DeviceId].size()) {
233feed674dSShilei Tian       // By default we double the stream pool every time
234feed674dSShilei Tian       resizeStreamPool(DeviceId, Id * 2);
235feed674dSShilei Tian     }
236feed674dSShilei Tian     return StreamPool[DeviceId][Id++];
237feed674dSShilei Tian   }
238feed674dSShilei Tian 
239feed674dSShilei Tian   // Return a CUstream back to pool. As mentioned above, per-device next
240feed674dSShilei Tian   // stream is always points to the next available CUstream, so when we return
241feed674dSShilei Tian   // a CUstream, we need to first decrease the id, and then copy the CUstream
242feed674dSShilei Tian   // back.
243feed674dSShilei Tian   // It is worth noting that, the order of streams return might be different
244feed674dSShilei Tian   // from that they're assigned, that saying, at some point, there might be
245feed674dSShilei Tian   // two identical CUstreams.
246feed674dSShilei Tian   // xxax+a+++++
247feed674dSShilei Tian   //     ^
248feed674dSShilei Tian   //     id
249feed674dSShilei Tian   // However, it doesn't matter, because they're always on the two sides of
250feed674dSShilei Tian   // id. The left one will in the end be overwritten by another CUstream.
251feed674dSShilei Tian   // Therefore, after several execution, the order of pool might be different
252feed674dSShilei Tian   // from its initial state.
253feed674dSShilei Tian   void returnStream(const int DeviceId, CUstream Stream) {
254feed674dSShilei Tian     const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]);
255feed674dSShilei Tian     int &Id = NextStreamId[DeviceId];
256feed674dSShilei Tian     assert(Id > 0 && "Wrong stream ID");
257feed674dSShilei Tian     StreamPool[DeviceId][--Id] = Stream;
258feed674dSShilei Tian   }
259feed674dSShilei Tian 
2604031bb98SShilei Tian   bool initializeDeviceStreamPool(const int DeviceId) {
2614031bb98SShilei Tian     assert(StreamPool[DeviceId].empty() && "stream pool has been initialized");
2624031bb98SShilei Tian 
2634031bb98SShilei Tian     resizeStreamPool(DeviceId, EnvNumInitialStreams);
2644031bb98SShilei Tian 
2654031bb98SShilei Tian     // Check the size of stream pool
2664031bb98SShilei Tian     if (StreamPool[DeviceId].size() != EnvNumInitialStreams)
2674031bb98SShilei Tian       return false;
2684031bb98SShilei Tian 
2694031bb98SShilei Tian     // Check whether each stream is valid
2704031bb98SShilei Tian     for (CUstream &S : StreamPool[DeviceId])
2714031bb98SShilei Tian       if (!S)
2724031bb98SShilei Tian         return false;
2734031bb98SShilei Tian 
2744031bb98SShilei Tian     return true;
275feed674dSShilei Tian   }
276feed674dSShilei Tian };
277feed674dSShilei Tian 
2784031bb98SShilei Tian class DeviceRTLTy {
2793de4cd12SGeorge Rokos   int NumberOfDevices;
2804031bb98SShilei Tian   // OpenMP environment properties
2813de4cd12SGeorge Rokos   int EnvNumTeams;
2823de4cd12SGeorge Rokos   int EnvTeamLimit;
2834031bb98SShilei Tian   // OpenMP requires flags
284c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
285c5fe030cSGheorghe-Teodor Bercea 
2864031bb98SShilei Tian   static constexpr const int HardTeamLimit = 1U << 16U; // 64k
2874031bb98SShilei Tian   static constexpr const int HardThreadLimit = 1024;
2884031bb98SShilei Tian   static constexpr const int DefaultNumTeams = 128;
2894031bb98SShilei Tian   static constexpr const int DefaultNumThreads = 128;
2903de4cd12SGeorge Rokos 
2914031bb98SShilei Tian   std::unique_ptr<StreamManagerTy> StreamManager;
2924031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
2934031bb98SShilei Tian   std::vector<CUmodule> Modules;
294feed674dSShilei Tian 
295*0871d6d5SShilei Tian   /// A class responsible for interacting with device native runtime library to
296*0871d6d5SShilei Tian   /// allocate and free memory.
297*0871d6d5SShilei Tian   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
298*0871d6d5SShilei Tian     const int DeviceId;
299*0871d6d5SShilei Tian     const std::vector<DeviceDataTy> &DeviceData;
300*0871d6d5SShilei Tian 
301*0871d6d5SShilei Tian   public:
302*0871d6d5SShilei Tian     CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData)
303*0871d6d5SShilei Tian         : DeviceId(DeviceId), DeviceData(DeviceData) {}
304*0871d6d5SShilei Tian 
305*0871d6d5SShilei Tian     void *allocate(size_t Size, void *) override {
306*0871d6d5SShilei Tian       if (Size == 0)
307*0871d6d5SShilei Tian         return nullptr;
308*0871d6d5SShilei Tian 
309*0871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
310*0871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
311*0871d6d5SShilei Tian         return nullptr;
312*0871d6d5SShilei Tian 
313*0871d6d5SShilei Tian       CUdeviceptr DevicePtr;
314*0871d6d5SShilei Tian       Err = cuMemAlloc(&DevicePtr, Size);
315*0871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
316*0871d6d5SShilei Tian         return nullptr;
317*0871d6d5SShilei Tian 
318*0871d6d5SShilei Tian       return (void *)DevicePtr;
319*0871d6d5SShilei Tian     }
320*0871d6d5SShilei Tian 
321*0871d6d5SShilei Tian     int free(void *TgtPtr) override {
322*0871d6d5SShilei Tian       CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
323*0871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
324*0871d6d5SShilei Tian         return OFFLOAD_FAIL;
325*0871d6d5SShilei Tian 
326*0871d6d5SShilei Tian       Err = cuMemFree((CUdeviceptr)TgtPtr);
327*0871d6d5SShilei Tian       if (!checkResult(Err, "Error returned from cuMemFree\n"))
328*0871d6d5SShilei Tian         return OFFLOAD_FAIL;
329*0871d6d5SShilei Tian 
330*0871d6d5SShilei Tian       return OFFLOAD_SUCCESS;
331*0871d6d5SShilei Tian     }
332*0871d6d5SShilei Tian   };
333*0871d6d5SShilei Tian 
334*0871d6d5SShilei Tian   /// A vector of device allocators
335*0871d6d5SShilei Tian   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
336*0871d6d5SShilei Tian 
337*0871d6d5SShilei Tian   /// A vector of memory managers. Since the memory manager is non-copyable and
338*0871d6d5SShilei Tian   // non-removable, we wrap them into std::unique_ptr.
339*0871d6d5SShilei Tian   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
340*0871d6d5SShilei Tian 
341*0871d6d5SShilei Tian   /// Whether use memory manager
342*0871d6d5SShilei Tian   bool UseMemoryManager = true;
343*0871d6d5SShilei Tian 
3443de4cd12SGeorge Rokos   // Record entry point associated with device
3454031bb98SShilei Tian   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) {
3464031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3473de4cd12SGeorge Rokos     E.Entries.push_back(entry);
3483de4cd12SGeorge Rokos   }
3493de4cd12SGeorge Rokos 
350ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
351ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
352ae209397SJoseph Huber                                              const void *Addr) const {
3534031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
3544031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
3554031bb98SShilei Tian       if (Itr.addr == Addr)
356ae209397SJoseph Huber         return &Itr;
3573de4cd12SGeorge Rokos 
358ae209397SJoseph Huber     return nullptr;
3593de4cd12SGeorge Rokos   }
3603de4cd12SGeorge Rokos 
3613de4cd12SGeorge Rokos   // Return the pointer to the target entries table
3624031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
3634031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3643de4cd12SGeorge Rokos 
3654031bb98SShilei Tian     if (E.Entries.empty())
3664031bb98SShilei Tian       return nullptr;
3673de4cd12SGeorge Rokos 
3683de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
3694031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
3704031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
3713de4cd12SGeorge Rokos 
3723de4cd12SGeorge Rokos     return &E.Table;
3733de4cd12SGeorge Rokos   }
3743de4cd12SGeorge Rokos 
3753de4cd12SGeorge Rokos   // Clear entries table for a device
3764031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
3774031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
3784031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
3793de4cd12SGeorge Rokos     E.Entries.clear();
3804031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
3813de4cd12SGeorge Rokos   }
3823de4cd12SGeorge Rokos 
3834031bb98SShilei Tian   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
3844031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
3854031bb98SShilei Tian 
3864031bb98SShilei Tian     if (!AsyncInfoPtr->Queue)
3874031bb98SShilei Tian       AsyncInfoPtr->Queue = StreamManager->getStream(DeviceId);
3884031bb98SShilei Tian 
3894031bb98SShilei Tian     return reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
390b305d26bSSergey Dmitriev   }
3914031bb98SShilei Tian 
3924031bb98SShilei Tian public:
3934031bb98SShilei Tian   // This class should not be copied
3944031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
3954031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
3964031bb98SShilei Tian 
3974031bb98SShilei Tian   DeviceRTLTy()
3984031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
3994031bb98SShilei Tian         RequiresFlags(OMP_REQ_UNDEFINED) {
400b305d26bSSergey Dmitriev 
4013de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
4023de4cd12SGeorge Rokos 
4034031bb98SShilei Tian     CUresult Err = cuInit(0);
4044031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
4053de4cd12SGeorge Rokos       return;
4063de4cd12SGeorge Rokos     }
4073de4cd12SGeorge Rokos 
4084031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
4094031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
4103de4cd12SGeorge Rokos       return;
4113de4cd12SGeorge Rokos 
4123de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
4133de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
4143de4cd12SGeorge Rokos       return;
4153de4cd12SGeorge Rokos     }
4163de4cd12SGeorge Rokos 
4174031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
4183de4cd12SGeorge Rokos 
4193de4cd12SGeorge Rokos     // Get environment variables regarding teams
4204031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
4213de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
4224031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
4233de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
4243de4cd12SGeorge Rokos     }
4254031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
4263de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
4274031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
4283de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
4293de4cd12SGeorge Rokos     }
430c5fe030cSGheorghe-Teodor Bercea 
431feed674dSShilei Tian     StreamManager =
4324031bb98SShilei Tian         std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData);
433*0871d6d5SShilei Tian 
434*0871d6d5SShilei Tian     for (int I = 0; I < NumberOfDevices; ++I)
435*0871d6d5SShilei Tian       DeviceAllocators.emplace_back(I, DeviceData);
436*0871d6d5SShilei Tian 
437*0871d6d5SShilei Tian     // Get the size threshold from environment variable
438*0871d6d5SShilei Tian     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
439*0871d6d5SShilei Tian     UseMemoryManager = Res.second;
440*0871d6d5SShilei Tian     size_t MemoryManagerThreshold = Res.first;
441*0871d6d5SShilei Tian 
442*0871d6d5SShilei Tian     if (UseMemoryManager)
443*0871d6d5SShilei Tian       for (int I = 0; I < NumberOfDevices; ++I)
444*0871d6d5SShilei Tian         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
445*0871d6d5SShilei Tian             DeviceAllocators[I], MemoryManagerThreshold));
4463de4cd12SGeorge Rokos   }
4473de4cd12SGeorge Rokos 
4484031bb98SShilei Tian   ~DeviceRTLTy() {
449*0871d6d5SShilei Tian     // We first destruct memory managers in case that its dependent data are
450*0871d6d5SShilei Tian     // destroyed before it.
451*0871d6d5SShilei Tian     for (auto &M : MemoryManagers)
452*0871d6d5SShilei Tian       M.release();
453*0871d6d5SShilei Tian 
454feed674dSShilei Tian     StreamManager = nullptr;
455feed674dSShilei Tian 
4564031bb98SShilei Tian     for (CUmodule &M : Modules)
4574031bb98SShilei Tian       // Close module
4584031bb98SShilei Tian       if (M)
4594031bb98SShilei Tian         checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n");
4604031bb98SShilei Tian 
4614031bb98SShilei Tian     for (DeviceDataTy &D : DeviceData) {
4624031bb98SShilei Tian       // Destroy context
463c5348aecSYe Luo       if (D.Context) {
464c5348aecSYe Luo         checkResult(cuCtxSetCurrent(D.Context),
465c5348aecSYe Luo                     "Error returned from cuCtxSetCurrent\n");
466c5348aecSYe Luo         CUdevice Device;
467c5348aecSYe Luo         checkResult(cuCtxGetDevice(&Device),
468c5348aecSYe Luo                     "Error returned from cuCtxGetDevice\n");
469c5348aecSYe Luo         checkResult(cuDevicePrimaryCtxRelease(Device),
470c5348aecSYe Luo                     "Error returned from cuDevicePrimaryCtxRelease\n");
471c5348aecSYe Luo       }
4723de4cd12SGeorge Rokos     }
4733de4cd12SGeorge Rokos   }
4743de4cd12SGeorge Rokos 
4754031bb98SShilei Tian   // Check whether a given DeviceId is valid
4764031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
4774031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
47832ed2927SShilei Tian   }
47932ed2927SShilei Tian 
480cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
4814031bb98SShilei Tian 
4824031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
4834031bb98SShilei Tian 
4844031bb98SShilei Tian   int initDevice(const int DeviceId) {
4854031bb98SShilei Tian     CUdevice Device;
4864031bb98SShilei Tian 
4874031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
4884031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
4894031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
49032ed2927SShilei Tian       return OFFLOAD_FAIL;
4913de4cd12SGeorge Rokos 
492c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
493c5348aecSYe Luo     // it is inactive
494c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
495c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
496c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
497c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
498c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
499c5348aecSYe Luo       return OFFLOAD_FAIL;
500c5348aecSYe Luo 
501c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
502c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
503c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
504c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
505c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
506c5348aecSYe Luo     } else {
507c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
508c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
509c5348aecSYe Luo       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
510c5348aecSYe Luo       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
511c5348aecSYe Luo         return OFFLOAD_FAIL;
512c5348aecSYe Luo     }
513c5348aecSYe Luo 
514c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
515c5348aecSYe Luo     // device is selected.
516c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
517c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
5183de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
5193de4cd12SGeorge Rokos 
5204031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
5214031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
5224031bb98SShilei Tian       return OFFLOAD_FAIL;
523a5153dbcSJohannes Doerfert 
524feed674dSShilei Tian     // Initialize stream pool
5254031bb98SShilei Tian     if (!StreamManager->initializeDeviceStreamPool(DeviceId))
5264031bb98SShilei Tian       return OFFLOAD_FAIL;
527a5153dbcSJohannes Doerfert 
528bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
5294031bb98SShilei Tian     int MaxGridDimX;
5304031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
5314031bb98SShilei Tian                                Device);
5324031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5334031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
5344031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5354031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
5364031bb98SShilei Tian     } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) {
5374031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
5384031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
5393de4cd12SGeorge Rokos     } else {
5403de4cd12SGeorge Rokos       DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping "
541bb51d398SJonas Hahnfeld          "at the hard limit\n",
5424031bb98SShilei Tian          MaxGridDimX, DeviceRTLTy::HardTeamLimit);
5434031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit;
5443de4cd12SGeorge Rokos     }
5453de4cd12SGeorge Rokos 
546bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
5474031bb98SShilei Tian     int MaxBlockDimX;
5484031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
5494031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
5504031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5514031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
5524031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
5534031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
5544031bb98SShilei Tian     } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) {
5554031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
5564031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
5573de4cd12SGeorge Rokos     } else {
5584031bb98SShilei Tian       DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
5594031bb98SShilei Tian          "capping at the hard limit\n",
5604031bb98SShilei Tian          MaxBlockDimX, DeviceRTLTy::HardThreadLimit);
5614031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
5623de4cd12SGeorge Rokos     }
5633de4cd12SGeorge Rokos 
5644031bb98SShilei Tian     // Get and set warp size
5654031bb98SShilei Tian     int WarpSize;
5664031bb98SShilei Tian     Err =
5674031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
5684031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
5694031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
5704031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
571bb51d398SJonas Hahnfeld     } else {
5724031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
5734031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
5743de4cd12SGeorge Rokos     }
5753de4cd12SGeorge Rokos 
5763de4cd12SGeorge Rokos     // Adjust teams to the env variables
5774031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
5783de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
5794031bb98SShilei Tian          EnvTeamLimit);
5804031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
5813de4cd12SGeorge Rokos     }
5823de4cd12SGeorge Rokos 
583ae209397SJoseph Huber     INFO(DeviceId,
584ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
585ae209397SJoseph Huber          "warp size of %d\n",
586ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
587ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
5883de4cd12SGeorge Rokos 
5893de4cd12SGeorge Rokos     // Set default number of teams
5904031bb98SShilei Tian     if (EnvNumTeams > 0) {
5913de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
5924031bb98SShilei Tian          EnvNumTeams);
5934031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
5943de4cd12SGeorge Rokos     } else {
5954031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
5963de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
5974031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
5983de4cd12SGeorge Rokos     }
5994031bb98SShilei Tian 
6004031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
6013de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
6024031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
6034031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
6043de4cd12SGeorge Rokos     }
6053de4cd12SGeorge Rokos 
6063de4cd12SGeorge Rokos     // Set default number of threads
6074031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
6083de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
6094031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
6104031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
6114031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
6123de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
6134031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
6144031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock;
6153de4cd12SGeorge Rokos     }
6163de4cd12SGeorge Rokos 
6173de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
6183de4cd12SGeorge Rokos   }
6193de4cd12SGeorge Rokos 
6204031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
6214031bb98SShilei Tian                                  const __tgt_device_image *Image) {
6224031bb98SShilei Tian     // Set the context we are using
6234031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
6244031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
6254031bb98SShilei Tian       return nullptr;
6263de4cd12SGeorge Rokos 
6273de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
6284031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
6293de4cd12SGeorge Rokos 
6303de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
6314031bb98SShilei Tian     CUmodule Module;
6324031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
6334031bb98SShilei Tian     Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
6344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
6354031bb98SShilei Tian       return nullptr;
6363de4cd12SGeorge Rokos 
6373de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
6384031bb98SShilei Tian 
6394031bb98SShilei Tian     Modules.push_back(Module);
6403de4cd12SGeorge Rokos 
6413de4cd12SGeorge Rokos     // Find the symbols in the module by name.
6424031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
6434031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
6443de4cd12SGeorge Rokos 
6455272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
6464031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
6474031bb98SShilei Tian       if (!E->addr) {
6484031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
6494031bb98SShilei Tian         // have always something in the address to uniquely identify the target
6504031bb98SShilei Tian         // region.
6514031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
6524031bb98SShilei Tian         return nullptr;
6533de4cd12SGeorge Rokos       }
6543de4cd12SGeorge Rokos 
6554031bb98SShilei Tian       if (E->size) {
6564031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
6574031bb98SShilei Tian         CUdeviceptr CUPtr;
6584031bb98SShilei Tian         size_t CUSize;
6594031bb98SShilei Tian         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
6604031bb98SShilei Tian         // We keep this style here because we need the name
6614031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
6622ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
6634031bb98SShilei Tian           CUDA_ERR_STRING(Err);
6644031bb98SShilei Tian           return nullptr;
6653de4cd12SGeorge Rokos         }
6663de4cd12SGeorge Rokos 
6674031bb98SShilei Tian         if (CUSize != E->size) {
6684031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
6694031bb98SShilei Tian              CUSize, E->size);
6704031bb98SShilei Tian           return nullptr;
6713de4cd12SGeorge Rokos         }
6723de4cd12SGeorge Rokos 
6733de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
6744031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
6754031bb98SShilei Tian 
6764031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
6773de4cd12SGeorge Rokos 
678aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
679aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
680aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
681aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
682aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
6834c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
684aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
6854031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
6864031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
6874031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
688aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
689c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
690c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
6914031bb98SShilei Tian           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
6924031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
6934031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
6944031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
695c5fe030cSGheorghe-Teodor Bercea         }
696c5fe030cSGheorghe-Teodor Bercea 
6974031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
6983de4cd12SGeorge Rokos 
6993de4cd12SGeorge Rokos         continue;
7003de4cd12SGeorge Rokos       }
7013de4cd12SGeorge Rokos 
7024031bb98SShilei Tian       CUfunction Func;
7034031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
7044031bb98SShilei Tian       // We keep this style here because we need the name
7054031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
7062ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
7074031bb98SShilei Tian         CUDA_ERR_STRING(Err);
7084031bb98SShilei Tian         return nullptr;
7093de4cd12SGeorge Rokos       }
7103de4cd12SGeorge Rokos 
7113de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
7124031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
7133de4cd12SGeorge Rokos 
7143de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
7153de4cd12SGeorge Rokos       int8_t ExecModeVal = ExecutionModeType::GENERIC;
7164031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
7173de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
7183de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
7193de4cd12SGeorge Rokos 
7203de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
7214031bb98SShilei Tian       size_t CUSize;
7224031bb98SShilei Tian       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
7234031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
7244031bb98SShilei Tian         if (CUSize != sizeof(int8_t)) {
7253de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
7264031bb98SShilei Tian              ExecModeName, CUSize, sizeof(int8_t));
7274031bb98SShilei Tian           return nullptr;
7283de4cd12SGeorge Rokos         }
7293de4cd12SGeorge Rokos 
7304031bb98SShilei Tian         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
7314031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
7322ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
7333de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
7344031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
7354031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7364031bb98SShilei Tian           return nullptr;
7373de4cd12SGeorge Rokos         }
7383de4cd12SGeorge Rokos 
7393de4cd12SGeorge Rokos         if (ExecModeVal < 0 || ExecModeVal > 1) {
7403de4cd12SGeorge Rokos           DP("Error wrong exec_mode value specified in cubin file: %d\n",
7413de4cd12SGeorge Rokos              ExecModeVal);
7424031bb98SShilei Tian           return nullptr;
7433de4cd12SGeorge Rokos         }
7443de4cd12SGeorge Rokos       } else {
7452ce16810SJoseph Huber         REPORT("Loading global exec_mode '%s' - symbol missing, using default "
7464031bb98SShilei Tian                "value GENERIC (1)\n",
7474031bb98SShilei Tian                ExecModeName);
7484031bb98SShilei Tian         CUDA_ERR_STRING(Err);
7493de4cd12SGeorge Rokos       }
7503de4cd12SGeorge Rokos 
7514031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
7523de4cd12SGeorge Rokos 
7534031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
7544031bb98SShilei Tian       Entry.addr = &KernelsList.back();
7554031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
7563de4cd12SGeorge Rokos     }
7573de4cd12SGeorge Rokos 
758e1c7a46dSGuansong Zhang     // send device environment data to the device
759e1c7a46dSGuansong Zhang     {
7604031bb98SShilei Tian       omptarget_device_environmentTy DeviceEnv{0};
761e1c7a46dSGuansong Zhang 
762e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG
7634031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
7644031bb98SShilei Tian         DeviceEnv.debug_level = std::stoi(EnvStr);
765e1c7a46dSGuansong Zhang #endif
766e1c7a46dSGuansong Zhang 
7674031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
7684031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
7694031bb98SShilei Tian       size_t CUSize;
770e1c7a46dSGuansong Zhang 
7714031bb98SShilei Tian       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
7724031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
7734031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
7742ce16810SJoseph Huber           REPORT(
7752ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
7764031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
7774031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7784031bb98SShilei Tian           return nullptr;
779e1c7a46dSGuansong Zhang         }
780e1c7a46dSGuansong Zhang 
7814031bb98SShilei Tian         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
7824031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
7832ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
784e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
7854031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
7864031bb98SShilei Tian           CUDA_ERR_STRING(Err);
7874031bb98SShilei Tian           return nullptr;
788e1c7a46dSGuansong Zhang         }
789e1c7a46dSGuansong Zhang 
7904031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
791e1c7a46dSGuansong Zhang       } else {
7924031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
7934031bb98SShilei Tian            DeviceEnvName);
7944031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
7954031bb98SShilei Tian            "environment setting.\n");
796e1c7a46dSGuansong Zhang       }
797e1c7a46dSGuansong Zhang     }
798e1c7a46dSGuansong Zhang 
7994031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
8003de4cd12SGeorge Rokos   }
8013de4cd12SGeorge Rokos 
802*0871d6d5SShilei Tian   void *dataAlloc(const int DeviceId, const int64_t Size) {
803*0871d6d5SShilei Tian     if (UseMemoryManager)
804*0871d6d5SShilei Tian       return MemoryManagers[DeviceId]->allocate(Size, nullptr);
8054031bb98SShilei Tian 
806*0871d6d5SShilei Tian     return DeviceAllocators[DeviceId].allocate(Size, nullptr);
8073de4cd12SGeorge Rokos   }
8083de4cd12SGeorge Rokos 
8094031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
8104031bb98SShilei Tian                  const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
8114031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
8123de4cd12SGeorge Rokos 
8134031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8144031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
8153de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
8163de4cd12SGeorge Rokos 
8174031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
8183de4cd12SGeorge Rokos 
8194031bb98SShilei Tian     Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
8204031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
8212ce16810SJoseph Huber       REPORT("Error when copying data from host to device. Pointers: host "
8222ce16810SJoseph Huber              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
8234031bb98SShilei Tian              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
8244031bb98SShilei Tian       CUDA_ERR_STRING(Err);
8253de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
8263de4cd12SGeorge Rokos     }
8273de4cd12SGeorge Rokos 
8283de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
8293de4cd12SGeorge Rokos   }
8303de4cd12SGeorge Rokos 
8314031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
8324031bb98SShilei Tian                    const int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
8334031bb98SShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
8344031bb98SShilei Tian 
8354031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
8364031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
83703ff643dSShilei Tian       return OFFLOAD_FAIL;
83803ff643dSShilei Tian 
8394031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfoPtr);
84003ff643dSShilei Tian 
8414031bb98SShilei Tian     Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
8424031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
8432ce16810SJoseph Huber       REPORT("Error when copying data from device to host. Pointers: host "
8442ce16810SJoseph Huber              "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
8454031bb98SShilei Tian              DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
8464031bb98SShilei Tian       CUDA_ERR_STRING(Err);
8473de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
8483de4cd12SGeorge Rokos     }
8493de4cd12SGeorge Rokos 
8504031bb98SShilei Tian     return OFFLOAD_SUCCESS;
8514031bb98SShilei Tian   }
8524031bb98SShilei Tian 
853a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
854a014fbbcSShilei Tian                    int64_t Size, __tgt_async_info *AsyncInfoPtr) const {
855a014fbbcSShilei Tian     assert(AsyncInfoPtr && "AsyncInfoPtr is nullptr");
856a014fbbcSShilei Tian 
857a014fbbcSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context);
858a014fbbcSShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
859a014fbbcSShilei Tian       return OFFLOAD_FAIL;
860a014fbbcSShilei Tian 
861a014fbbcSShilei Tian     CUstream Stream = getStream(SrcDevId, AsyncInfoPtr);
862a014fbbcSShilei Tian 
863a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
864a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
865a014fbbcSShilei Tian       int CanAccessPeer = 0;
866a014fbbcSShilei Tian       Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
867a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
8682ce16810SJoseph Huber         REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
869a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
870a014fbbcSShilei Tian                SrcDevId, DstDevId);
871a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
872a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
873a014fbbcSShilei Tian       }
874a014fbbcSShilei Tian 
875a014fbbcSShilei Tian       if (!CanAccessPeer) {
876a014fbbcSShilei Tian         DP("P2P memcpy not supported so fall back to D2D memcpy");
877a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
878a014fbbcSShilei Tian       }
879a014fbbcSShilei Tian 
880a014fbbcSShilei Tian       Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
881a014fbbcSShilei Tian       if (Err != CUDA_SUCCESS) {
8822ce16810SJoseph Huber         REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
883a014fbbcSShilei Tian                ", dst = %" PRId32 "\n",
884a014fbbcSShilei Tian                SrcDevId, DstDevId);
885a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
886a014fbbcSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
887a014fbbcSShilei Tian       }
888a014fbbcSShilei Tian 
889a014fbbcSShilei Tian       Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
890a014fbbcSShilei Tian                               (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context,
891a014fbbcSShilei Tian                               Size, Stream);
892a014fbbcSShilei Tian       if (Err == CUDA_SUCCESS)
893a014fbbcSShilei Tian         return OFFLOAD_SUCCESS;
894a014fbbcSShilei Tian 
8952ce16810SJoseph Huber       REPORT("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
8962ce16810SJoseph Huber              ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32
8972ce16810SJoseph Huber              "\n",
89845bb073dSYe Luo              DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
899a014fbbcSShilei Tian       CUDA_ERR_STRING(Err);
900a014fbbcSShilei Tian     }
901a014fbbcSShilei Tian 
902a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
903a014fbbcSShilei Tian   }
904a014fbbcSShilei Tian 
905*0871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
906*0871d6d5SShilei Tian     if (UseMemoryManager)
907*0871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
9084031bb98SShilei Tian 
909*0871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
9104031bb98SShilei Tian   }
9114031bb98SShilei Tian 
912aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
913aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
914aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
9154031bb98SShilei Tian                           const unsigned int LoopTripCount,
9164031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
9174031bb98SShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
9184031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
9194031bb98SShilei Tian       return OFFLOAD_FAIL;
9204031bb98SShilei Tian 
9213de4cd12SGeorge Rokos     // All args are references.
9224031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
9234031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
9243de4cd12SGeorge Rokos 
9254031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
9264031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
9274031bb98SShilei Tian       Args[I] = &Ptrs[I];
9281546d319SGeorge Rokos     }
9293de4cd12SGeorge Rokos 
930aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
9313de4cd12SGeorge Rokos 
932aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
9334031bb98SShilei Tian     if (ThreadLimit > 0) {
9344031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
9354031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
9363de4cd12SGeorge Rokos       // Add master warp if necessary
9373de4cd12SGeorge Rokos       if (KernelInfo->ExecutionMode == GENERIC) {
9384031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
9394031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
9403de4cd12SGeorge Rokos       }
941c13df8e5SGeorge Rokos     } else {
942c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
9434031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
9444031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
945c13df8e5SGeorge Rokos     }
9463de4cd12SGeorge Rokos 
9474031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
9483de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
9494031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
9504031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
9513de4cd12SGeorge Rokos     }
9523de4cd12SGeorge Rokos 
953aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
954aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
9554031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
9564031bb98SShilei Tian                                KernelInfo->Func);
957aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
958aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
959aa27cfc1SJohannes Doerfert     }
960aa27cfc1SJohannes Doerfert 
961aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
962aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
963aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
964aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
9653de4cd12SGeorge Rokos     }
9663de4cd12SGeorge Rokos 
9674031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
9684031bb98SShilei Tian     if (TeamNum <= 0) {
9694031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
970c13df8e5SGeorge Rokos         if (KernelInfo->ExecutionMode == SPMD) {
9714031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
9724031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
9734031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
9744031bb98SShilei Tian           // integer
9754031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
976c13df8e5SGeorge Rokos         } else {
977c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
978c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
979c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
980c13df8e5SGeorge Rokos           //
981c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
982c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
983c13df8e5SGeorge Rokos           //   #pragma omp parallel for
984c13df8e5SGeorge Rokos           //   for(...) {}
985c13df8e5SGeorge Rokos           // }
986c13df8e5SGeorge Rokos           //
987c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
988c13df8e5SGeorge Rokos           // loop.
9894031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
990c13df8e5SGeorge Rokos         }
99145bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
9924031bb98SShilei Tian            " and number of threads per block %d\n",
9934031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
9943de4cd12SGeorge Rokos       } else {
9954031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
9964031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
9973de4cd12SGeorge Rokos       }
9984031bb98SShilei Tian     } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) {
9993de4cd12SGeorge Rokos       DP("Capping number of teams to team limit %d\n",
10004031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
10014031bb98SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
10023de4cd12SGeorge Rokos     } else {
10034031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
10044031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
10053de4cd12SGeorge Rokos     }
10063de4cd12SGeorge Rokos 
1007ae209397SJoseph Huber     INFO(DeviceId,
1008ae209397SJoseph Huber          "Launching kernel %s with %d blocks and %d threads in %s "
1009ae209397SJoseph Huber          "mode\n",
1010ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1011ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1012ae209397SJoseph Huber              : "(null)",
1013ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
1014ae209397SJoseph Huber          (KernelInfo->ExecutionMode == SPMD) ? "SPMD" : "Generic");
10153de4cd12SGeorge Rokos 
10164031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
10174031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
10184031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
10194031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
10204031bb98SShilei Tian                          /* sharedMemBytes */ 0, Stream, &Args[0], nullptr);
10214031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
10224031bb98SShilei Tian       return OFFLOAD_FAIL;
10234031bb98SShilei Tian 
10244031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
10254031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
10264031bb98SShilei Tian 
10274031bb98SShilei Tian     return OFFLOAD_SUCCESS;
10284031bb98SShilei Tian   }
10294031bb98SShilei Tian 
10304031bb98SShilei Tian   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfoPtr) const {
10314031bb98SShilei Tian     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfoPtr->Queue);
10324031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
10334031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
10342ce16810SJoseph Huber       REPORT("Error when synchronizing stream. stream = " DPxMOD
10354031bb98SShilei Tian              ", async info ptr = " DPxMOD "\n",
10364031bb98SShilei Tian              DPxPTR(Stream), DPxPTR(AsyncInfoPtr));
10374031bb98SShilei Tian       CUDA_ERR_STRING(Err);
10383de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
10393de4cd12SGeorge Rokos     }
10403de4cd12SGeorge Rokos 
10414031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
10424031bb98SShilei Tian     // async_info. This is to make sure the synchronization only works for its
10434031bb98SShilei Tian     // own tasks.
10444031bb98SShilei Tian     StreamManager->returnStream(
10454031bb98SShilei Tian         DeviceId, reinterpret_cast<CUstream>(AsyncInfoPtr->Queue));
10464031bb98SShilei Tian     AsyncInfoPtr->Queue = nullptr;
10473de4cd12SGeorge Rokos 
10483de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
10493de4cd12SGeorge Rokos   }
10504031bb98SShilei Tian };
10514031bb98SShilei Tian 
10524031bb98SShilei Tian DeviceRTLTy DeviceRTL;
10534031bb98SShilei Tian } // namespace
10544031bb98SShilei Tian 
10554031bb98SShilei Tian // Exposed library API function
10564031bb98SShilei Tian #ifdef __cplusplus
10574031bb98SShilei Tian extern "C" {
10584031bb98SShilei Tian #endif
10594031bb98SShilei Tian 
10604031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
10614031bb98SShilei Tian   return elf_check_machine(image, /* EM_CUDA */ 190);
10624031bb98SShilei Tian }
10634031bb98SShilei Tian 
10644031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
10654031bb98SShilei Tian 
10664031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
106740470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
10684031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
10694031bb98SShilei Tian   return RequiresFlags;
10704031bb98SShilei Tian }
10714031bb98SShilei Tian 
1072a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) {
1073a014fbbcSShilei Tian   if (DeviceRTL.isValidDeviceId(src_dev_id) &&
1074a014fbbcSShilei Tian       DeviceRTL.isValidDeviceId(dst_dev_id))
1075a014fbbcSShilei Tian     return 1;
1076a014fbbcSShilei Tian 
1077a014fbbcSShilei Tian   return 0;
1078a014fbbcSShilei Tian }
1079a014fbbcSShilei Tian 
10804031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) {
10814031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10824031bb98SShilei Tian 
10834031bb98SShilei Tian   return DeviceRTL.initDevice(device_id);
10844031bb98SShilei Tian }
10854031bb98SShilei Tian 
10864031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id,
10874031bb98SShilei Tian                                           __tgt_device_image *image) {
10884031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10894031bb98SShilei Tian 
10904031bb98SShilei Tian   return DeviceRTL.loadBinary(device_id, image);
10914031bb98SShilei Tian }
10924031bb98SShilei Tian 
10934031bb98SShilei Tian void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *) {
10944031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
10954031bb98SShilei Tian 
10964031bb98SShilei Tian   return DeviceRTL.dataAlloc(device_id, size);
10974031bb98SShilei Tian }
10984031bb98SShilei Tian 
10994031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr,
11004031bb98SShilei Tian                               int64_t size) {
11014031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11024031bb98SShilei Tian 
11034031bb98SShilei Tian   __tgt_async_info async_info;
11044031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr,
11054031bb98SShilei Tian                                                  size, &async_info);
11064031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11074031bb98SShilei Tian     return OFFLOAD_FAIL;
11084031bb98SShilei Tian 
11094031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
11104031bb98SShilei Tian }
11114031bb98SShilei Tian 
11124031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr,
11134031bb98SShilei Tian                                     void *hst_ptr, int64_t size,
11144031bb98SShilei Tian                                     __tgt_async_info *async_info_ptr) {
11154031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11164031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
11174031bb98SShilei Tian 
11184031bb98SShilei Tian   return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size,
11194031bb98SShilei Tian                               async_info_ptr);
11204031bb98SShilei Tian }
11214031bb98SShilei Tian 
11224031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr,
11234031bb98SShilei Tian                                 int64_t size) {
11244031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11254031bb98SShilei Tian 
11264031bb98SShilei Tian   __tgt_async_info async_info;
11274031bb98SShilei Tian   const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr,
11284031bb98SShilei Tian                                                    size, &async_info);
11294031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11304031bb98SShilei Tian     return OFFLOAD_FAIL;
11314031bb98SShilei Tian 
11324031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
11334031bb98SShilei Tian }
11344031bb98SShilei Tian 
11354031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr,
11364031bb98SShilei Tian                                       void *tgt_ptr, int64_t size,
11374031bb98SShilei Tian                                       __tgt_async_info *async_info_ptr) {
11384031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11394031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
11404031bb98SShilei Tian 
11414031bb98SShilei Tian   return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size,
11424031bb98SShilei Tian                                 async_info_ptr);
11434031bb98SShilei Tian }
11444031bb98SShilei Tian 
1145a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr,
1146a014fbbcSShilei Tian                                       int dst_dev_id, void *dst_ptr,
1147a014fbbcSShilei Tian                                       int64_t size,
1148a014fbbcSShilei Tian                                       __tgt_async_info *async_info_ptr) {
1149a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1150a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1151a014fbbcSShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
1152a014fbbcSShilei Tian 
1153a014fbbcSShilei Tian   return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size,
1154a014fbbcSShilei Tian                                 async_info_ptr);
1155a014fbbcSShilei Tian }
1156a014fbbcSShilei Tian 
1157a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr,
1158a014fbbcSShilei Tian                                 int32_t dst_dev_id, void *dst_ptr,
1159a014fbbcSShilei Tian                                 int64_t size) {
1160a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid");
1161a014fbbcSShilei Tian   assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid");
1162a014fbbcSShilei Tian 
1163a014fbbcSShilei Tian   __tgt_async_info async_info;
1164a014fbbcSShilei Tian   const int32_t rc = __tgt_rtl_data_exchange_async(
1165a014fbbcSShilei Tian       src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &async_info);
1166a014fbbcSShilei Tian   if (rc != OFFLOAD_SUCCESS)
1167a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1168a014fbbcSShilei Tian 
1169a014fbbcSShilei Tian   return __tgt_rtl_synchronize(src_dev_id, &async_info);
1170a014fbbcSShilei Tian }
1171a014fbbcSShilei Tian 
11724031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) {
11734031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11744031bb98SShilei Tian 
11754031bb98SShilei Tian   return DeviceRTL.dataDelete(device_id, tgt_ptr);
11764031bb98SShilei Tian }
11774031bb98SShilei Tian 
11784031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr,
11794031bb98SShilei Tian                                          void **tgt_args,
11804031bb98SShilei Tian                                          ptrdiff_t *tgt_offsets,
11814031bb98SShilei Tian                                          int32_t arg_num, int32_t team_num,
11824031bb98SShilei Tian                                          int32_t thread_limit,
11834031bb98SShilei Tian                                          uint64_t loop_tripcount) {
11844031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
11854031bb98SShilei Tian 
11864031bb98SShilei Tian   __tgt_async_info async_info;
11874031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_team_region_async(
11884031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
11894031bb98SShilei Tian       thread_limit, loop_tripcount, &async_info);
11904031bb98SShilei Tian   if (rc != OFFLOAD_SUCCESS)
11914031bb98SShilei Tian     return OFFLOAD_FAIL;
11924031bb98SShilei Tian 
11934031bb98SShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
11944031bb98SShilei Tian }
11954031bb98SShilei Tian 
11964031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
11974031bb98SShilei Tian     int32_t device_id, void *tgt_entry_ptr, void **tgt_args,
11984031bb98SShilei Tian     ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num,
11994031bb98SShilei Tian     int32_t thread_limit, uint64_t loop_tripcount,
12004031bb98SShilei Tian     __tgt_async_info *async_info_ptr) {
12014031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12024031bb98SShilei Tian 
12034031bb98SShilei Tian   return DeviceRTL.runTargetTeamRegion(
12044031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num,
12054031bb98SShilei Tian       thread_limit, loop_tripcount, async_info_ptr);
12064031bb98SShilei Tian }
12073de4cd12SGeorge Rokos 
12083de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr,
120932ed2927SShilei Tian                                     void **tgt_args, ptrdiff_t *tgt_offsets,
121003ff643dSShilei Tian                                     int32_t arg_num) {
12114031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12124031bb98SShilei Tian 
121303ff643dSShilei Tian   __tgt_async_info async_info;
12144031bb98SShilei Tian   const int32_t rc = __tgt_rtl_run_target_region_async(
121503ff643dSShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &async_info);
121603ff643dSShilei Tian   if (rc != OFFLOAD_SUCCESS)
121703ff643dSShilei Tian     return OFFLOAD_FAIL;
121803ff643dSShilei Tian 
121903ff643dSShilei Tian   return __tgt_rtl_synchronize(device_id, &async_info);
122003ff643dSShilei Tian }
122103ff643dSShilei Tian 
122203ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id,
122303ff643dSShilei Tian                                           void *tgt_entry_ptr, void **tgt_args,
122403ff643dSShilei Tian                                           ptrdiff_t *tgt_offsets,
122532ed2927SShilei Tian                                           int32_t arg_num,
12264031bb98SShilei Tian                                           __tgt_async_info *async_info_ptr) {
12274031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12284031bb98SShilei Tian 
122903ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
12304031bb98SShilei Tian       device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num,
12314031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
12324031bb98SShilei Tian       async_info_ptr);
123332ed2927SShilei Tian }
123432ed2927SShilei Tian 
12354031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id,
12364031bb98SShilei Tian                               __tgt_async_info *async_info_ptr) {
12374031bb98SShilei Tian   assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid");
12384031bb98SShilei Tian   assert(async_info_ptr && "async_info_ptr is nullptr");
12394031bb98SShilei Tian   assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr");
124032ed2927SShilei Tian 
12414031bb98SShilei Tian   return DeviceRTL.synchronize(device_id, async_info_ptr);
12423de4cd12SGeorge Rokos }
12433de4cd12SGeorge Rokos 
12443de4cd12SGeorge Rokos #ifdef __cplusplus
12453de4cd12SGeorge Rokos }
12463de4cd12SGeorge Rokos #endif
1247