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
13*0b12f770SJoseph Huber #include "llvm/ADT/StringRef.h"
14*0b12f770SJoseph Huber
1510aa83ffSJohannes Doerfert #include <algorithm>
163de4cd12SGeorge Rokos #include <cassert>
173de4cd12SGeorge Rokos #include <cstddef>
183de4cd12SGeorge Rokos #include <cuda.h>
193de4cd12SGeorge Rokos #include <list>
20a5153dbcSJohannes Doerfert #include <memory>
21feed674dSShilei Tian #include <mutex>
223de4cd12SGeorge Rokos #include <string>
23a15f8589SJoseph Huber #include <unordered_map>
243de4cd12SGeorge Rokos #include <vector>
253de4cd12SGeorge Rokos
26ae95ceebSJoseph Huber #include "Debug.h"
270c554a47SJon Chesterfield #include "DeviceEnvironment.h"
2810aa83ffSJohannes Doerfert #include "omptarget.h"
291546d319SGeorge Rokos #include "omptargetplugin.h"
303de4cd12SGeorge Rokos
313de4cd12SGeorge Rokos #define TARGET_NAME CUDA
32ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
3378769ec4SMichael Kruse
340871d6d5SShilei Tian #include "MemoryManager.h"
350871d6d5SShilei Tian
36ca999f71SShilei Tian #include "llvm/Frontend/OpenMP/OMPConstants.h"
37ca999f71SShilei Tian
38*0b12f770SJoseph Huber using namespace llvm;
39*0b12f770SJoseph Huber
4078769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string.
41ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG
4278769ec4SMichael Kruse #define CUDA_ERR_STRING(err) \
4378769ec4SMichael Kruse do { \
44ae95ceebSJoseph Huber if (getDebugLevel() > 0) { \
4503111e5eSYe Luo const char *errStr = nullptr; \
4603111e5eSYe Luo CUresult errStr_status = cuGetErrorString(err, &errStr); \
4703111e5eSYe Luo if (errStr_status == CUDA_ERROR_INVALID_VALUE) \
482ce16810SJoseph Huber REPORT("Unrecognized CUDA error code: %d\n", err); \
4903111e5eSYe Luo else if (errStr_status == CUDA_SUCCESS) \
502ce16810SJoseph Huber REPORT("CUDA error is: %s\n", errStr); \
5103111e5eSYe Luo else { \
522ce16810SJoseph Huber REPORT("Unresolved CUDA error code: %d\n", err); \
532ce16810SJoseph Huber REPORT("Unsuccessful cuGetErrorString return status: %d\n", \
5403111e5eSYe Luo errStr_status); \
5503111e5eSYe Luo } \
562ce16810SJoseph Huber } else { \
572ce16810SJoseph Huber const char *errStr = nullptr; \
582ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \
592ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \
602ce16810SJoseph Huber REPORT("%s \n", errStr); \
6178769ec4SMichael Kruse } \
6278769ec4SMichael Kruse } while (false)
63b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG
642ce16810SJoseph Huber #define CUDA_ERR_STRING(err) \
652ce16810SJoseph Huber do { \
662ce16810SJoseph Huber const char *errStr = nullptr; \
672ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \
682ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \
692ce16810SJoseph Huber REPORT("%s \n", errStr); \
702ce16810SJoseph Huber } while (false)
71b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG
723de4cd12SGeorge Rokos
73d2f85d09SJose M Monsalve Diaz #define BOOL2TEXT(b) ((b) ? "Yes" : "No")
74d2f85d09SJose M Monsalve Diaz
75a81c68aeSShilei Tian #include "elf_common.h"
763de4cd12SGeorge Rokos
773de4cd12SGeorge Rokos /// Keep entries table per device.
783de4cd12SGeorge Rokos struct FuncOrGblEntryTy {
793de4cd12SGeorge Rokos __tgt_target_table Table;
803de4cd12SGeorge Rokos std::vector<__tgt_offload_entry> Entries;
813de4cd12SGeorge Rokos };
823de4cd12SGeorge Rokos
83dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags.
843de4cd12SGeorge Rokos struct KernelTy {
853de4cd12SGeorge Rokos CUfunction Func;
863de4cd12SGeorge Rokos
873de4cd12SGeorge Rokos // execution mode of kernel
88ca999f71SShilei Tian llvm::omp::OMPTgtExecModeFlags ExecutionMode;
893de4cd12SGeorge Rokos
90aa27cfc1SJohannes Doerfert /// Maximal number of threads per block for this kernel.
91aa27cfc1SJohannes Doerfert int MaxThreadsPerBlock = 0;
92aa27cfc1SJohannes Doerfert
KernelTyKernelTy93d27d0a67SJoseph Huber KernelTy(CUfunction Func, llvm::omp::OMPTgtExecModeFlags ExecutionMode)
94d27d0a67SJoseph Huber : Func(Func), ExecutionMode(ExecutionMode) {}
953de4cd12SGeorge Rokos };
963de4cd12SGeorge Rokos
97feed674dSShilei Tian namespace {
checkResult(CUresult Err,const char * ErrMsg)98feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) {
99feed674dSShilei Tian if (Err == CUDA_SUCCESS)
100feed674dSShilei Tian return true;
101feed674dSShilei Tian
1022ce16810SJoseph Huber REPORT("%s", ErrMsg);
103feed674dSShilei Tian CUDA_ERR_STRING(Err);
104feed674dSShilei Tian return false;
105feed674dSShilei Tian }
1064031bb98SShilei Tian
memcpyDtoD(const void * SrcPtr,void * DstPtr,int64_t Size,CUstream Stream)107a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size,
108a014fbbcSShilei Tian CUstream Stream) {
10995f0d1edSJon Chesterfield CUresult Err =
11095f0d1edSJon Chesterfield cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream);
111a014fbbcSShilei Tian
112a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) {
11329338459SJoseph Huber DP("Error when copying data from device to device. Pointers: src "
114a014fbbcSShilei Tian "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n",
115a014fbbcSShilei Tian DPxPTR(SrcPtr), DPxPTR(DstPtr), Size);
116a014fbbcSShilei Tian CUDA_ERR_STRING(Err);
117a014fbbcSShilei Tian return OFFLOAD_FAIL;
118a014fbbcSShilei Tian }
119a014fbbcSShilei Tian
120a014fbbcSShilei Tian return OFFLOAD_SUCCESS;
121a014fbbcSShilei Tian }
122a014fbbcSShilei Tian
recordEvent(void * EventPtr,__tgt_async_info * AsyncInfo)12329df4ab3SShilei Tian int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) {
12429df4ab3SShilei Tian CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
12529df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr);
12629df4ab3SShilei Tian
12729df4ab3SShilei Tian CUresult Err = cuEventRecord(Event, Stream);
12829df4ab3SShilei Tian if (Err != CUDA_SUCCESS) {
12929df4ab3SShilei Tian DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n",
13029df4ab3SShilei Tian DPxPTR(Stream), DPxPTR(Event));
13129df4ab3SShilei Tian CUDA_ERR_STRING(Err);
13229df4ab3SShilei Tian return OFFLOAD_FAIL;
13329df4ab3SShilei Tian }
13429df4ab3SShilei Tian
13529df4ab3SShilei Tian return OFFLOAD_SUCCESS;
13629df4ab3SShilei Tian }
13729df4ab3SShilei Tian
syncEvent(void * EventPtr)13829df4ab3SShilei Tian int syncEvent(void *EventPtr) {
13929df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr);
14029df4ab3SShilei Tian
14129df4ab3SShilei Tian CUresult Err = cuEventSynchronize(Event);
14229df4ab3SShilei Tian if (Err != CUDA_SUCCESS) {
14329df4ab3SShilei Tian DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event));
14429df4ab3SShilei Tian CUDA_ERR_STRING(Err);
14529df4ab3SShilei Tian return OFFLOAD_FAIL;
14629df4ab3SShilei Tian }
14729df4ab3SShilei Tian
14829df4ab3SShilei Tian return OFFLOAD_SUCCESS;
14929df4ab3SShilei Tian }
15029df4ab3SShilei Tian
1511660288bSJohannes Doerfert namespace {
1521660288bSJohannes Doerfert
1534031bb98SShilei Tian // Structure contains per-device data
1544031bb98SShilei Tian struct DeviceDataTy {
1555272d29eSJohannes Doerfert /// List that contains all the kernels.
1565272d29eSJohannes Doerfert std::list<KernelTy> KernelsList;
1575272d29eSJohannes Doerfert
1584031bb98SShilei Tian std::list<FuncOrGblEntryTy> FuncGblEntries;
1595272d29eSJohannes Doerfert
1604031bb98SShilei Tian CUcontext Context = nullptr;
1614031bb98SShilei Tian // Device properties
1621f940b69SJoseph Huber unsigned int ThreadsPerBlock = 0;
1631f940b69SJoseph Huber unsigned int BlocksPerGrid = 0;
1641f940b69SJoseph Huber unsigned int WarpSize = 0;
1654031bb98SShilei Tian // OpenMP properties
1664031bb98SShilei Tian int NumTeams = 0;
1674031bb98SShilei Tian int NumThreads = 0;
1684031bb98SShilei Tian };
169feed674dSShilei Tian
170a697a0a4SShilei Tian /// Resource allocator where \p T is the resource type.
171a697a0a4SShilei Tian /// Functions \p create and \p destroy return OFFLOAD_SUCCESS and OFFLOAD_FAIL
172a697a0a4SShilei Tian /// accordingly. The implementation should not raise any exception.
1731660288bSJohannes Doerfert template <typename T> struct AllocatorTy {
1741660288bSJohannes Doerfert using ElementTy = T;
~AllocatorTy__anondfa3b3cd0111::__anondfa3b3cd0211::AllocatorTy175ba93e4e3SJohannes Doerfert virtual ~AllocatorTy() {}
176ba93e4e3SJohannes Doerfert
177a697a0a4SShilei Tian /// Create a resource and assign to R.
1781660288bSJohannes Doerfert virtual int create(T &R) noexcept = 0;
179a697a0a4SShilei Tian /// Destroy the resource.
1801660288bSJohannes Doerfert virtual int destroy(T) noexcept = 0;
181a697a0a4SShilei Tian };
182feed674dSShilei Tian
183a697a0a4SShilei Tian /// Allocator for CUstream.
1841660288bSJohannes Doerfert struct StreamAllocatorTy final : public AllocatorTy<CUstream> {
185a697a0a4SShilei Tian /// See AllocatorTy<T>::create.
create__anondfa3b3cd0111::__anondfa3b3cd0211::StreamAllocatorTy1861660288bSJohannes Doerfert int create(CUstream &Stream) noexcept override {
187a697a0a4SShilei Tian if (!checkResult(cuStreamCreate(&Stream, CU_STREAM_NON_BLOCKING),
188a697a0a4SShilei Tian "Error returned from cuStreamCreate\n"))
189a697a0a4SShilei Tian return OFFLOAD_FAIL;
190a697a0a4SShilei Tian
191a697a0a4SShilei Tian return OFFLOAD_SUCCESS;
192feed674dSShilei Tian }
193feed674dSShilei Tian
194a697a0a4SShilei Tian /// See AllocatorTy<T>::destroy.
destroy__anondfa3b3cd0111::__anondfa3b3cd0211::StreamAllocatorTy1951660288bSJohannes Doerfert int destroy(CUstream Stream) noexcept override {
196a697a0a4SShilei Tian if (!checkResult(cuStreamDestroy(Stream),
197a697a0a4SShilei Tian "Error returned from cuStreamDestroy\n"))
198a697a0a4SShilei Tian return OFFLOAD_FAIL;
1994031bb98SShilei Tian
200a697a0a4SShilei Tian return OFFLOAD_SUCCESS;
201feed674dSShilei Tian }
202a697a0a4SShilei Tian };
203a697a0a4SShilei Tian
204943d1d83SShilei Tian /// Allocator for CUevent.
2051660288bSJohannes Doerfert struct EventAllocatorTy final : public AllocatorTy<CUevent> {
206943d1d83SShilei Tian /// See AllocatorTy<T>::create.
create__anondfa3b3cd0111::__anondfa3b3cd0211::EventAllocatorTy2071660288bSJohannes Doerfert int create(CUevent &Event) noexcept override {
208943d1d83SShilei Tian if (!checkResult(cuEventCreate(&Event, CU_EVENT_DEFAULT),
209943d1d83SShilei Tian "Error returned from cuEventCreate\n"))
210943d1d83SShilei Tian return OFFLOAD_FAIL;
211943d1d83SShilei Tian
212943d1d83SShilei Tian return OFFLOAD_SUCCESS;
213943d1d83SShilei Tian }
214943d1d83SShilei Tian
215943d1d83SShilei Tian /// See AllocatorTy<T>::destroy.
destroy__anondfa3b3cd0111::__anondfa3b3cd0211::EventAllocatorTy2161660288bSJohannes Doerfert int destroy(CUevent Event) noexcept override {
217943d1d83SShilei Tian if (!checkResult(cuEventDestroy(Event),
218943d1d83SShilei Tian "Error returned from cuEventDestroy\n"))
219943d1d83SShilei Tian return OFFLOAD_FAIL;
220943d1d83SShilei Tian
221943d1d83SShilei Tian return OFFLOAD_SUCCESS;
222943d1d83SShilei Tian }
223943d1d83SShilei Tian };
224943d1d83SShilei Tian
225a697a0a4SShilei Tian /// A generic pool of resources where \p T is the resource type.
226a697a0a4SShilei Tian /// \p T should be copyable as the object is stored in \p std::vector .
2271660288bSJohannes Doerfert template <typename AllocTy> class ResourcePoolTy {
2281660288bSJohannes Doerfert using ElementTy = typename AllocTy::ElementTy;
229a697a0a4SShilei Tian /// Index of the next available resource.
230a697a0a4SShilei Tian size_t Next = 0;
231a697a0a4SShilei Tian /// Mutex to guard the pool.
232a697a0a4SShilei Tian std::mutex Mutex;
233545fcc3dSShilei Tian /// Pool of resources. The difference between \p Resources and \p Pool is,
234545fcc3dSShilei Tian /// when a resource is acquired and released, it is all on \p Resources. When
235545fcc3dSShilei Tian /// a batch of new resources are needed, they are both added to \p Resources
236545fcc3dSShilei Tian /// and \p Pool. The reason for this setting is, \p Resources could contain
237545fcc3dSShilei Tian /// redundant elements because resources are not released, which can cause
238545fcc3dSShilei Tian /// double free. This setting makes sure that \p Pool always has every
239545fcc3dSShilei Tian /// resource allocated from the device.
2401660288bSJohannes Doerfert std::vector<ElementTy> Resources;
241545fcc3dSShilei Tian std::vector<ElementTy> Pool;
242a697a0a4SShilei Tian /// A reference to the corresponding allocator.
2431660288bSJohannes Doerfert AllocTy Allocator;
244a697a0a4SShilei Tian
245a697a0a4SShilei Tian /// If `Resources` is used up, we will fill in more resources. It assumes that
246a697a0a4SShilei Tian /// the new size `Size` should be always larger than the current size.
resize(size_t Size)247a697a0a4SShilei Tian bool resize(size_t Size) {
248545fcc3dSShilei Tian assert(Resources.size() == Pool.size() && "size mismatch");
249a697a0a4SShilei Tian auto CurSize = Resources.size();
250a697a0a4SShilei Tian assert(Size > CurSize && "Unexpected smaller size");
251545fcc3dSShilei Tian Pool.reserve(Size);
252a697a0a4SShilei Tian Resources.reserve(Size);
253a697a0a4SShilei Tian for (auto I = CurSize; I < Size; ++I) {
2541660288bSJohannes Doerfert ElementTy NewItem;
255a697a0a4SShilei Tian int Ret = Allocator.create(NewItem);
256a697a0a4SShilei Tian if (Ret != OFFLOAD_SUCCESS)
257a697a0a4SShilei Tian return false;
258545fcc3dSShilei Tian Pool.push_back(NewItem);
259a697a0a4SShilei Tian Resources.push_back(NewItem);
260a697a0a4SShilei Tian }
261a697a0a4SShilei Tian return true;
262feed674dSShilei Tian }
263feed674dSShilei Tian
264feed674dSShilei Tian public:
ResourcePoolTy(AllocTy && A,size_t Size=0)2651660288bSJohannes Doerfert ResourcePoolTy(AllocTy &&A, size_t Size = 0) noexcept
266a697a0a4SShilei Tian : Allocator(std::move(A)) {
267357c8031SShilei Tian if (Size)
268a697a0a4SShilei Tian (void)resize(Size);
269feed674dSShilei Tian }
270feed674dSShilei Tian
~ResourcePoolTy()271357c8031SShilei Tian ~ResourcePoolTy() noexcept { clear(); }
272feed674dSShilei Tian
273a697a0a4SShilei Tian /// Get a resource from pool. `Next` always points to the next available
274a697a0a4SShilei Tian /// resource. That means, `[0, next-1]` have been assigned, and `[id,]` are
275a697a0a4SShilei Tian /// still available. If there is no resource left, we will ask for more. Each
276a697a0a4SShilei Tian /// time a resource is assigned, the id will increase one.
277a697a0a4SShilei Tian /// xxxxxs+++++++++
278a697a0a4SShilei Tian /// ^
279a697a0a4SShilei Tian /// Next
280a697a0a4SShilei Tian /// After assignment, the pool becomes the following and s is assigned.
281a697a0a4SShilei Tian /// xxxxxs+++++++++
282a697a0a4SShilei Tian /// ^
283a697a0a4SShilei Tian /// Next
acquire(ElementTy & R)2841660288bSJohannes Doerfert int acquire(ElementTy &R) noexcept {
285a697a0a4SShilei Tian std::lock_guard<std::mutex> LG(Mutex);
286357c8031SShilei Tian if (Next == Resources.size()) {
287357c8031SShilei Tian auto NewSize = Resources.size() ? Resources.size() * 2 : 1;
288357c8031SShilei Tian if (!resize(NewSize))
289a697a0a4SShilei Tian return OFFLOAD_FAIL;
290357c8031SShilei Tian }
291357c8031SShilei Tian
292357c8031SShilei Tian assert(Next < Resources.size());
293a697a0a4SShilei Tian
294a697a0a4SShilei Tian R = Resources[Next++];
295a697a0a4SShilei Tian
296a697a0a4SShilei Tian return OFFLOAD_SUCCESS;
297feed674dSShilei Tian }
298feed674dSShilei Tian
299a697a0a4SShilei Tian /// Return the resource back to the pool. When we return a resource, we need
300a697a0a4SShilei Tian /// to first decrease `Next`, and then copy the resource back. It is worth
301a697a0a4SShilei Tian /// noting that, the order of resources return might be different from that
302a697a0a4SShilei Tian /// they're assigned, that saying, at some point, there might be two identical
303a697a0a4SShilei Tian /// resources.
304a697a0a4SShilei Tian /// xxax+a+++++
305a697a0a4SShilei Tian /// ^
306a697a0a4SShilei Tian /// Next
307a697a0a4SShilei Tian /// However, it doesn't matter, because they're always on the two sides of
308a697a0a4SShilei Tian /// `Next`. The left one will in the end be overwritten by another resource.
309a697a0a4SShilei Tian /// Therefore, after several execution, the order of pool might be different
310a697a0a4SShilei Tian /// from its initial state.
release(ElementTy R)3111660288bSJohannes Doerfert void release(ElementTy R) noexcept {
312a697a0a4SShilei Tian std::lock_guard<std::mutex> LG(Mutex);
313a697a0a4SShilei Tian Resources[--Next] = R;
314feed674dSShilei Tian }
315357c8031SShilei Tian
316357c8031SShilei Tian /// Released all stored resources and clear the pool.
317357c8031SShilei Tian /// Note: This function is not thread safe. Be sure to guard it if necessary.
clear()318357c8031SShilei Tian void clear() noexcept {
319545fcc3dSShilei Tian for (auto &R : Pool)
320357c8031SShilei Tian (void)Allocator.destroy(R);
321545fcc3dSShilei Tian Pool.clear();
322357c8031SShilei Tian Resources.clear();
323357c8031SShilei Tian }
324feed674dSShilei Tian };
325feed674dSShilei Tian
3261660288bSJohannes Doerfert } // namespace
3271660288bSJohannes Doerfert
3284031bb98SShilei Tian class DeviceRTLTy {
3293de4cd12SGeorge Rokos int NumberOfDevices;
3304031bb98SShilei Tian // OpenMP environment properties
3313de4cd12SGeorge Rokos int EnvNumTeams;
3323de4cd12SGeorge Rokos int EnvTeamLimit;
333422adaa8SJoseph Huber int EnvTeamThreadLimit;
3344031bb98SShilei Tian // OpenMP requires flags
335c5fe030cSGheorghe-Teodor Bercea int64_t RequiresFlags;
336f1c821faSJoseph Huber // Amount of dynamic shared memory to use at launch.
337f1c821faSJoseph Huber uint64_t DynamicMemorySize;
3381660288bSJohannes Doerfert
3391660288bSJohannes Doerfert /// Number of initial streams for each device.
340a697a0a4SShilei Tian int NumInitialStreams = 32;
341c5fe030cSGheorghe-Teodor Bercea
3421660288bSJohannes Doerfert /// Number of initial events for each device.
3431660288bSJohannes Doerfert int NumInitialEvents = 8;
3441660288bSJohannes Doerfert
345aca33b0bSShilei Tian static constexpr const int32_t HardThreadLimit = 1024;
346aca33b0bSShilei Tian static constexpr const int32_t DefaultNumTeams = 128;
347aca33b0bSShilei Tian static constexpr const int32_t DefaultNumThreads = 128;
3483de4cd12SGeorge Rokos
3491660288bSJohannes Doerfert using StreamPoolTy = ResourcePoolTy<StreamAllocatorTy>;
350a697a0a4SShilei Tian std::vector<std::unique_ptr<StreamPoolTy>> StreamPool;
351a697a0a4SShilei Tian
3521660288bSJohannes Doerfert using EventPoolTy = ResourcePoolTy<EventAllocatorTy>;
3531660288bSJohannes Doerfert std::vector<std::unique_ptr<EventPoolTy>> EventPool;
354943d1d83SShilei Tian
3554031bb98SShilei Tian std::vector<DeviceDataTy> DeviceData;
3565105c7cdSShilei Tian std::vector<std::vector<CUmodule>> Modules;
357feed674dSShilei Tian
35810aa83ffSJohannes Doerfert /// Vector of flags indicating the initalization status of all associated
35910aa83ffSJohannes Doerfert /// devices.
36010aa83ffSJohannes Doerfert std::vector<bool> InitializedFlags;
36110aa83ffSJohannes Doerfert
3622695e23aSShilei Tian enum class PeerAccessState : uint8_t { Unkown, Yes, No };
3632695e23aSShilei Tian std::vector<std::vector<PeerAccessState>> PeerAccessMatrix;
3642695e23aSShilei Tian std::mutex PeerAccessMatrixLock;
3652695e23aSShilei Tian
3660871d6d5SShilei Tian /// A class responsible for interacting with device native runtime library to
3670871d6d5SShilei Tian /// allocate and free memory.
3680871d6d5SShilei Tian class CUDADeviceAllocatorTy : public DeviceAllocatorTy {
369a15f8589SJoseph Huber std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs;
3700871d6d5SShilei Tian
3710871d6d5SShilei Tian public:
allocate(size_t Size,void *,TargetAllocTy Kind)372a15f8589SJoseph Huber void *allocate(size_t Size, void *, TargetAllocTy Kind) override {
3730871d6d5SShilei Tian if (Size == 0)
3740871d6d5SShilei Tian return nullptr;
3750871d6d5SShilei Tian
376a15f8589SJoseph Huber void *MemAlloc = nullptr;
37739d3283aSShilei Tian CUresult Err;
378a15f8589SJoseph Huber switch (Kind) {
379a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT:
380a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE:
3810871d6d5SShilei Tian CUdeviceptr DevicePtr;
38295f0d1edSJon Chesterfield Err = cuMemAlloc(&DevicePtr, Size);
383a15f8589SJoseph Huber MemAlloc = (void *)DevicePtr;
38495f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemAlloc\n"))
3850871d6d5SShilei Tian return nullptr;
386a15f8589SJoseph Huber break;
387a15f8589SJoseph Huber case TARGET_ALLOC_HOST:
388a15f8589SJoseph Huber void *HostPtr;
389a15f8589SJoseph Huber Err = cuMemAllocHost(&HostPtr, Size);
390a15f8589SJoseph Huber MemAlloc = HostPtr;
391a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocHost\n"))
392a15f8589SJoseph Huber return nullptr;
393a15f8589SJoseph Huber HostPinnedAllocs[MemAlloc] = Kind;
394a15f8589SJoseph Huber break;
395a15f8589SJoseph Huber case TARGET_ALLOC_SHARED:
396a15f8589SJoseph Huber CUdeviceptr SharedPtr;
397a15f8589SJoseph Huber Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL);
398a15f8589SJoseph Huber MemAlloc = (void *)SharedPtr;
399a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocManaged\n"))
400a15f8589SJoseph Huber return nullptr;
401a15f8589SJoseph Huber break;
402a15f8589SJoseph Huber }
4030871d6d5SShilei Tian
404a15f8589SJoseph Huber return MemAlloc;
4050871d6d5SShilei Tian }
4060871d6d5SShilei Tian
free(void * TgtPtr)4070871d6d5SShilei Tian int free(void *TgtPtr) override {
40839d3283aSShilei Tian CUresult Err;
409a15f8589SJoseph Huber // Host pinned memory must be freed differently.
410a15f8589SJoseph Huber TargetAllocTy Kind =
411a15f8589SJoseph Huber (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end())
412a15f8589SJoseph Huber ? TARGET_ALLOC_DEFAULT
413a15f8589SJoseph Huber : TARGET_ALLOC_HOST;
414a15f8589SJoseph Huber switch (Kind) {
415a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT:
416a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE:
417a15f8589SJoseph Huber case TARGET_ALLOC_SHARED:
41895f0d1edSJon Chesterfield Err = cuMemFree((CUdeviceptr)TgtPtr);
41995f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemFree\n"))
4200871d6d5SShilei Tian return OFFLOAD_FAIL;
421a15f8589SJoseph Huber break;
422a15f8589SJoseph Huber case TARGET_ALLOC_HOST:
423a15f8589SJoseph Huber Err = cuMemFreeHost(TgtPtr);
424a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemFreeHost\n"))
425a15f8589SJoseph Huber return OFFLOAD_FAIL;
426a15f8589SJoseph Huber break;
427a15f8589SJoseph Huber }
4280871d6d5SShilei Tian
4290871d6d5SShilei Tian return OFFLOAD_SUCCESS;
4300871d6d5SShilei Tian }
4310871d6d5SShilei Tian };
4320871d6d5SShilei Tian
4330871d6d5SShilei Tian /// A vector of device allocators
4340871d6d5SShilei Tian std::vector<CUDADeviceAllocatorTy> DeviceAllocators;
4350871d6d5SShilei Tian
4360871d6d5SShilei Tian /// A vector of memory managers. Since the memory manager is non-copyable and
4370871d6d5SShilei Tian // non-removable, we wrap them into std::unique_ptr.
4380871d6d5SShilei Tian std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers;
4390871d6d5SShilei Tian
4400871d6d5SShilei Tian /// Whether use memory manager
4410871d6d5SShilei Tian bool UseMemoryManager = true;
4420871d6d5SShilei Tian
4433de4cd12SGeorge Rokos // Record entry point associated with device
addOffloadEntry(const int DeviceId,const __tgt_offload_entry Entry)444d27d0a67SJoseph Huber void addOffloadEntry(const int DeviceId, const __tgt_offload_entry Entry) {
4454031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
446d27d0a67SJoseph Huber E.Entries.push_back(Entry);
4473de4cd12SGeorge Rokos }
4483de4cd12SGeorge Rokos
449ae209397SJoseph Huber // Return a pointer to the entry associated with the pointer
getOffloadEntry(const int DeviceId,const void * Addr) const450ae209397SJoseph Huber const __tgt_offload_entry *getOffloadEntry(const int DeviceId,
451ae209397SJoseph Huber const void *Addr) const {
4524031bb98SShilei Tian for (const __tgt_offload_entry &Itr :
4534031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.back().Entries)
4544031bb98SShilei Tian if (Itr.addr == Addr)
455ae209397SJoseph Huber return &Itr;
4563de4cd12SGeorge Rokos
457ae209397SJoseph Huber return nullptr;
4583de4cd12SGeorge Rokos }
4593de4cd12SGeorge Rokos
4603de4cd12SGeorge Rokos // Return the pointer to the target entries table
getOffloadEntriesTable(const int DeviceId)4614031bb98SShilei Tian __tgt_target_table *getOffloadEntriesTable(const int DeviceId) {
4624031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4633de4cd12SGeorge Rokos
4644031bb98SShilei Tian if (E.Entries.empty())
4654031bb98SShilei Tian return nullptr;
4663de4cd12SGeorge Rokos
4673de4cd12SGeorge Rokos // Update table info according to the entries and return the pointer
4684031bb98SShilei Tian E.Table.EntriesBegin = E.Entries.data();
4694031bb98SShilei Tian E.Table.EntriesEnd = E.Entries.data() + E.Entries.size();
4703de4cd12SGeorge Rokos
4713de4cd12SGeorge Rokos return &E.Table;
4723de4cd12SGeorge Rokos }
4733de4cd12SGeorge Rokos
4743de4cd12SGeorge Rokos // Clear entries table for a device
clearOffloadEntriesTable(const int DeviceId)4754031bb98SShilei Tian void clearOffloadEntriesTable(const int DeviceId) {
4764031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.emplace_back();
4774031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back();
4783de4cd12SGeorge Rokos E.Entries.clear();
4794031bb98SShilei Tian E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr;
4803de4cd12SGeorge Rokos }
4813de4cd12SGeorge Rokos
482f44e41afSSri Hari Krishna Narayanan public:
getStream(const int DeviceId,__tgt_async_info * AsyncInfo) const4835449fbb5SJohannes Doerfert CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const {
4845449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr");
4854031bb98SShilei Tian
486a697a0a4SShilei Tian if (!AsyncInfo->Queue) {
487a697a0a4SShilei Tian CUstream S;
488a697a0a4SShilei Tian if (StreamPool[DeviceId]->acquire(S) != OFFLOAD_SUCCESS)
489a697a0a4SShilei Tian return nullptr;
490a697a0a4SShilei Tian
491a697a0a4SShilei Tian AsyncInfo->Queue = S;
492a697a0a4SShilei Tian }
4934031bb98SShilei Tian
4945449fbb5SJohannes Doerfert return reinterpret_cast<CUstream>(AsyncInfo->Queue);
495b305d26bSSergey Dmitriev }
4964031bb98SShilei Tian
4974031bb98SShilei Tian // This class should not be copied
4984031bb98SShilei Tian DeviceRTLTy(const DeviceRTLTy &) = delete;
4994031bb98SShilei Tian DeviceRTLTy(DeviceRTLTy &&) = delete;
5004031bb98SShilei Tian
DeviceRTLTy()5014031bb98SShilei Tian DeviceRTLTy()
5024031bb98SShilei Tian : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1),
503f1c821faSJoseph Huber EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED),
5041660288bSJohannes Doerfert DynamicMemorySize(0) {
505b305d26bSSergey Dmitriev
5063de4cd12SGeorge Rokos DP("Start initializing CUDA\n");
5073de4cd12SGeorge Rokos
5084031bb98SShilei Tian CUresult Err = cuInit(0);
5097baff00eSJon Chesterfield if (Err == CUDA_ERROR_INVALID_HANDLE) {
5107baff00eSJon Chesterfield // Can't call cuGetErrorString if dlsym failed
5117baff00eSJon Chesterfield DP("Failed to load CUDA shared library\n");
5127baff00eSJon Chesterfield return;
5137baff00eSJon Chesterfield }
514cfa6e79dSJoel E. Denny if (Err == CUDA_ERROR_NO_DEVICE) {
515cfa6e79dSJoel E. Denny DP("There are no devices supporting CUDA.\n");
516cfa6e79dSJoel E. Denny return;
517cfa6e79dSJoel E. Denny }
5184031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuInit\n")) {
5193de4cd12SGeorge Rokos return;
5203de4cd12SGeorge Rokos }
5213de4cd12SGeorge Rokos
5224031bb98SShilei Tian Err = cuDeviceGetCount(&NumberOfDevices);
5234031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGetCount\n"))
5243de4cd12SGeorge Rokos return;
5253de4cd12SGeorge Rokos
5263de4cd12SGeorge Rokos if (NumberOfDevices == 0) {
5273de4cd12SGeorge Rokos DP("There are no devices supporting CUDA.\n");
5283de4cd12SGeorge Rokos return;
5293de4cd12SGeorge Rokos }
5303de4cd12SGeorge Rokos
5314031bb98SShilei Tian DeviceData.resize(NumberOfDevices);
53214de0820SJohannes Doerfert Modules.resize(NumberOfDevices);
533a697a0a4SShilei Tian StreamPool.resize(NumberOfDevices);
5341660288bSJohannes Doerfert EventPool.resize(NumberOfDevices);
5352695e23aSShilei Tian PeerAccessMatrix.resize(NumberOfDevices);
5362695e23aSShilei Tian for (auto &V : PeerAccessMatrix)
5372695e23aSShilei Tian V.resize(NumberOfDevices, PeerAccessState::Unkown);
5383de4cd12SGeorge Rokos
5393de4cd12SGeorge Rokos // Get environment variables regarding teams
5404031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) {
5413de4cd12SGeorge Rokos // OMP_TEAM_LIMIT has been set
5424031bb98SShilei Tian EnvTeamLimit = std::stoi(EnvStr);
5433de4cd12SGeorge Rokos DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit);
5443de4cd12SGeorge Rokos }
545422adaa8SJoseph Huber if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) {
546422adaa8SJoseph Huber // OMP_TEAMS_THREAD_LIMIT has been set
547422adaa8SJoseph Huber EnvTeamThreadLimit = std::stoi(EnvStr);
548422adaa8SJoseph Huber DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit);
549422adaa8SJoseph Huber }
5504031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) {
5513de4cd12SGeorge Rokos // OMP_NUM_TEAMS has been set
5524031bb98SShilei Tian EnvNumTeams = std::stoi(EnvStr);
5533de4cd12SGeorge Rokos DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams);
5543de4cd12SGeorge Rokos }
555f1c821faSJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_SHARED_MEMORY_SIZE")) {
556f1c821faSJoseph Huber // LIBOMPTARGET_SHARED_MEMORY_SIZE has been set
557f1c821faSJoseph Huber DynamicMemorySize = std::stoi(EnvStr);
55849e976c9SShilei Tian DP("Parsed LIBOMPTARGET_SHARED_MEMORY_SIZE = %" PRIu64 "\n",
55949e976c9SShilei Tian DynamicMemorySize);
560f1c821faSJoseph Huber }
561a697a0a4SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS")) {
562a697a0a4SShilei Tian // LIBOMPTARGET_NUM_INITIAL_STREAMS has been set
563a697a0a4SShilei Tian NumInitialStreams = std::stoi(EnvStr);
564a697a0a4SShilei Tian DP("Parsed LIBOMPTARGET_NUM_INITIAL_STREAMS=%d\n", NumInitialStreams);
565a697a0a4SShilei Tian }
5660871d6d5SShilei Tian
5670871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I)
56839d3283aSShilei Tian DeviceAllocators.emplace_back();
5690871d6d5SShilei Tian
5700871d6d5SShilei Tian // Get the size threshold from environment variable
5710871d6d5SShilei Tian std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv();
5720871d6d5SShilei Tian UseMemoryManager = Res.second;
5730871d6d5SShilei Tian size_t MemoryManagerThreshold = Res.first;
5740871d6d5SShilei Tian
5750871d6d5SShilei Tian if (UseMemoryManager)
5760871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I)
5770871d6d5SShilei Tian MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>(
5780871d6d5SShilei Tian DeviceAllocators[I], MemoryManagerThreshold));
57910aa83ffSJohannes Doerfert
58010aa83ffSJohannes Doerfert // We lazily initialize all devices later.
58110aa83ffSJohannes Doerfert InitializedFlags.assign(NumberOfDevices, false);
5823de4cd12SGeorge Rokos }
5833de4cd12SGeorge Rokos
~DeviceRTLTy()5844031bb98SShilei Tian ~DeviceRTLTy() {
58510aa83ffSJohannes Doerfert for (int DeviceId = 0; DeviceId < NumberOfDevices; ++DeviceId)
58610aa83ffSJohannes Doerfert deinitDevice(DeviceId);
5873de4cd12SGeorge Rokos }
5883de4cd12SGeorge Rokos
5894031bb98SShilei Tian // Check whether a given DeviceId is valid
isValidDeviceId(const int DeviceId) const5904031bb98SShilei Tian bool isValidDeviceId(const int DeviceId) const {
5914031bb98SShilei Tian return DeviceId >= 0 && DeviceId < NumberOfDevices;
59232ed2927SShilei Tian }
59332ed2927SShilei Tian
getNumOfDevices() const594cb038927SShilei Tian int getNumOfDevices() const { return NumberOfDevices; }
5954031bb98SShilei Tian
setRequiresFlag(const int64_t Flags)5964031bb98SShilei Tian void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; }
5974031bb98SShilei Tian
initDevice(const int DeviceId)5984031bb98SShilei Tian int initDevice(const int DeviceId) {
5994031bb98SShilei Tian CUdevice Device;
6004031bb98SShilei Tian
6014031bb98SShilei Tian DP("Getting device %d\n", DeviceId);
6024031bb98SShilei Tian CUresult Err = cuDeviceGet(&Device, DeviceId);
6034031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGet\n"))
60432ed2927SShilei Tian return OFFLOAD_FAIL;
6053de4cd12SGeorge Rokos
60610aa83ffSJohannes Doerfert assert(InitializedFlags[DeviceId] == false && "Reinitializing device!");
60710aa83ffSJohannes Doerfert InitializedFlags[DeviceId] = true;
60810aa83ffSJohannes Doerfert
609c5348aecSYe Luo // Query the current flags of the primary context and set its flags if
610c5348aecSYe Luo // it is inactive
611c5348aecSYe Luo unsigned int FormerPrimaryCtxFlags = 0;
612c5348aecSYe Luo int FormerPrimaryCtxIsActive = 0;
613c5348aecSYe Luo Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags,
614c5348aecSYe Luo &FormerPrimaryCtxIsActive);
615c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n"))
616c5348aecSYe Luo return OFFLOAD_FAIL;
617c5348aecSYe Luo
618c5348aecSYe Luo if (FormerPrimaryCtxIsActive) {
619c5348aecSYe Luo DP("The primary context is active, no change to its flags\n");
620c5348aecSYe Luo if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) !=
621c5348aecSYe Luo CU_CTX_SCHED_BLOCKING_SYNC)
622c5348aecSYe Luo DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n");
623c5348aecSYe Luo } else {
624c5348aecSYe Luo DP("The primary context is inactive, set its flags to "
625c5348aecSYe Luo "CU_CTX_SCHED_BLOCKING_SYNC\n");
62695f0d1edSJon Chesterfield Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC);
62795f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n"))
628c5348aecSYe Luo return OFFLOAD_FAIL;
629c5348aecSYe Luo }
630c5348aecSYe Luo
631c5348aecSYe Luo // Retain the per device primary context and save it to use whenever this
632c5348aecSYe Luo // device is selected.
633c5348aecSYe Luo Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device);
634c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n"))
6353de4cd12SGeorge Rokos return OFFLOAD_FAIL;
6363de4cd12SGeorge Rokos
6374031bb98SShilei Tian Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
6384031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n"))
6394031bb98SShilei Tian return OFFLOAD_FAIL;
640a5153dbcSJohannes Doerfert
6411660288bSJohannes Doerfert // Initialize the stream pool.
642a697a0a4SShilei Tian if (!StreamPool[DeviceId])
64339d3283aSShilei Tian StreamPool[DeviceId] = std::make_unique<StreamPoolTy>(StreamAllocatorTy(),
64439d3283aSShilei Tian NumInitialStreams);
6451660288bSJohannes Doerfert
6461660288bSJohannes Doerfert // Initialize the event pool.
6471660288bSJohannes Doerfert if (!EventPool[DeviceId])
64839d3283aSShilei Tian EventPool[DeviceId] =
64939d3283aSShilei Tian std::make_unique<EventPoolTy>(EventAllocatorTy(), NumInitialEvents);
650a5153dbcSJohannes Doerfert
651bb51d398SJonas Hahnfeld // Query attributes to determine number of threads/block and blocks/grid.
6524031bb98SShilei Tian int MaxGridDimX;
6534031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X,
6544031bb98SShilei Tian Device);
6554031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
6564031bb98SShilei Tian DP("Error getting max grid dimension, use default value %d\n",
6574031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams);
6584031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams;
659aca33b0bSShilei Tian } else {
6604031bb98SShilei Tian DP("Using %d CUDA blocks per grid\n", MaxGridDimX);
6614031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX;
6623de4cd12SGeorge Rokos }
6633de4cd12SGeorge Rokos
664bb51d398SJonas Hahnfeld // We are only exploiting threads along the x axis.
6654031bb98SShilei Tian int MaxBlockDimX;
6664031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxBlockDimX,
6674031bb98SShilei Tian CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device);
6684031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
6694031bb98SShilei Tian DP("Error getting max block dimension, use default value %d\n",
6704031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads);
6714031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads;
672422adaa8SJoseph Huber } else {
6734031bb98SShilei Tian DP("Using %d CUDA threads per block\n", MaxBlockDimX);
6744031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX;
675422adaa8SJoseph Huber
676422adaa8SJoseph Huber if (EnvTeamThreadLimit > 0 &&
677422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) {
678422adaa8SJoseph Huber DP("Max CUDA threads per block %d exceeds the thread limit %d set by "
679422adaa8SJoseph Huber "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n",
680422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit);
681422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit;
682422adaa8SJoseph Huber }
683422adaa8SJoseph Huber if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) {
6844031bb98SShilei Tian DP("Max CUDA threads per block %d exceeds the hard thread limit %d, "
6854031bb98SShilei Tian "capping at the hard limit\n",
686422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit);
6874031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit;
6883de4cd12SGeorge Rokos }
689422adaa8SJoseph Huber }
6903de4cd12SGeorge Rokos
6914031bb98SShilei Tian // Get and set warp size
6924031bb98SShilei Tian int WarpSize;
6934031bb98SShilei Tian Err =
6944031bb98SShilei Tian cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device);
6954031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
6964031bb98SShilei Tian DP("Error getting warp size, assume default value 32\n");
6974031bb98SShilei Tian DeviceData[DeviceId].WarpSize = 32;
698bb51d398SJonas Hahnfeld } else {
6994031bb98SShilei Tian DP("Using warp size %d\n", WarpSize);
7004031bb98SShilei Tian DeviceData[DeviceId].WarpSize = WarpSize;
7013de4cd12SGeorge Rokos }
7023de4cd12SGeorge Rokos
7033de4cd12SGeorge Rokos // Adjust teams to the env variables
7044031bb98SShilei Tian if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) {
7053de4cd12SGeorge Rokos DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n",
7064031bb98SShilei Tian EnvTeamLimit);
7074031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit;
7083de4cd12SGeorge Rokos }
7093de4cd12SGeorge Rokos
7103817ba13SJoseph Huber size_t StackLimit;
7113817ba13SJoseph Huber size_t HeapLimit;
7123817ba13SJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) {
7133817ba13SJoseph Huber StackLimit = std::stol(EnvStr);
7143817ba13SJoseph Huber if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS)
7153817ba13SJoseph Huber return OFFLOAD_FAIL;
7163817ba13SJoseph Huber } else {
7173817ba13SJoseph Huber if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS)
7183817ba13SJoseph Huber return OFFLOAD_FAIL;
7193817ba13SJoseph Huber }
7203817ba13SJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) {
7213817ba13SJoseph Huber HeapLimit = std::stol(EnvStr);
7223817ba13SJoseph Huber if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS)
7233817ba13SJoseph Huber return OFFLOAD_FAIL;
7243817ba13SJoseph Huber } else {
7253817ba13SJoseph Huber if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS)
7263817ba13SJoseph Huber return OFFLOAD_FAIL;
7273817ba13SJoseph Huber }
7283817ba13SJoseph Huber
729119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
730ae209397SJoseph Huber "Device supports up to %d CUDA blocks and %d threads with a "
731ae209397SJoseph Huber "warp size of %d\n",
732ae209397SJoseph Huber DeviceData[DeviceId].BlocksPerGrid,
733ae209397SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize);
7343817ba13SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
7353817ba13SJoseph Huber "Device heap size is %d Bytes, device stack size is %d Bytes per "
7363817ba13SJoseph Huber "thread\n",
7373817ba13SJoseph Huber (int)HeapLimit, (int)StackLimit);
7383de4cd12SGeorge Rokos
7393de4cd12SGeorge Rokos // Set default number of teams
7404031bb98SShilei Tian if (EnvNumTeams > 0) {
7413de4cd12SGeorge Rokos DP("Default number of teams set according to environment %d\n",
7424031bb98SShilei Tian EnvNumTeams);
7434031bb98SShilei Tian DeviceData[DeviceId].NumTeams = EnvNumTeams;
7443de4cd12SGeorge Rokos } else {
7454031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams;
7463de4cd12SGeorge Rokos DP("Default number of teams set according to library's default %d\n",
7474031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams);
7483de4cd12SGeorge Rokos }
7494031bb98SShilei Tian
7504031bb98SShilei Tian if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) {
7513de4cd12SGeorge Rokos DP("Default number of teams exceeds device limit, capping at %d\n",
7524031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid);
7534031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid;
7543de4cd12SGeorge Rokos }
7553de4cd12SGeorge Rokos
7563de4cd12SGeorge Rokos // Set default number of threads
7574031bb98SShilei Tian DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads;
7583de4cd12SGeorge Rokos DP("Default number of threads set according to library's default %d\n",
7594031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads);
7604031bb98SShilei Tian if (DeviceData[DeviceId].NumThreads >
7614031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock) {
7623de4cd12SGeorge Rokos DP("Default number of threads exceeds device limit, capping at %d\n",
7634031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock);
764c060c634SShilei Tian DeviceData[DeviceId].NumThreads = DeviceData[DeviceId].ThreadsPerBlock;
7653de4cd12SGeorge Rokos }
7663de4cd12SGeorge Rokos
7673de4cd12SGeorge Rokos return OFFLOAD_SUCCESS;
7683de4cd12SGeorge Rokos }
7693de4cd12SGeorge Rokos
deinitDevice(const int DeviceId)77010aa83ffSJohannes Doerfert int deinitDevice(const int DeviceId) {
77110aa83ffSJohannes Doerfert auto IsInitialized = InitializedFlags[DeviceId];
77210aa83ffSJohannes Doerfert if (!IsInitialized)
77310aa83ffSJohannes Doerfert return OFFLOAD_SUCCESS;
77410aa83ffSJohannes Doerfert InitializedFlags[DeviceId] = false;
77510aa83ffSJohannes Doerfert
77610aa83ffSJohannes Doerfert if (UseMemoryManager)
77710aa83ffSJohannes Doerfert MemoryManagers[DeviceId].release();
77810aa83ffSJohannes Doerfert
77910aa83ffSJohannes Doerfert StreamPool[DeviceId].reset();
7801660288bSJohannes Doerfert EventPool[DeviceId].reset();
78110aa83ffSJohannes Doerfert
78210aa83ffSJohannes Doerfert DeviceDataTy &D = DeviceData[DeviceId];
7835105c7cdSShilei Tian if (!checkResult(cuCtxSetCurrent(D.Context),
7845105c7cdSShilei Tian "Error returned from cuCtxSetCurrent\n"))
7855105c7cdSShilei Tian return OFFLOAD_FAIL;
7865105c7cdSShilei Tian
7875105c7cdSShilei Tian // Unload all modules.
7885105c7cdSShilei Tian for (auto &M : Modules[DeviceId])
7895105c7cdSShilei Tian if (!checkResult(cuModuleUnload(M),
7905105c7cdSShilei Tian "Error returned from cuModuleUnload\n"))
7915105c7cdSShilei Tian return OFFLOAD_FAIL;
7925105c7cdSShilei Tian
7935105c7cdSShilei Tian // Destroy context.
79410aa83ffSJohannes Doerfert CUdevice Device;
7955105c7cdSShilei Tian if (!checkResult(cuCtxGetDevice(&Device),
79610aa83ffSJohannes Doerfert "Error returned from cuCtxGetDevice\n"))
7975105c7cdSShilei Tian return OFFLOAD_FAIL;
7985105c7cdSShilei Tian
7995105c7cdSShilei Tian if (!checkResult(cuDevicePrimaryCtxRelease(Device),
8005105c7cdSShilei Tian "Error returned from cuDevicePrimaryCtxRelease\n"))
8015105c7cdSShilei Tian return OFFLOAD_FAIL;
8025105c7cdSShilei Tian
80310aa83ffSJohannes Doerfert return OFFLOAD_SUCCESS;
80410aa83ffSJohannes Doerfert }
80510aa83ffSJohannes Doerfert
loadBinary(const int DeviceId,const __tgt_device_image * Image)8064031bb98SShilei Tian __tgt_target_table *loadBinary(const int DeviceId,
8074031bb98SShilei Tian const __tgt_device_image *Image) {
8083de4cd12SGeorge Rokos // Clear the offload table as we are going to create a new one.
8094031bb98SShilei Tian clearOffloadEntriesTable(DeviceId);
8103de4cd12SGeorge Rokos
8113de4cd12SGeorge Rokos // Create the module and extract the function pointers.
8124031bb98SShilei Tian CUmodule Module;
8134031bb98SShilei Tian DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart));
81439d3283aSShilei Tian CUresult Err =
81539d3283aSShilei Tian cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr);
8164031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n"))
8174031bb98SShilei Tian return nullptr;
8183de4cd12SGeorge Rokos
8193de4cd12SGeorge Rokos DP("CUDA module successfully loaded!\n");
8204031bb98SShilei Tian
8215105c7cdSShilei Tian Modules[DeviceId].push_back(Module);
8223de4cd12SGeorge Rokos
8233de4cd12SGeorge Rokos // Find the symbols in the module by name.
8244031bb98SShilei Tian const __tgt_offload_entry *HostBegin = Image->EntriesBegin;
8254031bb98SShilei Tian const __tgt_offload_entry *HostEnd = Image->EntriesEnd;
8263de4cd12SGeorge Rokos
8275272d29eSJohannes Doerfert std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList;
8284031bb98SShilei Tian for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) {
8294031bb98SShilei Tian if (!E->addr) {
8304031bb98SShilei Tian // We return nullptr when something like this happens, the host should
8314031bb98SShilei Tian // have always something in the address to uniquely identify the target
8324031bb98SShilei Tian // region.
8334031bb98SShilei Tian DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size);
8344031bb98SShilei Tian return nullptr;
8353de4cd12SGeorge Rokos }
8363de4cd12SGeorge Rokos
8374031bb98SShilei Tian if (E->size) {
8384031bb98SShilei Tian __tgt_offload_entry Entry = *E;
8394031bb98SShilei Tian CUdeviceptr CUPtr;
8404031bb98SShilei Tian size_t CUSize;
84195f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name);
8424031bb98SShilei Tian // We keep this style here because we need the name
8434031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
8442ce16810SJoseph Huber REPORT("Loading global '%s' Failed\n", E->name);
8454031bb98SShilei Tian CUDA_ERR_STRING(Err);
8464031bb98SShilei Tian return nullptr;
8473de4cd12SGeorge Rokos }
8483de4cd12SGeorge Rokos
8494031bb98SShilei Tian if (CUSize != E->size) {
8504031bb98SShilei Tian DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name,
8514031bb98SShilei Tian CUSize, E->size);
8524031bb98SShilei Tian return nullptr;
8533de4cd12SGeorge Rokos }
8543de4cd12SGeorge Rokos
8553de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n",
8564031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr));
8574031bb98SShilei Tian
8584031bb98SShilei Tian Entry.addr = (void *)(CUPtr);
8593de4cd12SGeorge Rokos
860aace6d28SGheorghe-Teodor Bercea // Note: In the current implementation declare target variables
861aace6d28SGheorghe-Teodor Bercea // can either be link or to. This means that once unified
862aace6d28SGheorghe-Teodor Bercea // memory is activated via the requires directive, the variable
863aace6d28SGheorghe-Teodor Bercea // can be used directly from the host in both cases.
864aace6d28SGheorghe-Teodor Bercea // TODO: when variables types other than to or link are added,
8654c6a098aSKazuaki Ishizaki // the below condition should be changed to explicitly
866aace6d28SGheorghe-Teodor Bercea // check for to and link variables types:
8674031bb98SShilei Tian // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags &
8684031bb98SShilei Tian // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO))
8694031bb98SShilei Tian if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) {
870aace6d28SGheorghe-Teodor Bercea // If unified memory is present any target link or to variables
871c5fe030cSGheorghe-Teodor Bercea // can access host addresses directly. There is no longer a
872c5fe030cSGheorghe-Teodor Bercea // need for device copies.
87395f0d1edSJon Chesterfield cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *));
8744031bb98SShilei Tian DP("Copy linked variable host address (" DPxMOD
8754031bb98SShilei Tian ") to device address (" DPxMOD ")\n",
8764031bb98SShilei Tian DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr));
877c5fe030cSGheorghe-Teodor Bercea }
878c5fe030cSGheorghe-Teodor Bercea
8794031bb98SShilei Tian addOffloadEntry(DeviceId, Entry);
8803de4cd12SGeorge Rokos
8813de4cd12SGeorge Rokos continue;
8823de4cd12SGeorge Rokos }
8833de4cd12SGeorge Rokos
8844031bb98SShilei Tian CUfunction Func;
8854031bb98SShilei Tian Err = cuModuleGetFunction(&Func, Module, E->name);
8864031bb98SShilei Tian // We keep this style here because we need the name
8874031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
8882ce16810SJoseph Huber REPORT("Loading '%s' Failed\n", E->name);
8894031bb98SShilei Tian CUDA_ERR_STRING(Err);
8904031bb98SShilei Tian return nullptr;
8913de4cd12SGeorge Rokos }
8923de4cd12SGeorge Rokos
8933de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n",
8944031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(Func));
8953de4cd12SGeorge Rokos
8963de4cd12SGeorge Rokos // default value GENERIC (in case symbol is missing from cubin file)
897ca999f71SShilei Tian llvm::omp::OMPTgtExecModeFlags ExecModeVal;
8984031bb98SShilei Tian std::string ExecModeNameStr(E->name);
8993de4cd12SGeorge Rokos ExecModeNameStr += "_exec_mode";
9003de4cd12SGeorge Rokos const char *ExecModeName = ExecModeNameStr.c_str();
9013de4cd12SGeorge Rokos
9023de4cd12SGeorge Rokos CUdeviceptr ExecModePtr;
9034031bb98SShilei Tian size_t CUSize;
90495f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName);
9054031bb98SShilei Tian if (Err == CUDA_SUCCESS) {
906ca999f71SShilei Tian if (CUSize != sizeof(llvm::omp::OMPTgtExecModeFlags)) {
9073de4cd12SGeorge Rokos DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n",
908ca999f71SShilei Tian ExecModeName, CUSize, sizeof(llvm::omp::OMPTgtExecModeFlags));
9094031bb98SShilei Tian return nullptr;
9103de4cd12SGeorge Rokos }
9113de4cd12SGeorge Rokos
91295f0d1edSJon Chesterfield Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize);
9134031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
9142ce16810SJoseph Huber REPORT("Error when copying data from device to host. Pointers: "
9153de4cd12SGeorge Rokos "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n",
9164031bb98SShilei Tian DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize);
9174031bb98SShilei Tian CUDA_ERR_STRING(Err);
9184031bb98SShilei Tian return nullptr;
9193de4cd12SGeorge Rokos }
9203de4cd12SGeorge Rokos } else {
921edb8acdcSJoseph Huber DP("Loading global exec_mode '%s' - symbol missing, using default "
9224031bb98SShilei Tian "value GENERIC (1)\n",
9234031bb98SShilei Tian ExecModeName);
9243de4cd12SGeorge Rokos }
9253de4cd12SGeorge Rokos
9264031bb98SShilei Tian KernelsList.emplace_back(Func, ExecModeVal);
9273de4cd12SGeorge Rokos
9284031bb98SShilei Tian __tgt_offload_entry Entry = *E;
9294031bb98SShilei Tian Entry.addr = &KernelsList.back();
9304031bb98SShilei Tian addOffloadEntry(DeviceId, Entry);
9313de4cd12SGeorge Rokos }
9323de4cd12SGeorge Rokos
933e1c7a46dSGuansong Zhang // send device environment data to the device
934e1c7a46dSGuansong Zhang {
935ec02c34bSJoseph Huber // TODO: The device ID used here is not the real device ID used by OpenMP.
9360c554a47SJon Chesterfield DeviceEnvironmentTy DeviceEnv{0, static_cast<uint32_t>(NumberOfDevices),
9370c554a47SJon Chesterfield static_cast<uint32_t>(DeviceId),
9380c554a47SJon Chesterfield static_cast<uint32_t>(DynamicMemorySize)};
939e1c7a46dSGuansong Zhang
9404031bb98SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG"))
9410c554a47SJon Chesterfield DeviceEnv.DebugKind = std::stoi(EnvStr);
942e1c7a46dSGuansong Zhang
9434031bb98SShilei Tian const char *DeviceEnvName = "omptarget_device_environment";
9444031bb98SShilei Tian CUdeviceptr DeviceEnvPtr;
9454031bb98SShilei Tian size_t CUSize;
946e1c7a46dSGuansong Zhang
94795f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName);
9484031bb98SShilei Tian if (Err == CUDA_SUCCESS) {
9494031bb98SShilei Tian if (CUSize != sizeof(DeviceEnv)) {
9502ce16810SJoseph Huber REPORT(
9512ce16810SJoseph Huber "Global device_environment '%s' - size mismatch (%zu != %zu)\n",
9524031bb98SShilei Tian DeviceEnvName, CUSize, sizeof(int32_t));
9534031bb98SShilei Tian CUDA_ERR_STRING(Err);
9544031bb98SShilei Tian return nullptr;
955e1c7a46dSGuansong Zhang }
956e1c7a46dSGuansong Zhang
95795f0d1edSJon Chesterfield Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize);
9584031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
9592ce16810SJoseph Huber REPORT("Error when copying data from host to device. Pointers: "
960e1c7a46dSGuansong Zhang "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n",
9614031bb98SShilei Tian DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize);
9624031bb98SShilei Tian CUDA_ERR_STRING(Err);
9634031bb98SShilei Tian return nullptr;
964e1c7a46dSGuansong Zhang }
965e1c7a46dSGuansong Zhang
9664031bb98SShilei Tian DP("Sending global device environment data %zu bytes\n", CUSize);
967e1c7a46dSGuansong Zhang } else {
9684031bb98SShilei Tian DP("Finding global device environment '%s' - symbol missing.\n",
9694031bb98SShilei Tian DeviceEnvName);
9704031bb98SShilei Tian DP("Continue, considering this is a device RTL which does not accept "
9714031bb98SShilei Tian "environment setting.\n");
972e1c7a46dSGuansong Zhang }
973e1c7a46dSGuansong Zhang }
974e1c7a46dSGuansong Zhang
9754031bb98SShilei Tian return getOffloadEntriesTable(DeviceId);
9763de4cd12SGeorge Rokos }
9773de4cd12SGeorge Rokos
dataAlloc(const int DeviceId,const int64_t Size,const TargetAllocTy Kind)978a15f8589SJoseph Huber void *dataAlloc(const int DeviceId, const int64_t Size,
979a15f8589SJoseph Huber const TargetAllocTy Kind) {
980a15f8589SJoseph Huber switch (Kind) {
981a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT:
982a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE:
9830871d6d5SShilei Tian if (UseMemoryManager)
9840871d6d5SShilei Tian return MemoryManagers[DeviceId]->allocate(Size, nullptr);
985a15f8589SJoseph Huber else
986a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
987a15f8589SJoseph Huber case TARGET_ALLOC_HOST:
988a15f8589SJoseph Huber case TARGET_ALLOC_SHARED:
989a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind);
990a15f8589SJoseph Huber }
9914031bb98SShilei Tian
992a15f8589SJoseph Huber REPORT("Invalid target data allocation kind or requested allocator not "
993a15f8589SJoseph Huber "implemented yet\n");
994a15f8589SJoseph Huber
995a15f8589SJoseph Huber return nullptr;
9963de4cd12SGeorge Rokos }
9973de4cd12SGeorge Rokos
dataSubmit(const int DeviceId,const void * TgtPtr,const void * HstPtr,const int64_t Size,__tgt_async_info * AsyncInfo) const9984031bb98SShilei Tian int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr,
9995449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const {
10005449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr");
10013de4cd12SGeorge Rokos
10025449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo);
100339d3283aSShilei Tian CUresult Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream);
10044031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
100529338459SJoseph Huber DP("Error when copying data from host to device. Pointers: host "
10062ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
10074031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
10084031bb98SShilei Tian CUDA_ERR_STRING(Err);
10093de4cd12SGeorge Rokos return OFFLOAD_FAIL;
10103de4cd12SGeorge Rokos }
10113de4cd12SGeorge Rokos
10123de4cd12SGeorge Rokos return OFFLOAD_SUCCESS;
10133de4cd12SGeorge Rokos }
10143de4cd12SGeorge Rokos
dataRetrieve(const int DeviceId,void * HstPtr,const void * TgtPtr,const int64_t Size,__tgt_async_info * AsyncInfo) const10154031bb98SShilei Tian int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr,
10165449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const {
10175449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr");
10184031bb98SShilei Tian
10195449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo);
102039d3283aSShilei Tian CUresult Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream);
10214031bb98SShilei Tian if (Err != CUDA_SUCCESS) {
102229338459SJoseph Huber DP("Error when copying data from device to host. Pointers: host "
10232ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n",
10244031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size);
10254031bb98SShilei Tian CUDA_ERR_STRING(Err);
10263de4cd12SGeorge Rokos return OFFLOAD_FAIL;
10273de4cd12SGeorge Rokos }
10283de4cd12SGeorge Rokos
10294031bb98SShilei Tian return OFFLOAD_SUCCESS;
10304031bb98SShilei Tian }
10314031bb98SShilei Tian
dataExchange(int SrcDevId,const void * SrcPtr,int DstDevId,void * DstPtr,int64_t Size,__tgt_async_info * AsyncInfo)1032a014fbbcSShilei Tian int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr,
10332695e23aSShilei Tian int64_t Size, __tgt_async_info *AsyncInfo) {
10345449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr");
1035a014fbbcSShilei Tian
103639d3283aSShilei Tian CUresult Err;
10375449fbb5SJohannes Doerfert CUstream Stream = getStream(SrcDevId, AsyncInfo);
1038a014fbbcSShilei Tian
1039a014fbbcSShilei Tian // If they are two devices, we try peer to peer copy first
1040a014fbbcSShilei Tian if (SrcDevId != DstDevId) {
10412695e23aSShilei Tian std::lock_guard<std::mutex> LG(PeerAccessMatrixLock);
10422695e23aSShilei Tian
10432695e23aSShilei Tian switch (PeerAccessMatrix[SrcDevId][DstDevId]) {
10442695e23aSShilei Tian case PeerAccessState::No: {
10452695e23aSShilei Tian REPORT("Peer access from %" PRId32 " to %" PRId32
10462695e23aSShilei Tian " is not supported. Fall back to D2D memcpy.\n",
10472695e23aSShilei Tian SrcDevId, DstDevId);
10482695e23aSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
10492695e23aSShilei Tian }
10502695e23aSShilei Tian case PeerAccessState::Unkown: {
1051a014fbbcSShilei Tian int CanAccessPeer = 0;
1052a014fbbcSShilei Tian Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId);
1053a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) {
10542ce16810SJoseph Huber REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32
10552695e23aSShilei Tian ", dst = %" PRId32 ". Fall back to D2D memcpy.\n",
1056a014fbbcSShilei Tian SrcDevId, DstDevId);
1057a014fbbcSShilei Tian CUDA_ERR_STRING(Err);
10582695e23aSShilei Tian PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1059a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1060a014fbbcSShilei Tian }
1061a014fbbcSShilei Tian
1062a014fbbcSShilei Tian if (!CanAccessPeer) {
10632695e23aSShilei Tian REPORT("P2P access from %d to %d is not supported. Fall back to D2D "
10642695e23aSShilei Tian "memcpy.\n",
10652695e23aSShilei Tian SrcDevId, DstDevId);
10662695e23aSShilei Tian PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1067a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1068a014fbbcSShilei Tian }
1069a014fbbcSShilei Tian
1070a014fbbcSShilei Tian Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0);
1071a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) {
10722ce16810SJoseph Huber REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32
10732695e23aSShilei Tian ", dst = %" PRId32 ". Fall back to D2D memcpy.\n",
1074a014fbbcSShilei Tian SrcDevId, DstDevId);
1075a014fbbcSShilei Tian CUDA_ERR_STRING(Err);
10762695e23aSShilei Tian PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::No;
1077a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1078a014fbbcSShilei Tian }
1079a014fbbcSShilei Tian
10802695e23aSShilei Tian PeerAccessMatrix[SrcDevId][DstDevId] = PeerAccessState::Yes;
10812695e23aSShilei Tian
10822695e23aSShilei Tian LLVM_FALLTHROUGH;
10832695e23aSShilei Tian }
10842695e23aSShilei Tian case PeerAccessState::Yes: {
10852695e23aSShilei Tian Err = cuMemcpyPeerAsync(
10862695e23aSShilei Tian (CUdeviceptr)DstPtr, DeviceData[DstDevId].Context,
10872695e23aSShilei Tian (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context, Size, Stream);
1088a014fbbcSShilei Tian if (Err == CUDA_SUCCESS)
1089a014fbbcSShilei Tian return OFFLOAD_SUCCESS;
1090a014fbbcSShilei Tian
109129338459SJoseph Huber DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD
10922695e23aSShilei Tian ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32
10932695e23aSShilei Tian ". Fall back to D2D memcpy.\n",
109445bb073dSYe Luo DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId);
1095a014fbbcSShilei Tian CUDA_ERR_STRING(Err);
10962695e23aSShilei Tian
10972695e23aSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
10982695e23aSShilei Tian }
10992695e23aSShilei Tian }
1100a014fbbcSShilei Tian }
1101a014fbbcSShilei Tian
1102a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream);
1103a014fbbcSShilei Tian }
1104a014fbbcSShilei Tian
dataDelete(const int DeviceId,void * TgtPtr)11050871d6d5SShilei Tian int dataDelete(const int DeviceId, void *TgtPtr) {
11060871d6d5SShilei Tian if (UseMemoryManager)
11070871d6d5SShilei Tian return MemoryManagers[DeviceId]->free(TgtPtr);
11084031bb98SShilei Tian
11090871d6d5SShilei Tian return DeviceAllocators[DeviceId].free(TgtPtr);
11104031bb98SShilei Tian }
11114031bb98SShilei Tian
runTargetTeamRegion(const int DeviceId,void * TgtEntryPtr,void ** TgtArgs,ptrdiff_t * TgtOffsets,const int ArgNum,const int TeamNum,const int ThreadLimit,const unsigned int LoopTripCount,__tgt_async_info * AsyncInfo) const1112aa27cfc1SJohannes Doerfert int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs,
1113aa27cfc1SJohannes Doerfert ptrdiff_t *TgtOffsets, const int ArgNum,
1114aa27cfc1SJohannes Doerfert const int TeamNum, const int ThreadLimit,
11154031bb98SShilei Tian const unsigned int LoopTripCount,
11164031bb98SShilei Tian __tgt_async_info *AsyncInfo) const {
11173de4cd12SGeorge Rokos // All args are references.
11184031bb98SShilei Tian std::vector<void *> Args(ArgNum);
11194031bb98SShilei Tian std::vector<void *> Ptrs(ArgNum);
11203de4cd12SGeorge Rokos
11214031bb98SShilei Tian for (int I = 0; I < ArgNum; ++I) {
11224031bb98SShilei Tian Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]);
11234031bb98SShilei Tian Args[I] = &Ptrs[I];
11241546d319SGeorge Rokos }
11253de4cd12SGeorge Rokos
1126aa27cfc1SJohannes Doerfert KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr);
11273de4cd12SGeorge Rokos
1128ca999f71SShilei Tian const bool IsSPMDGenericMode =
1129ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD;
1130ca999f71SShilei Tian const bool IsSPMDMode =
1131ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_SPMD;
1132ca999f71SShilei Tian const bool IsGenericMode =
1133ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC;
1134ca999f71SShilei Tian
1135aa27cfc1SJohannes Doerfert int CudaThreadsPerBlock;
11364031bb98SShilei Tian if (ThreadLimit > 0) {
11374031bb98SShilei Tian DP("Setting CUDA threads per block to requested %d\n", ThreadLimit);
11384031bb98SShilei Tian CudaThreadsPerBlock = ThreadLimit;
11393de4cd12SGeorge Rokos // Add master warp if necessary
1140ca999f71SShilei Tian if (IsGenericMode) {
11414031bb98SShilei Tian DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize);
11424031bb98SShilei Tian CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize;
11433de4cd12SGeorge Rokos }
1144c13df8e5SGeorge Rokos } else {
1145c13df8e5SGeorge Rokos DP("Setting CUDA threads per block to default %d\n",
11464031bb98SShilei Tian DeviceData[DeviceId].NumThreads);
11474031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads;
1148c13df8e5SGeorge Rokos }
11493de4cd12SGeorge Rokos
11504031bb98SShilei Tian if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) {
11513de4cd12SGeorge Rokos DP("Threads per block capped at device limit %d\n",
11524031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock);
11534031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock;
11543de4cd12SGeorge Rokos }
11553de4cd12SGeorge Rokos
115639d3283aSShilei Tian CUresult Err;
1157aa27cfc1SJohannes Doerfert if (!KernelInfo->MaxThreadsPerBlock) {
1158aa27cfc1SJohannes Doerfert Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock,
11594031bb98SShilei Tian CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK,
11604031bb98SShilei Tian KernelInfo->Func);
1161aa27cfc1SJohannes Doerfert if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n"))
1162aa27cfc1SJohannes Doerfert return OFFLOAD_FAIL;
1163aa27cfc1SJohannes Doerfert }
1164aa27cfc1SJohannes Doerfert
1165aa27cfc1SJohannes Doerfert if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) {
1166aa27cfc1SJohannes Doerfert DP("Threads per block capped at kernel limit %d\n",
1167aa27cfc1SJohannes Doerfert KernelInfo->MaxThreadsPerBlock);
1168aa27cfc1SJohannes Doerfert CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock;
11693de4cd12SGeorge Rokos }
11703de4cd12SGeorge Rokos
11714031bb98SShilei Tian unsigned int CudaBlocksPerGrid;
11724031bb98SShilei Tian if (TeamNum <= 0) {
11734031bb98SShilei Tian if (LoopTripCount > 0 && EnvNumTeams < 0) {
1174ca999f71SShilei Tian if (IsSPMDGenericMode) {
1175ca999f71SShilei Tian // If we reach this point, then we are executing a kernel that was
1176ca999f71SShilei Tian // transformed from Generic-mode to SPMD-mode. This kernel has
1177ca999f71SShilei Tian // SPMD-mode execution, but needs its blocks to be scheduled
1178ca999f71SShilei Tian // differently because the current loop trip count only applies to the
1179ca999f71SShilei Tian // `teams distribute` region and will create var too few blocks using
1180ca999f71SShilei Tian // the regular SPMD-mode method.
1181ca999f71SShilei Tian CudaBlocksPerGrid = LoopTripCount;
1182ca999f71SShilei Tian } else if (IsSPMDMode) {
11834031bb98SShilei Tian // We have a combined construct, i.e. `target teams distribute
11844031bb98SShilei Tian // parallel for [simd]`. We launch so many teams so that each thread
11854031bb98SShilei Tian // will execute one iteration of the loop. round up to the nearest
11864031bb98SShilei Tian // integer
11874031bb98SShilei Tian CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1;
1188ca999f71SShilei Tian } else if (IsGenericMode) {
1189c13df8e5SGeorge Rokos // If we reach this point, then we have a non-combined construct, i.e.
1190c13df8e5SGeorge Rokos // `teams distribute` with a nested `parallel for` and each team is
1191c13df8e5SGeorge Rokos // assigned one iteration of the `distribute` loop. E.g.:
1192c13df8e5SGeorge Rokos //
1193c13df8e5SGeorge Rokos // #pragma omp target teams distribute
1194c13df8e5SGeorge Rokos // for(...loop_tripcount...) {
1195c13df8e5SGeorge Rokos // #pragma omp parallel for
1196c13df8e5SGeorge Rokos // for(...) {}
1197c13df8e5SGeorge Rokos // }
1198c13df8e5SGeorge Rokos //
1199c13df8e5SGeorge Rokos // Threads within a team will execute the iterations of the `parallel`
1200c13df8e5SGeorge Rokos // loop.
12014031bb98SShilei Tian CudaBlocksPerGrid = LoopTripCount;
1202a158d366SJoseph Huber } else {
1203ca999f71SShilei Tian REPORT("Unknown execution mode: %d\n",
1204ca999f71SShilei Tian static_cast<int8_t>(KernelInfo->ExecutionMode));
1205a158d366SJoseph Huber return OFFLOAD_FAIL;
1206c13df8e5SGeorge Rokos }
120745bb073dSYe Luo DP("Using %d teams due to loop trip count %" PRIu32
12084031bb98SShilei Tian " and number of threads per block %d\n",
12094031bb98SShilei Tian CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock);
12103de4cd12SGeorge Rokos } else {
12114031bb98SShilei Tian DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams);
12124031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams;
12133de4cd12SGeorge Rokos }
12143de4cd12SGeorge Rokos } else {
12154031bb98SShilei Tian DP("Using requested number of teams %d\n", TeamNum);
12164031bb98SShilei Tian CudaBlocksPerGrid = TeamNum;
12173de4cd12SGeorge Rokos }
12183de4cd12SGeorge Rokos
1219f6685f77SShilei Tian if (CudaBlocksPerGrid > DeviceData[DeviceId].BlocksPerGrid) {
1220f6685f77SShilei Tian DP("Capping number of teams to team limit %d\n",
1221f6685f77SShilei Tian DeviceData[DeviceId].BlocksPerGrid);
1222f6685f77SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid;
1223f6685f77SShilei Tian }
1224f6685f77SShilei Tian
1225119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId,
1226ca999f71SShilei Tian "Launching kernel %s with %d blocks and %d threads in %s mode\n",
1227ae209397SJoseph Huber (getOffloadEntry(DeviceId, TgtEntryPtr))
1228ae209397SJoseph Huber ? getOffloadEntry(DeviceId, TgtEntryPtr)->name
1229ae209397SJoseph Huber : "(null)",
1230ae209397SJoseph Huber CudaBlocksPerGrid, CudaThreadsPerBlock,
1231ca999f71SShilei Tian (!IsSPMDMode ? (IsGenericMode ? "Generic" : "SPMD-Generic") : "SPMD"));
12323de4cd12SGeorge Rokos
12334031bb98SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo);
12344031bb98SShilei Tian Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1,
12354031bb98SShilei Tian /* gridDimZ */ 1, CudaThreadsPerBlock,
12364031bb98SShilei Tian /* blockDimY */ 1, /* blockDimZ */ 1,
1237f1c821faSJoseph Huber DynamicMemorySize, Stream, &Args[0], nullptr);
12384031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuLaunchKernel\n"))
12394031bb98SShilei Tian return OFFLOAD_FAIL;
12404031bb98SShilei Tian
12414031bb98SShilei Tian DP("Launch of entry point at " DPxMOD " successful!\n",
12424031bb98SShilei Tian DPxPTR(TgtEntryPtr));
12434031bb98SShilei Tian
12444031bb98SShilei Tian return OFFLOAD_SUCCESS;
12454031bb98SShilei Tian }
12464031bb98SShilei Tian
synchronize(const int DeviceId,__tgt_async_info * AsyncInfo) const12475449fbb5SJohannes Doerfert int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const {
12485449fbb5SJohannes Doerfert CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue);
12494031bb98SShilei Tian CUresult Err = cuStreamSynchronize(Stream);
12503de4cd12SGeorge Rokos
12514031bb98SShilei Tian // Once the stream is synchronized, return it to stream pool and reset
12525449fbb5SJohannes Doerfert // AsyncInfo. This is to make sure the synchronization only works for its
12534031bb98SShilei Tian // own tasks.
1254a697a0a4SShilei Tian StreamPool[DeviceId]->release(reinterpret_cast<CUstream>(AsyncInfo->Queue));
12555449fbb5SJohannes Doerfert AsyncInfo->Queue = nullptr;
12563de4cd12SGeorge Rokos
125716064e71SJoseph Huber if (Err != CUDA_SUCCESS) {
125829338459SJoseph Huber DP("Error when synchronizing stream. stream = " DPxMOD
125916064e71SJoseph Huber ", async info ptr = " DPxMOD "\n",
126016064e71SJoseph Huber DPxPTR(Stream), DPxPTR(AsyncInfo));
126116064e71SJoseph Huber CUDA_ERR_STRING(Err);
126216064e71SJoseph Huber }
126316064e71SJoseph Huber return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL;
12643de4cd12SGeorge Rokos }
1265d2f85d09SJose M Monsalve Diaz
printDeviceInfo(int32_t DeviceId)1266d27d0a67SJoseph Huber void printDeviceInfo(int32_t DeviceId) {
1267d2f85d09SJose M Monsalve Diaz char TmpChar[1000];
1268d2f85d09SJose M Monsalve Diaz std::string TmpStr;
1269d2f85d09SJose M Monsalve Diaz size_t TmpSt;
1270d2f85d09SJose M Monsalve Diaz int TmpInt, TmpInt2, TmpInt3;
1271d2f85d09SJose M Monsalve Diaz
1272d2f85d09SJose M Monsalve Diaz CUdevice Device;
1273d27d0a67SJoseph Huber checkResult(cuDeviceGet(&Device, DeviceId),
1274d2f85d09SJose M Monsalve Diaz "Error returned from cuCtxGetDevice\n");
1275d2f85d09SJose M Monsalve Diaz
1276d2f85d09SJose M Monsalve Diaz cuDriverGetVersion(&TmpInt);
1277d2f85d09SJose M Monsalve Diaz printf(" CUDA Driver Version: \t\t%d \n", TmpInt);
1278d27d0a67SJoseph Huber printf(" CUDA Device Number: \t\t%d \n", DeviceId);
1279d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetName(TmpChar, 1000, Device),
1280d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetName\n");
1281d2f85d09SJose M Monsalve Diaz printf(" Device Name: \t\t\t%s \n", TmpChar);
1282d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceTotalMem(&TmpSt, Device),
1283d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceTotalMem\n");
1284d2f85d09SJose M Monsalve Diaz printf(" Global Memory Size: \t\t%zu bytes \n", TmpSt);
1285d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1286d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device),
1287d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1288d2f85d09SJose M Monsalve Diaz printf(" Number of Multiprocessors: \t\t%d \n", TmpInt);
1289d2f85d09SJose M Monsalve Diaz checkResult(
1290d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device),
1291d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1292d2f85d09SJose M Monsalve Diaz printf(" Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt));
1293d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1294d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device),
1295d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1296d2f85d09SJose M Monsalve Diaz printf(" Total Constant Memory: \t\t%d bytes\n", TmpInt);
1297d2f85d09SJose M Monsalve Diaz checkResult(
1298d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(
1299d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device),
1300d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1301d2f85d09SJose M Monsalve Diaz printf(" Max Shared Memory per Block: \t%d bytes \n", TmpInt);
130228939b6aSShilei Tian checkResult(
130328939b6aSShilei Tian cuDeviceGetAttribute(
1304d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device),
1305d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1306d2f85d09SJose M Monsalve Diaz printf(" Registers per Block: \t\t%d \n", TmpInt);
1307d2f85d09SJose M Monsalve Diaz checkResult(
1308d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device),
1309d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1310d2f85d09SJose M Monsalve Diaz printf(" Warp Size: \t\t\t\t%d Threads \n", TmpInt);
1311d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1312d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device),
1313d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1314d2f85d09SJose M Monsalve Diaz printf(" Maximum Threads per Block: \t\t%d \n", TmpInt);
131528939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
131628939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device),
1317d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
131828939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
131928939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device),
1320d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
132128939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
132228939b6aSShilei Tian &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device),
1323d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1324d2f85d09SJose M Monsalve Diaz printf(" Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2,
1325d2f85d09SJose M Monsalve Diaz TmpInt3);
132628939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
132728939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device),
1328d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
132928939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
133028939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device),
1331d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
133228939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
133328939b6aSShilei Tian &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device),
1334d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1335d2f85d09SJose M Monsalve Diaz printf(" Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2,
1336d2f85d09SJose M Monsalve Diaz TmpInt3);
1337d2f85d09SJose M Monsalve Diaz checkResult(
1338d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device),
1339d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1340d2f85d09SJose M Monsalve Diaz printf(" Maximum Memory Pitch: \t\t%d bytes \n", TmpInt);
1341d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1342d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device),
1343d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1344d2f85d09SJose M Monsalve Diaz printf(" Texture Alignment: \t\t\t%d bytes \n", TmpInt);
1345d2f85d09SJose M Monsalve Diaz checkResult(
1346d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device),
1347d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1348d2f85d09SJose M Monsalve Diaz printf(" Clock Rate: \t\t\t%d kHz\n", TmpInt);
1349d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1350d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device),
1351d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1352d2f85d09SJose M Monsalve Diaz printf(" Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1353d2f85d09SJose M Monsalve Diaz checkResult(
1354d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device),
1355d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1356d2f85d09SJose M Monsalve Diaz printf(" Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1357d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1358d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device),
1359d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1360d2f85d09SJose M Monsalve Diaz printf(" Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1361d2f85d09SJose M Monsalve Diaz checkResult(
1362d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device),
1363d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1364d2f85d09SJose M Monsalve Diaz if (TmpInt == CU_COMPUTEMODE_DEFAULT)
1365d2f85d09SJose M Monsalve Diaz TmpStr = "DEFAULT";
1366d2f85d09SJose M Monsalve Diaz else if (TmpInt == CU_COMPUTEMODE_PROHIBITED)
1367d2f85d09SJose M Monsalve Diaz TmpStr = "PROHIBITED";
1368d2f85d09SJose M Monsalve Diaz else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS)
1369d2f85d09SJose M Monsalve Diaz TmpStr = "EXCLUSIVE PROCESS";
1370d2f85d09SJose M Monsalve Diaz else
1371d2f85d09SJose M Monsalve Diaz TmpStr = "unknown";
1372d2f85d09SJose M Monsalve Diaz printf(" Compute Mode: \t\t\t%s \n", TmpStr.c_str());
1373d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1374d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device),
1375d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1376d2f85d09SJose M Monsalve Diaz printf(" Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt));
1377d2f85d09SJose M Monsalve Diaz checkResult(
1378d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device),
1379d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1380d2f85d09SJose M Monsalve Diaz printf(" ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1381d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1382d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device),
1383d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1384d2f85d09SJose M Monsalve Diaz printf(" Memory Clock Rate: \t\t\t%d kHz\n", TmpInt);
138528939b6aSShilei Tian checkResult(
138628939b6aSShilei Tian cuDeviceGetAttribute(
1387d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device),
1388d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1389d2f85d09SJose M Monsalve Diaz printf(" Memory Bus Width: \t\t\t%d bits\n", TmpInt);
139028939b6aSShilei Tian checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE,
139128939b6aSShilei Tian Device),
1392d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1393d2f85d09SJose M Monsalve Diaz printf(" L2 Cache Size: \t\t\t%d bytes \n", TmpInt);
139428939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
139528939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR,
139628939b6aSShilei Tian Device),
1397d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1398d2f85d09SJose M Monsalve Diaz printf(" Max Threads Per SMP: \t\t%d \n", TmpInt);
1399d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1400d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device),
1401d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1402d2f85d09SJose M Monsalve Diaz printf(" Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt);
1403d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1404d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device),
1405d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1406d2f85d09SJose M Monsalve Diaz printf(" Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt));
140728939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
140828939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device),
1409d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1410d2f85d09SJose M Monsalve Diaz printf(" Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt));
1411d2f85d09SJose M Monsalve Diaz checkResult(
1412d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(
1413d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device),
1414d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1415d2f85d09SJose M Monsalve Diaz printf(" Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt));
1416d2f85d09SJose M Monsalve Diaz checkResult(
1417d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(
1418d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device),
1419d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1420d2f85d09SJose M Monsalve Diaz printf(" Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt));
1421d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute(
1422d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device),
1423d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1424d2f85d09SJose M Monsalve Diaz printf(" Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt));
142528939b6aSShilei Tian checkResult(cuDeviceGetAttribute(
142628939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device),
1427d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1428d2f85d09SJose M Monsalve Diaz printf(" Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt));
142928939b6aSShilei Tian checkResult(
143028939b6aSShilei Tian cuDeviceGetAttribute(
143128939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device),
1432d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
143328939b6aSShilei Tian checkResult(
143428939b6aSShilei Tian cuDeviceGetAttribute(
143528939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device),
1436d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n");
1437d2f85d09SJose M Monsalve Diaz printf(" Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2);
1438d2f85d09SJose M Monsalve Diaz }
143929df4ab3SShilei Tian
createEvent(int DeviceId,void ** P)14401660288bSJohannes Doerfert int createEvent(int DeviceId, void **P) {
1441943d1d83SShilei Tian CUevent Event = nullptr;
14421660288bSJohannes Doerfert if (EventPool[DeviceId]->acquire(Event) != OFFLOAD_SUCCESS)
1443943d1d83SShilei Tian return OFFLOAD_FAIL;
1444943d1d83SShilei Tian *P = Event;
1445943d1d83SShilei Tian return OFFLOAD_SUCCESS;
1446943d1d83SShilei Tian }
1447943d1d83SShilei Tian
destroyEvent(int DeviceId,void * EventPtr)14481660288bSJohannes Doerfert int destroyEvent(int DeviceId, void *EventPtr) {
14491660288bSJohannes Doerfert EventPool[DeviceId]->release(reinterpret_cast<CUevent>(EventPtr));
1450943d1d83SShilei Tian return OFFLOAD_SUCCESS;
1451943d1d83SShilei Tian }
1452943d1d83SShilei Tian
waitEvent(const int DeviceId,__tgt_async_info * AsyncInfo,void * EventPtr) const145329df4ab3SShilei Tian int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo,
145429df4ab3SShilei Tian void *EventPtr) const {
145529df4ab3SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo);
145629df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr);
145729df4ab3SShilei Tian
145829df4ab3SShilei Tian // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from
145929df4ab3SShilei Tian // specific CUDA version, and defined as 0x0. In previous version, per CUDA
146029df4ab3SShilei Tian // API document, that argument has to be 0x0.
146129df4ab3SShilei Tian CUresult Err = cuStreamWaitEvent(Stream, Event, 0);
146229df4ab3SShilei Tian if (Err != CUDA_SUCCESS) {
146329df4ab3SShilei Tian DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n",
146429df4ab3SShilei Tian DPxPTR(Stream), DPxPTR(Event));
146529df4ab3SShilei Tian CUDA_ERR_STRING(Err);
146629df4ab3SShilei Tian return OFFLOAD_FAIL;
146729df4ab3SShilei Tian }
146829df4ab3SShilei Tian
146929df4ab3SShilei Tian return OFFLOAD_SUCCESS;
147029df4ab3SShilei Tian }
1471f44e41afSSri Hari Krishna Narayanan
releaseAsyncInfo(int DeviceId,__tgt_async_info * AsyncInfo) const1472f44e41afSSri Hari Krishna Narayanan int releaseAsyncInfo(int DeviceId, __tgt_async_info *AsyncInfo) const {
1473f44e41afSSri Hari Krishna Narayanan if (AsyncInfo->Queue) {
1474f44e41afSSri Hari Krishna Narayanan StreamPool[DeviceId]->release(
1475f44e41afSSri Hari Krishna Narayanan reinterpret_cast<CUstream>(AsyncInfo->Queue));
1476f44e41afSSri Hari Krishna Narayanan AsyncInfo->Queue = nullptr;
1477f44e41afSSri Hari Krishna Narayanan }
1478f44e41afSSri Hari Krishna Narayanan
1479f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS;
1480f44e41afSSri Hari Krishna Narayanan }
1481f44e41afSSri Hari Krishna Narayanan
initAsyncInfo(int DeviceId,__tgt_async_info ** AsyncInfo) const1482f44e41afSSri Hari Krishna Narayanan int initAsyncInfo(int DeviceId, __tgt_async_info **AsyncInfo) const {
1483f44e41afSSri Hari Krishna Narayanan *AsyncInfo = new __tgt_async_info;
1484f44e41afSSri Hari Krishna Narayanan getStream(DeviceId, *AsyncInfo);
1485f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS;
1486f44e41afSSri Hari Krishna Narayanan }
1487f44e41afSSri Hari Krishna Narayanan
initDeviceInfo(int DeviceId,__tgt_device_info * DeviceInfo,const char ** ErrStr) const1488f44e41afSSri Hari Krishna Narayanan int initDeviceInfo(int DeviceId, __tgt_device_info *DeviceInfo,
1489f44e41afSSri Hari Krishna Narayanan const char **ErrStr) const {
1490f44e41afSSri Hari Krishna Narayanan assert(DeviceInfo && "DeviceInfo is nullptr");
1491f44e41afSSri Hari Krishna Narayanan
1492f44e41afSSri Hari Krishna Narayanan if (!DeviceInfo->Context)
1493f44e41afSSri Hari Krishna Narayanan DeviceInfo->Context = DeviceData[DeviceId].Context;
1494f44e41afSSri Hari Krishna Narayanan if (!DeviceInfo->Device) {
1495f44e41afSSri Hari Krishna Narayanan CUdevice Dev;
1496f44e41afSSri Hari Krishna Narayanan CUresult Err = cuDeviceGet(&Dev, DeviceId);
1497f44e41afSSri Hari Krishna Narayanan if (Err == CUDA_SUCCESS) {
1498f44e41afSSri Hari Krishna Narayanan DeviceInfo->Device = reinterpret_cast<void *>(Dev);
1499f44e41afSSri Hari Krishna Narayanan } else {
1500f44e41afSSri Hari Krishna Narayanan cuGetErrorString(Err, ErrStr);
1501f44e41afSSri Hari Krishna Narayanan return OFFLOAD_FAIL;
1502f44e41afSSri Hari Krishna Narayanan }
1503f44e41afSSri Hari Krishna Narayanan }
1504f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS;
1505f44e41afSSri Hari Krishna Narayanan }
150639d3283aSShilei Tian
setContext(int DeviceId)150739d3283aSShilei Tian int setContext(int DeviceId) {
150839d3283aSShilei Tian assert(InitializedFlags[DeviceId] && "Device is not initialized");
150939d3283aSShilei Tian
151039d3283aSShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context);
151139d3283aSShilei Tian if (!checkResult(Err, "error returned from cuCtxSetCurrent"))
151239d3283aSShilei Tian return OFFLOAD_FAIL;
151339d3283aSShilei Tian
151439d3283aSShilei Tian return OFFLOAD_SUCCESS;
151539d3283aSShilei Tian }
15164031bb98SShilei Tian };
15174031bb98SShilei Tian
15184031bb98SShilei Tian DeviceRTLTy DeviceRTL;
15194031bb98SShilei Tian } // namespace
15204031bb98SShilei Tian
15214031bb98SShilei Tian // Exposed library API function
15224031bb98SShilei Tian #ifdef __cplusplus
15234031bb98SShilei Tian extern "C" {
15244031bb98SShilei Tian #endif
15254031bb98SShilei Tian
__tgt_rtl_is_valid_binary(__tgt_device_image * Image)1526d27d0a67SJoseph Huber int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *Image) {
1527d27d0a67SJoseph Huber return elf_check_machine(Image, /* EM_CUDA */ 190);
15284031bb98SShilei Tian }
15294031bb98SShilei Tian
__tgt_rtl_is_valid_binary_info(__tgt_device_image * image,__tgt_image_info * info)1530e01ce4e8SJoseph Huber int32_t __tgt_rtl_is_valid_binary_info(__tgt_device_image *image,
1531e01ce4e8SJoseph Huber __tgt_image_info *info) {
1532e01ce4e8SJoseph Huber if (!__tgt_rtl_is_valid_binary(image))
1533e01ce4e8SJoseph Huber return false;
1534e01ce4e8SJoseph Huber
1535e01ce4e8SJoseph Huber // A subarchitecture was not specified. Assume it is compatible.
1536*0b12f770SJoseph Huber if (!info || !info->Arch)
1537e01ce4e8SJoseph Huber return true;
1538e01ce4e8SJoseph Huber
1539e01ce4e8SJoseph Huber int32_t NumberOfDevices = 0;
1540e01ce4e8SJoseph Huber if (cuDeviceGetCount(&NumberOfDevices) != CUDA_SUCCESS)
1541e01ce4e8SJoseph Huber return false;
1542e01ce4e8SJoseph Huber
1543*0b12f770SJoseph Huber StringRef ArchStr = StringRef(info->Arch).drop_front(sizeof("sm_") - 1);
1544e01ce4e8SJoseph Huber for (int32_t DeviceId = 0; DeviceId < NumberOfDevices; ++DeviceId) {
1545e01ce4e8SJoseph Huber CUdevice Device;
1546e01ce4e8SJoseph Huber if (cuDeviceGet(&Device, DeviceId) != CUDA_SUCCESS)
1547e01ce4e8SJoseph Huber return false;
1548e01ce4e8SJoseph Huber
1549e01ce4e8SJoseph Huber int32_t Major, Minor;
1550e01ce4e8SJoseph Huber if (cuDeviceGetAttribute(&Major,
1551e01ce4e8SJoseph Huber CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR,
1552e01ce4e8SJoseph Huber Device) != CUDA_SUCCESS)
1553e01ce4e8SJoseph Huber return false;
1554e01ce4e8SJoseph Huber if (cuDeviceGetAttribute(&Minor,
1555e01ce4e8SJoseph Huber CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR,
1556e01ce4e8SJoseph Huber Device) != CUDA_SUCCESS)
1557e01ce4e8SJoseph Huber return false;
1558e01ce4e8SJoseph Huber
1559*0b12f770SJoseph Huber // A cubin generated for a certain compute capability is supported to run on
1560*0b12f770SJoseph Huber // any GPU with the same major revision and same or higher minor revision.
1561*0b12f770SJoseph Huber int32_t ImageMajor = ArchStr[0] - '0';
1562*0b12f770SJoseph Huber int32_t ImageMinor = ArchStr[1] - '0';
1563*0b12f770SJoseph Huber if (Major != ImageMajor || Minor < ImageMinor)
1564e01ce4e8SJoseph Huber return false;
1565e01ce4e8SJoseph Huber }
1566e01ce4e8SJoseph Huber
1567e01ce4e8SJoseph Huber DP("Image has compatible compute capability: %s\n", info->Arch);
1568e01ce4e8SJoseph Huber return true;
1569e01ce4e8SJoseph Huber }
1570e01ce4e8SJoseph Huber
__tgt_rtl_number_of_devices()15714031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); }
15724031bb98SShilei Tian
__tgt_rtl_init_requires(int64_t RequiresFlags)15734031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
157440470eb2SGeorge Rokos DP("Init requires flags to %" PRId64 "\n", RequiresFlags);
15754031bb98SShilei Tian DeviceRTL.setRequiresFlag(RequiresFlags);
15764031bb98SShilei Tian return RequiresFlags;
15774031bb98SShilei Tian }
15784031bb98SShilei Tian
__tgt_rtl_is_data_exchangable(int32_t SrcDevId,int DstDevId)1579d27d0a67SJoseph Huber int32_t __tgt_rtl_is_data_exchangable(int32_t SrcDevId, int DstDevId) {
1580d27d0a67SJoseph Huber if (DeviceRTL.isValidDeviceId(SrcDevId) &&
1581d27d0a67SJoseph Huber DeviceRTL.isValidDeviceId(DstDevId))
1582a014fbbcSShilei Tian return 1;
1583a014fbbcSShilei Tian
1584a014fbbcSShilei Tian return 0;
1585a014fbbcSShilei Tian }
1586a014fbbcSShilei Tian
__tgt_rtl_init_device(int32_t DeviceId)1587d27d0a67SJoseph Huber int32_t __tgt_rtl_init_device(int32_t DeviceId) {
1588d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
158939d3283aSShilei Tian // Context is set when init the device.
15904031bb98SShilei Tian
1591d27d0a67SJoseph Huber return DeviceRTL.initDevice(DeviceId);
15924031bb98SShilei Tian }
15934031bb98SShilei Tian
__tgt_rtl_deinit_device(int32_t DeviceId)1594d27d0a67SJoseph Huber int32_t __tgt_rtl_deinit_device(int32_t DeviceId) {
1595d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
159639d3283aSShilei Tian // Context is set when deinit the device.
159710aa83ffSJohannes Doerfert
1598d27d0a67SJoseph Huber return DeviceRTL.deinitDevice(DeviceId);
159910aa83ffSJohannes Doerfert }
160010aa83ffSJohannes Doerfert
__tgt_rtl_load_binary(int32_t DeviceId,__tgt_device_image * Image)1601d27d0a67SJoseph Huber __tgt_target_table *__tgt_rtl_load_binary(int32_t DeviceId,
1602d27d0a67SJoseph Huber __tgt_device_image *Image) {
1603d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
16044031bb98SShilei Tian
1605d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
160639d3283aSShilei Tian return nullptr;
160739d3283aSShilei Tian
1608d27d0a67SJoseph Huber return DeviceRTL.loadBinary(DeviceId, Image);
16094031bb98SShilei Tian }
16104031bb98SShilei Tian
__tgt_rtl_data_alloc(int32_t DeviceId,int64_t Size,void *,int32_t Kind)1611d27d0a67SJoseph Huber void *__tgt_rtl_data_alloc(int32_t DeviceId, int64_t Size, void *,
1612d27d0a67SJoseph Huber int32_t Kind) {
1613d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
16144031bb98SShilei Tian
1615d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
161639d3283aSShilei Tian return nullptr;
161739d3283aSShilei Tian
1618d27d0a67SJoseph Huber return DeviceRTL.dataAlloc(DeviceId, Size, (TargetAllocTy)Kind);
16194031bb98SShilei Tian }
16204031bb98SShilei Tian
__tgt_rtl_data_submit(int32_t DeviceId,void * TgtPtr,void * HstPtr,int64_t Size)1621d27d0a67SJoseph Huber int32_t __tgt_rtl_data_submit(int32_t DeviceId, void *TgtPtr, void *HstPtr,
1622d27d0a67SJoseph Huber int64_t Size) {
1623d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
162439d3283aSShilei Tian // Context is set in __tgt_rtl_data_submit_async.
16254031bb98SShilei Tian
16265449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo;
1627d27d0a67SJoseph Huber const int32_t Rc =
1628d27d0a67SJoseph Huber __tgt_rtl_data_submit_async(DeviceId, TgtPtr, HstPtr, Size, &AsyncInfo);
1629d27d0a67SJoseph Huber if (Rc != OFFLOAD_SUCCESS)
16304031bb98SShilei Tian return OFFLOAD_FAIL;
16314031bb98SShilei Tian
1632d27d0a67SJoseph Huber return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
16334031bb98SShilei Tian }
16344031bb98SShilei Tian
__tgt_rtl_data_submit_async(int32_t DeviceId,void * TgtPtr,void * HstPtr,int64_t Size,__tgt_async_info * AsyncInfoPtr)1635d27d0a67SJoseph Huber int32_t __tgt_rtl_data_submit_async(int32_t DeviceId, void *TgtPtr,
1636d27d0a67SJoseph Huber void *HstPtr, int64_t Size,
1637d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1638d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1639d27d0a67SJoseph Huber assert(AsyncInfoPtr && "async_info_ptr is nullptr");
16404031bb98SShilei Tian
1641d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
164239d3283aSShilei Tian return OFFLOAD_FAIL;
164339d3283aSShilei Tian
1644d27d0a67SJoseph Huber return DeviceRTL.dataSubmit(DeviceId, TgtPtr, HstPtr, Size, AsyncInfoPtr);
16454031bb98SShilei Tian }
16464031bb98SShilei Tian
__tgt_rtl_data_retrieve(int32_t DeviceId,void * HstPtr,void * TgtPtr,int64_t Size)1647d27d0a67SJoseph Huber int32_t __tgt_rtl_data_retrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr,
1648d27d0a67SJoseph Huber int64_t Size) {
1649d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
165039d3283aSShilei Tian // Context is set in __tgt_rtl_data_retrieve_async.
16514031bb98SShilei Tian
16525449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo;
1653d27d0a67SJoseph Huber const int32_t Rc =
1654d27d0a67SJoseph Huber __tgt_rtl_data_retrieve_async(DeviceId, HstPtr, TgtPtr, Size, &AsyncInfo);
1655d27d0a67SJoseph Huber if (Rc != OFFLOAD_SUCCESS)
16564031bb98SShilei Tian return OFFLOAD_FAIL;
16574031bb98SShilei Tian
1658d27d0a67SJoseph Huber return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
16594031bb98SShilei Tian }
16604031bb98SShilei Tian
__tgt_rtl_data_retrieve_async(int32_t DeviceId,void * HstPtr,void * TgtPtr,int64_t Size,__tgt_async_info * AsyncInfoPtr)1661d27d0a67SJoseph Huber int32_t __tgt_rtl_data_retrieve_async(int32_t DeviceId, void *HstPtr,
1662d27d0a67SJoseph Huber void *TgtPtr, int64_t Size,
1663d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1664d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1665d27d0a67SJoseph Huber assert(AsyncInfoPtr && "async_info_ptr is nullptr");
16664031bb98SShilei Tian
1667d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
166839d3283aSShilei Tian return OFFLOAD_FAIL;
166939d3283aSShilei Tian
1670d27d0a67SJoseph Huber return DeviceRTL.dataRetrieve(DeviceId, HstPtr, TgtPtr, Size, AsyncInfoPtr);
16714031bb98SShilei Tian }
16724031bb98SShilei Tian
__tgt_rtl_data_exchange_async(int32_t SrcDevId,void * SrcPtr,int DstDevId,void * DstPtr,int64_t Size,__tgt_async_info * AsyncInfo)1673d27d0a67SJoseph Huber int32_t __tgt_rtl_data_exchange_async(int32_t SrcDevId, void *SrcPtr,
1674d27d0a67SJoseph Huber int DstDevId, void *DstPtr, int64_t Size,
16755449fbb5SJohannes Doerfert __tgt_async_info *AsyncInfo) {
1676d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(SrcDevId) && "src_dev_id is invalid");
1677d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DstDevId) && "dst_dev_id is invalid");
16785449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr");
16792695e23aSShilei Tian
1680d27d0a67SJoseph Huber if (DeviceRTL.setContext(SrcDevId) != OFFLOAD_SUCCESS)
16812695e23aSShilei Tian return OFFLOAD_FAIL;
16822695e23aSShilei Tian
1683d27d0a67SJoseph Huber return DeviceRTL.dataExchange(SrcDevId, SrcPtr, DstDevId, DstPtr, Size,
16845449fbb5SJohannes Doerfert AsyncInfo);
1685a014fbbcSShilei Tian }
1686a014fbbcSShilei Tian
__tgt_rtl_data_exchange(int32_t SrcDevId,void * SrcPtr,int32_t DstDevId,void * DstPtr,int64_t Size)1687d27d0a67SJoseph Huber int32_t __tgt_rtl_data_exchange(int32_t SrcDevId, void *SrcPtr,
1688d27d0a67SJoseph Huber int32_t DstDevId, void *DstPtr, int64_t Size) {
1689d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(SrcDevId) && "src_dev_id is invalid");
1690d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DstDevId) && "dst_dev_id is invalid");
169139d3283aSShilei Tian // Context is set in __tgt_rtl_data_exchange_async.
1692a014fbbcSShilei Tian
16935449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo;
1694d27d0a67SJoseph Huber const int32_t Rc = __tgt_rtl_data_exchange_async(SrcDevId, SrcPtr, DstDevId,
1695d27d0a67SJoseph Huber DstPtr, Size, &AsyncInfo);
1696d27d0a67SJoseph Huber if (Rc != OFFLOAD_SUCCESS)
1697a014fbbcSShilei Tian return OFFLOAD_FAIL;
1698a014fbbcSShilei Tian
1699d27d0a67SJoseph Huber return __tgt_rtl_synchronize(SrcDevId, &AsyncInfo);
1700a014fbbcSShilei Tian }
1701a014fbbcSShilei Tian
__tgt_rtl_data_delete(int32_t DeviceId,void * TgtPtr)1702d27d0a67SJoseph Huber int32_t __tgt_rtl_data_delete(int32_t DeviceId, void *TgtPtr) {
1703d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
17044031bb98SShilei Tian
1705d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
170639d3283aSShilei Tian return OFFLOAD_FAIL;
170739d3283aSShilei Tian
1708d27d0a67SJoseph Huber return DeviceRTL.dataDelete(DeviceId, TgtPtr);
17094031bb98SShilei Tian }
17104031bb98SShilei Tian
__tgt_rtl_run_target_team_region(int32_t DeviceId,void * TgtEntryPtr,void ** TgtArgs,ptrdiff_t * TgtOffsets,int32_t ArgNum,int32_t TeamNum,int32_t ThreadLimit,uint64_t LoopTripcount)1711d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_team_region(int32_t DeviceId, void *TgtEntryPtr,
1712d27d0a67SJoseph Huber void **TgtArgs, ptrdiff_t *TgtOffsets,
1713d27d0a67SJoseph Huber int32_t ArgNum, int32_t TeamNum,
1714d27d0a67SJoseph Huber int32_t ThreadLimit,
1715d27d0a67SJoseph Huber uint64_t LoopTripcount) {
1716d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
171739d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_team_region_async.
17184031bb98SShilei Tian
17195449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo;
1720d27d0a67SJoseph Huber const int32_t Rc = __tgt_rtl_run_target_team_region_async(
1721d27d0a67SJoseph Huber DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum, TeamNum, ThreadLimit,
1722d27d0a67SJoseph Huber LoopTripcount, &AsyncInfo);
1723d27d0a67SJoseph Huber if (Rc != OFFLOAD_SUCCESS)
17244031bb98SShilei Tian return OFFLOAD_FAIL;
17254031bb98SShilei Tian
1726d27d0a67SJoseph Huber return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
17274031bb98SShilei Tian }
17284031bb98SShilei Tian
__tgt_rtl_run_target_team_region_async(int32_t DeviceId,void * TgtEntryPtr,void ** TgtArgs,ptrdiff_t * TgtOffsets,int32_t ArgNum,int32_t TeamNum,int32_t ThreadLimit,uint64_t LoopTripcount,__tgt_async_info * AsyncInfoPtr)17294031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async(
1730d27d0a67SJoseph Huber int32_t DeviceId, void *TgtEntryPtr, void **TgtArgs, ptrdiff_t *TgtOffsets,
1731d27d0a67SJoseph Huber int32_t ArgNum, int32_t TeamNum, int32_t ThreadLimit,
1732d27d0a67SJoseph Huber uint64_t LoopTripcount, __tgt_async_info *AsyncInfoPtr) {
1733d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
17344031bb98SShilei Tian
1735d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
173639d3283aSShilei Tian return OFFLOAD_FAIL;
173739d3283aSShilei Tian
1738d27d0a67SJoseph Huber return DeviceRTL.runTargetTeamRegion(DeviceId, TgtEntryPtr, TgtArgs,
1739d27d0a67SJoseph Huber TgtOffsets, ArgNum, TeamNum, ThreadLimit,
1740d27d0a67SJoseph Huber LoopTripcount, AsyncInfoPtr);
17414031bb98SShilei Tian }
17423de4cd12SGeorge Rokos
__tgt_rtl_run_target_region(int32_t DeviceId,void * TgtEntryPtr,void ** TgtArgs,ptrdiff_t * TgtOffsets,int32_t ArgNum)1743d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_region(int32_t DeviceId, void *TgtEntryPtr,
1744d27d0a67SJoseph Huber void **TgtArgs, ptrdiff_t *TgtOffsets,
1745d27d0a67SJoseph Huber int32_t ArgNum) {
1746d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
174739d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_region_async.
17484031bb98SShilei Tian
17495449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo;
1750d27d0a67SJoseph Huber const int32_t Rc = __tgt_rtl_run_target_region_async(
1751d27d0a67SJoseph Huber DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum, &AsyncInfo);
1752d27d0a67SJoseph Huber if (Rc != OFFLOAD_SUCCESS)
175303ff643dSShilei Tian return OFFLOAD_FAIL;
175403ff643dSShilei Tian
1755d27d0a67SJoseph Huber return __tgt_rtl_synchronize(DeviceId, &AsyncInfo);
175603ff643dSShilei Tian }
175703ff643dSShilei Tian
__tgt_rtl_run_target_region_async(int32_t DeviceId,void * TgtEntryPtr,void ** TgtArgs,ptrdiff_t * TgtOffsets,int32_t ArgNum,__tgt_async_info * AsyncInfoPtr)1758d27d0a67SJoseph Huber int32_t __tgt_rtl_run_target_region_async(int32_t DeviceId, void *TgtEntryPtr,
1759d27d0a67SJoseph Huber void **TgtArgs, ptrdiff_t *TgtOffsets,
1760d27d0a67SJoseph Huber int32_t ArgNum,
1761d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1762d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
176339d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_team_region_async.
176403ff643dSShilei Tian return __tgt_rtl_run_target_team_region_async(
1765d27d0a67SJoseph Huber DeviceId, TgtEntryPtr, TgtArgs, TgtOffsets, ArgNum,
17664031bb98SShilei Tian /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0,
1767d27d0a67SJoseph Huber AsyncInfoPtr);
176832ed2927SShilei Tian }
176932ed2927SShilei Tian
__tgt_rtl_synchronize(int32_t DeviceId,__tgt_async_info * AsyncInfoPtr)1770d27d0a67SJoseph Huber int32_t __tgt_rtl_synchronize(int32_t DeviceId,
1771d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1772d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1773d27d0a67SJoseph Huber assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1774d27d0a67SJoseph Huber assert(AsyncInfoPtr->Queue && "async_info_ptr->Queue is nullptr");
177539d3283aSShilei Tian // NOTE: We don't need to set context for stream sync.
1776d27d0a67SJoseph Huber return DeviceRTL.synchronize(DeviceId, AsyncInfoPtr);
17773de4cd12SGeorge Rokos }
17783de4cd12SGeorge Rokos
__tgt_rtl_set_info_flag(uint32_t NewInfoLevel)17792b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) {
178059b68490SJoseph Huber std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal();
17812b6f2008SJoseph Huber InfoLevel.store(NewInfoLevel);
17822b6f2008SJoseph Huber }
17832b6f2008SJoseph Huber
__tgt_rtl_print_device_info(int32_t DeviceId)1784d27d0a67SJoseph Huber void __tgt_rtl_print_device_info(int32_t DeviceId) {
1785d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
178639d3283aSShilei Tian // NOTE: We don't need to set context for print device info.
1787d27d0a67SJoseph Huber DeviceRTL.printDeviceInfo(DeviceId);
1788d2f85d09SJose M Monsalve Diaz }
1789d2f85d09SJose M Monsalve Diaz
__tgt_rtl_create_event(int32_t DeviceId,void ** Event)1790d27d0a67SJoseph Huber int32_t __tgt_rtl_create_event(int32_t DeviceId, void **Event) {
1791d27d0a67SJoseph Huber assert(Event && "event is nullptr");
179239d3283aSShilei Tian
1793d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
179439d3283aSShilei Tian return OFFLOAD_FAIL;
179539d3283aSShilei Tian
1796d27d0a67SJoseph Huber return DeviceRTL.createEvent(DeviceId, Event);
179729df4ab3SShilei Tian }
179829df4ab3SShilei Tian
__tgt_rtl_record_event(int32_t DeviceId,void * EventPtr,__tgt_async_info * AsyncInfoPtr)1799d27d0a67SJoseph Huber int32_t __tgt_rtl_record_event(int32_t DeviceId, void *EventPtr,
1800d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1801d27d0a67SJoseph Huber assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1802d27d0a67SJoseph Huber assert(AsyncInfoPtr->Queue && "async_info_ptr->Queue is nullptr");
1803d27d0a67SJoseph Huber assert(EventPtr && "event_ptr is nullptr");
180439d3283aSShilei Tian // NOTE: We might not need to set context for event record.
1805d27d0a67SJoseph Huber return recordEvent(EventPtr, AsyncInfoPtr);
180629df4ab3SShilei Tian }
180729df4ab3SShilei Tian
__tgt_rtl_wait_event(int32_t DeviceId,void * EventPtr,__tgt_async_info * AsyncInfoPtr)1808d27d0a67SJoseph Huber int32_t __tgt_rtl_wait_event(int32_t DeviceId, void *EventPtr,
1809d27d0a67SJoseph Huber __tgt_async_info *AsyncInfoPtr) {
1810d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1811d27d0a67SJoseph Huber assert(AsyncInfoPtr && "async_info_ptr is nullptr");
1812d27d0a67SJoseph Huber assert(EventPtr && "event is nullptr");
1813a3a42c3cSJohannes Doerfert // If we don't have a queue we need to set the context.
1814d27d0a67SJoseph Huber if (!AsyncInfoPtr->Queue && DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
1815a3a42c3cSJohannes Doerfert return OFFLOAD_FAIL;
1816d27d0a67SJoseph Huber return DeviceRTL.waitEvent(DeviceId, AsyncInfoPtr, EventPtr);
181729df4ab3SShilei Tian }
181829df4ab3SShilei Tian
__tgt_rtl_sync_event(int32_t DeviceId,void * EventPtr)1819d27d0a67SJoseph Huber int32_t __tgt_rtl_sync_event(int32_t DeviceId, void *EventPtr) {
1820d27d0a67SJoseph Huber assert(EventPtr && "event is nullptr");
182139d3283aSShilei Tian // NOTE: We might not need to set context for event sync.
1822d27d0a67SJoseph Huber return syncEvent(EventPtr);
182329df4ab3SShilei Tian }
182429df4ab3SShilei Tian
__tgt_rtl_destroy_event(int32_t DeviceId,void * EventPtr)1825d27d0a67SJoseph Huber int32_t __tgt_rtl_destroy_event(int32_t DeviceId, void *EventPtr) {
1826d27d0a67SJoseph Huber assert(EventPtr && "event is nullptr");
182729df4ab3SShilei Tian
1828d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
182939d3283aSShilei Tian return OFFLOAD_FAIL;
183039d3283aSShilei Tian
1831d27d0a67SJoseph Huber return DeviceRTL.destroyEvent(DeviceId, EventPtr);
183229df4ab3SShilei Tian }
183329df4ab3SShilei Tian
__tgt_rtl_release_async_info(int32_t DeviceId,__tgt_async_info * AsyncInfo)1834d27d0a67SJoseph Huber int32_t __tgt_rtl_release_async_info(int32_t DeviceId,
1835d27d0a67SJoseph Huber __tgt_async_info *AsyncInfo) {
1836d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1837d27d0a67SJoseph Huber assert(AsyncInfo && "async_info is nullptr");
1838f44e41afSSri Hari Krishna Narayanan
1839d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
184039d3283aSShilei Tian return OFFLOAD_FAIL;
184139d3283aSShilei Tian
1842d27d0a67SJoseph Huber return DeviceRTL.releaseAsyncInfo(DeviceId, AsyncInfo);
1843f44e41afSSri Hari Krishna Narayanan }
1844f44e41afSSri Hari Krishna Narayanan
__tgt_rtl_init_async_info(int32_t DeviceId,__tgt_async_info ** AsyncInfo)1845d27d0a67SJoseph Huber int32_t __tgt_rtl_init_async_info(int32_t DeviceId,
1846d27d0a67SJoseph Huber __tgt_async_info **AsyncInfo) {
1847d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1848d27d0a67SJoseph Huber assert(AsyncInfo && "async_info is nullptr");
1849f44e41afSSri Hari Krishna Narayanan
1850d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
185139d3283aSShilei Tian return OFFLOAD_FAIL;
185239d3283aSShilei Tian
1853d27d0a67SJoseph Huber return DeviceRTL.initAsyncInfo(DeviceId, AsyncInfo);
1854f44e41afSSri Hari Krishna Narayanan }
1855f44e41afSSri Hari Krishna Narayanan
__tgt_rtl_init_device_info(int32_t DeviceId,__tgt_device_info * DeviceInfoPtr,const char ** ErrStr)1856d27d0a67SJoseph Huber int32_t __tgt_rtl_init_device_info(int32_t DeviceId,
1857d27d0a67SJoseph Huber __tgt_device_info *DeviceInfoPtr,
1858d27d0a67SJoseph Huber const char **ErrStr) {
1859d27d0a67SJoseph Huber assert(DeviceRTL.isValidDeviceId(DeviceId) && "device_id is invalid");
1860d27d0a67SJoseph Huber assert(DeviceInfoPtr && "device_info_ptr is nullptr");
1861f44e41afSSri Hari Krishna Narayanan
1862d27d0a67SJoseph Huber if (DeviceRTL.setContext(DeviceId) != OFFLOAD_SUCCESS)
186339d3283aSShilei Tian return OFFLOAD_FAIL;
186439d3283aSShilei Tian
1865d27d0a67SJoseph Huber return DeviceRTL.initDeviceInfo(DeviceId, DeviceInfoPtr, ErrStr);
1866f44e41afSSri Hari Krishna Narayanan }
1867f44e41afSSri Hari Krishna Narayanan
18683de4cd12SGeorge Rokos #ifdef __cplusplus
18693de4cd12SGeorge Rokos }
18703de4cd12SGeorge Rokos #endif
1871