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 
1310aa83ffSJohannes Doerfert #include <algorithm>
143de4cd12SGeorge Rokos #include <cassert>
153de4cd12SGeorge Rokos #include <cstddef>
163de4cd12SGeorge Rokos #include <cuda.h>
173de4cd12SGeorge Rokos #include <list>
18a5153dbcSJohannes Doerfert #include <memory>
19feed674dSShilei Tian #include <mutex>
203de4cd12SGeorge Rokos #include <string>
21a15f8589SJoseph Huber #include <unordered_map>
223de4cd12SGeorge Rokos #include <vector>
233de4cd12SGeorge Rokos 
24ae95ceebSJoseph Huber #include "Debug.h"
250c554a47SJon Chesterfield #include "DeviceEnvironment.h"
2610aa83ffSJohannes Doerfert #include "omptarget.h"
271546d319SGeorge Rokos #include "omptargetplugin.h"
283de4cd12SGeorge Rokos 
293de4cd12SGeorge Rokos #define TARGET_NAME CUDA
30ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
3178769ec4SMichael Kruse 
320871d6d5SShilei Tian #include "MemoryManager.h"
330871d6d5SShilei Tian 
34ca999f71SShilei Tian #include "llvm/Frontend/OpenMP/OMPConstants.h"
35ca999f71SShilei Tian 
3678769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
37ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
3878769ec4SMichael Kruse #define CUDA_ERR_STRING(err)                                                   \
3978769ec4SMichael Kruse   do {                                                                         \
40ae95ceebSJoseph Huber     if (getDebugLevel() > 0) {                                                 \
4103111e5eSYe Luo       const char *errStr = nullptr;                                            \
4203111e5eSYe Luo       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
4303111e5eSYe Luo       if (errStr_status == CUDA_ERROR_INVALID_VALUE)                           \
442ce16810SJoseph Huber         REPORT("Unrecognized CUDA error code: %d\n", err);                     \
4503111e5eSYe Luo       else if (errStr_status == CUDA_SUCCESS)                                  \
462ce16810SJoseph Huber         REPORT("CUDA error is: %s\n", errStr);                                 \
4703111e5eSYe Luo       else {                                                                   \
482ce16810SJoseph Huber         REPORT("Unresolved CUDA error code: %d\n", err);                       \
492ce16810SJoseph Huber         REPORT("Unsuccessful cuGetErrorString return status: %d\n",            \
5003111e5eSYe Luo                errStr_status);                                                 \
5103111e5eSYe Luo       }                                                                        \
522ce16810SJoseph Huber     } else {                                                                   \
532ce16810SJoseph Huber       const char *errStr = nullptr;                                            \
542ce16810SJoseph Huber       CUresult errStr_status = cuGetErrorString(err, &errStr);                 \
552ce16810SJoseph Huber       if (errStr_status == CUDA_SUCCESS)                                       \
562ce16810SJoseph Huber         REPORT("%s \n", errStr);                                               \
5778769ec4SMichael Kruse     }                                                                          \
5878769ec4SMichael Kruse   } while (false)
59b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
602ce16810SJoseph Huber #define CUDA_ERR_STRING(err)                                                   \
612ce16810SJoseph Huber   do {                                                                         \
622ce16810SJoseph Huber     const char *errStr = nullptr;                                              \
632ce16810SJoseph Huber     CUresult errStr_status = cuGetErrorString(err, &errStr);                   \
642ce16810SJoseph Huber     if (errStr_status == CUDA_SUCCESS)                                         \
652ce16810SJoseph Huber       REPORT("%s \n", errStr);                                                 \
662ce16810SJoseph Huber   } while (false)
67b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
683de4cd12SGeorge Rokos 
69d2f85d09SJose M Monsalve Diaz #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
70d2f85d09SJose M Monsalve Diaz 
71a81c68aeSShilei Tian #include "elf_common.h"
723de4cd12SGeorge Rokos 
733de4cd12SGeorge Rokos /// Keep entries table per device.
743de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
753de4cd12SGeorge Rokos   __tgt_target_table Table;
763de4cd12SGeorge Rokos   std::vector<__tgt_offload_entry> Entries;
773de4cd12SGeorge Rokos };
783de4cd12SGeorge Rokos 
79dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
803de4cd12SGeorge Rokos struct KernelTy {
813de4cd12SGeorge Rokos   CUfunction Func;
823de4cd12SGeorge Rokos 
833de4cd12SGeorge Rokos   // execution mode of kernel
84ca999f71SShilei Tian   llvm::omp::OMPTgtExecModeFlags ExecutionMode;
853de4cd12SGeorge Rokos 
86aa27cfc1SJohannes Doerfert   /// Maximal number of threads per block for this kernel.
87aa27cfc1SJohannes Doerfert   int MaxThreadsPerBlock = 0;
88aa27cfc1SJohannes Doerfert 
89d27d0a67SJoseph Huber   KernelTy(CUfunction Func, llvm::omp::OMPTgtExecModeFlags ExecutionMode)
90d27d0a67SJoseph Huber       : Func(Func), ExecutionMode(ExecutionMode) {}
913de4cd12SGeorge Rokos };
923de4cd12SGeorge Rokos 
93feed674dSShilei Tian namespace {
94feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
95feed674dSShilei Tian   if (Err == CUDA_SUCCESS)
96feed674dSShilei Tian     return true;
97feed674dSShilei Tian 
982ce16810SJoseph Huber   REPORT("%s", ErrMsg);
99feed674dSShilei Tian   CUDA_ERR_STRING(Err);
100feed674dSShilei Tian   return false;
101feed674dSShilei Tian }
1024031bb98SShilei Tian 
103a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
104a014fbbcSShilei Tian                CUstream Stream) {
10595f0d1edSJon Chesterfield   CUresult Err =
10695f0d1edSJon Chesterfield       cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
107a014fbbcSShilei Tian 
108a014fbbcSShilei Tian   if (Err != CUDA_SUCCESS) {
10929338459SJoseph Huber     DP("Error when copying data from device to device. Pointers: src "
110a014fbbcSShilei Tian        "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
111a014fbbcSShilei Tian        DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
112a014fbbcSShilei Tian     CUDA_ERR_STRING(Err);
113a014fbbcSShilei Tian     return OFFLOAD_FAIL;
114a014fbbcSShilei Tian   }
115a014fbbcSShilei Tian 
116a014fbbcSShilei Tian   return OFFLOAD_SUCCESS;
117a014fbbcSShilei Tian }
118a014fbbcSShilei Tian 
11929df4ab3SShilei Tian int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) {
12029df4ab3SShilei Tian   CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
12129df4ab3SShilei Tian   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
12229df4ab3SShilei Tian 
12329df4ab3SShilei Tian   CUresult Err = cuEventRecord(Event, Stream);
12429df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
12529df4ab3SShilei Tian     DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n",
12629df4ab3SShilei Tian        DPxPTR(Stream), DPxPTR(Event));
12729df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
12829df4ab3SShilei Tian     return OFFLOAD_FAIL;
12929df4ab3SShilei Tian   }
13029df4ab3SShilei Tian 
13129df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
13229df4ab3SShilei Tian }
13329df4ab3SShilei Tian 
13429df4ab3SShilei Tian int syncEvent(void *EventPtr) {
13529df4ab3SShilei Tian   CUevent Event = reinterpret_cast<CUevent>(EventPtr);
13629df4ab3SShilei Tian 
13729df4ab3SShilei Tian   CUresult Err = cuEventSynchronize(Event);
13829df4ab3SShilei Tian   if (Err != CUDA_SUCCESS) {
13929df4ab3SShilei Tian     DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event));
14029df4ab3SShilei Tian     CUDA_ERR_STRING(Err);
14129df4ab3SShilei Tian     return OFFLOAD_FAIL;
14229df4ab3SShilei Tian   }
14329df4ab3SShilei Tian 
14429df4ab3SShilei Tian   return OFFLOAD_SUCCESS;
14529df4ab3SShilei Tian }
14629df4ab3SShilei Tian 
1471660288bSJohannes Doerfert namespace {
1481660288bSJohannes Doerfert 
1494031bb98SShilei Tian // Structure contains per-device data
1504031bb98SShilei Tian struct DeviceDataTy {
1515272d29eSJohannes Doerfert   /// List that contains all the kernels.
1525272d29eSJohannes Doerfert   std::list<KernelTy> KernelsList;
1535272d29eSJohannes Doerfert 
1544031bb98SShilei Tian   std::list<FuncOrGblEntryTy> FuncGblEntries;
1555272d29eSJohannes Doerfert 
1564031bb98SShilei Tian   CUcontext Context = nullptr;
1574031bb98SShilei Tian   // Device properties
1581f940b69SJoseph Huber   unsigned int ThreadsPerBlock = 0;
1591f940b69SJoseph Huber   unsigned int BlocksPerGrid = 0;
1601f940b69SJoseph Huber   unsigned int WarpSize = 0;
1614031bb98SShilei Tian   // OpenMP properties
1624031bb98SShilei Tian   int NumTeams = 0;
1634031bb98SShilei Tian   int NumThreads = 0;
1644031bb98SShilei Tian };
165feed674dSShilei Tian 
166a697a0a4SShilei Tian /// Resource allocator where \p T is the resource type.
167a697a0a4SShilei Tian /// Functions \p create and \p destroy return OFFLOAD_SUCCESS and OFFLOAD_FAIL
168a697a0a4SShilei Tian /// accordingly. The implementation should not raise any exception.
1691660288bSJohannes Doerfert template <typename T> struct AllocatorTy {
1701660288bSJohannes Doerfert   using ElementTy = T;
171ba93e4e3SJohannes Doerfert   virtual ~AllocatorTy() {}
172ba93e4e3SJohannes Doerfert 
173a697a0a4SShilei Tian   /// Create a resource and assign to R.
1741660288bSJohannes Doerfert   virtual int create(T &R) noexcept = 0;
175a697a0a4SShilei Tian   /// Destroy the resource.
1761660288bSJohannes Doerfert   virtual int destroy(T) noexcept = 0;
177a697a0a4SShilei Tian };
178feed674dSShilei Tian 
179a697a0a4SShilei Tian /// Allocator for CUstream.
1801660288bSJohannes Doerfert struct StreamAllocatorTy final : public AllocatorTy<CUstream> {
181a697a0a4SShilei Tian   /// See AllocatorTy<T>::create.
1821660288bSJohannes Doerfert   int create(CUstream &Stream) noexcept override {
183a697a0a4SShilei Tian     if (!checkResult(cuStreamCreate(&Stream, CU_STREAM_NON_BLOCKING),
184a697a0a4SShilei Tian                      "Error returned from cuStreamCreate\n"))
185a697a0a4SShilei Tian       return OFFLOAD_FAIL;
186a697a0a4SShilei Tian 
187a697a0a4SShilei Tian     return OFFLOAD_SUCCESS;
188feed674dSShilei Tian   }
189feed674dSShilei Tian 
190a697a0a4SShilei Tian   /// See AllocatorTy<T>::destroy.
1911660288bSJohannes Doerfert   int destroy(CUstream Stream) noexcept override {
192a697a0a4SShilei Tian     if (!checkResult(cuStreamDestroy(Stream),
193a697a0a4SShilei Tian                      "Error returned from cuStreamDestroy\n"))
194a697a0a4SShilei Tian       return OFFLOAD_FAIL;
1954031bb98SShilei Tian 
196a697a0a4SShilei Tian     return OFFLOAD_SUCCESS;
197feed674dSShilei Tian   }
198a697a0a4SShilei Tian };
199a697a0a4SShilei Tian 
200943d1d83SShilei Tian /// Allocator for CUevent.
2011660288bSJohannes Doerfert struct EventAllocatorTy final : public AllocatorTy<CUevent> {
202943d1d83SShilei Tian   /// See AllocatorTy<T>::create.
2031660288bSJohannes Doerfert   int create(CUevent &Event) noexcept override {
204943d1d83SShilei Tian     if (!checkResult(cuEventCreate(&Event, CU_EVENT_DEFAULT),
205943d1d83SShilei Tian                      "Error returned from cuEventCreate\n"))
206943d1d83SShilei Tian       return OFFLOAD_FAIL;
207943d1d83SShilei Tian 
208943d1d83SShilei Tian     return OFFLOAD_SUCCESS;
209943d1d83SShilei Tian   }
210943d1d83SShilei Tian 
211943d1d83SShilei Tian   /// See AllocatorTy<T>::destroy.
2121660288bSJohannes Doerfert   int destroy(CUevent Event) noexcept override {
213943d1d83SShilei Tian     if (!checkResult(cuEventDestroy(Event),
214943d1d83SShilei Tian                      "Error returned from cuEventDestroy\n"))
215943d1d83SShilei Tian       return OFFLOAD_FAIL;
216943d1d83SShilei Tian 
217943d1d83SShilei Tian     return OFFLOAD_SUCCESS;
218943d1d83SShilei Tian   }
219943d1d83SShilei Tian };
220943d1d83SShilei Tian 
221a697a0a4SShilei Tian /// A generic pool of resources where \p T is the resource type.
222a697a0a4SShilei Tian /// \p T should be copyable as the object is stored in \p std::vector .
2231660288bSJohannes Doerfert template <typename AllocTy> class ResourcePoolTy {
2241660288bSJohannes Doerfert   using ElementTy = typename AllocTy::ElementTy;
225a697a0a4SShilei Tian   /// Index of the next available resource.
226a697a0a4SShilei Tian   size_t Next = 0;
227a697a0a4SShilei Tian   /// Mutex to guard the pool.
228a697a0a4SShilei Tian   std::mutex Mutex;
229545fcc3dSShilei Tian   /// Pool of resources. The difference between \p Resources and \p Pool is,
230545fcc3dSShilei Tian   /// when a resource is acquired and released, it is all on \p Resources. When
231545fcc3dSShilei Tian   /// a batch of new resources are needed, they are both added to \p Resources
232545fcc3dSShilei Tian   /// and \p Pool. The reason for this setting is, \p Resources could contain
233545fcc3dSShilei Tian   /// redundant elements because resources are not released, which can cause
234545fcc3dSShilei Tian   /// double free. This setting makes sure that \p Pool always has every
235545fcc3dSShilei Tian   /// resource allocated from the device.
2361660288bSJohannes Doerfert   std::vector<ElementTy> Resources;
237545fcc3dSShilei Tian   std::vector<ElementTy> Pool;
238a697a0a4SShilei Tian   /// A reference to the corresponding allocator.
2391660288bSJohannes Doerfert   AllocTy Allocator;
240a697a0a4SShilei Tian 
241a697a0a4SShilei Tian   /// If `Resources` is used up, we will fill in more resources. It assumes that
242a697a0a4SShilei Tian   /// the new size `Size` should be always larger than the current size.
243a697a0a4SShilei Tian   bool resize(size_t Size) {
244545fcc3dSShilei Tian     assert(Resources.size() == Pool.size() && "size mismatch");
245a697a0a4SShilei Tian     auto CurSize = Resources.size();
246a697a0a4SShilei Tian     assert(Size > CurSize && "Unexpected smaller size");
247545fcc3dSShilei Tian     Pool.reserve(Size);
248a697a0a4SShilei Tian     Resources.reserve(Size);
249a697a0a4SShilei Tian     for (auto I = CurSize; I < Size; ++I) {
2501660288bSJohannes Doerfert       ElementTy NewItem;
251a697a0a4SShilei Tian       int Ret = Allocator.create(NewItem);
252a697a0a4SShilei Tian       if (Ret != OFFLOAD_SUCCESS)
253a697a0a4SShilei Tian         return false;
254545fcc3dSShilei Tian       Pool.push_back(NewItem);
255a697a0a4SShilei Tian       Resources.push_back(NewItem);
256a697a0a4SShilei Tian     }
257a697a0a4SShilei Tian     return true;
258feed674dSShilei Tian   }
259feed674dSShilei Tian 
260feed674dSShilei Tian public:
2611660288bSJohannes Doerfert   ResourcePoolTy(AllocTy &&A, size_t Size = 0) noexcept
262a697a0a4SShilei Tian       : Allocator(std::move(A)) {
263357c8031SShilei Tian     if (Size)
264a697a0a4SShilei Tian       (void)resize(Size);
265feed674dSShilei Tian   }
266feed674dSShilei Tian 
267357c8031SShilei Tian   ~ResourcePoolTy() noexcept { clear(); }
268feed674dSShilei Tian 
269a697a0a4SShilei Tian   /// Get a resource from pool. `Next` always points to the next available
270a697a0a4SShilei Tian   /// resource. That means, `[0, next-1]` have been assigned, and `[id,]` are
271a697a0a4SShilei Tian   /// still available. If there is no resource left, we will ask for more. Each
272a697a0a4SShilei Tian   /// time a resource is assigned, the id will increase one.
273a697a0a4SShilei Tian   /// xxxxxs+++++++++
274a697a0a4SShilei Tian   ///      ^
275a697a0a4SShilei Tian   ///      Next
276a697a0a4SShilei Tian   /// After assignment, the pool becomes the following and s is assigned.
277a697a0a4SShilei Tian   /// xxxxxs+++++++++
278a697a0a4SShilei Tian   ///       ^
279a697a0a4SShilei Tian   ///       Next
2801660288bSJohannes Doerfert   int acquire(ElementTy &R) noexcept {
281a697a0a4SShilei Tian     std::lock_guard<std::mutex> LG(Mutex);
282357c8031SShilei Tian     if (Next == Resources.size()) {
283357c8031SShilei Tian       auto NewSize = Resources.size() ? Resources.size() * 2 : 1;
284357c8031SShilei Tian       if (!resize(NewSize))
285a697a0a4SShilei Tian         return OFFLOAD_FAIL;
286357c8031SShilei Tian     }
287357c8031SShilei Tian 
288357c8031SShilei Tian     assert(Next < Resources.size());
289a697a0a4SShilei Tian 
290a697a0a4SShilei Tian     R = Resources[Next++];
291a697a0a4SShilei Tian 
292a697a0a4SShilei Tian     return OFFLOAD_SUCCESS;
293feed674dSShilei Tian   }
294feed674dSShilei Tian 
295a697a0a4SShilei Tian   /// Return the resource back to the pool. When we return a resource, we need
296a697a0a4SShilei Tian   /// to first decrease `Next`, and then copy the resource back. It is worth
297a697a0a4SShilei Tian   /// noting that, the order of resources return might be different from that
298a697a0a4SShilei Tian   /// they're assigned, that saying, at some point, there might be two identical
299a697a0a4SShilei Tian   /// resources.
300a697a0a4SShilei Tian   /// xxax+a+++++
301a697a0a4SShilei Tian   ///     ^
302a697a0a4SShilei Tian   ///     Next
303a697a0a4SShilei Tian   /// However, it doesn't matter, because they're always on the two sides of
304a697a0a4SShilei Tian   /// `Next`. The left one will in the end be overwritten by another resource.
305a697a0a4SShilei Tian   /// Therefore, after several execution, the order of pool might be different
306a697a0a4SShilei Tian   /// from its initial state.
3071660288bSJohannes Doerfert   void release(ElementTy R) noexcept {
308a697a0a4SShilei Tian     std::lock_guard<std::mutex> LG(Mutex);
309a697a0a4SShilei Tian     Resources[--Next] = R;
310feed674dSShilei Tian   }
311357c8031SShilei Tian 
312357c8031SShilei Tian   /// Released all stored resources and clear the pool.
313357c8031SShilei Tian   /// Note: This function is not thread safe. Be sure to guard it if necessary.
314357c8031SShilei Tian   void clear() noexcept {
315545fcc3dSShilei Tian     for (auto &R : Pool)
316357c8031SShilei Tian       (void)Allocator.destroy(R);
317545fcc3dSShilei Tian     Pool.clear();
318357c8031SShilei Tian     Resources.clear();
319357c8031SShilei Tian   }
320feed674dSShilei Tian };
321feed674dSShilei Tian 
3221660288bSJohannes Doerfert } // namespace
3231660288bSJohannes Doerfert 
3244031bb98SShilei Tian class DeviceRTLTy {
3253de4cd12SGeorge Rokos   int NumberOfDevices;
3264031bb98SShilei Tian   // OpenMP environment properties
3273de4cd12SGeorge Rokos   int EnvNumTeams;
3283de4cd12SGeorge Rokos   int EnvTeamLimit;
329422adaa8SJoseph Huber   int EnvTeamThreadLimit;
3304031bb98SShilei Tian   // OpenMP requires flags
331c5fe030cSGheorghe-Teodor Bercea   int64_t RequiresFlags;
332f1c821faSJoseph Huber   // Amount of dynamic shared memory to use at launch.
333f1c821faSJoseph Huber   uint64_t DynamicMemorySize;
3341660288bSJohannes Doerfert 
3351660288bSJohannes Doerfert   /// Number of initial streams for each device.
336a697a0a4SShilei Tian   int NumInitialStreams = 32;
337c5fe030cSGheorghe-Teodor Bercea 
3381660288bSJohannes Doerfert   /// Number of initial events for each device.
3391660288bSJohannes Doerfert   int NumInitialEvents = 8;
3401660288bSJohannes Doerfert 
341aca33b0bSShilei Tian   static constexpr const int32_t HardThreadLimit = 1024;
342aca33b0bSShilei Tian   static constexpr const int32_t DefaultNumTeams = 128;
343aca33b0bSShilei Tian   static constexpr const int32_t DefaultNumThreads = 128;
3443de4cd12SGeorge Rokos 
3451660288bSJohannes Doerfert   using StreamPoolTy = ResourcePoolTy<StreamAllocatorTy>;
346a697a0a4SShilei Tian   std::vector<std::unique_ptr<StreamPoolTy>> StreamPool;
347a697a0a4SShilei Tian 
3481660288bSJohannes Doerfert   using EventPoolTy = ResourcePoolTy<EventAllocatorTy>;
3491660288bSJohannes Doerfert   std::vector<std::unique_ptr<EventPoolTy>> EventPool;
350943d1d83SShilei Tian 
3514031bb98SShilei Tian   std::vector<DeviceDataTy> DeviceData;
3525105c7cdSShilei Tian   std::vector<std::vector<CUmodule>> Modules;
353feed674dSShilei Tian 
35410aa83ffSJohannes Doerfert   /// Vector of flags indicating the initalization status of all associated
35510aa83ffSJohannes Doerfert   /// devices.
35610aa83ffSJohannes Doerfert   std::vector<bool> InitializedFlags;
35710aa83ffSJohannes Doerfert 
3582695e23aSShilei Tian   enum class PeerAccessState : uint8_t { Unkown, Yes, No };
3592695e23aSShilei Tian   std::vector<std::vector<PeerAccessState>> PeerAccessMatrix;
3602695e23aSShilei Tian   std::mutex PeerAccessMatrixLock;
3612695e23aSShilei Tian 
3620871d6d5SShilei Tian   /// A class responsible for interacting with device native runtime library to
3630871d6d5SShilei Tian   /// allocate and free memory.
3640871d6d5SShilei Tian   class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
365a15f8589SJoseph Huber     std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
3660871d6d5SShilei Tian 
3670871d6d5SShilei Tian   public:
368a15f8589SJoseph Huber     void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
3690871d6d5SShilei Tian       if (Size == 0)
3700871d6d5SShilei Tian         return nullptr;
3710871d6d5SShilei Tian 
372a15f8589SJoseph Huber       void *MemAlloc = nullptr;
37339d3283aSShilei Tian       CUresult Err;
374a15f8589SJoseph Huber       switch (Kind) {
375a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
376a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
3770871d6d5SShilei Tian         CUdeviceptr DevicePtr;
37895f0d1edSJon Chesterfield         Err = cuMemAlloc(&DevicePtr, Size);
379a15f8589SJoseph Huber         MemAlloc = (void *)DevicePtr;
38095f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
3810871d6d5SShilei Tian           return nullptr;
382a15f8589SJoseph Huber         break;
383a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
384a15f8589SJoseph Huber         void *HostPtr;
385a15f8589SJoseph Huber         Err = cuMemAllocHost(&HostPtr, Size);
386a15f8589SJoseph Huber         MemAlloc = HostPtr;
387a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
388a15f8589SJoseph Huber           return nullptr;
389a15f8589SJoseph Huber         HostPinnedAllocs[MemAlloc] = Kind;
390a15f8589SJoseph Huber         break;
391a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
392a15f8589SJoseph Huber         CUdeviceptr SharedPtr;
393a15f8589SJoseph Huber         Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
394a15f8589SJoseph Huber         MemAlloc = (void *)SharedPtr;
395a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
396a15f8589SJoseph Huber           return nullptr;
397a15f8589SJoseph Huber         break;
398a15f8589SJoseph Huber       }
3990871d6d5SShilei Tian 
400a15f8589SJoseph Huber       return MemAlloc;
4010871d6d5SShilei Tian     }
4020871d6d5SShilei Tian 
4030871d6d5SShilei Tian     int free(void *TgtPtr) override {
40439d3283aSShilei Tian       CUresult Err;
405a15f8589SJoseph Huber       // Host pinned memory must be freed differently.
406a15f8589SJoseph Huber       TargetAllocTy Kind =
407a15f8589SJoseph Huber           (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
408a15f8589SJoseph Huber               ? TARGET_ALLOC_DEFAULT
409a15f8589SJoseph Huber               : TARGET_ALLOC_HOST;
410a15f8589SJoseph Huber       switch (Kind) {
411a15f8589SJoseph Huber       case TARGET_ALLOC_DEFAULT:
412a15f8589SJoseph Huber       case TARGET_ALLOC_DEVICE:
413a15f8589SJoseph Huber       case TARGET_ALLOC_SHARED:
41495f0d1edSJon Chesterfield         Err = cuMemFree((CUdeviceptr)TgtPtr);
41595f0d1edSJon Chesterfield         if (!checkResult(Err, "Error returned from cuMemFree\n"))
4160871d6d5SShilei Tian           return OFFLOAD_FAIL;
417a15f8589SJoseph Huber         break;
418a15f8589SJoseph Huber       case TARGET_ALLOC_HOST:
419a15f8589SJoseph Huber         Err = cuMemFreeHost(TgtPtr);
420a15f8589SJoseph Huber         if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
421a15f8589SJoseph Huber           return OFFLOAD_FAIL;
422a15f8589SJoseph Huber         break;
423a15f8589SJoseph Huber       }
4240871d6d5SShilei Tian 
4250871d6d5SShilei Tian       return OFFLOAD_SUCCESS;
4260871d6d5SShilei Tian     }
4270871d6d5SShilei Tian   };
4280871d6d5SShilei Tian 
4290871d6d5SShilei Tian   /// A vector of device allocators
4300871d6d5SShilei Tian   std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
4310871d6d5SShilei Tian 
4320871d6d5SShilei Tian   /// A vector of memory managers. Since the memory manager is non-copyable and
4330871d6d5SShilei Tian   // non-removable, we wrap them into std::unique_ptr.
4340871d6d5SShilei Tian   std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
4350871d6d5SShilei Tian 
4360871d6d5SShilei Tian   /// Whether use memory manager
4370871d6d5SShilei Tian   bool UseMemoryManager = true;
4380871d6d5SShilei Tian 
4393de4cd12SGeorge Rokos   // Record entry point associated with device
440d27d0a67SJoseph Huber   void addOffloadEntry(const int DeviceId, const __tgt_offload_entry Entry) {
4414031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
442d27d0a67SJoseph Huber     E.Entries.push_back(Entry);
4433de4cd12SGeorge Rokos   }
4443de4cd12SGeorge Rokos 
445ae209397SJoseph Huber   // Return a pointer to the entry associated with the pointer
446ae209397SJoseph Huber   const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
447ae209397SJoseph Huber                                              const void *Addr) const {
4484031bb98SShilei Tian     for (const __tgt_offload_entry &Itr :
4494031bb98SShilei Tian          DeviceData[DeviceId].FuncGblEntries.back().Entries)
4504031bb98SShilei Tian       if (Itr.addr == Addr)
451ae209397SJoseph Huber         return &Itr;
4523de4cd12SGeorge Rokos 
453ae209397SJoseph Huber     return nullptr;
4543de4cd12SGeorge Rokos   }
4553de4cd12SGeorge Rokos 
4563de4cd12SGeorge Rokos   // Return the pointer to the target entries table
4574031bb98SShilei Tian   __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
4584031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4593de4cd12SGeorge Rokos 
4604031bb98SShilei Tian     if (E.Entries.empty())
4614031bb98SShilei Tian       return nullptr;
4623de4cd12SGeorge Rokos 
4633de4cd12SGeorge Rokos     // Update table info according to the entries and return the pointer
4644031bb98SShilei Tian     E.Table.EntriesBegin = E.Entries.data();
4654031bb98SShilei Tian     E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
4663de4cd12SGeorge Rokos 
4673de4cd12SGeorge Rokos     return &E.Table;
4683de4cd12SGeorge Rokos   }
4693de4cd12SGeorge Rokos 
4703de4cd12SGeorge Rokos   // Clear entries table for a device
4714031bb98SShilei Tian   void clearOffloadEntriesTable(const int DeviceId) {
4724031bb98SShilei Tian     DeviceData[DeviceId].FuncGblEntries.emplace_back();
4734031bb98SShilei Tian     FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4743de4cd12SGeorge Rokos     E.Entries.clear();
4754031bb98SShilei Tian     E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
4763de4cd12SGeorge Rokos   }
4773de4cd12SGeorge Rokos 
478f44e41afSSri Hari Krishna Narayanan public:
4795449fbb5SJohannes Doerfert   CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
4805449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
4814031bb98SShilei Tian 
482a697a0a4SShilei Tian     if (!AsyncInfo->Queue) {
483a697a0a4SShilei Tian       CUstream S;
484a697a0a4SShilei Tian       if (StreamPool[DeviceId]->acquire(S) != OFFLOAD_SUCCESS)
485a697a0a4SShilei Tian         return nullptr;
486a697a0a4SShilei Tian 
487a697a0a4SShilei Tian       AsyncInfo->Queue = S;
488a697a0a4SShilei Tian     }
4894031bb98SShilei Tian 
4905449fbb5SJohannes Doerfert     return reinterpret_cast<CUstream>(AsyncInfo->Queue);
491b305d26bSSergey Dmitriev   }
4924031bb98SShilei Tian 
4934031bb98SShilei Tian   // This class should not be copied
4944031bb98SShilei Tian   DeviceRTLTy(const DeviceRTLTy &) = delete;
4954031bb98SShilei Tian   DeviceRTLTy(DeviceRTLTy &&) = delete;
4964031bb98SShilei Tian 
4974031bb98SShilei Tian   DeviceRTLTy()
4984031bb98SShilei Tian       : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
499f1c821faSJoseph Huber         EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED),
5001660288bSJohannes Doerfert         DynamicMemorySize(0) {
501b305d26bSSergey Dmitriev 
5023de4cd12SGeorge Rokos     DP("Start initializing CUDA\n");
5033de4cd12SGeorge Rokos 
5044031bb98SShilei Tian     CUresult Err = cuInit(0);
5057baff00eSJon Chesterfield     if (Err == CUDA_ERROR_INVALID_HANDLE) {
5067baff00eSJon Chesterfield       // Can't call cuGetErrorString if dlsym failed
5077baff00eSJon Chesterfield       DP("Failed to load CUDA shared library\n");
5087baff00eSJon Chesterfield       return;
5097baff00eSJon Chesterfield     }
510*cfa6e79dSJoel E. Denny     if (Err == CUDA_ERROR_NO_DEVICE) {
511*cfa6e79dSJoel E. Denny       DP("There are no devices supporting CUDA.\n");
512*cfa6e79dSJoel E. Denny       return;
513*cfa6e79dSJoel E. Denny     }
5144031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuInit\n")) {
5153de4cd12SGeorge Rokos       return;
5163de4cd12SGeorge Rokos     }
5173de4cd12SGeorge Rokos 
5184031bb98SShilei Tian     Err = cuDeviceGetCount(&NumberOfDevices);
5194031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
5203de4cd12SGeorge Rokos       return;
5213de4cd12SGeorge Rokos 
5223de4cd12SGeorge Rokos     if (NumberOfDevices == 0) {
5233de4cd12SGeorge Rokos       DP("There are no devices supporting CUDA.\n");
5243de4cd12SGeorge Rokos       return;
5253de4cd12SGeorge Rokos     }
5263de4cd12SGeorge Rokos 
5274031bb98SShilei Tian     DeviceData.resize(NumberOfDevices);
52814de0820SJohannes Doerfert     Modules.resize(NumberOfDevices);
529a697a0a4SShilei Tian     StreamPool.resize(NumberOfDevices);
5301660288bSJohannes Doerfert     EventPool.resize(NumberOfDevices);
5312695e23aSShilei Tian     PeerAccessMatrix.resize(NumberOfDevices);
5322695e23aSShilei Tian     for (auto &V : PeerAccessMatrix)
5332695e23aSShilei Tian       V.resize(NumberOfDevices, PeerAccessState::Unkown);
5343de4cd12SGeorge Rokos 
5353de4cd12SGeorge Rokos     // Get environment variables regarding teams
5364031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
5373de4cd12SGeorge Rokos       // OMP_TEAM_LIMIT has been set
5384031bb98SShilei Tian       EnvTeamLimit = std::stoi(EnvStr);
5393de4cd12SGeorge Rokos       DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
5403de4cd12SGeorge Rokos     }
541422adaa8SJoseph Huber     if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
542422adaa8SJoseph Huber       // OMP_TEAMS_THREAD_LIMIT has been set
543422adaa8SJoseph Huber       EnvTeamThreadLimit = std::stoi(EnvStr);
544422adaa8SJoseph Huber       DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
545422adaa8SJoseph Huber     }
5464031bb98SShilei Tian     if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
5473de4cd12SGeorge Rokos       // OMP_NUM_TEAMS has been set
5484031bb98SShilei Tian       EnvNumTeams = std::stoi(EnvStr);
5493de4cd12SGeorge Rokos       DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
5503de4cd12SGeorge Rokos     }
551f1c821faSJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_SHARED_MEMORY_SIZE")) {
552f1c821faSJoseph Huber       // LIBOMPTARGET_SHARED_MEMORY_SIZE has been set
553f1c821faSJoseph Huber       DynamicMemorySize = std::stoi(EnvStr);
55449e976c9SShilei Tian       DP("Parsed LIBOMPTARGET_SHARED_MEMORY_SIZE = %" PRIu64 "\n",
55549e976c9SShilei Tian          DynamicMemorySize);
556f1c821faSJoseph Huber     }
557a697a0a4SShilei Tian     if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS")) {
558a697a0a4SShilei Tian       // LIBOMPTARGET_NUM_INITIAL_STREAMS has been set
559a697a0a4SShilei Tian       NumInitialStreams = std::stoi(EnvStr);
560a697a0a4SShilei Tian       DP("Parsed LIBOMPTARGET_NUM_INITIAL_STREAMS=%d\n", NumInitialStreams);
561a697a0a4SShilei Tian     }
5620871d6d5SShilei Tian 
5630871d6d5SShilei Tian     for (int I = 0; I < NumberOfDevices; ++I)
56439d3283aSShilei Tian       DeviceAllocators.emplace_back();
5650871d6d5SShilei Tian 
5660871d6d5SShilei Tian     // Get the size threshold from environment variable
5670871d6d5SShilei Tian     std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
5680871d6d5SShilei Tian     UseMemoryManager = Res.second;
5690871d6d5SShilei Tian     size_t MemoryManagerThreshold = Res.first;
5700871d6d5SShilei Tian 
5710871d6d5SShilei Tian     if (UseMemoryManager)
5720871d6d5SShilei Tian       for (int I = 0; I < NumberOfDevices; ++I)
5730871d6d5SShilei Tian         MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
5740871d6d5SShilei Tian             DeviceAllocators[I], MemoryManagerThreshold));
57510aa83ffSJohannes Doerfert 
57610aa83ffSJohannes Doerfert     // We lazily initialize all devices later.
57710aa83ffSJohannes Doerfert     InitializedFlags.assign(NumberOfDevices, false);
5783de4cd12SGeorge Rokos   }
5793de4cd12SGeorge Rokos 
5804031bb98SShilei Tian   ~DeviceRTLTy() {
58110aa83ffSJohannes Doerfert     for (int DeviceId = 0; DeviceId < NumberOfDevices; ++DeviceId)
58210aa83ffSJohannes Doerfert       deinitDevice(DeviceId);
5833de4cd12SGeorge Rokos   }
5843de4cd12SGeorge Rokos 
5854031bb98SShilei Tian   // Check whether a given DeviceId is valid
5864031bb98SShilei Tian   bool isValidDeviceId(const int DeviceId) const {
5874031bb98SShilei Tian     return DeviceId >= 0 && DeviceId < NumberOfDevices;
58832ed2927SShilei Tian   }
58932ed2927SShilei Tian 
590cb038927SShilei Tian   int getNumOfDevices() const { return NumberOfDevices; }
5914031bb98SShilei Tian 
5924031bb98SShilei Tian   void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
5934031bb98SShilei Tian 
5944031bb98SShilei Tian   int initDevice(const int DeviceId) {
5954031bb98SShilei Tian     CUdevice Device;
5964031bb98SShilei Tian 
5974031bb98SShilei Tian     DP("Getting device %d\n", DeviceId);
5984031bb98SShilei Tian     CUresult Err = cuDeviceGet(&Device, DeviceId);
5994031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
60032ed2927SShilei Tian       return OFFLOAD_FAIL;
6013de4cd12SGeorge Rokos 
60210aa83ffSJohannes Doerfert     assert(InitializedFlags[DeviceId] == false && "Reinitializing device!");
60310aa83ffSJohannes Doerfert     InitializedFlags[DeviceId] = true;
60410aa83ffSJohannes Doerfert 
605c5348aecSYe Luo     // Query the current flags of the primary context and set its flags if
606c5348aecSYe Luo     // it is inactive
607c5348aecSYe Luo     unsigned int FormerPrimaryCtxFlags = 0;
608c5348aecSYe Luo     int FormerPrimaryCtxIsActive = 0;
609c5348aecSYe Luo     Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
610c5348aecSYe Luo                                      &FormerPrimaryCtxIsActive);
611c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
612c5348aecSYe Luo       return OFFLOAD_FAIL;
613c5348aecSYe Luo 
614c5348aecSYe Luo     if (FormerPrimaryCtxIsActive) {
615c5348aecSYe Luo       DP("The primary context is active, no change to its flags\n");
616c5348aecSYe Luo       if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
617c5348aecSYe Luo           CU_CTX_SCHED_BLOCKING_SYNC)
618c5348aecSYe Luo         DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
619c5348aecSYe Luo     } else {
620c5348aecSYe Luo       DP("The primary context is inactive, set its flags to "
621c5348aecSYe Luo          "CU_CTX_SCHED_BLOCKING_SYNC\n");
62295f0d1edSJon Chesterfield       Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
62395f0d1edSJon Chesterfield       if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
624c5348aecSYe Luo         return OFFLOAD_FAIL;
625c5348aecSYe Luo     }
626c5348aecSYe Luo 
627c5348aecSYe Luo     // Retain the per device primary context and save it to use whenever this
628c5348aecSYe Luo     // device is selected.
629c5348aecSYe Luo     Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
630c5348aecSYe Luo     if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
6313de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
6323de4cd12SGeorge Rokos 
6334031bb98SShilei Tian     Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
6344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
6354031bb98SShilei Tian       return OFFLOAD_FAIL;
636a5153dbcSJohannes Doerfert 
6371660288bSJohannes Doerfert     // Initialize the stream pool.
638a697a0a4SShilei Tian     if (!StreamPool[DeviceId])
63939d3283aSShilei Tian       StreamPool[DeviceId] = std::make_unique<StreamPoolTy>(StreamAllocatorTy(),
64039d3283aSShilei Tian                                                             NumInitialStreams);
6411660288bSJohannes Doerfert 
6421660288bSJohannes Doerfert     // Initialize the event pool.
6431660288bSJohannes Doerfert     if (!EventPool[DeviceId])
64439d3283aSShilei Tian       EventPool[DeviceId] =
64539d3283aSShilei Tian           std::make_unique<EventPoolTy>(EventAllocatorTy(), NumInitialEvents);
646a5153dbcSJohannes Doerfert 
647bb51d398SJonas Hahnfeld     // Query attributes to determine number of threads/block and blocks/grid.
6484031bb98SShilei Tian     int MaxGridDimX;
6494031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
6504031bb98SShilei Tian                                Device);
6514031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6524031bb98SShilei Tian       DP("Error getting max grid dimension, use default value %d\n",
6534031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
6544031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
655aca33b0bSShilei Tian     } else {
6564031bb98SShilei Tian       DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
6574031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
6583de4cd12SGeorge Rokos     }
6593de4cd12SGeorge Rokos 
660bb51d398SJonas Hahnfeld     // We are only exploiting threads along the x axis.
6614031bb98SShilei Tian     int MaxBlockDimX;
6624031bb98SShilei Tian     Err = cuDeviceGetAttribute(&MaxBlockDimX,
6634031bb98SShilei Tian                                CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
6644031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6654031bb98SShilei Tian       DP("Error getting max block dimension, use default value %d\n",
6664031bb98SShilei Tian          DeviceRTLTy::DefaultNumThreads);
6674031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
668422adaa8SJoseph Huber     } else {
6694031bb98SShilei Tian       DP("Using %d CUDA threads per block\n", MaxBlockDimX);
6704031bb98SShilei Tian       DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
671422adaa8SJoseph Huber 
672422adaa8SJoseph Huber       if (EnvTeamThreadLimit > 0 &&
673422adaa8SJoseph Huber           DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
674422adaa8SJoseph Huber         DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
675422adaa8SJoseph Huber            "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
676422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
677422adaa8SJoseph Huber         DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
678422adaa8SJoseph Huber       }
679422adaa8SJoseph Huber       if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
6804031bb98SShilei Tian         DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
6814031bb98SShilei Tian            "capping at the hard limit\n",
682422adaa8SJoseph Huber            DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
6834031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
6843de4cd12SGeorge Rokos       }
685422adaa8SJoseph Huber     }
6863de4cd12SGeorge Rokos 
6874031bb98SShilei Tian     // Get and set warp size
6884031bb98SShilei Tian     int WarpSize;
6894031bb98SShilei Tian     Err =
6904031bb98SShilei Tian         cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
6914031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
6924031bb98SShilei Tian       DP("Error getting warp size, assume default value 32\n");
6934031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = 32;
694bb51d398SJonas Hahnfeld     } else {
6954031bb98SShilei Tian       DP("Using warp size %d\n", WarpSize);
6964031bb98SShilei Tian       DeviceData[DeviceId].WarpSize = WarpSize;
6973de4cd12SGeorge Rokos     }
6983de4cd12SGeorge Rokos 
6993de4cd12SGeorge Rokos     // Adjust teams to the env variables
7004031bb98SShilei Tian     if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
7013de4cd12SGeorge Rokos       DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
7024031bb98SShilei Tian          EnvTeamLimit);
7034031bb98SShilei Tian       DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
7043de4cd12SGeorge Rokos     }
7053de4cd12SGeorge Rokos 
7063817ba13SJoseph Huber     size_t StackLimit;
7073817ba13SJoseph Huber     size_t HeapLimit;
7083817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
7093817ba13SJoseph Huber       StackLimit = std::stol(EnvStr);
7103817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
7113817ba13SJoseph Huber         return OFFLOAD_FAIL;
7123817ba13SJoseph Huber     } else {
7133817ba13SJoseph Huber       if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
7143817ba13SJoseph Huber         return OFFLOAD_FAIL;
7153817ba13SJoseph Huber     }
7163817ba13SJoseph Huber     if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
7173817ba13SJoseph Huber       HeapLimit = std::stol(EnvStr);
7183817ba13SJoseph Huber       if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
7193817ba13SJoseph Huber         return OFFLOAD_FAIL;
7203817ba13SJoseph Huber     } else {
7213817ba13SJoseph Huber       if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
7223817ba13SJoseph Huber         return OFFLOAD_FAIL;
7233817ba13SJoseph Huber     }
7243817ba13SJoseph Huber 
725119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
726ae209397SJoseph Huber          "Device supports up to %d CUDA blocks and %d threads with a "
727ae209397SJoseph Huber          "warp size of %d\n",
728ae209397SJoseph Huber          DeviceData[DeviceId].BlocksPerGrid,
729ae209397SJoseph Huber          DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
7303817ba13SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
7313817ba13SJoseph Huber          "Device heap size is %d Bytes, device stack size is %d Bytes per "
7323817ba13SJoseph Huber          "thread\n",
7333817ba13SJoseph Huber          (int)HeapLimit, (int)StackLimit);
7343de4cd12SGeorge Rokos 
7353de4cd12SGeorge Rokos     // Set default number of teams
7364031bb98SShilei Tian     if (EnvNumTeams > 0) {
7373de4cd12SGeorge Rokos       DP("Default number of teams set according to environment %d\n",
7384031bb98SShilei Tian          EnvNumTeams);
7394031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = EnvNumTeams;
7403de4cd12SGeorge Rokos     } else {
7414031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
7423de4cd12SGeorge Rokos       DP("Default number of teams set according to library's default %d\n",
7434031bb98SShilei Tian          DeviceRTLTy::DefaultNumTeams);
7443de4cd12SGeorge Rokos     }
7454031bb98SShilei Tian 
7464031bb98SShilei Tian     if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
7473de4cd12SGeorge Rokos       DP("Default number of teams exceeds device limit, capping at %d\n",
7484031bb98SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
7494031bb98SShilei Tian       DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
7503de4cd12SGeorge Rokos     }
7513de4cd12SGeorge Rokos 
7523de4cd12SGeorge Rokos     // Set default number of threads
7534031bb98SShilei Tian     DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
7543de4cd12SGeorge Rokos     DP("Default number of threads set according to library's default %d\n",
7554031bb98SShilei Tian        DeviceRTLTy::DefaultNumThreads);
7564031bb98SShilei Tian     if (DeviceData[DeviceId].NumThreads >
7574031bb98SShilei Tian         DeviceData[DeviceId].ThreadsPerBlock) {
7583de4cd12SGeorge Rokos       DP("Default number of threads exceeds device limit, capping at %d\n",
7594031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
760c060c634SShilei Tian       DeviceData[DeviceId].NumThreads = DeviceData[DeviceId].ThreadsPerBlock;
7613de4cd12SGeorge Rokos     }
7623de4cd12SGeorge Rokos 
7633de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
7643de4cd12SGeorge Rokos   }
7653de4cd12SGeorge Rokos 
76610aa83ffSJohannes Doerfert   int deinitDevice(const int DeviceId) {
76710aa83ffSJohannes Doerfert     auto IsInitialized = InitializedFlags[DeviceId];
76810aa83ffSJohannes Doerfert     if (!IsInitialized)
76910aa83ffSJohannes Doerfert       return OFFLOAD_SUCCESS;
77010aa83ffSJohannes Doerfert     InitializedFlags[DeviceId] = false;
77110aa83ffSJohannes Doerfert 
77210aa83ffSJohannes Doerfert     if (UseMemoryManager)
77310aa83ffSJohannes Doerfert       MemoryManagers[DeviceId].release();
77410aa83ffSJohannes Doerfert 
77510aa83ffSJohannes Doerfert     StreamPool[DeviceId].reset();
7761660288bSJohannes Doerfert     EventPool[DeviceId].reset();
77710aa83ffSJohannes Doerfert 
77810aa83ffSJohannes Doerfert     DeviceDataTy &D = DeviceData[DeviceId];
7795105c7cdSShilei Tian     if (!checkResult(cuCtxSetCurrent(D.Context),
7805105c7cdSShilei Tian                      "Error returned from cuCtxSetCurrent\n"))
7815105c7cdSShilei Tian       return OFFLOAD_FAIL;
7825105c7cdSShilei Tian 
7835105c7cdSShilei Tian     // Unload all modules.
7845105c7cdSShilei Tian     for (auto &M : Modules[DeviceId])
7855105c7cdSShilei Tian       if (!checkResult(cuModuleUnload(M),
7865105c7cdSShilei Tian                        "Error returned from cuModuleUnload\n"))
7875105c7cdSShilei Tian         return OFFLOAD_FAIL;
7885105c7cdSShilei Tian 
7895105c7cdSShilei Tian     // Destroy context.
79010aa83ffSJohannes Doerfert     CUdevice Device;
7915105c7cdSShilei Tian     if (!checkResult(cuCtxGetDevice(&Device),
79210aa83ffSJohannes Doerfert                      "Error returned from cuCtxGetDevice\n"))
7935105c7cdSShilei Tian       return OFFLOAD_FAIL;
7945105c7cdSShilei Tian 
7955105c7cdSShilei Tian     if (!checkResult(cuDevicePrimaryCtxRelease(Device),
7965105c7cdSShilei Tian                      "Error returned from cuDevicePrimaryCtxRelease\n"))
7975105c7cdSShilei Tian       return OFFLOAD_FAIL;
7985105c7cdSShilei Tian 
79910aa83ffSJohannes Doerfert     return OFFLOAD_SUCCESS;
80010aa83ffSJohannes Doerfert   }
80110aa83ffSJohannes Doerfert 
8024031bb98SShilei Tian   __tgt_target_table *loadBinary(const int DeviceId,
8034031bb98SShilei Tian                                  const __tgt_device_image *Image) {
8043de4cd12SGeorge Rokos     // Clear the offload table as we are going to create a new one.
8054031bb98SShilei Tian     clearOffloadEntriesTable(DeviceId);
8063de4cd12SGeorge Rokos 
8073de4cd12SGeorge Rokos     // Create the module and extract the function pointers.
8084031bb98SShilei Tian     CUmodule Module;
8094031bb98SShilei Tian     DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
81039d3283aSShilei Tian     CUresult Err =
81139d3283aSShilei Tian         cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
8124031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
8134031bb98SShilei Tian       return nullptr;
8143de4cd12SGeorge Rokos 
8153de4cd12SGeorge Rokos     DP("CUDA module successfully loaded!\n");
8164031bb98SShilei Tian 
8175105c7cdSShilei Tian     Modules[DeviceId].push_back(Module);
8183de4cd12SGeorge Rokos 
8193de4cd12SGeorge Rokos     // Find the symbols in the module by name.
8204031bb98SShilei Tian     const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
8214031bb98SShilei Tian     const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
8223de4cd12SGeorge Rokos 
8235272d29eSJohannes Doerfert     std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
8244031bb98SShilei Tian     for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
8254031bb98SShilei Tian       if (!E->addr) {
8264031bb98SShilei Tian         // We return nullptr when something like this happens, the host should
8274031bb98SShilei Tian         // have always something in the address to uniquely identify the target
8284031bb98SShilei Tian         // region.
8294031bb98SShilei Tian         DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
8304031bb98SShilei Tian         return nullptr;
8313de4cd12SGeorge Rokos       }
8323de4cd12SGeorge Rokos 
8334031bb98SShilei Tian       if (E->size) {
8344031bb98SShilei Tian         __tgt_offload_entry Entry = *E;
8354031bb98SShilei Tian         CUdeviceptr CUPtr;
8364031bb98SShilei Tian         size_t CUSize;
83795f0d1edSJon Chesterfield         Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
8384031bb98SShilei Tian         // We keep this style here because we need the name
8394031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
8402ce16810SJoseph Huber           REPORT("Loading global '%s' Failed\n", E->name);
8414031bb98SShilei Tian           CUDA_ERR_STRING(Err);
8424031bb98SShilei Tian           return nullptr;
8433de4cd12SGeorge Rokos         }
8443de4cd12SGeorge Rokos 
8454031bb98SShilei Tian         if (CUSize != E->size) {
8464031bb98SShilei Tian           DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
8474031bb98SShilei Tian              CUSize, E->size);
8484031bb98SShilei Tian           return nullptr;
8493de4cd12SGeorge Rokos         }
8503de4cd12SGeorge Rokos 
8513de4cd12SGeorge Rokos         DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
8524031bb98SShilei Tian            DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
8534031bb98SShilei Tian 
8544031bb98SShilei Tian         Entry.addr = (void *)(CUPtr);
8553de4cd12SGeorge Rokos 
856aace6d28SGheorghe-Teodor Bercea         // Note: In the current implementation declare target variables
857aace6d28SGheorghe-Teodor Bercea         // can either be link or to. This means that once unified
858aace6d28SGheorghe-Teodor Bercea         // memory is activated via the requires directive, the variable
859aace6d28SGheorghe-Teodor Bercea         // can be used directly from the host in both cases.
860aace6d28SGheorghe-Teodor Bercea         // TODO: when variables types other than to or link are added,
8614c6a098aSKazuaki Ishizaki         // the below condition should be changed to explicitly
862aace6d28SGheorghe-Teodor Bercea         // check for to and link variables types:
8634031bb98SShilei Tian         // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
8644031bb98SShilei Tian         // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
8654031bb98SShilei Tian         if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
866aace6d28SGheorghe-Teodor Bercea           // If unified memory is present any target link or to variables
867c5fe030cSGheorghe-Teodor Bercea           // can access host addresses directly. There is no longer a
868c5fe030cSGheorghe-Teodor Bercea           // need for device copies.
86995f0d1edSJon Chesterfield           cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
8704031bb98SShilei Tian           DP("Copy linked variable host address (" DPxMOD
8714031bb98SShilei Tian              ") to device address (" DPxMOD ")\n",
8724031bb98SShilei Tian              DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
873c5fe030cSGheorghe-Teodor Bercea         }
874c5fe030cSGheorghe-Teodor Bercea 
8754031bb98SShilei Tian         addOffloadEntry(DeviceId, Entry);
8763de4cd12SGeorge Rokos 
8773de4cd12SGeorge Rokos         continue;
8783de4cd12SGeorge Rokos       }
8793de4cd12SGeorge Rokos 
8804031bb98SShilei Tian       CUfunction Func;
8814031bb98SShilei Tian       Err = cuModuleGetFunction(&Func, Module, E->name);
8824031bb98SShilei Tian       // We keep this style here because we need the name
8834031bb98SShilei Tian       if (Err != CUDA_SUCCESS) {
8842ce16810SJoseph Huber         REPORT("Loading '%s' Failed\n", E->name);
8854031bb98SShilei Tian         CUDA_ERR_STRING(Err);
8864031bb98SShilei Tian         return nullptr;
8873de4cd12SGeorge Rokos       }
8883de4cd12SGeorge Rokos 
8893de4cd12SGeorge Rokos       DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
8904031bb98SShilei Tian          DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
8913de4cd12SGeorge Rokos 
8923de4cd12SGeorge Rokos       // default value GENERIC (in case symbol is missing from cubin file)
893ca999f71SShilei Tian       llvm::omp::OMPTgtExecModeFlags ExecModeVal;
8944031bb98SShilei Tian       std::string ExecModeNameStr(E->name);
8953de4cd12SGeorge Rokos       ExecModeNameStr += "_exec_mode";
8963de4cd12SGeorge Rokos       const char *ExecModeName = ExecModeNameStr.c_str();
8973de4cd12SGeorge Rokos 
8983de4cd12SGeorge Rokos       CUdeviceptr ExecModePtr;
8994031bb98SShilei Tian       size_t CUSize;
90095f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
9014031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
902ca999f71SShilei Tian         if (CUSize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
9033de4cd12SGeorge Rokos           DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
904ca999f71SShilei Tian              ExecModeName, CUSize, sizeof(llvm::omp::OMPTgtExecModeFlags));
9054031bb98SShilei Tian           return nullptr;
9063de4cd12SGeorge Rokos         }
9073de4cd12SGeorge Rokos 
90895f0d1edSJon Chesterfield         Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
9094031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
9102ce16810SJoseph Huber           REPORT("Error when copying data from device to host. Pointers: "
9113de4cd12SGeorge Rokos                  "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
9124031bb98SShilei Tian                  DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
9134031bb98SShilei Tian           CUDA_ERR_STRING(Err);
9144031bb98SShilei Tian           return nullptr;
9153de4cd12SGeorge Rokos         }
9163de4cd12SGeorge Rokos       } else {
917edb8acdcSJoseph Huber         DP("Loading global exec_mode '%s' - symbol missing, using default "
9184031bb98SShilei Tian            "value GENERIC (1)\n",
9194031bb98SShilei Tian            ExecModeName);
9203de4cd12SGeorge Rokos       }
9213de4cd12SGeorge Rokos 
9224031bb98SShilei Tian       KernelsList.emplace_back(Func, ExecModeVal);
9233de4cd12SGeorge Rokos 
9244031bb98SShilei Tian       __tgt_offload_entry Entry = *E;
9254031bb98SShilei Tian       Entry.addr = &KernelsList.back();
9264031bb98SShilei Tian       addOffloadEntry(DeviceId, Entry);
9273de4cd12SGeorge Rokos     }
9283de4cd12SGeorge Rokos 
929e1c7a46dSGuansong Zhang     // send device environment data to the device
930e1c7a46dSGuansong Zhang     {
931ec02c34bSJoseph Huber       // TODO: The device ID used here is not the real device ID used by OpenMP.
9320c554a47SJon Chesterfield       DeviceEnvironmentTy DeviceEnv{0, static_cast<uint32_t>(NumberOfDevices),
9330c554a47SJon Chesterfield                                     static_cast<uint32_t>(DeviceId),
9340c554a47SJon Chesterfield                                     static_cast<uint32_t>(DynamicMemorySize)};
935e1c7a46dSGuansong Zhang 
9364031bb98SShilei Tian       if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
9370c554a47SJon Chesterfield         DeviceEnv.DebugKind = std::stoi(EnvStr);
938e1c7a46dSGuansong Zhang 
9394031bb98SShilei Tian       const char *DeviceEnvName = "omptarget_device_environment";
9404031bb98SShilei Tian       CUdeviceptr DeviceEnvPtr;
9414031bb98SShilei Tian       size_t CUSize;
942e1c7a46dSGuansong Zhang 
94395f0d1edSJon Chesterfield       Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
9444031bb98SShilei Tian       if (Err == CUDA_SUCCESS) {
9454031bb98SShilei Tian         if (CUSize != sizeof(DeviceEnv)) {
9462ce16810SJoseph Huber           REPORT(
9472ce16810SJoseph Huber               "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
9484031bb98SShilei Tian               DeviceEnvName, CUSize, sizeof(int32_t));
9494031bb98SShilei Tian           CUDA_ERR_STRING(Err);
9504031bb98SShilei Tian           return nullptr;
951e1c7a46dSGuansong Zhang         }
952e1c7a46dSGuansong Zhang 
95395f0d1edSJon Chesterfield         Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
9544031bb98SShilei Tian         if (Err != CUDA_SUCCESS) {
9552ce16810SJoseph Huber           REPORT("Error when copying data from host to device. Pointers: "
956e1c7a46dSGuansong Zhang                  "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
9574031bb98SShilei Tian                  DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
9584031bb98SShilei Tian           CUDA_ERR_STRING(Err);
9594031bb98SShilei Tian           return nullptr;
960e1c7a46dSGuansong Zhang         }
961e1c7a46dSGuansong Zhang 
9624031bb98SShilei Tian         DP("Sending global device environment data %zu bytes\n", CUSize);
963e1c7a46dSGuansong Zhang       } else {
9644031bb98SShilei Tian         DP("Finding global device environment '%s' - symbol missing.\n",
9654031bb98SShilei Tian            DeviceEnvName);
9664031bb98SShilei Tian         DP("Continue, considering this is a device RTL which does not accept "
9674031bb98SShilei Tian            "environment setting.\n");
968e1c7a46dSGuansong Zhang       }
969e1c7a46dSGuansong Zhang     }
970e1c7a46dSGuansong Zhang 
9714031bb98SShilei Tian     return getOffloadEntriesTable(DeviceId);
9723de4cd12SGeorge Rokos   }
9733de4cd12SGeorge Rokos 
974a15f8589SJoseph Huber   void *dataAlloc(const int DeviceId, const int64_t Size,
975a15f8589SJoseph Huber                   const TargetAllocTy Kind) {
976a15f8589SJoseph Huber     switch (Kind) {
977a15f8589SJoseph Huber     case TARGET_ALLOC_DEFAULT:
978a15f8589SJoseph Huber     case TARGET_ALLOC_DEVICE:
9790871d6d5SShilei Tian       if (UseMemoryManager)
9800871d6d5SShilei Tian         return MemoryManagers[DeviceId]->allocate(Size, nullptr);
981a15f8589SJoseph Huber       else
982a15f8589SJoseph Huber         return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
983a15f8589SJoseph Huber     case TARGET_ALLOC_HOST:
984a15f8589SJoseph Huber     case TARGET_ALLOC_SHARED:
985a15f8589SJoseph Huber       return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
986a15f8589SJoseph Huber     }
9874031bb98SShilei Tian 
988a15f8589SJoseph Huber     REPORT("Invalid target data allocation kind or requested allocator not "
989a15f8589SJoseph Huber            "implemented yet\n");
990a15f8589SJoseph Huber 
991a15f8589SJoseph Huber     return nullptr;
9923de4cd12SGeorge Rokos   }
9933de4cd12SGeorge Rokos 
9944031bb98SShilei Tian   int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
9955449fbb5SJohannes Doerfert                  const int64_t Size, __tgt_async_info *AsyncInfo) const {
9965449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
9973de4cd12SGeorge Rokos 
9985449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
99939d3283aSShilei Tian     CUresult Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
10004031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
100129338459SJoseph Huber       DP("Error when copying data from host to device. Pointers: host "
10022ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
10034031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
10044031bb98SShilei Tian       CUDA_ERR_STRING(Err);
10053de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
10063de4cd12SGeorge Rokos     }
10073de4cd12SGeorge Rokos 
10083de4cd12SGeorge Rokos     return OFFLOAD_SUCCESS;
10093de4cd12SGeorge Rokos   }
10103de4cd12SGeorge Rokos 
10114031bb98SShilei Tian   int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
10125449fbb5SJohannes Doerfert                    const int64_t Size, __tgt_async_info *AsyncInfo) const {
10135449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
10144031bb98SShilei Tian 
10155449fbb5SJohannes Doerfert     CUstream Stream = getStream(DeviceId, AsyncInfo);
101639d3283aSShilei Tian     CUresult Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
10174031bb98SShilei Tian     if (Err != CUDA_SUCCESS) {
101829338459SJoseph Huber       DP("Error when copying data from device to host. Pointers: host "
10192ce16810SJoseph Huber          "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
10204031bb98SShilei Tian          DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
10214031bb98SShilei Tian       CUDA_ERR_STRING(Err);
10223de4cd12SGeorge Rokos       return OFFLOAD_FAIL;
10233de4cd12SGeorge Rokos     }
10243de4cd12SGeorge Rokos 
10254031bb98SShilei Tian     return OFFLOAD_SUCCESS;
10264031bb98SShilei Tian   }
10274031bb98SShilei Tian 
1028a014fbbcSShilei Tian   int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
10292695e23aSShilei Tian                    int64_t Size, __tgt_async_info *AsyncInfo) {
10305449fbb5SJohannes Doerfert     assert(AsyncInfo && "AsyncInfo is nullptr");
1031a014fbbcSShilei Tian 
103239d3283aSShilei Tian     CUresult Err;
10335449fbb5SJohannes Doerfert     CUstream Stream = getStream(SrcDevId, AsyncInfo);
1034a014fbbcSShilei Tian 
1035a014fbbcSShilei Tian     // If they are two devices, we try peer to peer copy first
1036a014fbbcSShilei Tian     if (SrcDevId != DstDevId) {
10372695e23aSShilei Tian       std::lock_guard<std::mutex> LG(PeerAccessMatrixLock);
10382695e23aSShilei Tian 
10392695e23aSShilei Tian       switch (PeerAccessMatrix[SrcDevId][DstDevId]) {
10402695e23aSShilei Tian       case PeerAccessState::No: {
10412695e23aSShilei Tian         REPORT("Peer access from %" PRId32 " to %" PRId32
10422695e23aSShilei Tian                " is not supported. Fall back to D2D memcpy.\n",
10432695e23aSShilei Tian                SrcDevId, DstDevId);
10442695e23aSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
10452695e23aSShilei Tian       }
10462695e23aSShilei Tian       case PeerAccessState::Unkown: {
1047a014fbbcSShilei Tian         int CanAccessPeer = 0;
1048a014fbbcSShilei Tian         Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
1049a014fbbcSShilei Tian         if (Err != CUDA_SUCCESS) {
10502ce16810SJoseph Huber           REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
10512695e23aSShilei Tian                  ", dst = %" PRId32 ". Fall back to D2D memcpy.\n",
1052a014fbbcSShilei Tian                  SrcDevId, DstDevId);
1053a014fbbcSShilei Tian           CUDA_ERR_STRING(Err);
10542695e23aSShilei Tian           PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1055a014fbbcSShilei Tian           return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1056a014fbbcSShilei Tian         }
1057a014fbbcSShilei Tian 
1058a014fbbcSShilei Tian         if (!CanAccessPeer) {
10592695e23aSShilei Tian           REPORT("P2P access from %d to %d is not supported. Fall back to D2D "
10602695e23aSShilei Tian                  "memcpy.\n",
10612695e23aSShilei Tian                  SrcDevId, DstDevId);
10622695e23aSShilei Tian           PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1063a014fbbcSShilei Tian           return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1064a014fbbcSShilei Tian         }
1065a014fbbcSShilei Tian 
1066a014fbbcSShilei Tian         Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
1067a014fbbcSShilei Tian         if (Err != CUDA_SUCCESS) {
10682ce16810SJoseph Huber           REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
10692695e23aSShilei Tian                  ", dst = %" PRId32 ". Fall back to D2D memcpy.\n",
1070a014fbbcSShilei Tian                  SrcDevId, DstDevId);
1071a014fbbcSShilei Tian           CUDA_ERR_STRING(Err);
10722695e23aSShilei Tian           PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1073a014fbbcSShilei Tian           return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1074a014fbbcSShilei Tian         }
1075a014fbbcSShilei Tian 
10762695e23aSShilei Tian         PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::Yes;
10772695e23aSShilei Tian 
10782695e23aSShilei Tian         LLVM_FALLTHROUGH;
10792695e23aSShilei Tian       }
10802695e23aSShilei Tian       case PeerAccessState::Yes: {
10812695e23aSShilei Tian         Err = cuMemcpyPeerAsync(
10822695e23aSShilei Tian             (CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
10832695e23aSShilei Tian             (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context, Size, Stream);
1084a014fbbcSShilei Tian         if (Err == CUDA_SUCCESS)
1085a014fbbcSShilei Tian           return OFFLOAD_SUCCESS;
1086a014fbbcSShilei Tian 
108729338459SJoseph Huber         DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
10882695e23aSShilei Tian            ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32
10892695e23aSShilei Tian            ". Fall back to D2D memcpy.\n",
109045bb073dSYe Luo            DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
1091a014fbbcSShilei Tian         CUDA_ERR_STRING(Err);
10922695e23aSShilei Tian 
10932695e23aSShilei Tian         return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
10942695e23aSShilei Tian       }
10952695e23aSShilei Tian       }
1096a014fbbcSShilei Tian     }
1097a014fbbcSShilei Tian 
1098a014fbbcSShilei Tian     return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1099a014fbbcSShilei Tian   }
1100a014fbbcSShilei Tian 
11010871d6d5SShilei Tian   int dataDelete(const int DeviceId, void *TgtPtr) {
11020871d6d5SShilei Tian     if (UseMemoryManager)
11030871d6d5SShilei Tian       return MemoryManagers[DeviceId]->free(TgtPtr);
11044031bb98SShilei Tian 
11050871d6d5SShilei Tian     return DeviceAllocators[DeviceId].free(TgtPtr);
11064031bb98SShilei Tian   }
11074031bb98SShilei Tian 
1108aa27cfc1SJohannes Doerfert   int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1109aa27cfc1SJohannes Doerfert                           ptrdiff_t *TgtOffsets, const int ArgNum,
1110aa27cfc1SJohannes Doerfert                           const int TeamNum, const int ThreadLimit,
11114031bb98SShilei Tian                           const unsigned int LoopTripCount,
11124031bb98SShilei Tian                           __tgt_async_info *AsyncInfo) const {
11133de4cd12SGeorge Rokos     // All args are references.
11144031bb98SShilei Tian     std::vector<void *> Args(ArgNum);
11154031bb98SShilei Tian     std::vector<void *> Ptrs(ArgNum);
11163de4cd12SGeorge Rokos 
11174031bb98SShilei Tian     for (int I = 0; I < ArgNum; ++I) {
11184031bb98SShilei Tian       Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
11194031bb98SShilei Tian       Args[I] = &Ptrs[I];
11201546d319SGeorge Rokos     }
11213de4cd12SGeorge Rokos 
1122aa27cfc1SJohannes Doerfert     KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
11233de4cd12SGeorge Rokos 
1124ca999f71SShilei Tian     const bool IsSPMDGenericMode =
1125ca999f71SShilei Tian         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD;
1126ca999f71SShilei Tian     const bool IsSPMDMode =
1127ca999f71SShilei Tian         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
1128ca999f71SShilei Tian     const bool IsGenericMode =
1129ca999f71SShilei Tian         KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
1130ca999f71SShilei Tian 
1131aa27cfc1SJohannes Doerfert     int CudaThreadsPerBlock;
11324031bb98SShilei Tian     if (ThreadLimit > 0) {
11334031bb98SShilei Tian       DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
11344031bb98SShilei Tian       CudaThreadsPerBlock = ThreadLimit;
11353de4cd12SGeorge Rokos       // Add master warp if necessary
1136ca999f71SShilei Tian       if (IsGenericMode) {
11374031bb98SShilei Tian         DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
11384031bb98SShilei Tian         CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
11393de4cd12SGeorge Rokos       }
1140c13df8e5SGeorge Rokos     } else {
1141c13df8e5SGeorge Rokos       DP("Setting CUDA threads per block to default %d\n",
11424031bb98SShilei Tian          DeviceData[DeviceId].NumThreads);
11434031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1144c13df8e5SGeorge Rokos     }
11453de4cd12SGeorge Rokos 
11464031bb98SShilei Tian     if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
11473de4cd12SGeorge Rokos       DP("Threads per block capped at device limit %d\n",
11484031bb98SShilei Tian          DeviceData[DeviceId].ThreadsPerBlock);
11494031bb98SShilei Tian       CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
11503de4cd12SGeorge Rokos     }
11513de4cd12SGeorge Rokos 
115239d3283aSShilei Tian     CUresult Err;
1153aa27cfc1SJohannes Doerfert     if (!KernelInfo->MaxThreadsPerBlock) {
1154aa27cfc1SJohannes Doerfert       Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
11554031bb98SShilei Tian                                CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
11564031bb98SShilei Tian                                KernelInfo->Func);
1157aa27cfc1SJohannes Doerfert       if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1158aa27cfc1SJohannes Doerfert         return OFFLOAD_FAIL;
1159aa27cfc1SJohannes Doerfert     }
1160aa27cfc1SJohannes Doerfert 
1161aa27cfc1SJohannes Doerfert     if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1162aa27cfc1SJohannes Doerfert       DP("Threads per block capped at kernel limit %d\n",
1163aa27cfc1SJohannes Doerfert          KernelInfo->MaxThreadsPerBlock);
1164aa27cfc1SJohannes Doerfert       CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
11653de4cd12SGeorge Rokos     }
11663de4cd12SGeorge Rokos 
11674031bb98SShilei Tian     unsigned int CudaBlocksPerGrid;
11684031bb98SShilei Tian     if (TeamNum <= 0) {
11694031bb98SShilei Tian       if (LoopTripCount > 0 && EnvNumTeams < 0) {
1170ca999f71SShilei Tian         if (IsSPMDGenericMode) {
1171ca999f71SShilei Tian           // If we reach this point, then we are executing a kernel that was
1172ca999f71SShilei Tian           // transformed from Generic-mode to SPMD-mode. This kernel has
1173ca999f71SShilei Tian           // SPMD-mode execution, but needs its blocks to be scheduled
1174ca999f71SShilei Tian           // differently because the current loop trip count only applies to the
1175ca999f71SShilei Tian           // `teams distribute` region and will create var too few blocks using
1176ca999f71SShilei Tian           // the regular SPMD-mode method.
1177ca999f71SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
1178ca999f71SShilei Tian         } else if (IsSPMDMode) {
11794031bb98SShilei Tian           // We have a combined construct, i.e. `target teams distribute
11804031bb98SShilei Tian           // parallel for [simd]`. We launch so many teams so that each thread
11814031bb98SShilei Tian           // will execute one iteration of the loop. round up to the nearest
11824031bb98SShilei Tian           // integer
11834031bb98SShilei Tian           CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
1184ca999f71SShilei Tian         } else if (IsGenericMode) {
1185c13df8e5SGeorge Rokos           // If we reach this point, then we have a non-combined construct, i.e.
1186c13df8e5SGeorge Rokos           // `teams distribute` with a nested `parallel for` and each team is
1187c13df8e5SGeorge Rokos           // assigned one iteration of the `distribute` loop. E.g.:
1188c13df8e5SGeorge Rokos           //
1189c13df8e5SGeorge Rokos           // #pragma omp target teams distribute
1190c13df8e5SGeorge Rokos           // for(...loop_tripcount...) {
1191c13df8e5SGeorge Rokos           //   #pragma omp parallel for
1192c13df8e5SGeorge Rokos           //   for(...) {}
1193c13df8e5SGeorge Rokos           // }
1194c13df8e5SGeorge Rokos           //
1195c13df8e5SGeorge Rokos           // Threads within a team will execute the iterations of the `parallel`
1196c13df8e5SGeorge Rokos           // loop.
11974031bb98SShilei Tian           CudaBlocksPerGrid = LoopTripCount;
1198a158d366SJoseph Huber         } else {
1199ca999f71SShilei Tian           REPORT("Unknown execution mode: %d\n",
1200ca999f71SShilei Tian                  static_cast<int8_t>(KernelInfo->ExecutionMode));
1201a158d366SJoseph Huber           return OFFLOAD_FAIL;
1202c13df8e5SGeorge Rokos         }
120345bb073dSYe Luo         DP("Using %d teams due to loop trip count %" PRIu32
12044031bb98SShilei Tian            " and number of threads per block %d\n",
12054031bb98SShilei Tian            CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
12063de4cd12SGeorge Rokos       } else {
12074031bb98SShilei Tian         DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
12084031bb98SShilei Tian         CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
12093de4cd12SGeorge Rokos       }
12103de4cd12SGeorge Rokos     } else {
12114031bb98SShilei Tian       DP("Using requested number of teams %d\n", TeamNum);
12124031bb98SShilei Tian       CudaBlocksPerGrid = TeamNum;
12133de4cd12SGeorge Rokos     }
12143de4cd12SGeorge Rokos 
1215f6685f77SShilei Tian     if (CudaBlocksPerGrid > DeviceData[DeviceId].BlocksPerGrid) {
1216f6685f77SShilei Tian       DP("Capping number of teams to team limit %d\n",
1217f6685f77SShilei Tian          DeviceData[DeviceId].BlocksPerGrid);
1218f6685f77SShilei Tian       CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
1219f6685f77SShilei Tian     }
1220f6685f77SShilei Tian 
1221119a9ea1SJoseph Huber     INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1222ca999f71SShilei Tian          "Launching kernel %s with %d blocks and %d threads in %s mode\n",
1223ae209397SJoseph Huber          (getOffloadEntry(DeviceId, TgtEntryPtr))
1224ae209397SJoseph Huber              ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1225ae209397SJoseph Huber              : "(null)",
1226ae209397SJoseph Huber          CudaBlocksPerGrid, CudaThreadsPerBlock,
1227ca999f71SShilei Tian          (!IsSPMDMode ? (IsGenericMode ? "Generic" : "SPMD-Generic") : "SPMD"));
12283de4cd12SGeorge Rokos 
12294031bb98SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
12304031bb98SShilei Tian     Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
12314031bb98SShilei Tian                          /* gridDimZ */ 1, CudaThreadsPerBlock,
12324031bb98SShilei Tian                          /* blockDimY */ 1, /* blockDimZ */ 1,
1233f1c821faSJoseph Huber                          DynamicMemorySize, Stream, &Args[0], nullptr);
12344031bb98SShilei Tian     if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
12354031bb98SShilei Tian       return OFFLOAD_FAIL;
12364031bb98SShilei Tian 
12374031bb98SShilei Tian     DP("Launch of entry point at " DPxMOD " successful!\n",
12384031bb98SShilei Tian        DPxPTR(TgtEntryPtr));
12394031bb98SShilei Tian 
12404031bb98SShilei Tian     return OFFLOAD_SUCCESS;
12414031bb98SShilei Tian   }
12424031bb98SShilei Tian 
12435449fbb5SJohannes Doerfert   int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
12445449fbb5SJohannes Doerfert     CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
12454031bb98SShilei Tian     CUresult Err = cuStreamSynchronize(Stream);
12463de4cd12SGeorge Rokos 
12474031bb98SShilei Tian     // Once the stream is synchronized, return it to stream pool and reset
12485449fbb5SJohannes Doerfert     // AsyncInfo. This is to make sure the synchronization only works for its
12494031bb98SShilei Tian     // own tasks.
1250a697a0a4SShilei Tian     StreamPool[DeviceId]->release(reinterpret_cast<CUstream>(AsyncInfo->Queue));
12515449fbb5SJohannes Doerfert     AsyncInfo->Queue = nullptr;
12523de4cd12SGeorge Rokos 
125316064e71SJoseph Huber     if (Err != CUDA_SUCCESS) {
125429338459SJoseph Huber       DP("Error when synchronizing stream. stream = " DPxMOD
125516064e71SJoseph Huber          ", async info ptr = " DPxMOD "\n",
125616064e71SJoseph Huber          DPxPTR(Stream), DPxPTR(AsyncInfo));
125716064e71SJoseph Huber       CUDA_ERR_STRING(Err);
125816064e71SJoseph Huber     }
125916064e71SJoseph Huber     return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
12603de4cd12SGeorge Rokos   }
1261d2f85d09SJose M Monsalve Diaz 
1262d27d0a67SJoseph Huber   void printDeviceInfo(int32_t DeviceId) {
1263d2f85d09SJose M Monsalve Diaz     char TmpChar[1000];
1264d2f85d09SJose M Monsalve Diaz     std::string TmpStr;
1265d2f85d09SJose M Monsalve Diaz     size_t TmpSt;
1266d2f85d09SJose M Monsalve Diaz     int TmpInt, TmpInt2, TmpInt3;
1267d2f85d09SJose M Monsalve Diaz 
1268d2f85d09SJose M Monsalve Diaz     CUdevice Device;
1269d27d0a67SJoseph Huber     checkResult(cuDeviceGet(&Device, DeviceId),
1270d2f85d09SJose M Monsalve Diaz                 "Error returned from cuCtxGetDevice\n");
1271d2f85d09SJose M Monsalve Diaz 
1272d2f85d09SJose M Monsalve Diaz     cuDriverGetVersion(&TmpInt);
1273d2f85d09SJose M Monsalve Diaz     printf("    CUDA Driver Version: \t\t%d \n", TmpInt);
1274d27d0a67SJoseph Huber     printf("    CUDA Device Number: \t\t%d \n", DeviceId);
1275d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1276d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetName\n");
1277d2f85d09SJose M Monsalve Diaz     printf("    Device Name: \t\t\t%s \n", TmpChar);
1278d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceTotalMem(&TmpSt, Device),
1279d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceTotalMem\n");
1280d2f85d09SJose M Monsalve Diaz     printf("    Global Memory Size: \t\t%zu bytes \n", TmpSt);
1281d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1282d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1283d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1284d2f85d09SJose M Monsalve Diaz     printf("    Number of Multiprocessors: \t\t%d \n", TmpInt);
1285d2f85d09SJose M Monsalve Diaz     checkResult(
1286d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1287d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1288d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1289d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1290d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1291d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1292d2f85d09SJose M Monsalve Diaz     printf("    Total Constant Memory: \t\t%d bytes\n", TmpInt);
1293d2f85d09SJose M Monsalve Diaz     checkResult(
1294d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1295d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1296d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1297d2f85d09SJose M Monsalve Diaz     printf("    Max Shared Memory per Block: \t%d bytes \n", TmpInt);
129828939b6aSShilei Tian     checkResult(
129928939b6aSShilei Tian         cuDeviceGetAttribute(
1300d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1301d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1302d2f85d09SJose M Monsalve Diaz     printf("    Registers per Block: \t\t%d \n", TmpInt);
1303d2f85d09SJose M Monsalve Diaz     checkResult(
1304d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1305d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1306d2f85d09SJose M Monsalve Diaz     printf("    Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1307d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1308d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1309d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1310d2f85d09SJose M Monsalve Diaz     printf("    Maximum Threads per Block: \t\t%d \n", TmpInt);
131128939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
131228939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1313d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
131428939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
131528939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1316d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
131728939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
131828939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1319d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1320d2f85d09SJose M Monsalve Diaz     printf("    Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1321d2f85d09SJose M Monsalve Diaz            TmpInt3);
132228939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
132328939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1324d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
132528939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
132628939b6aSShilei Tian                     &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1327d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
132828939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
132928939b6aSShilei Tian                     &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1330d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1331d2f85d09SJose M Monsalve Diaz     printf("    Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1332d2f85d09SJose M Monsalve Diaz            TmpInt3);
1333d2f85d09SJose M Monsalve Diaz     checkResult(
1334d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1335d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1336d2f85d09SJose M Monsalve Diaz     printf("    Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1337d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1338d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1339d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1340d2f85d09SJose M Monsalve Diaz     printf("    Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1341d2f85d09SJose M Monsalve Diaz     checkResult(
1342d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1343d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1344d2f85d09SJose M Monsalve Diaz     printf("    Clock Rate: \t\t\t%d kHz\n", TmpInt);
1345d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1346d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1347d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1348d2f85d09SJose M Monsalve Diaz     printf("    Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1349d2f85d09SJose M Monsalve Diaz     checkResult(
1350d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1351d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1352d2f85d09SJose M Monsalve Diaz     printf("    Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1353d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1354d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1355d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1356d2f85d09SJose M Monsalve Diaz     printf("    Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1357d2f85d09SJose M Monsalve Diaz     checkResult(
1358d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1359d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1360d2f85d09SJose M Monsalve Diaz     if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1361d2f85d09SJose M Monsalve Diaz       TmpStr = "DEFAULT";
1362d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1363d2f85d09SJose M Monsalve Diaz       TmpStr = "PROHIBITED";
1364d2f85d09SJose M Monsalve Diaz     else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1365d2f85d09SJose M Monsalve Diaz       TmpStr = "EXCLUSIVE PROCESS";
1366d2f85d09SJose M Monsalve Diaz     else
1367d2f85d09SJose M Monsalve Diaz       TmpStr = "unknown";
1368d2f85d09SJose M Monsalve Diaz     printf("    Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1369d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1370d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1371d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1372d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1373d2f85d09SJose M Monsalve Diaz     checkResult(
1374d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1375d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1376d2f85d09SJose M Monsalve Diaz     printf("    ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1377d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1378d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1379d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1380d2f85d09SJose M Monsalve Diaz     printf("    Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
138128939b6aSShilei Tian     checkResult(
138228939b6aSShilei Tian         cuDeviceGetAttribute(
1383d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1384d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1385d2f85d09SJose M Monsalve Diaz     printf("    Memory Bus Width: \t\t\t%d bits\n", TmpInt);
138628939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
138728939b6aSShilei Tian                                      Device),
1388d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1389d2f85d09SJose M Monsalve Diaz     printf("    L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
139028939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
139128939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
139228939b6aSShilei Tian                     Device),
1393d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1394d2f85d09SJose M Monsalve Diaz     printf("    Max Threads Per SMP: \t\t%d \n", TmpInt);
1395d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1396d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1397d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1398d2f85d09SJose M Monsalve Diaz     printf("    Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1399d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1400d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1401d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1402d2f85d09SJose M Monsalve Diaz     printf("    Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
140328939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
140428939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1405d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1406d2f85d09SJose M Monsalve Diaz     printf("    Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1407d2f85d09SJose M Monsalve Diaz     checkResult(
1408d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1409d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1410d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1411d2f85d09SJose M Monsalve Diaz     printf("    Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1412d2f85d09SJose M Monsalve Diaz     checkResult(
1413d2f85d09SJose M Monsalve Diaz         cuDeviceGetAttribute(
1414d2f85d09SJose M Monsalve Diaz             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1415d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1416d2f85d09SJose M Monsalve Diaz     printf("    Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1417d2f85d09SJose M Monsalve Diaz     checkResult(cuDeviceGetAttribute(
1418d2f85d09SJose M Monsalve Diaz                     &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1419d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1420d2f85d09SJose M Monsalve Diaz     printf("    Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
142128939b6aSShilei Tian     checkResult(cuDeviceGetAttribute(
142228939b6aSShilei Tian                     &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1423d2f85d09SJose M Monsalve Diaz                 "Error returned from cuDeviceGetAttribute\n");
1424d2f85d09SJose M Monsalve Diaz     printf("    Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
142528939b6aSShilei Tian     checkResult(
142628939b6aSShilei Tian         cuDeviceGetAttribute(
142728939b6aSShilei Tian             &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1428d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
142928939b6aSShilei Tian     checkResult(
143028939b6aSShilei Tian         cuDeviceGetAttribute(
143128939b6aSShilei Tian             &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1432d2f85d09SJose M Monsalve Diaz         "Error returned from cuDeviceGetAttribute\n");
1433d2f85d09SJose M Monsalve Diaz     printf("    Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1434d2f85d09SJose M Monsalve Diaz   }
143529df4ab3SShilei Tian 
14361660288bSJohannes Doerfert   int createEvent(int DeviceId, void **P) {
1437943d1d83SShilei Tian     CUevent Event = nullptr;
14381660288bSJohannes Doerfert     if (EventPool[DeviceId]->acquire(Event) != OFFLOAD_SUCCESS)
1439943d1d83SShilei Tian       return OFFLOAD_FAIL;
1440943d1d83SShilei Tian     *P = Event;
1441943d1d83SShilei Tian     return OFFLOAD_SUCCESS;
1442943d1d83SShilei Tian   }
1443943d1d83SShilei Tian 
14441660288bSJohannes Doerfert   int destroyEvent(int DeviceId, void *EventPtr) {
14451660288bSJohannes Doerfert     EventPool[DeviceId]->release(reinterpret_cast<CUevent>(EventPtr));
1446943d1d83SShilei Tian     return OFFLOAD_SUCCESS;
1447943d1d83SShilei Tian   }
1448943d1d83SShilei Tian 
144929df4ab3SShilei Tian   int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo,
145029df4ab3SShilei Tian                 void *EventPtr) const {
145129df4ab3SShilei Tian     CUstream Stream = getStream(DeviceId, AsyncInfo);
145229df4ab3SShilei Tian     CUevent Event = reinterpret_cast<CUevent>(EventPtr);
145329df4ab3SShilei Tian 
145429df4ab3SShilei Tian     // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from
145529df4ab3SShilei Tian     // specific CUDA version, and defined as 0x0. In previous version, per CUDA
145629df4ab3SShilei Tian     // API document, that argument has to be 0x0.
145729df4ab3SShilei Tian     CUresult Err = cuStreamWaitEvent(Stream, Event, 0);
145829df4ab3SShilei Tian     if (Err != CUDA_SUCCESS) {
145929df4ab3SShilei Tian       DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n",
146029df4ab3SShilei Tian          DPxPTR(Stream), DPxPTR(Event));
146129df4ab3SShilei Tian       CUDA_ERR_STRING(Err);
146229df4ab3SShilei Tian       return OFFLOAD_FAIL;
146329df4ab3SShilei Tian     }
146429df4ab3SShilei Tian 
146529df4ab3SShilei Tian     return OFFLOAD_SUCCESS;
146629df4ab3SShilei Tian   }
1467f44e41afSSri Hari Krishna Narayanan 
1468f44e41afSSri Hari Krishna Narayanan   int releaseAsyncInfo(int DeviceId, __tgt_async_info *AsyncInfo) const {
1469f44e41afSSri Hari Krishna Narayanan     if (AsyncInfo->Queue) {
1470f44e41afSSri Hari Krishna Narayanan       StreamPool[DeviceId]->release(
1471f44e41afSSri Hari Krishna Narayanan           reinterpret_cast<CUstream>(AsyncInfo->Queue));
1472f44e41afSSri Hari Krishna Narayanan       AsyncInfo->Queue = nullptr;
1473f44e41afSSri Hari Krishna Narayanan     }
1474f44e41afSSri Hari Krishna Narayanan 
1475f44e41afSSri Hari Krishna Narayanan     return OFFLOAD_SUCCESS;
1476f44e41afSSri Hari Krishna Narayanan   }
1477f44e41afSSri Hari Krishna Narayanan 
1478f44e41afSSri Hari Krishna Narayanan   int initAsyncInfo(int DeviceId, __tgt_async_info **AsyncInfo) const {
1479f44e41afSSri Hari Krishna Narayanan     *AsyncInfo = new __tgt_async_info;
1480f44e41afSSri Hari Krishna Narayanan     getStream(DeviceId, *AsyncInfo);
1481f44e41afSSri Hari Krishna Narayanan     return OFFLOAD_SUCCESS;
1482f44e41afSSri Hari Krishna Narayanan   }
1483f44e41afSSri Hari Krishna Narayanan 
1484f44e41afSSri Hari Krishna Narayanan   int initDeviceInfo(int DeviceId, __tgt_device_info *DeviceInfo,
1485f44e41afSSri Hari Krishna Narayanan                      const char **ErrStr) const {
1486f44e41afSSri Hari Krishna Narayanan     assert(DeviceInfo && "DeviceInfo is nullptr");
1487f44e41afSSri Hari Krishna Narayanan 
1488f44e41afSSri Hari Krishna Narayanan     if (!DeviceInfo->Context)
1489f44e41afSSri Hari Krishna Narayanan       DeviceInfo->Context = DeviceData[DeviceId].Context;
1490f44e41afSSri Hari Krishna Narayanan     if (!DeviceInfo->Device) {
1491f44e41afSSri Hari Krishna Narayanan       CUdevice Dev;
1492f44e41afSSri Hari Krishna Narayanan       CUresult Err = cuDeviceGet(&Dev, DeviceId);
1493f44e41afSSri Hari Krishna Narayanan       if (Err == CUDA_SUCCESS) {
1494f44e41afSSri Hari Krishna Narayanan         DeviceInfo->Device = reinterpret_cast<void *>(Dev);
1495f44e41afSSri Hari Krishna Narayanan       } else {
1496f44e41afSSri Hari Krishna Narayanan         cuGetErrorString(Err, ErrStr);
1497f44e41afSSri Hari Krishna Narayanan         return OFFLOAD_FAIL;
1498f44e41afSSri Hari Krishna Narayanan       }
1499f44e41afSSri Hari Krishna Narayanan     }
1500f44e41afSSri Hari Krishna Narayanan     return OFFLOAD_SUCCESS;
1501f44e41afSSri Hari Krishna Narayanan   }
150239d3283aSShilei Tian 
150339d3283aSShilei Tian   int setContext(int DeviceId) {
150439d3283aSShilei Tian     assert(InitializedFlags[DeviceId] && "Device is not initialized");
150539d3283aSShilei Tian 
150639d3283aSShilei Tian     CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
150739d3283aSShilei Tian     if (!checkResult(Err, "error returned from cuCtxSetCurrent"))
150839d3283aSShilei Tian       return OFFLOAD_FAIL;
150939d3283aSShilei Tian 
151039d3283aSShilei Tian     return OFFLOAD_SUCCESS;
151139d3283aSShilei Tian   }
15124031bb98SShilei Tian };
15134031bb98SShilei Tian 
15144031bb98SShilei Tian DeviceRTLTy DeviceRTL;
15154031bb98SShilei Tian } // namespace
15164031bb98SShilei Tian 
15174031bb98SShilei Tian // Exposed library API function
15184031bb98SShilei Tian #ifdef __cplusplus
15194031bb98SShilei Tian extern "C" {
15204031bb98SShilei Tian #endif
15214031bb98SShilei Tian 
1522d27d0a67SJoseph Huber int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *Image) {
1523d27d0a67SJoseph Huber   return elf_check_machine(Image, /* EM_CUDA */ 190);
15244031bb98SShilei Tian }
15254031bb98SShilei Tian 
1526e01ce4e8SJoseph Huber int32_t __tgt_rtl_is_valid_binary_info(__tgt_device_image *image,
1527e01ce4e8SJoseph Huber                                        __tgt_image_info *info) {
1528e01ce4e8SJoseph Huber   if (!__tgt_rtl_is_valid_binary(image))
1529e01ce4e8SJoseph Huber     return false;
1530e01ce4e8SJoseph Huber 
1531e01ce4e8SJoseph Huber   // A subarchitecture was not specified. Assume it is compatible.
1532e01ce4e8SJoseph Huber   if (!info->Arch)
1533e01ce4e8SJoseph Huber     return true;
1534e01ce4e8SJoseph Huber 
1535e01ce4e8SJoseph Huber   int32_t NumberOfDevices = 0;
1536e01ce4e8SJoseph Huber   if (cuDeviceGetCount(&NumberOfDevices) != CUDA_SUCCESS)
1537e01ce4e8SJoseph Huber     return false;
1538e01ce4e8SJoseph Huber 
1539e01ce4e8SJoseph Huber   for (int32_t DeviceId = 0; DeviceId < NumberOfDevices; ++DeviceId) {
1540e01ce4e8SJoseph Huber     CUdevice Device;
1541e01ce4e8SJoseph Huber     if (cuDeviceGet(&Device, DeviceId) != CUDA_SUCCESS)
1542e01ce4e8SJoseph Huber       return false;
1543e01ce4e8SJoseph Huber 
1544e01ce4e8SJoseph Huber     int32_t Major, Minor;
1545e01ce4e8SJoseph Huber     if (cuDeviceGetAttribute(&Major,
1546e01ce4e8SJoseph Huber                              CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,
1547e01ce4e8SJoseph Huber                              Device) != CUDA_SUCCESS)
1548e01ce4e8SJoseph Huber       return false;
1549e01ce4e8SJoseph Huber     if (cuDeviceGetAttribute(&Minor,
1550e01ce4e8SJoseph Huber                              CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,
1551e01ce4e8SJoseph Huber                              Device) != CUDA_SUCCESS)
1552e01ce4e8SJoseph Huber       return false;
1553e01ce4e8SJoseph Huber 
1554e01ce4e8SJoseph Huber     std::string ArchStr = "sm_" + std::to_string(Major) + std::to_string(Minor);
1555e01ce4e8SJoseph Huber     if (ArchStr != info->Arch)
1556e01ce4e8SJoseph Huber       return false;
1557e01ce4e8SJoseph Huber   }
1558e01ce4e8SJoseph Huber 
1559e01ce4e8SJoseph Huber   DP("Image has compatible compute capability: %s\n", info->Arch);
1560e01ce4e8SJoseph Huber   return true;
1561e01ce4e8SJoseph Huber }
1562e01ce4e8SJoseph Huber 
15634031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
15644031bb98SShilei Tian 
15654031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
156640470eb2SGeorge Rokos   DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
15674031bb98SShilei Tian   DeviceRTL.setRequiresFlag(RequiresFlags);
15684031bb98SShilei Tian   return RequiresFlags;
15694031bb98SShilei Tian }
15704031bb98SShilei Tian 
1571d27d0a67SJoseph Huber int32_t __tgt_rtl_is_data_exchangable(int32_t SrcDevId, int DstDevId) {
1572d27d0a67SJoseph Huber   if (DeviceRTL.isValidDeviceId(SrcDevId) &&
1573d27d0a67SJoseph Huber       DeviceRTL.isValidDeviceId(DstDevId))
1574a014fbbcSShilei Tian     return 1;
1575a014fbbcSShilei Tian 
1576a014fbbcSShilei Tian   return 0;
1577a014fbbcSShilei Tian }
1578a014fbbcSShilei Tian 
1579d27d0a67SJoseph Huber int32_t __tgt_rtl_init_device(int32_t DeviceId) {
1580d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
158139d3283aSShilei Tian   // Context is set when init the device.
15824031bb98SShilei Tian 
1583d27d0a67SJoseph Huber   return DeviceRTL.initDevice(DeviceId);
15844031bb98SShilei Tian }
15854031bb98SShilei Tian 
1586d27d0a67SJoseph Huber int32_t __tgt_rtl_deinit_device(int32_t DeviceId) {
1587d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
158839d3283aSShilei Tian   // Context is set when deinit the device.
158910aa83ffSJohannes Doerfert 
1590d27d0a67SJoseph Huber   return DeviceRTL.deinitDevice(DeviceId);
159110aa83ffSJohannes Doerfert }
159210aa83ffSJohannes Doerfert 
1593d27d0a67SJoseph Huber __tgt_target_table *__tgt_rtl_load_binary(int32_t DeviceId,
1594d27d0a67SJoseph Huber                                           __tgt_device_image *Image) {
1595d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
15964031bb98SShilei Tian 
1597d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
159839d3283aSShilei Tian     return nullptr;
159939d3283aSShilei Tian 
1600d27d0a67SJoseph Huber   return DeviceRTL.loadBinary(DeviceId, Image);
16014031bb98SShilei Tian }
16024031bb98SShilei Tian 
1603d27d0a67SJoseph Huber void *__tgt_rtl_data_alloc(int32_t DeviceId, int64_t Size, void *,
1604d27d0a67SJoseph Huber                            int32_t Kind) {
1605d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
16064031bb98SShilei Tian 
1607d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
160839d3283aSShilei Tian     return nullptr;
160939d3283aSShilei Tian 
1610d27d0a67SJoseph Huber   return DeviceRTL.dataAlloc(DeviceId, Size, (TargetAllocTy)Kind);
16114031bb98SShilei Tian }
16124031bb98SShilei Tian 
1613d27d0a67SJoseph Huber int32_t __tgt_rtl_data_submit(int32_t DeviceId, void *TgtPtr, void *HstPtr,
1614d27d0a67SJoseph Huber                               int64_t Size) {
1615d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
161639d3283aSShilei Tian   // Context is set in __tgt_rtl_data_submit_async.
16174031bb98SShilei Tian 
16185449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1619d27d0a67SJoseph Huber   const int32_t Rc =
1620d27d0a67SJoseph Huber       __tgt_rtl_data_submit_async(DeviceId, TgtPtr, HstPtr, Size, &AsyncInfo);
1621d27d0a67SJoseph Huber   if (Rc != OFFLOAD_SUCCESS)
16224031bb98SShilei Tian     return OFFLOAD_FAIL;
16234031bb98SShilei Tian 
1624d27d0a67SJoseph Huber   return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
16254031bb98SShilei Tian }
16264031bb98SShilei Tian 
1627d27d0a67SJoseph Huber int32_t __tgt_rtl_data_submit_async(int32_t DeviceId, void *TgtPtr,
1628d27d0a67SJoseph Huber                                     void *HstPtr, int64_t Size,
1629d27d0a67SJoseph Huber                                     __tgt_async_info *AsyncInfoPtr) {
1630d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1631d27d0a67SJoseph Huber   assert(AsyncInfoPtr && "async_info_ptr is nullptr");
16324031bb98SShilei Tian 
1633d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
163439d3283aSShilei Tian     return OFFLOAD_FAIL;
163539d3283aSShilei Tian 
1636d27d0a67SJoseph Huber   return DeviceRTL.dataSubmit(DeviceId, TgtPtr, HstPtr, Size, AsyncInfoPtr);
16374031bb98SShilei Tian }
16384031bb98SShilei Tian 
1639d27d0a67SJoseph Huber int32_t __tgt_rtl_data_retrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr,
1640d27d0a67SJoseph Huber                                 int64_t Size) {
1641d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
164239d3283aSShilei Tian   // Context is set in __tgt_rtl_data_retrieve_async.
16434031bb98SShilei Tian 
16445449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1645d27d0a67SJoseph Huber   const int32_t Rc =
1646d27d0a67SJoseph Huber       __tgt_rtl_data_retrieve_async(DeviceId, HstPtr, TgtPtr, Size, &AsyncInfo);
1647d27d0a67SJoseph Huber   if (Rc != OFFLOAD_SUCCESS)
16484031bb98SShilei Tian     return OFFLOAD_FAIL;
16494031bb98SShilei Tian 
1650d27d0a67SJoseph Huber   return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
16514031bb98SShilei Tian }
16524031bb98SShilei Tian 
1653d27d0a67SJoseph Huber int32_t __tgt_rtl_data_retrieve_async(int32_t DeviceId, void *HstPtr,
1654d27d0a67SJoseph Huber                                       void *TgtPtr, int64_t Size,
1655d27d0a67SJoseph Huber                                       __tgt_async_info *AsyncInfoPtr) {
1656d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1657d27d0a67SJoseph Huber   assert(AsyncInfoPtr && "async_info_ptr is nullptr");
16584031bb98SShilei Tian 
1659d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
166039d3283aSShilei Tian     return OFFLOAD_FAIL;
166139d3283aSShilei Tian 
1662d27d0a67SJoseph Huber   return DeviceRTL.dataRetrieve(DeviceId, HstPtr, TgtPtr, Size, AsyncInfoPtr);
16634031bb98SShilei Tian }
16644031bb98SShilei Tian 
1665d27d0a67SJoseph Huber int32_t __tgt_rtl_data_exchange_async(int32_t SrcDevId, void *SrcPtr,
1666d27d0a67SJoseph Huber                                       int DstDevId, void *DstPtr, int64_t Size,
16675449fbb5SJohannes Doerfert                                       __tgt_async_info *AsyncInfo) {
1668d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(SrcDevId) && "src_dev_id is invalid");
1669d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DstDevId) && "dst_dev_id is invalid");
16705449fbb5SJohannes Doerfert   assert(AsyncInfo && "AsyncInfo is nullptr");
16712695e23aSShilei Tian 
1672d27d0a67SJoseph Huber   if (DeviceRTL.setContext(SrcDevId) != OFFLOAD_SUCCESS)
16732695e23aSShilei Tian     return OFFLOAD_FAIL;
16742695e23aSShilei Tian 
1675d27d0a67SJoseph Huber   return DeviceRTL.dataExchange(SrcDevId, SrcPtr, DstDevId, DstPtr, Size,
16765449fbb5SJohannes Doerfert                                 AsyncInfo);
1677a014fbbcSShilei Tian }
1678a014fbbcSShilei Tian 
1679d27d0a67SJoseph Huber int32_t __tgt_rtl_data_exchange(int32_t SrcDevId, void *SrcPtr,
1680d27d0a67SJoseph Huber                                 int32_t DstDevId, void *DstPtr, int64_t Size) {
1681d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(SrcDevId) && "src_dev_id is invalid");
1682d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DstDevId) && "dst_dev_id is invalid");
168339d3283aSShilei Tian   // Context is set in __tgt_rtl_data_exchange_async.
1684a014fbbcSShilei Tian 
16855449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1686d27d0a67SJoseph Huber   const int32_t Rc = __tgt_rtl_data_exchange_async(SrcDevId, SrcPtr, DstDevId,
1687d27d0a67SJoseph Huber                                                    DstPtr, Size, &AsyncInfo);
1688d27d0a67SJoseph Huber   if (Rc != OFFLOAD_SUCCESS)
1689a014fbbcSShilei Tian     return OFFLOAD_FAIL;
1690a014fbbcSShilei Tian 
1691d27d0a67SJoseph Huber   return __tgt_rtl_synchronize(SrcDevId, &AsyncInfo);
1692a014fbbcSShilei Tian }
1693a014fbbcSShilei Tian 
1694d27d0a67SJoseph Huber int32_t __tgt_rtl_data_delete(int32_t DeviceId, void *TgtPtr) {
1695d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
16964031bb98SShilei Tian 
1697d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
169839d3283aSShilei Tian     return OFFLOAD_FAIL;
169939d3283aSShilei Tian 
1700d27d0a67SJoseph Huber   return DeviceRTL.dataDelete(DeviceId, TgtPtr);
17014031bb98SShilei Tian }
17024031bb98SShilei Tian 
1703d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_team_region(int32_t DeviceId, void *TgtEntryPtr,
1704d27d0a67SJoseph Huber                                          void **TgtArgs, ptrdiff_t *TgtOffsets,
1705d27d0a67SJoseph Huber                                          int32_t ArgNum, int32_t TeamNum,
1706d27d0a67SJoseph Huber                                          int32_t ThreadLimit,
1707d27d0a67SJoseph Huber                                          uint64_t LoopTripcount) {
1708d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
170939d3283aSShilei Tian   // Context is set in __tgt_rtl_run_target_team_region_async.
17104031bb98SShilei Tian 
17115449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1712d27d0a67SJoseph Huber   const int32_t Rc = __tgt_rtl_run_target_team_region_async(
1713d27d0a67SJoseph Huber       DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum, TeamNum, ThreadLimit,
1714d27d0a67SJoseph Huber       LoopTripcount, &AsyncInfo);
1715d27d0a67SJoseph Huber   if (Rc != OFFLOAD_SUCCESS)
17164031bb98SShilei Tian     return OFFLOAD_FAIL;
17174031bb98SShilei Tian 
1718d27d0a67SJoseph Huber   return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
17194031bb98SShilei Tian }
17204031bb98SShilei Tian 
17214031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
1722d27d0a67SJoseph Huber     int32_t DeviceId, void *TgtEntryPtr, void **TgtArgs, ptrdiff_t *TgtOffsets,
1723d27d0a67SJoseph Huber     int32_t ArgNum, int32_t TeamNum, int32_t ThreadLimit,
1724d27d0a67SJoseph Huber     uint64_t LoopTripcount, __tgt_async_info *AsyncInfoPtr) {
1725d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
17264031bb98SShilei Tian 
1727d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
172839d3283aSShilei Tian     return OFFLOAD_FAIL;
172939d3283aSShilei Tian 
1730d27d0a67SJoseph Huber   return DeviceRTL.runTargetTeamRegion(DeviceId, TgtEntryPtr, TgtArgs,
1731d27d0a67SJoseph Huber                                        TgtOffsets, ArgNum, TeamNum, ThreadLimit,
1732d27d0a67SJoseph Huber                                        LoopTripcount, AsyncInfoPtr);
17334031bb98SShilei Tian }
17343de4cd12SGeorge Rokos 
1735d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_region(int32_t DeviceId, void *TgtEntryPtr,
1736d27d0a67SJoseph Huber                                     void **TgtArgs, ptrdiff_t *TgtOffsets,
1737d27d0a67SJoseph Huber                                     int32_t ArgNum) {
1738d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
173939d3283aSShilei Tian   // Context is set in __tgt_rtl_run_target_region_async.
17404031bb98SShilei Tian 
17415449fbb5SJohannes Doerfert   __tgt_async_info AsyncInfo;
1742d27d0a67SJoseph Huber   const int32_t Rc = __tgt_rtl_run_target_region_async(
1743d27d0a67SJoseph Huber       DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum, &AsyncInfo);
1744d27d0a67SJoseph Huber   if (Rc != OFFLOAD_SUCCESS)
174503ff643dSShilei Tian     return OFFLOAD_FAIL;
174603ff643dSShilei Tian 
1747d27d0a67SJoseph Huber   return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
174803ff643dSShilei Tian }
174903ff643dSShilei Tian 
1750d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_region_async(int32_t DeviceId, void *TgtEntryPtr,
1751d27d0a67SJoseph Huber                                           void **TgtArgs, ptrdiff_t *TgtOffsets,
1752d27d0a67SJoseph Huber                                           int32_t ArgNum,
1753d27d0a67SJoseph Huber                                           __tgt_async_info *AsyncInfoPtr) {
1754d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
175539d3283aSShilei Tian   // Context is set in __tgt_rtl_run_target_team_region_async.
175603ff643dSShilei Tian   return __tgt_rtl_run_target_team_region_async(
1757d27d0a67SJoseph Huber       DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum,
17584031bb98SShilei Tian       /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1759d27d0a67SJoseph Huber       AsyncInfoPtr);
176032ed2927SShilei Tian }
176132ed2927SShilei Tian 
1762d27d0a67SJoseph Huber int32_t __tgt_rtl_synchronize(int32_t DeviceId,
1763d27d0a67SJoseph Huber                               __tgt_async_info *AsyncInfoPtr) {
1764d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1765d27d0a67SJoseph Huber   assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1766d27d0a67SJoseph Huber   assert(AsyncInfoPtr->Queue && "async_info_ptr->Queue is nullptr");
176739d3283aSShilei Tian   // NOTE: We don't need to set context for stream sync.
1768d27d0a67SJoseph Huber   return DeviceRTL.synchronize(DeviceId, AsyncInfoPtr);
17693de4cd12SGeorge Rokos }
17703de4cd12SGeorge Rokos 
17712b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
177259b68490SJoseph Huber   std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
17732b6f2008SJoseph Huber   InfoLevel.store(NewInfoLevel);
17742b6f2008SJoseph Huber }
17752b6f2008SJoseph Huber 
1776d27d0a67SJoseph Huber void __tgt_rtl_print_device_info(int32_t DeviceId) {
1777d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
177839d3283aSShilei Tian   // NOTE: We don't need to set context for print device info.
1779d27d0a67SJoseph Huber   DeviceRTL.printDeviceInfo(DeviceId);
1780d2f85d09SJose M Monsalve Diaz }
1781d2f85d09SJose M Monsalve Diaz 
1782d27d0a67SJoseph Huber int32_t __tgt_rtl_create_event(int32_t DeviceId, void **Event) {
1783d27d0a67SJoseph Huber   assert(Event && "event is nullptr");
178439d3283aSShilei Tian 
1785d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
178639d3283aSShilei Tian     return OFFLOAD_FAIL;
178739d3283aSShilei Tian 
1788d27d0a67SJoseph Huber   return DeviceRTL.createEvent(DeviceId, Event);
178929df4ab3SShilei Tian }
179029df4ab3SShilei Tian 
1791d27d0a67SJoseph Huber int32_t __tgt_rtl_record_event(int32_t DeviceId, void *EventPtr,
1792d27d0a67SJoseph Huber                                __tgt_async_info *AsyncInfoPtr) {
1793d27d0a67SJoseph Huber   assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1794d27d0a67SJoseph Huber   assert(AsyncInfoPtr->Queue && "async_info_ptr->Queue is nullptr");
1795d27d0a67SJoseph Huber   assert(EventPtr && "event_ptr is nullptr");
179639d3283aSShilei Tian   // NOTE: We might not need to set context for event record.
1797d27d0a67SJoseph Huber   return recordEvent(EventPtr, AsyncInfoPtr);
179829df4ab3SShilei Tian }
179929df4ab3SShilei Tian 
1800d27d0a67SJoseph Huber int32_t __tgt_rtl_wait_event(int32_t DeviceId, void *EventPtr,
1801d27d0a67SJoseph Huber                              __tgt_async_info *AsyncInfoPtr) {
1802d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1803d27d0a67SJoseph Huber   assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1804d27d0a67SJoseph Huber   assert(EventPtr && "event is nullptr");
1805a3a42c3cSJohannes Doerfert   // If we don't have a queue we need to set the context.
1806d27d0a67SJoseph Huber   if (!AsyncInfoPtr->Queue && DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
1807a3a42c3cSJohannes Doerfert     return OFFLOAD_FAIL;
1808d27d0a67SJoseph Huber   return DeviceRTL.waitEvent(DeviceId, AsyncInfoPtr, EventPtr);
180929df4ab3SShilei Tian }
181029df4ab3SShilei Tian 
1811d27d0a67SJoseph Huber int32_t __tgt_rtl_sync_event(int32_t DeviceId, void *EventPtr) {
1812d27d0a67SJoseph Huber   assert(EventPtr && "event is nullptr");
181339d3283aSShilei Tian   // NOTE: We might not need to set context for event sync.
1814d27d0a67SJoseph Huber   return syncEvent(EventPtr);
181529df4ab3SShilei Tian }
181629df4ab3SShilei Tian 
1817d27d0a67SJoseph Huber int32_t __tgt_rtl_destroy_event(int32_t DeviceId, void *EventPtr) {
1818d27d0a67SJoseph Huber   assert(EventPtr && "event is nullptr");
181929df4ab3SShilei Tian 
1820d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
182139d3283aSShilei Tian     return OFFLOAD_FAIL;
182239d3283aSShilei Tian 
1823d27d0a67SJoseph Huber   return DeviceRTL.destroyEvent(DeviceId, EventPtr);
182429df4ab3SShilei Tian }
182529df4ab3SShilei Tian 
1826d27d0a67SJoseph Huber int32_t __tgt_rtl_release_async_info(int32_t DeviceId,
1827d27d0a67SJoseph Huber                                      __tgt_async_info *AsyncInfo) {
1828d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1829d27d0a67SJoseph Huber   assert(AsyncInfo && "async_info is nullptr");
1830f44e41afSSri Hari Krishna Narayanan 
1831d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
183239d3283aSShilei Tian     return OFFLOAD_FAIL;
183339d3283aSShilei Tian 
1834d27d0a67SJoseph Huber   return DeviceRTL.releaseAsyncInfo(DeviceId, AsyncInfo);
1835f44e41afSSri Hari Krishna Narayanan }
1836f44e41afSSri Hari Krishna Narayanan 
1837d27d0a67SJoseph Huber int32_t __tgt_rtl_init_async_info(int32_t DeviceId,
1838d27d0a67SJoseph Huber                                   __tgt_async_info **AsyncInfo) {
1839d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1840d27d0a67SJoseph Huber   assert(AsyncInfo && "async_info is nullptr");
1841f44e41afSSri Hari Krishna Narayanan 
1842d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
184339d3283aSShilei Tian     return OFFLOAD_FAIL;
184439d3283aSShilei Tian 
1845d27d0a67SJoseph Huber   return DeviceRTL.initAsyncInfo(DeviceId, AsyncInfo);
1846f44e41afSSri Hari Krishna Narayanan }
1847f44e41afSSri Hari Krishna Narayanan 
1848d27d0a67SJoseph Huber int32_t __tgt_rtl_init_device_info(int32_t DeviceId,
1849d27d0a67SJoseph Huber                                    __tgt_device_info *DeviceInfoPtr,
1850d27d0a67SJoseph Huber                                    const char **ErrStr) {
1851d27d0a67SJoseph Huber   assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1852d27d0a67SJoseph Huber   assert(DeviceInfoPtr && "device_info_ptr is nullptr");
1853f44e41afSSri Hari Krishna Narayanan 
1854d27d0a67SJoseph Huber   if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
185539d3283aSShilei Tian     return OFFLOAD_FAIL;
185639d3283aSShilei Tian 
1857d27d0a67SJoseph Huber   return DeviceRTL.initDeviceInfo(DeviceId, DeviceInfoPtr, ErrStr);
1858f44e41afSSri Hari Krishna Narayanan }
1859f44e41afSSri Hari Krishna Narayanan 
18603de4cd12SGeorge Rokos #ifdef __cplusplus
18613de4cd12SGeorge Rokos }
18623de4cd12SGeorge Rokos #endif
1863