13de4cd12SGeorge Rokos //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===// 23de4cd12SGeorge Rokos // 357b08b09SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 457b08b09SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 557b08b09SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 63de4cd12SGeorge Rokos // 73de4cd12SGeorge Rokos //===----------------------------------------------------------------------===// 83de4cd12SGeorge Rokos // 93de4cd12SGeorge Rokos // RTL for CUDA machine 103de4cd12SGeorge Rokos // 113de4cd12SGeorge Rokos //===----------------------------------------------------------------------===// 123de4cd12SGeorge Rokos 1310aa83ffSJohannes Doerfert #include <algorithm> 143de4cd12SGeorge Rokos #include <cassert> 153de4cd12SGeorge Rokos #include <cstddef> 163de4cd12SGeorge Rokos #include <cuda.h> 173de4cd12SGeorge Rokos #include <list> 18a5153dbcSJohannes Doerfert #include <memory> 19feed674dSShilei Tian #include <mutex> 203de4cd12SGeorge Rokos #include <string> 21a15f8589SJoseph Huber #include <unordered_map> 223de4cd12SGeorge Rokos #include <vector> 233de4cd12SGeorge Rokos 24ae95ceebSJoseph Huber #include "Debug.h" 250c554a47SJon Chesterfield #include "DeviceEnvironment.h" 2610aa83ffSJohannes Doerfert #include "omptarget.h" 271546d319SGeorge Rokos #include "omptargetplugin.h" 283de4cd12SGeorge Rokos 293de4cd12SGeorge Rokos #define TARGET_NAME CUDA 30ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL" 3178769ec4SMichael Kruse 320871d6d5SShilei Tian #include "MemoryManager.h" 330871d6d5SShilei Tian 34ca999f71SShilei Tian #include "llvm/Frontend/OpenMP/OMPConstants.h" 35ca999f71SShilei Tian 3678769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string. 37ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG 3878769ec4SMichael Kruse #define CUDA_ERR_STRING(err) \ 3978769ec4SMichael Kruse do { \ 40ae95ceebSJoseph Huber if (getDebugLevel() > 0) { \ 4103111e5eSYe Luo const char *errStr = nullptr; \ 4203111e5eSYe Luo CUresult errStr_status = cuGetErrorString(err, &errStr); \ 4303111e5eSYe Luo if (errStr_status == CUDA_ERROR_INVALID_VALUE) \ 442ce16810SJoseph Huber REPORT("Unrecognized CUDA error code: %d\n", err); \ 4503111e5eSYe Luo else if (errStr_status == CUDA_SUCCESS) \ 462ce16810SJoseph Huber REPORT("CUDA error is: %s\n", errStr); \ 4703111e5eSYe Luo else { \ 482ce16810SJoseph Huber REPORT("Unresolved CUDA error code: %d\n", err); \ 492ce16810SJoseph Huber REPORT("Unsuccessful cuGetErrorString return status: %d\n", \ 5003111e5eSYe Luo errStr_status); \ 5103111e5eSYe Luo } \ 522ce16810SJoseph Huber } else { \ 532ce16810SJoseph Huber const char *errStr = nullptr; \ 542ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \ 552ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \ 562ce16810SJoseph Huber REPORT("%s \n", errStr); \ 5778769ec4SMichael Kruse } \ 5878769ec4SMichael Kruse } while (false) 59b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG 602ce16810SJoseph Huber #define CUDA_ERR_STRING(err) \ 612ce16810SJoseph Huber do { \ 622ce16810SJoseph Huber const char *errStr = nullptr; \ 632ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \ 642ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \ 652ce16810SJoseph Huber REPORT("%s \n", errStr); \ 662ce16810SJoseph Huber } while (false) 67b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG 683de4cd12SGeorge Rokos 69d2f85d09SJose M Monsalve Diaz #define BOOL2TEXT(b) ((b) ? "Yes" : "No") 70d2f85d09SJose M Monsalve Diaz 71a81c68aeSShilei Tian #include "elf_common.h" 723de4cd12SGeorge Rokos 733de4cd12SGeorge Rokos /// Keep entries table per device. 743de4cd12SGeorge Rokos struct FuncOrGblEntryTy { 753de4cd12SGeorge Rokos __tgt_target_table Table; 763de4cd12SGeorge Rokos std::vector<__tgt_offload_entry> Entries; 773de4cd12SGeorge Rokos }; 783de4cd12SGeorge Rokos 79dc34b1c9SRon Lieberman /// Use a single entity to encode a kernel and a set of flags. 803de4cd12SGeorge Rokos struct KernelTy { 813de4cd12SGeorge Rokos CUfunction Func; 823de4cd12SGeorge Rokos 833de4cd12SGeorge Rokos // execution mode of kernel 84ca999f71SShilei Tian llvm::omp::OMPTgtExecModeFlags ExecutionMode; 853de4cd12SGeorge Rokos 86aa27cfc1SJohannes Doerfert /// Maximal number of threads per block for this kernel. 87aa27cfc1SJohannes Doerfert int MaxThreadsPerBlock = 0; 88aa27cfc1SJohannes Doerfert 89ca999f71SShilei Tian KernelTy(CUfunction _Func, llvm::omp::OMPTgtExecModeFlags _ExecutionMode) 903de4cd12SGeorge Rokos : Func(_Func), ExecutionMode(_ExecutionMode) {} 913de4cd12SGeorge Rokos }; 923de4cd12SGeorge Rokos 93feed674dSShilei Tian namespace { 94feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) { 95feed674dSShilei Tian if (Err == CUDA_SUCCESS) 96feed674dSShilei Tian return true; 97feed674dSShilei Tian 982ce16810SJoseph Huber REPORT("%s", ErrMsg); 99feed674dSShilei Tian CUDA_ERR_STRING(Err); 100feed674dSShilei Tian return false; 101feed674dSShilei Tian } 1024031bb98SShilei Tian 103a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size, 104a014fbbcSShilei Tian CUstream Stream) { 10595f0d1edSJon Chesterfield CUresult Err = 10695f0d1edSJon Chesterfield cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream); 107a014fbbcSShilei Tian 108a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 10929338459SJoseph Huber DP("Error when copying data from device to device. Pointers: src " 110a014fbbcSShilei Tian "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n", 111a014fbbcSShilei Tian DPxPTR(SrcPtr), DPxPTR(DstPtr), Size); 112a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 113a014fbbcSShilei Tian return OFFLOAD_FAIL; 114a014fbbcSShilei Tian } 115a014fbbcSShilei Tian 116a014fbbcSShilei Tian return OFFLOAD_SUCCESS; 117a014fbbcSShilei Tian } 118a014fbbcSShilei Tian 11929df4ab3SShilei Tian int recordEvent(void *EventPtr, __tgt_async_info *AsyncInfo) { 12029df4ab3SShilei Tian CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue); 12129df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr); 12229df4ab3SShilei Tian 12329df4ab3SShilei Tian CUresult Err = cuEventRecord(Event, Stream); 12429df4ab3SShilei Tian if (Err != CUDA_SUCCESS) { 12529df4ab3SShilei Tian DP("Error when recording event. stream = " DPxMOD ", event = " DPxMOD "\n", 12629df4ab3SShilei Tian DPxPTR(Stream), DPxPTR(Event)); 12729df4ab3SShilei Tian CUDA_ERR_STRING(Err); 12829df4ab3SShilei Tian return OFFLOAD_FAIL; 12929df4ab3SShilei Tian } 13029df4ab3SShilei Tian 13129df4ab3SShilei Tian return OFFLOAD_SUCCESS; 13229df4ab3SShilei Tian } 13329df4ab3SShilei Tian 13429df4ab3SShilei Tian int syncEvent(void *EventPtr) { 13529df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr); 13629df4ab3SShilei Tian 13729df4ab3SShilei Tian CUresult Err = cuEventSynchronize(Event); 13829df4ab3SShilei Tian if (Err != CUDA_SUCCESS) { 13929df4ab3SShilei Tian DP("Error when syncing event = " DPxMOD "\n", DPxPTR(Event)); 14029df4ab3SShilei Tian CUDA_ERR_STRING(Err); 14129df4ab3SShilei Tian return OFFLOAD_FAIL; 14229df4ab3SShilei Tian } 14329df4ab3SShilei Tian 14429df4ab3SShilei Tian return OFFLOAD_SUCCESS; 14529df4ab3SShilei Tian } 14629df4ab3SShilei Tian 1471660288bSJohannes Doerfert namespace { 1481660288bSJohannes Doerfert 1494031bb98SShilei Tian // Structure contains per-device data 1504031bb98SShilei Tian struct DeviceDataTy { 1515272d29eSJohannes Doerfert /// List that contains all the kernels. 1525272d29eSJohannes Doerfert std::list<KernelTy> KernelsList; 1535272d29eSJohannes Doerfert 1544031bb98SShilei Tian std::list<FuncOrGblEntryTy> FuncGblEntries; 1555272d29eSJohannes Doerfert 1564031bb98SShilei Tian CUcontext Context = nullptr; 1574031bb98SShilei Tian // Device properties 1584031bb98SShilei Tian int ThreadsPerBlock = 0; 1594031bb98SShilei Tian int BlocksPerGrid = 0; 1604031bb98SShilei Tian int WarpSize = 0; 1614031bb98SShilei Tian // OpenMP properties 1624031bb98SShilei Tian int NumTeams = 0; 1634031bb98SShilei Tian int NumThreads = 0; 1644031bb98SShilei Tian }; 165feed674dSShilei Tian 166a697a0a4SShilei Tian /// Resource allocator where \p T is the resource type. 167a697a0a4SShilei Tian /// Functions \p create and \p destroy return OFFLOAD_SUCCESS and OFFLOAD_FAIL 168a697a0a4SShilei Tian /// accordingly. The implementation should not raise any exception. 1691660288bSJohannes Doerfert template <typename T> struct AllocatorTy { 1701660288bSJohannes Doerfert using ElementTy = T; 171a697a0a4SShilei Tian /// Create a resource and assign to R. 1721660288bSJohannes Doerfert virtual int create(T &R) noexcept = 0; 173a697a0a4SShilei Tian /// Destroy the resource. 1741660288bSJohannes Doerfert virtual int destroy(T) noexcept = 0; 175a697a0a4SShilei Tian }; 176feed674dSShilei Tian 177a697a0a4SShilei Tian /// Allocator for CUstream. 1781660288bSJohannes Doerfert struct StreamAllocatorTy final : public AllocatorTy<CUstream> { 179a697a0a4SShilei Tian /// See AllocatorTy<T>::create. 1801660288bSJohannes Doerfert int create(CUstream &Stream) noexcept override { 181a697a0a4SShilei Tian if (!checkResult(cuStreamCreate(&Stream, CU_STREAM_NON_BLOCKING), 182a697a0a4SShilei Tian "Error returned from cuStreamCreate\n")) 183a697a0a4SShilei Tian return OFFLOAD_FAIL; 184a697a0a4SShilei Tian 185a697a0a4SShilei Tian return OFFLOAD_SUCCESS; 186feed674dSShilei Tian } 187feed674dSShilei Tian 188a697a0a4SShilei Tian /// See AllocatorTy<T>::destroy. 1891660288bSJohannes Doerfert int destroy(CUstream Stream) noexcept override { 190a697a0a4SShilei Tian if (!checkResult(cuStreamDestroy(Stream), 191a697a0a4SShilei Tian "Error returned from cuStreamDestroy\n")) 192a697a0a4SShilei Tian return OFFLOAD_FAIL; 1934031bb98SShilei Tian 194a697a0a4SShilei Tian return OFFLOAD_SUCCESS; 195feed674dSShilei Tian } 196a697a0a4SShilei Tian }; 197a697a0a4SShilei Tian 198943d1d83SShilei Tian /// Allocator for CUevent. 1991660288bSJohannes Doerfert struct EventAllocatorTy final : public AllocatorTy<CUevent> { 200943d1d83SShilei Tian /// See AllocatorTy<T>::create. 2011660288bSJohannes Doerfert int create(CUevent &Event) noexcept override { 202943d1d83SShilei Tian if (!checkResult(cuEventCreate(&Event, CU_EVENT_DEFAULT), 203943d1d83SShilei Tian "Error returned from cuEventCreate\n")) 204943d1d83SShilei Tian return OFFLOAD_FAIL; 205943d1d83SShilei Tian 206943d1d83SShilei Tian return OFFLOAD_SUCCESS; 207943d1d83SShilei Tian } 208943d1d83SShilei Tian 209943d1d83SShilei Tian /// See AllocatorTy<T>::destroy. 2101660288bSJohannes Doerfert int destroy(CUevent Event) noexcept override { 211943d1d83SShilei Tian if (!checkResult(cuEventDestroy(Event), 212943d1d83SShilei Tian "Error returned from cuEventDestroy\n")) 213943d1d83SShilei Tian return OFFLOAD_FAIL; 214943d1d83SShilei Tian 215943d1d83SShilei Tian return OFFLOAD_SUCCESS; 216943d1d83SShilei Tian } 217943d1d83SShilei Tian }; 218943d1d83SShilei Tian 219a697a0a4SShilei Tian /// A generic pool of resources where \p T is the resource type. 220a697a0a4SShilei Tian /// \p T should be copyable as the object is stored in \p std::vector . 2211660288bSJohannes Doerfert template <typename AllocTy> class ResourcePoolTy { 2221660288bSJohannes Doerfert using ElementTy = typename AllocTy::ElementTy; 223a697a0a4SShilei Tian /// Index of the next available resource. 224a697a0a4SShilei Tian size_t Next = 0; 225a697a0a4SShilei Tian /// Mutex to guard the pool. 226a697a0a4SShilei Tian std::mutex Mutex; 227*545fcc3dSShilei Tian /// Pool of resources. The difference between \p Resources and \p Pool is, 228*545fcc3dSShilei Tian /// when a resource is acquired and released, it is all on \p Resources. When 229*545fcc3dSShilei Tian /// a batch of new resources are needed, they are both added to \p Resources 230*545fcc3dSShilei Tian /// and \p Pool. The reason for this setting is, \p Resources could contain 231*545fcc3dSShilei Tian /// redundant elements because resources are not released, which can cause 232*545fcc3dSShilei Tian /// double free. This setting makes sure that \p Pool always has every 233*545fcc3dSShilei Tian /// resource allocated from the device. 2341660288bSJohannes Doerfert std::vector<ElementTy> Resources; 235*545fcc3dSShilei Tian std::vector<ElementTy> Pool; 236a697a0a4SShilei Tian /// A reference to the corresponding allocator. 2371660288bSJohannes Doerfert AllocTy Allocator; 238a697a0a4SShilei Tian 239a697a0a4SShilei Tian /// If `Resources` is used up, we will fill in more resources. It assumes that 240a697a0a4SShilei Tian /// the new size `Size` should be always larger than the current size. 241a697a0a4SShilei Tian bool resize(size_t Size) { 242*545fcc3dSShilei Tian assert(Resources.size() == Pool.size() && "size mismatch"); 243a697a0a4SShilei Tian auto CurSize = Resources.size(); 244a697a0a4SShilei Tian assert(Size > CurSize && "Unexpected smaller size"); 245*545fcc3dSShilei Tian Pool.reserve(Size); 246a697a0a4SShilei Tian Resources.reserve(Size); 247a697a0a4SShilei Tian for (auto I = CurSize; I < Size; ++I) { 2481660288bSJohannes Doerfert ElementTy NewItem; 249a697a0a4SShilei Tian int Ret = Allocator.create(NewItem); 250a697a0a4SShilei Tian if (Ret != OFFLOAD_SUCCESS) 251a697a0a4SShilei Tian return false; 252*545fcc3dSShilei Tian Pool.push_back(NewItem); 253a697a0a4SShilei Tian Resources.push_back(NewItem); 254a697a0a4SShilei Tian } 255a697a0a4SShilei Tian return true; 256feed674dSShilei Tian } 257feed674dSShilei Tian 258feed674dSShilei Tian public: 2591660288bSJohannes Doerfert ResourcePoolTy(AllocTy &&A, size_t Size = 0) noexcept 260a697a0a4SShilei Tian : Allocator(std::move(A)) { 261357c8031SShilei Tian if (Size) 262a697a0a4SShilei Tian (void)resize(Size); 263feed674dSShilei Tian } 264feed674dSShilei Tian 265357c8031SShilei Tian ~ResourcePoolTy() noexcept { clear(); } 266feed674dSShilei Tian 267a697a0a4SShilei Tian /// Get a resource from pool. `Next` always points to the next available 268a697a0a4SShilei Tian /// resource. That means, `[0, next-1]` have been assigned, and `[id,]` are 269a697a0a4SShilei Tian /// still available. If there is no resource left, we will ask for more. Each 270a697a0a4SShilei Tian /// time a resource is assigned, the id will increase one. 271a697a0a4SShilei Tian /// xxxxxs+++++++++ 272a697a0a4SShilei Tian /// ^ 273a697a0a4SShilei Tian /// Next 274a697a0a4SShilei Tian /// After assignment, the pool becomes the following and s is assigned. 275a697a0a4SShilei Tian /// xxxxxs+++++++++ 276a697a0a4SShilei Tian /// ^ 277a697a0a4SShilei Tian /// Next 2781660288bSJohannes Doerfert int acquire(ElementTy &R) noexcept { 279a697a0a4SShilei Tian std::lock_guard<std::mutex> LG(Mutex); 280357c8031SShilei Tian if (Next == Resources.size()) { 281357c8031SShilei Tian auto NewSize = Resources.size() ? Resources.size() * 2 : 1; 282357c8031SShilei Tian if (!resize(NewSize)) 283a697a0a4SShilei Tian return OFFLOAD_FAIL; 284357c8031SShilei Tian } 285357c8031SShilei Tian 286357c8031SShilei Tian assert(Next < Resources.size()); 287a697a0a4SShilei Tian 288a697a0a4SShilei Tian R = Resources[Next++]; 289a697a0a4SShilei Tian 290a697a0a4SShilei Tian return OFFLOAD_SUCCESS; 291feed674dSShilei Tian } 292feed674dSShilei Tian 293a697a0a4SShilei Tian /// Return the resource back to the pool. When we return a resource, we need 294a697a0a4SShilei Tian /// to first decrease `Next`, and then copy the resource back. It is worth 295a697a0a4SShilei Tian /// noting that, the order of resources return might be different from that 296a697a0a4SShilei Tian /// they're assigned, that saying, at some point, there might be two identical 297a697a0a4SShilei Tian /// resources. 298a697a0a4SShilei Tian /// xxax+a+++++ 299a697a0a4SShilei Tian /// ^ 300a697a0a4SShilei Tian /// Next 301a697a0a4SShilei Tian /// However, it doesn't matter, because they're always on the two sides of 302a697a0a4SShilei Tian /// `Next`. The left one will in the end be overwritten by another resource. 303a697a0a4SShilei Tian /// Therefore, after several execution, the order of pool might be different 304a697a0a4SShilei Tian /// from its initial state. 3051660288bSJohannes Doerfert void release(ElementTy R) noexcept { 306a697a0a4SShilei Tian std::lock_guard<std::mutex> LG(Mutex); 307a697a0a4SShilei Tian Resources[--Next] = R; 308feed674dSShilei Tian } 309357c8031SShilei Tian 310357c8031SShilei Tian /// Released all stored resources and clear the pool. 311357c8031SShilei Tian /// Note: This function is not thread safe. Be sure to guard it if necessary. 312357c8031SShilei Tian void clear() noexcept { 313*545fcc3dSShilei Tian for (auto &R : Pool) 314357c8031SShilei Tian (void)Allocator.destroy(R); 315*545fcc3dSShilei Tian Pool.clear(); 316357c8031SShilei Tian Resources.clear(); 317357c8031SShilei Tian } 318feed674dSShilei Tian }; 319feed674dSShilei Tian 3201660288bSJohannes Doerfert } // namespace 3211660288bSJohannes Doerfert 3224031bb98SShilei Tian class DeviceRTLTy { 3233de4cd12SGeorge Rokos int NumberOfDevices; 3244031bb98SShilei Tian // OpenMP environment properties 3253de4cd12SGeorge Rokos int EnvNumTeams; 3263de4cd12SGeorge Rokos int EnvTeamLimit; 327422adaa8SJoseph Huber int EnvTeamThreadLimit; 3284031bb98SShilei Tian // OpenMP requires flags 329c5fe030cSGheorghe-Teodor Bercea int64_t RequiresFlags; 330f1c821faSJoseph Huber // Amount of dynamic shared memory to use at launch. 331f1c821faSJoseph Huber uint64_t DynamicMemorySize; 3321660288bSJohannes Doerfert 3331660288bSJohannes Doerfert /// Number of initial streams for each device. 334a697a0a4SShilei Tian int NumInitialStreams = 32; 335c5fe030cSGheorghe-Teodor Bercea 3361660288bSJohannes Doerfert /// Number of initial events for each device. 3371660288bSJohannes Doerfert int NumInitialEvents = 8; 3381660288bSJohannes Doerfert 339aca33b0bSShilei Tian static constexpr const int32_t HardThreadLimit = 1024; 340aca33b0bSShilei Tian static constexpr const int32_t DefaultNumTeams = 128; 341aca33b0bSShilei Tian static constexpr const int32_t DefaultNumThreads = 128; 3423de4cd12SGeorge Rokos 3431660288bSJohannes Doerfert using StreamPoolTy = ResourcePoolTy<StreamAllocatorTy>; 344a697a0a4SShilei Tian std::vector<std::unique_ptr<StreamPoolTy>> StreamPool; 345a697a0a4SShilei Tian 3461660288bSJohannes Doerfert using EventPoolTy = ResourcePoolTy<EventAllocatorTy>; 3471660288bSJohannes Doerfert std::vector<std::unique_ptr<EventPoolTy>> EventPool; 348943d1d83SShilei Tian 3494031bb98SShilei Tian std::vector<DeviceDataTy> DeviceData; 3505105c7cdSShilei Tian std::vector<std::vector<CUmodule>> Modules; 351feed674dSShilei Tian 35210aa83ffSJohannes Doerfert /// Vector of flags indicating the initalization status of all associated 35310aa83ffSJohannes Doerfert /// devices. 35410aa83ffSJohannes Doerfert std::vector<bool> InitializedFlags; 35510aa83ffSJohannes Doerfert 3560871d6d5SShilei Tian /// A class responsible for interacting with device native runtime library to 3570871d6d5SShilei Tian /// allocate and free memory. 3580871d6d5SShilei Tian class CUDADeviceAllocatorTy : public DeviceAllocatorTy { 359a15f8589SJoseph Huber std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs; 3600871d6d5SShilei Tian 3610871d6d5SShilei Tian public: 362a15f8589SJoseph Huber void *allocate(size_t Size, void *, TargetAllocTy Kind) override { 3630871d6d5SShilei Tian if (Size == 0) 3640871d6d5SShilei Tian return nullptr; 3650871d6d5SShilei Tian 366a15f8589SJoseph Huber void *MemAlloc = nullptr; 36739d3283aSShilei Tian CUresult Err; 368a15f8589SJoseph Huber switch (Kind) { 369a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 370a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 3710871d6d5SShilei Tian CUdeviceptr DevicePtr; 37295f0d1edSJon Chesterfield Err = cuMemAlloc(&DevicePtr, Size); 373a15f8589SJoseph Huber MemAlloc = (void *)DevicePtr; 37495f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemAlloc\n")) 3750871d6d5SShilei Tian return nullptr; 376a15f8589SJoseph Huber break; 377a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 378a15f8589SJoseph Huber void *HostPtr; 379a15f8589SJoseph Huber Err = cuMemAllocHost(&HostPtr, Size); 380a15f8589SJoseph Huber MemAlloc = HostPtr; 381a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocHost\n")) 382a15f8589SJoseph Huber return nullptr; 383a15f8589SJoseph Huber HostPinnedAllocs[MemAlloc] = Kind; 384a15f8589SJoseph Huber break; 385a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 386a15f8589SJoseph Huber CUdeviceptr SharedPtr; 387a15f8589SJoseph Huber Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL); 388a15f8589SJoseph Huber MemAlloc = (void *)SharedPtr; 389a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocManaged\n")) 390a15f8589SJoseph Huber return nullptr; 391a15f8589SJoseph Huber break; 392a15f8589SJoseph Huber } 3930871d6d5SShilei Tian 394a15f8589SJoseph Huber return MemAlloc; 3950871d6d5SShilei Tian } 3960871d6d5SShilei Tian 3970871d6d5SShilei Tian int free(void *TgtPtr) override { 39839d3283aSShilei Tian CUresult Err; 399a15f8589SJoseph Huber // Host pinned memory must be freed differently. 400a15f8589SJoseph Huber TargetAllocTy Kind = 401a15f8589SJoseph Huber (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end()) 402a15f8589SJoseph Huber ? TARGET_ALLOC_DEFAULT 403a15f8589SJoseph Huber : TARGET_ALLOC_HOST; 404a15f8589SJoseph Huber switch (Kind) { 405a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 406a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 407a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 40895f0d1edSJon Chesterfield Err = cuMemFree((CUdeviceptr)TgtPtr); 40995f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemFree\n")) 4100871d6d5SShilei Tian return OFFLOAD_FAIL; 411a15f8589SJoseph Huber break; 412a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 413a15f8589SJoseph Huber Err = cuMemFreeHost(TgtPtr); 414a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemFreeHost\n")) 415a15f8589SJoseph Huber return OFFLOAD_FAIL; 416a15f8589SJoseph Huber break; 417a15f8589SJoseph Huber } 4180871d6d5SShilei Tian 4190871d6d5SShilei Tian return OFFLOAD_SUCCESS; 4200871d6d5SShilei Tian } 4210871d6d5SShilei Tian }; 4220871d6d5SShilei Tian 4230871d6d5SShilei Tian /// A vector of device allocators 4240871d6d5SShilei Tian std::vector<CUDADeviceAllocatorTy> DeviceAllocators; 4250871d6d5SShilei Tian 4260871d6d5SShilei Tian /// A vector of memory managers. Since the memory manager is non-copyable and 4270871d6d5SShilei Tian // non-removable, we wrap them into std::unique_ptr. 4280871d6d5SShilei Tian std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers; 4290871d6d5SShilei Tian 4300871d6d5SShilei Tian /// Whether use memory manager 4310871d6d5SShilei Tian bool UseMemoryManager = true; 4320871d6d5SShilei Tian 4333de4cd12SGeorge Rokos // Record entry point associated with device 4344031bb98SShilei Tian void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) { 4354031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4363de4cd12SGeorge Rokos E.Entries.push_back(entry); 4373de4cd12SGeorge Rokos } 4383de4cd12SGeorge Rokos 439ae209397SJoseph Huber // Return a pointer to the entry associated with the pointer 440ae209397SJoseph Huber const __tgt_offload_entry *getOffloadEntry(const int DeviceId, 441ae209397SJoseph Huber const void *Addr) const { 4424031bb98SShilei Tian for (const __tgt_offload_entry &Itr : 4434031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.back().Entries) 4444031bb98SShilei Tian if (Itr.addr == Addr) 445ae209397SJoseph Huber return &Itr; 4463de4cd12SGeorge Rokos 447ae209397SJoseph Huber return nullptr; 4483de4cd12SGeorge Rokos } 4493de4cd12SGeorge Rokos 4503de4cd12SGeorge Rokos // Return the pointer to the target entries table 4514031bb98SShilei Tian __tgt_target_table *getOffloadEntriesTable(const int DeviceId) { 4524031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4533de4cd12SGeorge Rokos 4544031bb98SShilei Tian if (E.Entries.empty()) 4554031bb98SShilei Tian return nullptr; 4563de4cd12SGeorge Rokos 4573de4cd12SGeorge Rokos // Update table info according to the entries and return the pointer 4584031bb98SShilei Tian E.Table.EntriesBegin = E.Entries.data(); 4594031bb98SShilei Tian E.Table.EntriesEnd = E.Entries.data() + E.Entries.size(); 4603de4cd12SGeorge Rokos 4613de4cd12SGeorge Rokos return &E.Table; 4623de4cd12SGeorge Rokos } 4633de4cd12SGeorge Rokos 4643de4cd12SGeorge Rokos // Clear entries table for a device 4654031bb98SShilei Tian void clearOffloadEntriesTable(const int DeviceId) { 4664031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.emplace_back(); 4674031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4683de4cd12SGeorge Rokos E.Entries.clear(); 4694031bb98SShilei Tian E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr; 4703de4cd12SGeorge Rokos } 4713de4cd12SGeorge Rokos 472f44e41afSSri Hari Krishna Narayanan public: 4735449fbb5SJohannes Doerfert CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const { 4745449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 4754031bb98SShilei Tian 476a697a0a4SShilei Tian if (!AsyncInfo->Queue) { 477a697a0a4SShilei Tian CUstream S; 478a697a0a4SShilei Tian if (StreamPool[DeviceId]->acquire(S) != OFFLOAD_SUCCESS) 479a697a0a4SShilei Tian return nullptr; 480a697a0a4SShilei Tian 481a697a0a4SShilei Tian AsyncInfo->Queue = S; 482a697a0a4SShilei Tian } 4834031bb98SShilei Tian 4845449fbb5SJohannes Doerfert return reinterpret_cast<CUstream>(AsyncInfo->Queue); 485b305d26bSSergey Dmitriev } 4864031bb98SShilei Tian 4874031bb98SShilei Tian // This class should not be copied 4884031bb98SShilei Tian DeviceRTLTy(const DeviceRTLTy &) = delete; 4894031bb98SShilei Tian DeviceRTLTy(DeviceRTLTy &&) = delete; 4904031bb98SShilei Tian 4914031bb98SShilei Tian DeviceRTLTy() 4924031bb98SShilei Tian : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1), 493f1c821faSJoseph Huber EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED), 4941660288bSJohannes Doerfert DynamicMemorySize(0) { 495b305d26bSSergey Dmitriev 4963de4cd12SGeorge Rokos DP("Start initializing CUDA\n"); 4973de4cd12SGeorge Rokos 4984031bb98SShilei Tian CUresult Err = cuInit(0); 4997baff00eSJon Chesterfield if (Err == CUDA_ERROR_INVALID_HANDLE) { 5007baff00eSJon Chesterfield // Can't call cuGetErrorString if dlsym failed 5017baff00eSJon Chesterfield DP("Failed to load CUDA shared library\n"); 5027baff00eSJon Chesterfield return; 5037baff00eSJon Chesterfield } 5044031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuInit\n")) { 5053de4cd12SGeorge Rokos return; 5063de4cd12SGeorge Rokos } 5073de4cd12SGeorge Rokos 5084031bb98SShilei Tian Err = cuDeviceGetCount(&NumberOfDevices); 5094031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGetCount\n")) 5103de4cd12SGeorge Rokos return; 5113de4cd12SGeorge Rokos 5123de4cd12SGeorge Rokos if (NumberOfDevices == 0) { 5133de4cd12SGeorge Rokos DP("There are no devices supporting CUDA.\n"); 5143de4cd12SGeorge Rokos return; 5153de4cd12SGeorge Rokos } 5163de4cd12SGeorge Rokos 5174031bb98SShilei Tian DeviceData.resize(NumberOfDevices); 51814de0820SJohannes Doerfert Modules.resize(NumberOfDevices); 519a697a0a4SShilei Tian StreamPool.resize(NumberOfDevices); 5201660288bSJohannes Doerfert EventPool.resize(NumberOfDevices); 5213de4cd12SGeorge Rokos 5223de4cd12SGeorge Rokos // Get environment variables regarding teams 5234031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) { 5243de4cd12SGeorge Rokos // OMP_TEAM_LIMIT has been set 5254031bb98SShilei Tian EnvTeamLimit = std::stoi(EnvStr); 5263de4cd12SGeorge Rokos DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit); 5273de4cd12SGeorge Rokos } 528422adaa8SJoseph Huber if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) { 529422adaa8SJoseph Huber // OMP_TEAMS_THREAD_LIMIT has been set 530422adaa8SJoseph Huber EnvTeamThreadLimit = std::stoi(EnvStr); 531422adaa8SJoseph Huber DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit); 532422adaa8SJoseph Huber } 5334031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) { 5343de4cd12SGeorge Rokos // OMP_NUM_TEAMS has been set 5354031bb98SShilei Tian EnvNumTeams = std::stoi(EnvStr); 5363de4cd12SGeorge Rokos DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams); 5373de4cd12SGeorge Rokos } 538f1c821faSJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_SHARED_MEMORY_SIZE")) { 539f1c821faSJoseph Huber // LIBOMPTARGET_SHARED_MEMORY_SIZE has been set 540f1c821faSJoseph Huber DynamicMemorySize = std::stoi(EnvStr); 54149e976c9SShilei Tian DP("Parsed LIBOMPTARGET_SHARED_MEMORY_SIZE = %" PRIu64 "\n", 54249e976c9SShilei Tian DynamicMemorySize); 543f1c821faSJoseph Huber } 544a697a0a4SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS")) { 545a697a0a4SShilei Tian // LIBOMPTARGET_NUM_INITIAL_STREAMS has been set 546a697a0a4SShilei Tian NumInitialStreams = std::stoi(EnvStr); 547a697a0a4SShilei Tian DP("Parsed LIBOMPTARGET_NUM_INITIAL_STREAMS=%d\n", NumInitialStreams); 548a697a0a4SShilei Tian } 5490871d6d5SShilei Tian 5500871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 55139d3283aSShilei Tian DeviceAllocators.emplace_back(); 5520871d6d5SShilei Tian 5530871d6d5SShilei Tian // Get the size threshold from environment variable 5540871d6d5SShilei Tian std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv(); 5550871d6d5SShilei Tian UseMemoryManager = Res.second; 5560871d6d5SShilei Tian size_t MemoryManagerThreshold = Res.first; 5570871d6d5SShilei Tian 5580871d6d5SShilei Tian if (UseMemoryManager) 5590871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 5600871d6d5SShilei Tian MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>( 5610871d6d5SShilei Tian DeviceAllocators[I], MemoryManagerThreshold)); 56210aa83ffSJohannes Doerfert 56310aa83ffSJohannes Doerfert // We lazily initialize all devices later. 56410aa83ffSJohannes Doerfert InitializedFlags.assign(NumberOfDevices, false); 5653de4cd12SGeorge Rokos } 5663de4cd12SGeorge Rokos 5674031bb98SShilei Tian ~DeviceRTLTy() { 56810aa83ffSJohannes Doerfert for (int DeviceId = 0; DeviceId < NumberOfDevices; ++DeviceId) 56910aa83ffSJohannes Doerfert deinitDevice(DeviceId); 5703de4cd12SGeorge Rokos } 5713de4cd12SGeorge Rokos 5724031bb98SShilei Tian // Check whether a given DeviceId is valid 5734031bb98SShilei Tian bool isValidDeviceId(const int DeviceId) const { 5744031bb98SShilei Tian return DeviceId >= 0 && DeviceId < NumberOfDevices; 57532ed2927SShilei Tian } 57632ed2927SShilei Tian 577cb038927SShilei Tian int getNumOfDevices() const { return NumberOfDevices; } 5784031bb98SShilei Tian 5794031bb98SShilei Tian void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; } 5804031bb98SShilei Tian 5814031bb98SShilei Tian int initDevice(const int DeviceId) { 5824031bb98SShilei Tian CUdevice Device; 5834031bb98SShilei Tian 5844031bb98SShilei Tian DP("Getting device %d\n", DeviceId); 5854031bb98SShilei Tian CUresult Err = cuDeviceGet(&Device, DeviceId); 5864031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGet\n")) 58732ed2927SShilei Tian return OFFLOAD_FAIL; 5883de4cd12SGeorge Rokos 58910aa83ffSJohannes Doerfert assert(InitializedFlags[DeviceId] == false && "Reinitializing device!"); 59010aa83ffSJohannes Doerfert InitializedFlags[DeviceId] = true; 59110aa83ffSJohannes Doerfert 592c5348aecSYe Luo // Query the current flags of the primary context and set its flags if 593c5348aecSYe Luo // it is inactive 594c5348aecSYe Luo unsigned int FormerPrimaryCtxFlags = 0; 595c5348aecSYe Luo int FormerPrimaryCtxIsActive = 0; 596c5348aecSYe Luo Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags, 597c5348aecSYe Luo &FormerPrimaryCtxIsActive); 598c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n")) 599c5348aecSYe Luo return OFFLOAD_FAIL; 600c5348aecSYe Luo 601c5348aecSYe Luo if (FormerPrimaryCtxIsActive) { 602c5348aecSYe Luo DP("The primary context is active, no change to its flags\n"); 603c5348aecSYe Luo if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) != 604c5348aecSYe Luo CU_CTX_SCHED_BLOCKING_SYNC) 605c5348aecSYe Luo DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n"); 606c5348aecSYe Luo } else { 607c5348aecSYe Luo DP("The primary context is inactive, set its flags to " 608c5348aecSYe Luo "CU_CTX_SCHED_BLOCKING_SYNC\n"); 60995f0d1edSJon Chesterfield Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC); 61095f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n")) 611c5348aecSYe Luo return OFFLOAD_FAIL; 612c5348aecSYe Luo } 613c5348aecSYe Luo 614c5348aecSYe Luo // Retain the per device primary context and save it to use whenever this 615c5348aecSYe Luo // device is selected. 616c5348aecSYe Luo Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device); 617c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n")) 6183de4cd12SGeorge Rokos return OFFLOAD_FAIL; 6193de4cd12SGeorge Rokos 6204031bb98SShilei Tian Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 6214031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 6224031bb98SShilei Tian return OFFLOAD_FAIL; 623a5153dbcSJohannes Doerfert 6241660288bSJohannes Doerfert // Initialize the stream pool. 625a697a0a4SShilei Tian if (!StreamPool[DeviceId]) 62639d3283aSShilei Tian StreamPool[DeviceId] = std::make_unique<StreamPoolTy>(StreamAllocatorTy(), 62739d3283aSShilei Tian NumInitialStreams); 6281660288bSJohannes Doerfert 6291660288bSJohannes Doerfert // Initialize the event pool. 6301660288bSJohannes Doerfert if (!EventPool[DeviceId]) 63139d3283aSShilei Tian EventPool[DeviceId] = 63239d3283aSShilei Tian std::make_unique<EventPoolTy>(EventAllocatorTy(), NumInitialEvents); 633a5153dbcSJohannes Doerfert 634bb51d398SJonas Hahnfeld // Query attributes to determine number of threads/block and blocks/grid. 6354031bb98SShilei Tian int MaxGridDimX; 6364031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, 6374031bb98SShilei Tian Device); 6384031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6394031bb98SShilei Tian DP("Error getting max grid dimension, use default value %d\n", 6404031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 6414031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams; 642aca33b0bSShilei Tian } else { 6434031bb98SShilei Tian DP("Using %d CUDA blocks per grid\n", MaxGridDimX); 6444031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX; 6453de4cd12SGeorge Rokos } 6463de4cd12SGeorge Rokos 647bb51d398SJonas Hahnfeld // We are only exploiting threads along the x axis. 6484031bb98SShilei Tian int MaxBlockDimX; 6494031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxBlockDimX, 6504031bb98SShilei Tian CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device); 6514031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6524031bb98SShilei Tian DP("Error getting max block dimension, use default value %d\n", 6534031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 6544031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads; 655422adaa8SJoseph Huber } else { 6564031bb98SShilei Tian DP("Using %d CUDA threads per block\n", MaxBlockDimX); 6574031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX; 658422adaa8SJoseph Huber 659422adaa8SJoseph Huber if (EnvTeamThreadLimit > 0 && 660422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) { 661422adaa8SJoseph Huber DP("Max CUDA threads per block %d exceeds the thread limit %d set by " 662422adaa8SJoseph Huber "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n", 663422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit); 664422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit; 665422adaa8SJoseph Huber } 666422adaa8SJoseph Huber if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) { 6674031bb98SShilei Tian DP("Max CUDA threads per block %d exceeds the hard thread limit %d, " 6684031bb98SShilei Tian "capping at the hard limit\n", 669422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit); 6704031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit; 6713de4cd12SGeorge Rokos } 672422adaa8SJoseph Huber } 6733de4cd12SGeorge Rokos 6744031bb98SShilei Tian // Get and set warp size 6754031bb98SShilei Tian int WarpSize; 6764031bb98SShilei Tian Err = 6774031bb98SShilei Tian cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device); 6784031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6794031bb98SShilei Tian DP("Error getting warp size, assume default value 32\n"); 6804031bb98SShilei Tian DeviceData[DeviceId].WarpSize = 32; 681bb51d398SJonas Hahnfeld } else { 6824031bb98SShilei Tian DP("Using warp size %d\n", WarpSize); 6834031bb98SShilei Tian DeviceData[DeviceId].WarpSize = WarpSize; 6843de4cd12SGeorge Rokos } 6853de4cd12SGeorge Rokos 6863de4cd12SGeorge Rokos // Adjust teams to the env variables 6874031bb98SShilei Tian if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) { 6883de4cd12SGeorge Rokos DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n", 6894031bb98SShilei Tian EnvTeamLimit); 6904031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit; 6913de4cd12SGeorge Rokos } 6923de4cd12SGeorge Rokos 6933817ba13SJoseph Huber size_t StackLimit; 6943817ba13SJoseph Huber size_t HeapLimit; 6953817ba13SJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_STACK_SIZE")) { 6963817ba13SJoseph Huber StackLimit = std::stol(EnvStr); 6973817ba13SJoseph Huber if (cuCtxSetLimit(CU_LIMIT_STACK_SIZE, StackLimit) != CUDA_SUCCESS) 6983817ba13SJoseph Huber return OFFLOAD_FAIL; 6993817ba13SJoseph Huber } else { 7003817ba13SJoseph Huber if (cuCtxGetLimit(&StackLimit, CU_LIMIT_STACK_SIZE) != CUDA_SUCCESS) 7013817ba13SJoseph Huber return OFFLOAD_FAIL; 7023817ba13SJoseph Huber } 7033817ba13SJoseph Huber if (const char *EnvStr = getenv("LIBOMPTARGET_HEAP_SIZE")) { 7043817ba13SJoseph Huber HeapLimit = std::stol(EnvStr); 7053817ba13SJoseph Huber if (cuCtxSetLimit(CU_LIMIT_MALLOC_HEAP_SIZE, HeapLimit) != CUDA_SUCCESS) 7063817ba13SJoseph Huber return OFFLOAD_FAIL; 7073817ba13SJoseph Huber } else { 7083817ba13SJoseph Huber if (cuCtxGetLimit(&HeapLimit, CU_LIMIT_MALLOC_HEAP_SIZE) != CUDA_SUCCESS) 7093817ba13SJoseph Huber return OFFLOAD_FAIL; 7103817ba13SJoseph Huber } 7113817ba13SJoseph Huber 712119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 713ae209397SJoseph Huber "Device supports up to %d CUDA blocks and %d threads with a " 714ae209397SJoseph Huber "warp size of %d\n", 715ae209397SJoseph Huber DeviceData[DeviceId].BlocksPerGrid, 716ae209397SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize); 7173817ba13SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 7183817ba13SJoseph Huber "Device heap size is %d Bytes, device stack size is %d Bytes per " 7193817ba13SJoseph Huber "thread\n", 7203817ba13SJoseph Huber (int)HeapLimit, (int)StackLimit); 7213de4cd12SGeorge Rokos 7223de4cd12SGeorge Rokos // Set default number of teams 7234031bb98SShilei Tian if (EnvNumTeams > 0) { 7243de4cd12SGeorge Rokos DP("Default number of teams set according to environment %d\n", 7254031bb98SShilei Tian EnvNumTeams); 7264031bb98SShilei Tian DeviceData[DeviceId].NumTeams = EnvNumTeams; 7273de4cd12SGeorge Rokos } else { 7284031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams; 7293de4cd12SGeorge Rokos DP("Default number of teams set according to library's default %d\n", 7304031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 7313de4cd12SGeorge Rokos } 7324031bb98SShilei Tian 7334031bb98SShilei Tian if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) { 7343de4cd12SGeorge Rokos DP("Default number of teams exceeds device limit, capping at %d\n", 7354031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 7364031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid; 7373de4cd12SGeorge Rokos } 7383de4cd12SGeorge Rokos 7393de4cd12SGeorge Rokos // Set default number of threads 7404031bb98SShilei Tian DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads; 7413de4cd12SGeorge Rokos DP("Default number of threads set according to library's default %d\n", 7424031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 7434031bb98SShilei Tian if (DeviceData[DeviceId].NumThreads > 7444031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock) { 7453de4cd12SGeorge Rokos DP("Default number of threads exceeds device limit, capping at %d\n", 7464031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 747c060c634SShilei Tian DeviceData[DeviceId].NumThreads = DeviceData[DeviceId].ThreadsPerBlock; 7483de4cd12SGeorge Rokos } 7493de4cd12SGeorge Rokos 7503de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 7513de4cd12SGeorge Rokos } 7523de4cd12SGeorge Rokos 75310aa83ffSJohannes Doerfert int deinitDevice(const int DeviceId) { 75410aa83ffSJohannes Doerfert auto IsInitialized = InitializedFlags[DeviceId]; 75510aa83ffSJohannes Doerfert if (!IsInitialized) 75610aa83ffSJohannes Doerfert return OFFLOAD_SUCCESS; 75710aa83ffSJohannes Doerfert InitializedFlags[DeviceId] = false; 75810aa83ffSJohannes Doerfert 75910aa83ffSJohannes Doerfert if (UseMemoryManager) 76010aa83ffSJohannes Doerfert MemoryManagers[DeviceId].release(); 76110aa83ffSJohannes Doerfert 76210aa83ffSJohannes Doerfert StreamPool[DeviceId].reset(); 7631660288bSJohannes Doerfert EventPool[DeviceId].reset(); 76410aa83ffSJohannes Doerfert 76510aa83ffSJohannes Doerfert DeviceDataTy &D = DeviceData[DeviceId]; 7665105c7cdSShilei Tian if (!checkResult(cuCtxSetCurrent(D.Context), 7675105c7cdSShilei Tian "Error returned from cuCtxSetCurrent\n")) 7685105c7cdSShilei Tian return OFFLOAD_FAIL; 7695105c7cdSShilei Tian 7705105c7cdSShilei Tian // Unload all modules. 7715105c7cdSShilei Tian for (auto &M : Modules[DeviceId]) 7725105c7cdSShilei Tian if (!checkResult(cuModuleUnload(M), 7735105c7cdSShilei Tian "Error returned from cuModuleUnload\n")) 7745105c7cdSShilei Tian return OFFLOAD_FAIL; 7755105c7cdSShilei Tian 7765105c7cdSShilei Tian // Destroy context. 77710aa83ffSJohannes Doerfert CUdevice Device; 7785105c7cdSShilei Tian if (!checkResult(cuCtxGetDevice(&Device), 77910aa83ffSJohannes Doerfert "Error returned from cuCtxGetDevice\n")) 7805105c7cdSShilei Tian return OFFLOAD_FAIL; 7815105c7cdSShilei Tian 7825105c7cdSShilei Tian if (!checkResult(cuDevicePrimaryCtxRelease(Device), 7835105c7cdSShilei Tian "Error returned from cuDevicePrimaryCtxRelease\n")) 7845105c7cdSShilei Tian return OFFLOAD_FAIL; 7855105c7cdSShilei Tian 78610aa83ffSJohannes Doerfert return OFFLOAD_SUCCESS; 78710aa83ffSJohannes Doerfert } 78810aa83ffSJohannes Doerfert 7894031bb98SShilei Tian __tgt_target_table *loadBinary(const int DeviceId, 7904031bb98SShilei Tian const __tgt_device_image *Image) { 7913de4cd12SGeorge Rokos // Clear the offload table as we are going to create a new one. 7924031bb98SShilei Tian clearOffloadEntriesTable(DeviceId); 7933de4cd12SGeorge Rokos 7943de4cd12SGeorge Rokos // Create the module and extract the function pointers. 7954031bb98SShilei Tian CUmodule Module; 7964031bb98SShilei Tian DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart)); 79739d3283aSShilei Tian CUresult Err = 79839d3283aSShilei Tian cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr); 7994031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n")) 8004031bb98SShilei Tian return nullptr; 8013de4cd12SGeorge Rokos 8023de4cd12SGeorge Rokos DP("CUDA module successfully loaded!\n"); 8034031bb98SShilei Tian 8045105c7cdSShilei Tian Modules[DeviceId].push_back(Module); 8053de4cd12SGeorge Rokos 8063de4cd12SGeorge Rokos // Find the symbols in the module by name. 8074031bb98SShilei Tian const __tgt_offload_entry *HostBegin = Image->EntriesBegin; 8084031bb98SShilei Tian const __tgt_offload_entry *HostEnd = Image->EntriesEnd; 8093de4cd12SGeorge Rokos 8105272d29eSJohannes Doerfert std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList; 8114031bb98SShilei Tian for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) { 8124031bb98SShilei Tian if (!E->addr) { 8134031bb98SShilei Tian // We return nullptr when something like this happens, the host should 8144031bb98SShilei Tian // have always something in the address to uniquely identify the target 8154031bb98SShilei Tian // region. 8164031bb98SShilei Tian DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size); 8174031bb98SShilei Tian return nullptr; 8183de4cd12SGeorge Rokos } 8193de4cd12SGeorge Rokos 8204031bb98SShilei Tian if (E->size) { 8214031bb98SShilei Tian __tgt_offload_entry Entry = *E; 8224031bb98SShilei Tian CUdeviceptr CUPtr; 8234031bb98SShilei Tian size_t CUSize; 82495f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name); 8254031bb98SShilei Tian // We keep this style here because we need the name 8264031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 8272ce16810SJoseph Huber REPORT("Loading global '%s' Failed\n", E->name); 8284031bb98SShilei Tian CUDA_ERR_STRING(Err); 8294031bb98SShilei Tian return nullptr; 8303de4cd12SGeorge Rokos } 8313de4cd12SGeorge Rokos 8324031bb98SShilei Tian if (CUSize != E->size) { 8334031bb98SShilei Tian DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name, 8344031bb98SShilei Tian CUSize, E->size); 8354031bb98SShilei Tian return nullptr; 8363de4cd12SGeorge Rokos } 8373de4cd12SGeorge Rokos 8383de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n", 8394031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr)); 8404031bb98SShilei Tian 8414031bb98SShilei Tian Entry.addr = (void *)(CUPtr); 8423de4cd12SGeorge Rokos 843aace6d28SGheorghe-Teodor Bercea // Note: In the current implementation declare target variables 844aace6d28SGheorghe-Teodor Bercea // can either be link or to. This means that once unified 845aace6d28SGheorghe-Teodor Bercea // memory is activated via the requires directive, the variable 846aace6d28SGheorghe-Teodor Bercea // can be used directly from the host in both cases. 847aace6d28SGheorghe-Teodor Bercea // TODO: when variables types other than to or link are added, 8484c6a098aSKazuaki Ishizaki // the below condition should be changed to explicitly 849aace6d28SGheorghe-Teodor Bercea // check for to and link variables types: 8504031bb98SShilei Tian // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags & 8514031bb98SShilei Tian // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO)) 8524031bb98SShilei Tian if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) { 853aace6d28SGheorghe-Teodor Bercea // If unified memory is present any target link or to variables 854c5fe030cSGheorghe-Teodor Bercea // can access host addresses directly. There is no longer a 855c5fe030cSGheorghe-Teodor Bercea // need for device copies. 85695f0d1edSJon Chesterfield cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *)); 8574031bb98SShilei Tian DP("Copy linked variable host address (" DPxMOD 8584031bb98SShilei Tian ") to device address (" DPxMOD ")\n", 8594031bb98SShilei Tian DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr)); 860c5fe030cSGheorghe-Teodor Bercea } 861c5fe030cSGheorghe-Teodor Bercea 8624031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 8633de4cd12SGeorge Rokos 8643de4cd12SGeorge Rokos continue; 8653de4cd12SGeorge Rokos } 8663de4cd12SGeorge Rokos 8674031bb98SShilei Tian CUfunction Func; 8684031bb98SShilei Tian Err = cuModuleGetFunction(&Func, Module, E->name); 8694031bb98SShilei Tian // We keep this style here because we need the name 8704031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 8712ce16810SJoseph Huber REPORT("Loading '%s' Failed\n", E->name); 8724031bb98SShilei Tian CUDA_ERR_STRING(Err); 8734031bb98SShilei Tian return nullptr; 8743de4cd12SGeorge Rokos } 8753de4cd12SGeorge Rokos 8763de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n", 8774031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(Func)); 8783de4cd12SGeorge Rokos 8793de4cd12SGeorge Rokos // default value GENERIC (in case symbol is missing from cubin file) 880ca999f71SShilei Tian llvm::omp::OMPTgtExecModeFlags ExecModeVal; 8814031bb98SShilei Tian std::string ExecModeNameStr(E->name); 8823de4cd12SGeorge Rokos ExecModeNameStr += "_exec_mode"; 8833de4cd12SGeorge Rokos const char *ExecModeName = ExecModeNameStr.c_str(); 8843de4cd12SGeorge Rokos 8853de4cd12SGeorge Rokos CUdeviceptr ExecModePtr; 8864031bb98SShilei Tian size_t CUSize; 88795f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName); 8884031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 889ca999f71SShilei Tian if (CUSize != sizeof(llvm::omp::OMPTgtExecModeFlags)) { 8903de4cd12SGeorge Rokos DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n", 891ca999f71SShilei Tian ExecModeName, CUSize, sizeof(llvm::omp::OMPTgtExecModeFlags)); 8924031bb98SShilei Tian return nullptr; 8933de4cd12SGeorge Rokos } 8943de4cd12SGeorge Rokos 89595f0d1edSJon Chesterfield Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize); 8964031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 8972ce16810SJoseph Huber REPORT("Error when copying data from device to host. Pointers: " 8983de4cd12SGeorge Rokos "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n", 8994031bb98SShilei Tian DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize); 9004031bb98SShilei Tian CUDA_ERR_STRING(Err); 9014031bb98SShilei Tian return nullptr; 9023de4cd12SGeorge Rokos } 9033de4cd12SGeorge Rokos } else { 904edb8acdcSJoseph Huber DP("Loading global exec_mode '%s' - symbol missing, using default " 9054031bb98SShilei Tian "value GENERIC (1)\n", 9064031bb98SShilei Tian ExecModeName); 9073de4cd12SGeorge Rokos } 9083de4cd12SGeorge Rokos 9094031bb98SShilei Tian KernelsList.emplace_back(Func, ExecModeVal); 9103de4cd12SGeorge Rokos 9114031bb98SShilei Tian __tgt_offload_entry Entry = *E; 9124031bb98SShilei Tian Entry.addr = &KernelsList.back(); 9134031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 9143de4cd12SGeorge Rokos } 9153de4cd12SGeorge Rokos 916e1c7a46dSGuansong Zhang // send device environment data to the device 917e1c7a46dSGuansong Zhang { 918ec02c34bSJoseph Huber // TODO: The device ID used here is not the real device ID used by OpenMP. 9190c554a47SJon Chesterfield DeviceEnvironmentTy DeviceEnv{0, static_cast<uint32_t>(NumberOfDevices), 9200c554a47SJon Chesterfield static_cast<uint32_t>(DeviceId), 9210c554a47SJon Chesterfield static_cast<uint32_t>(DynamicMemorySize)}; 922e1c7a46dSGuansong Zhang 9234031bb98SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) 9240c554a47SJon Chesterfield DeviceEnv.DebugKind = std::stoi(EnvStr); 925e1c7a46dSGuansong Zhang 9264031bb98SShilei Tian const char *DeviceEnvName = "omptarget_device_environment"; 9274031bb98SShilei Tian CUdeviceptr DeviceEnvPtr; 9284031bb98SShilei Tian size_t CUSize; 929e1c7a46dSGuansong Zhang 93095f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName); 9314031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 9324031bb98SShilei Tian if (CUSize != sizeof(DeviceEnv)) { 9332ce16810SJoseph Huber REPORT( 9342ce16810SJoseph Huber "Global device_environment '%s' - size mismatch (%zu != %zu)\n", 9354031bb98SShilei Tian DeviceEnvName, CUSize, sizeof(int32_t)); 9364031bb98SShilei Tian CUDA_ERR_STRING(Err); 9374031bb98SShilei Tian return nullptr; 938e1c7a46dSGuansong Zhang } 939e1c7a46dSGuansong Zhang 94095f0d1edSJon Chesterfield Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize); 9414031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 9422ce16810SJoseph Huber REPORT("Error when copying data from host to device. Pointers: " 943e1c7a46dSGuansong Zhang "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n", 9444031bb98SShilei Tian DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize); 9454031bb98SShilei Tian CUDA_ERR_STRING(Err); 9464031bb98SShilei Tian return nullptr; 947e1c7a46dSGuansong Zhang } 948e1c7a46dSGuansong Zhang 9494031bb98SShilei Tian DP("Sending global device environment data %zu bytes\n", CUSize); 950e1c7a46dSGuansong Zhang } else { 9514031bb98SShilei Tian DP("Finding global device environment '%s' - symbol missing.\n", 9524031bb98SShilei Tian DeviceEnvName); 9534031bb98SShilei Tian DP("Continue, considering this is a device RTL which does not accept " 9544031bb98SShilei Tian "environment setting.\n"); 955e1c7a46dSGuansong Zhang } 956e1c7a46dSGuansong Zhang } 957e1c7a46dSGuansong Zhang 9584031bb98SShilei Tian return getOffloadEntriesTable(DeviceId); 9593de4cd12SGeorge Rokos } 9603de4cd12SGeorge Rokos 961a15f8589SJoseph Huber void *dataAlloc(const int DeviceId, const int64_t Size, 962a15f8589SJoseph Huber const TargetAllocTy Kind) { 963a15f8589SJoseph Huber switch (Kind) { 964a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 965a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 9660871d6d5SShilei Tian if (UseMemoryManager) 9670871d6d5SShilei Tian return MemoryManagers[DeviceId]->allocate(Size, nullptr); 968a15f8589SJoseph Huber else 969a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 970a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 971a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 972a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 973a15f8589SJoseph Huber } 9744031bb98SShilei Tian 975a15f8589SJoseph Huber REPORT("Invalid target data allocation kind or requested allocator not " 976a15f8589SJoseph Huber "implemented yet\n"); 977a15f8589SJoseph Huber 978a15f8589SJoseph Huber return nullptr; 9793de4cd12SGeorge Rokos } 9803de4cd12SGeorge Rokos 9814031bb98SShilei Tian int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr, 9825449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 9835449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 9843de4cd12SGeorge Rokos 9855449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 98639d3283aSShilei Tian CUresult Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream); 9874031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 98829338459SJoseph Huber DP("Error when copying data from host to device. Pointers: host " 9892ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n", 9904031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size); 9914031bb98SShilei Tian CUDA_ERR_STRING(Err); 9923de4cd12SGeorge Rokos return OFFLOAD_FAIL; 9933de4cd12SGeorge Rokos } 9943de4cd12SGeorge Rokos 9953de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 9963de4cd12SGeorge Rokos } 9973de4cd12SGeorge Rokos 9984031bb98SShilei Tian int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr, 9995449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 10005449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 10014031bb98SShilei Tian 10025449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 100339d3283aSShilei Tian CUresult Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream); 10044031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 100529338459SJoseph Huber DP("Error when copying data from device to host. 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 10124031bb98SShilei Tian return OFFLOAD_SUCCESS; 10134031bb98SShilei Tian } 10144031bb98SShilei Tian 1015a014fbbcSShilei Tian int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr, 10165449fbb5SJohannes Doerfert int64_t Size, __tgt_async_info *AsyncInfo) const { 10175449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 1018a014fbbcSShilei Tian 101939d3283aSShilei Tian CUresult Err; 10205449fbb5SJohannes Doerfert CUstream Stream = getStream(SrcDevId, AsyncInfo); 1021a014fbbcSShilei Tian 1022a014fbbcSShilei Tian // If they are two devices, we try peer to peer copy first 1023a014fbbcSShilei Tian if (SrcDevId != DstDevId) { 1024a014fbbcSShilei Tian int CanAccessPeer = 0; 1025a014fbbcSShilei Tian Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId); 1026a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 10272ce16810SJoseph Huber REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32 1028a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 1029a014fbbcSShilei Tian SrcDevId, DstDevId); 1030a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 1031a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 1032a014fbbcSShilei Tian } 1033a014fbbcSShilei Tian 1034a014fbbcSShilei Tian if (!CanAccessPeer) { 1035a014fbbcSShilei Tian DP("P2P memcpy not supported so fall back to D2D memcpy"); 1036a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 1037a014fbbcSShilei Tian } 1038a014fbbcSShilei Tian 1039a014fbbcSShilei Tian Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0); 1040a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 10412ce16810SJoseph Huber REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32 1042a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 1043a014fbbcSShilei Tian SrcDevId, DstDevId); 1044a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 1045a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 1046a014fbbcSShilei Tian } 1047a014fbbcSShilei Tian 1048a014fbbcSShilei Tian Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context, 1049a014fbbcSShilei Tian (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context, 1050a014fbbcSShilei Tian Size, Stream); 1051a014fbbcSShilei Tian if (Err == CUDA_SUCCESS) 1052a014fbbcSShilei Tian return OFFLOAD_SUCCESS; 1053a014fbbcSShilei Tian 105429338459SJoseph Huber DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD 105529338459SJoseph Huber ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n", 105645bb073dSYe Luo DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId); 1057a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 1058a014fbbcSShilei Tian } 1059a014fbbcSShilei Tian 1060a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 1061a014fbbcSShilei Tian } 1062a014fbbcSShilei Tian 10630871d6d5SShilei Tian int dataDelete(const int DeviceId, void *TgtPtr) { 10640871d6d5SShilei Tian if (UseMemoryManager) 10650871d6d5SShilei Tian return MemoryManagers[DeviceId]->free(TgtPtr); 10664031bb98SShilei Tian 10670871d6d5SShilei Tian return DeviceAllocators[DeviceId].free(TgtPtr); 10684031bb98SShilei Tian } 10694031bb98SShilei Tian 1070aa27cfc1SJohannes Doerfert int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs, 1071aa27cfc1SJohannes Doerfert ptrdiff_t *TgtOffsets, const int ArgNum, 1072aa27cfc1SJohannes Doerfert const int TeamNum, const int ThreadLimit, 10734031bb98SShilei Tian const unsigned int LoopTripCount, 10744031bb98SShilei Tian __tgt_async_info *AsyncInfo) const { 10753de4cd12SGeorge Rokos // All args are references. 10764031bb98SShilei Tian std::vector<void *> Args(ArgNum); 10774031bb98SShilei Tian std::vector<void *> Ptrs(ArgNum); 10783de4cd12SGeorge Rokos 10794031bb98SShilei Tian for (int I = 0; I < ArgNum; ++I) { 10804031bb98SShilei Tian Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]); 10814031bb98SShilei Tian Args[I] = &Ptrs[I]; 10821546d319SGeorge Rokos } 10833de4cd12SGeorge Rokos 1084aa27cfc1SJohannes Doerfert KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr); 10853de4cd12SGeorge Rokos 1086ca999f71SShilei Tian const bool IsSPMDGenericMode = 1087ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD; 1088ca999f71SShilei Tian const bool IsSPMDMode = 1089ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_SPMD; 1090ca999f71SShilei Tian const bool IsGenericMode = 1091ca999f71SShilei Tian KernelInfo->ExecutionMode == llvm::omp::OMP_TGT_EXEC_MODE_GENERIC; 1092ca999f71SShilei Tian 1093aa27cfc1SJohannes Doerfert int CudaThreadsPerBlock; 10944031bb98SShilei Tian if (ThreadLimit > 0) { 10954031bb98SShilei Tian DP("Setting CUDA threads per block to requested %d\n", ThreadLimit); 10964031bb98SShilei Tian CudaThreadsPerBlock = ThreadLimit; 10973de4cd12SGeorge Rokos // Add master warp if necessary 1098ca999f71SShilei Tian if (IsGenericMode) { 10994031bb98SShilei Tian DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize); 11004031bb98SShilei Tian CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize; 11013de4cd12SGeorge Rokos } 1102c13df8e5SGeorge Rokos } else { 1103c13df8e5SGeorge Rokos DP("Setting CUDA threads per block to default %d\n", 11044031bb98SShilei Tian DeviceData[DeviceId].NumThreads); 11054031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads; 1106c13df8e5SGeorge Rokos } 11073de4cd12SGeorge Rokos 11084031bb98SShilei Tian if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) { 11093de4cd12SGeorge Rokos DP("Threads per block capped at device limit %d\n", 11104031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 11114031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock; 11123de4cd12SGeorge Rokos } 11133de4cd12SGeorge Rokos 111439d3283aSShilei Tian CUresult Err; 1115aa27cfc1SJohannes Doerfert if (!KernelInfo->MaxThreadsPerBlock) { 1116aa27cfc1SJohannes Doerfert Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock, 11174031bb98SShilei Tian CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, 11184031bb98SShilei Tian KernelInfo->Func); 1119aa27cfc1SJohannes Doerfert if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n")) 1120aa27cfc1SJohannes Doerfert return OFFLOAD_FAIL; 1121aa27cfc1SJohannes Doerfert } 1122aa27cfc1SJohannes Doerfert 1123aa27cfc1SJohannes Doerfert if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) { 1124aa27cfc1SJohannes Doerfert DP("Threads per block capped at kernel limit %d\n", 1125aa27cfc1SJohannes Doerfert KernelInfo->MaxThreadsPerBlock); 1126aa27cfc1SJohannes Doerfert CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock; 11273de4cd12SGeorge Rokos } 11283de4cd12SGeorge Rokos 11294031bb98SShilei Tian unsigned int CudaBlocksPerGrid; 11304031bb98SShilei Tian if (TeamNum <= 0) { 11314031bb98SShilei Tian if (LoopTripCount > 0 && EnvNumTeams < 0) { 1132ca999f71SShilei Tian if (IsSPMDGenericMode) { 1133ca999f71SShilei Tian // If we reach this point, then we are executing a kernel that was 1134ca999f71SShilei Tian // transformed from Generic-mode to SPMD-mode. This kernel has 1135ca999f71SShilei Tian // SPMD-mode execution, but needs its blocks to be scheduled 1136ca999f71SShilei Tian // differently because the current loop trip count only applies to the 1137ca999f71SShilei Tian // `teams distribute` region and will create var too few blocks using 1138ca999f71SShilei Tian // the regular SPMD-mode method. 1139ca999f71SShilei Tian CudaBlocksPerGrid = LoopTripCount; 1140ca999f71SShilei Tian } else if (IsSPMDMode) { 11414031bb98SShilei Tian // We have a combined construct, i.e. `target teams distribute 11424031bb98SShilei Tian // parallel for [simd]`. We launch so many teams so that each thread 11434031bb98SShilei Tian // will execute one iteration of the loop. round up to the nearest 11444031bb98SShilei Tian // integer 11454031bb98SShilei Tian CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1; 1146ca999f71SShilei Tian } else if (IsGenericMode) { 1147c13df8e5SGeorge Rokos // If we reach this point, then we have a non-combined construct, i.e. 1148c13df8e5SGeorge Rokos // `teams distribute` with a nested `parallel for` and each team is 1149c13df8e5SGeorge Rokos // assigned one iteration of the `distribute` loop. E.g.: 1150c13df8e5SGeorge Rokos // 1151c13df8e5SGeorge Rokos // #pragma omp target teams distribute 1152c13df8e5SGeorge Rokos // for(...loop_tripcount...) { 1153c13df8e5SGeorge Rokos // #pragma omp parallel for 1154c13df8e5SGeorge Rokos // for(...) {} 1155c13df8e5SGeorge Rokos // } 1156c13df8e5SGeorge Rokos // 1157c13df8e5SGeorge Rokos // Threads within a team will execute the iterations of the `parallel` 1158c13df8e5SGeorge Rokos // loop. 11594031bb98SShilei Tian CudaBlocksPerGrid = LoopTripCount; 1160a158d366SJoseph Huber } else { 1161ca999f71SShilei Tian REPORT("Unknown execution mode: %d\n", 1162ca999f71SShilei Tian static_cast<int8_t>(KernelInfo->ExecutionMode)); 1163a158d366SJoseph Huber return OFFLOAD_FAIL; 1164c13df8e5SGeorge Rokos } 116545bb073dSYe Luo DP("Using %d teams due to loop trip count %" PRIu32 11664031bb98SShilei Tian " and number of threads per block %d\n", 11674031bb98SShilei Tian CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock); 11683de4cd12SGeorge Rokos } else { 11694031bb98SShilei Tian DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams); 11704031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams; 11713de4cd12SGeorge Rokos } 11723de4cd12SGeorge Rokos } else { 11734031bb98SShilei Tian DP("Using requested number of teams %d\n", TeamNum); 11744031bb98SShilei Tian CudaBlocksPerGrid = TeamNum; 11753de4cd12SGeorge Rokos } 11763de4cd12SGeorge Rokos 1177f6685f77SShilei Tian if (CudaBlocksPerGrid > DeviceData[DeviceId].BlocksPerGrid) { 1178f6685f77SShilei Tian DP("Capping number of teams to team limit %d\n", 1179f6685f77SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 1180f6685f77SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid; 1181f6685f77SShilei Tian } 1182f6685f77SShilei Tian 1183119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 1184ca999f71SShilei Tian "Launching kernel %s with %d blocks and %d threads in %s mode\n", 1185ae209397SJoseph Huber (getOffloadEntry(DeviceId, TgtEntryPtr)) 1186ae209397SJoseph Huber ? getOffloadEntry(DeviceId, TgtEntryPtr)->name 1187ae209397SJoseph Huber : "(null)", 1188ae209397SJoseph Huber CudaBlocksPerGrid, CudaThreadsPerBlock, 1189ca999f71SShilei Tian (!IsSPMDMode ? (IsGenericMode ? "Generic" : "SPMD-Generic") : "SPMD")); 11903de4cd12SGeorge Rokos 11914031bb98SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo); 11924031bb98SShilei Tian Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1, 11934031bb98SShilei Tian /* gridDimZ */ 1, CudaThreadsPerBlock, 11944031bb98SShilei Tian /* blockDimY */ 1, /* blockDimZ */ 1, 1195f1c821faSJoseph Huber DynamicMemorySize, Stream, &Args[0], nullptr); 11964031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuLaunchKernel\n")) 11974031bb98SShilei Tian return OFFLOAD_FAIL; 11984031bb98SShilei Tian 11994031bb98SShilei Tian DP("Launch of entry point at " DPxMOD " successful!\n", 12004031bb98SShilei Tian DPxPTR(TgtEntryPtr)); 12014031bb98SShilei Tian 12024031bb98SShilei Tian return OFFLOAD_SUCCESS; 12034031bb98SShilei Tian } 12044031bb98SShilei Tian 12055449fbb5SJohannes Doerfert int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const { 12065449fbb5SJohannes Doerfert CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue); 12074031bb98SShilei Tian CUresult Err = cuStreamSynchronize(Stream); 12083de4cd12SGeorge Rokos 12094031bb98SShilei Tian // Once the stream is synchronized, return it to stream pool and reset 12105449fbb5SJohannes Doerfert // AsyncInfo. This is to make sure the synchronization only works for its 12114031bb98SShilei Tian // own tasks. 1212a697a0a4SShilei Tian StreamPool[DeviceId]->release(reinterpret_cast<CUstream>(AsyncInfo->Queue)); 12135449fbb5SJohannes Doerfert AsyncInfo->Queue = nullptr; 12143de4cd12SGeorge Rokos 121516064e71SJoseph Huber if (Err != CUDA_SUCCESS) { 121629338459SJoseph Huber DP("Error when synchronizing stream. stream = " DPxMOD 121716064e71SJoseph Huber ", async info ptr = " DPxMOD "\n", 121816064e71SJoseph Huber DPxPTR(Stream), DPxPTR(AsyncInfo)); 121916064e71SJoseph Huber CUDA_ERR_STRING(Err); 122016064e71SJoseph Huber } 122116064e71SJoseph Huber return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL; 12223de4cd12SGeorge Rokos } 1223d2f85d09SJose M Monsalve Diaz 1224d2f85d09SJose M Monsalve Diaz void printDeviceInfo(int32_t device_id) { 1225d2f85d09SJose M Monsalve Diaz char TmpChar[1000]; 1226d2f85d09SJose M Monsalve Diaz std::string TmpStr; 1227d2f85d09SJose M Monsalve Diaz size_t TmpSt; 1228d2f85d09SJose M Monsalve Diaz int TmpInt, TmpInt2, TmpInt3; 1229d2f85d09SJose M Monsalve Diaz 1230d2f85d09SJose M Monsalve Diaz CUdevice Device; 1231d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGet(&Device, device_id), 1232d2f85d09SJose M Monsalve Diaz "Error returned from cuCtxGetDevice\n"); 1233d2f85d09SJose M Monsalve Diaz 1234d2f85d09SJose M Monsalve Diaz cuDriverGetVersion(&TmpInt); 1235d2f85d09SJose M Monsalve Diaz printf(" CUDA Driver Version: \t\t%d \n", TmpInt); 1236d2f85d09SJose M Monsalve Diaz printf(" CUDA Device Number: \t\t%d \n", device_id); 1237d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetName(TmpChar, 1000, Device), 1238d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetName\n"); 1239d2f85d09SJose M Monsalve Diaz printf(" Device Name: \t\t\t%s \n", TmpChar); 1240d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceTotalMem(&TmpSt, Device), 1241d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceTotalMem\n"); 1242d2f85d09SJose M Monsalve Diaz printf(" Global Memory Size: \t\t%zu bytes \n", TmpSt); 1243d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1244d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, Device), 1245d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1246d2f85d09SJose M Monsalve Diaz printf(" Number of Multiprocessors: \t\t%d \n", TmpInt); 1247d2f85d09SJose M Monsalve Diaz checkResult( 1248d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, Device), 1249d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1250d2f85d09SJose M Monsalve Diaz printf(" Concurrent Copy and Execution: \t%s \n", BOOL2TEXT(TmpInt)); 1251d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1252d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_TOTAL_CONSTANT_MEMORY, Device), 1253d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1254d2f85d09SJose M Monsalve Diaz printf(" Total Constant Memory: \t\t%d bytes\n", TmpInt); 1255d2f85d09SJose M Monsalve Diaz checkResult( 1256d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute( 1257d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_SHARED_MEMORY_PER_BLOCK, Device), 1258d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1259d2f85d09SJose M Monsalve Diaz printf(" Max Shared Memory per Block: \t%d bytes \n", TmpInt); 126028939b6aSShilei Tian checkResult( 126128939b6aSShilei Tian cuDeviceGetAttribute( 1262d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, Device), 1263d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1264d2f85d09SJose M Monsalve Diaz printf(" Registers per Block: \t\t%d \n", TmpInt); 1265d2f85d09SJose M Monsalve Diaz checkResult( 1266d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device), 1267d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1268d2f85d09SJose M Monsalve Diaz printf(" Warp Size: \t\t\t\t%d Threads \n", TmpInt); 1269d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1270d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, Device), 1271d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1272d2f85d09SJose M Monsalve Diaz printf(" Maximum Threads per Block: \t\t%d \n", TmpInt); 127328939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 127428939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device), 1275d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 127628939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 127728939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y, Device), 1278d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 127928939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 128028939b6aSShilei Tian &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z, Device), 1281d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1282d2f85d09SJose M Monsalve Diaz printf(" Maximum Block Dimensions: \t\t%d, %d, %d \n", TmpInt, TmpInt2, 1283d2f85d09SJose M Monsalve Diaz TmpInt3); 128428939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 128528939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, Device), 1286d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 128728939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 128828939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y, Device), 1289d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 129028939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 129128939b6aSShilei Tian &TmpInt3, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z, Device), 1292d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1293d2f85d09SJose M Monsalve Diaz printf(" Maximum Grid Dimensions: \t\t%d x %d x %d \n", TmpInt, TmpInt2, 1294d2f85d09SJose M Monsalve Diaz TmpInt3); 1295d2f85d09SJose M Monsalve Diaz checkResult( 1296d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_MAX_PITCH, Device), 1297d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1298d2f85d09SJose M Monsalve Diaz printf(" Maximum Memory Pitch: \t\t%d bytes \n", TmpInt); 1299d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1300d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_TEXTURE_ALIGNMENT, Device), 1301d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1302d2f85d09SJose M Monsalve Diaz printf(" Texture Alignment: \t\t\t%d bytes \n", TmpInt); 1303d2f85d09SJose M Monsalve Diaz checkResult( 1304d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, Device), 1305d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1306d2f85d09SJose M Monsalve Diaz printf(" Clock Rate: \t\t\t%d kHz\n", TmpInt); 1307d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1308d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_KERNEL_EXEC_TIMEOUT, Device), 1309d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1310d2f85d09SJose M Monsalve Diaz printf(" Execution Timeout: \t\t\t%s \n", BOOL2TEXT(TmpInt)); 1311d2f85d09SJose M Monsalve Diaz checkResult( 1312d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_INTEGRATED, Device), 1313d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1314d2f85d09SJose M Monsalve Diaz printf(" Integrated Device: \t\t\t%s \n", BOOL2TEXT(TmpInt)); 1315d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1316d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, Device), 1317d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1318d2f85d09SJose M Monsalve Diaz printf(" Can Map Host Memory: \t\t%s \n", BOOL2TEXT(TmpInt)); 1319d2f85d09SJose M Monsalve Diaz checkResult( 1320d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, Device), 1321d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1322d2f85d09SJose M Monsalve Diaz if (TmpInt == CU_COMPUTEMODE_DEFAULT) 1323d2f85d09SJose M Monsalve Diaz TmpStr = "DEFAULT"; 1324d2f85d09SJose M Monsalve Diaz else if (TmpInt == CU_COMPUTEMODE_PROHIBITED) 1325d2f85d09SJose M Monsalve Diaz TmpStr = "PROHIBITED"; 1326d2f85d09SJose M Monsalve Diaz else if (TmpInt == CU_COMPUTEMODE_EXCLUSIVE_PROCESS) 1327d2f85d09SJose M Monsalve Diaz TmpStr = "EXCLUSIVE PROCESS"; 1328d2f85d09SJose M Monsalve Diaz else 1329d2f85d09SJose M Monsalve Diaz TmpStr = "unknown"; 1330d2f85d09SJose M Monsalve Diaz printf(" Compute Mode: \t\t\t%s \n", TmpStr.c_str()); 1331d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1332d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, Device), 1333d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1334d2f85d09SJose M Monsalve Diaz printf(" Concurrent Kernels: \t\t%s \n", BOOL2TEXT(TmpInt)); 1335d2f85d09SJose M Monsalve Diaz checkResult( 1336d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_ECC_ENABLED, Device), 1337d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1338d2f85d09SJose M Monsalve Diaz printf(" ECC Enabled: \t\t\t%s \n", BOOL2TEXT(TmpInt)); 1339d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1340d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_MEMORY_CLOCK_RATE, Device), 1341d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1342d2f85d09SJose M Monsalve Diaz printf(" Memory Clock Rate: \t\t\t%d kHz\n", TmpInt); 134328939b6aSShilei Tian checkResult( 134428939b6aSShilei Tian cuDeviceGetAttribute( 1345d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_GLOBAL_MEMORY_BUS_WIDTH, Device), 1346d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1347d2f85d09SJose M Monsalve Diaz printf(" Memory Bus Width: \t\t\t%d bits\n", TmpInt); 134828939b6aSShilei Tian checkResult(cuDeviceGetAttribute(&TmpInt, CU_DEVICE_ATTRIBUTE_L2_CACHE_SIZE, 134928939b6aSShilei Tian Device), 1350d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1351d2f85d09SJose M Monsalve Diaz printf(" L2 Cache Size: \t\t\t%d bytes \n", TmpInt); 135228939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 135328939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, 135428939b6aSShilei Tian Device), 1355d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1356d2f85d09SJose M Monsalve Diaz printf(" Max Threads Per SMP: \t\t%d \n", TmpInt); 1357d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1358d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_ASYNC_ENGINE_COUNT, Device), 1359d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1360d2f85d09SJose M Monsalve Diaz printf(" Async Engines: \t\t\t%s (%d) \n", BOOL2TEXT(TmpInt), TmpInt); 1361d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1362d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, Device), 1363d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1364d2f85d09SJose M Monsalve Diaz printf(" Unified Addressing: \t\t%s \n", BOOL2TEXT(TmpInt)); 136528939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 136628939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MANAGED_MEMORY, Device), 1367d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1368d2f85d09SJose M Monsalve Diaz printf(" Managed Memory: \t\t\t%s \n", BOOL2TEXT(TmpInt)); 1369d2f85d09SJose M Monsalve Diaz checkResult( 1370d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute( 1371d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_CONCURRENT_MANAGED_ACCESS, Device), 1372d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1373d2f85d09SJose M Monsalve Diaz printf(" Concurrent Managed Memory: \t\t%s \n", BOOL2TEXT(TmpInt)); 1374d2f85d09SJose M Monsalve Diaz checkResult( 1375d2f85d09SJose M Monsalve Diaz cuDeviceGetAttribute( 1376d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_PREEMPTION_SUPPORTED, Device), 1377d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1378d2f85d09SJose M Monsalve Diaz printf(" Preemption Supported: \t\t%s \n", BOOL2TEXT(TmpInt)); 1379d2f85d09SJose M Monsalve Diaz checkResult(cuDeviceGetAttribute( 1380d2f85d09SJose M Monsalve Diaz &TmpInt, CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH, Device), 1381d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1382d2f85d09SJose M Monsalve Diaz printf(" Cooperative Launch: \t\t%s \n", BOOL2TEXT(TmpInt)); 138328939b6aSShilei Tian checkResult(cuDeviceGetAttribute( 138428939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_MULTI_GPU_BOARD, Device), 1385d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1386d2f85d09SJose M Monsalve Diaz printf(" Multi-Device Boars: \t\t%s \n", BOOL2TEXT(TmpInt)); 138728939b6aSShilei Tian checkResult( 138828939b6aSShilei Tian cuDeviceGetAttribute( 138928939b6aSShilei Tian &TmpInt, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR, Device), 1390d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 139128939b6aSShilei Tian checkResult( 139228939b6aSShilei Tian cuDeviceGetAttribute( 139328939b6aSShilei Tian &TmpInt2, CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR, Device), 1394d2f85d09SJose M Monsalve Diaz "Error returned from cuDeviceGetAttribute\n"); 1395d2f85d09SJose M Monsalve Diaz printf(" Compute Capabilities: \t\t%d%d \n", TmpInt, TmpInt2); 1396d2f85d09SJose M Monsalve Diaz } 139729df4ab3SShilei Tian 13981660288bSJohannes Doerfert int createEvent(int DeviceId, void **P) { 1399943d1d83SShilei Tian CUevent Event = nullptr; 14001660288bSJohannes Doerfert if (EventPool[DeviceId]->acquire(Event) != OFFLOAD_SUCCESS) 1401943d1d83SShilei Tian return OFFLOAD_FAIL; 1402943d1d83SShilei Tian *P = Event; 1403943d1d83SShilei Tian return OFFLOAD_SUCCESS; 1404943d1d83SShilei Tian } 1405943d1d83SShilei Tian 14061660288bSJohannes Doerfert int destroyEvent(int DeviceId, void *EventPtr) { 14071660288bSJohannes Doerfert EventPool[DeviceId]->release(reinterpret_cast<CUevent>(EventPtr)); 1408943d1d83SShilei Tian return OFFLOAD_SUCCESS; 1409943d1d83SShilei Tian } 1410943d1d83SShilei Tian 141129df4ab3SShilei Tian int waitEvent(const int DeviceId, __tgt_async_info *AsyncInfo, 141229df4ab3SShilei Tian void *EventPtr) const { 141329df4ab3SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo); 141429df4ab3SShilei Tian CUevent Event = reinterpret_cast<CUevent>(EventPtr); 141529df4ab3SShilei Tian 141629df4ab3SShilei Tian // We don't use CU_EVENT_WAIT_DEFAULT here as it is only available from 141729df4ab3SShilei Tian // specific CUDA version, and defined as 0x0. In previous version, per CUDA 141829df4ab3SShilei Tian // API document, that argument has to be 0x0. 141929df4ab3SShilei Tian CUresult Err = cuStreamWaitEvent(Stream, Event, 0); 142029df4ab3SShilei Tian if (Err != CUDA_SUCCESS) { 142129df4ab3SShilei Tian DP("Error when waiting event. stream = " DPxMOD ", event = " DPxMOD "\n", 142229df4ab3SShilei Tian DPxPTR(Stream), DPxPTR(Event)); 142329df4ab3SShilei Tian CUDA_ERR_STRING(Err); 142429df4ab3SShilei Tian return OFFLOAD_FAIL; 142529df4ab3SShilei Tian } 142629df4ab3SShilei Tian 142729df4ab3SShilei Tian return OFFLOAD_SUCCESS; 142829df4ab3SShilei Tian } 1429f44e41afSSri Hari Krishna Narayanan 1430f44e41afSSri Hari Krishna Narayanan int releaseAsyncInfo(int DeviceId, __tgt_async_info *AsyncInfo) const { 1431f44e41afSSri Hari Krishna Narayanan if (AsyncInfo->Queue) { 1432f44e41afSSri Hari Krishna Narayanan StreamPool[DeviceId]->release( 1433f44e41afSSri Hari Krishna Narayanan reinterpret_cast<CUstream>(AsyncInfo->Queue)); 1434f44e41afSSri Hari Krishna Narayanan AsyncInfo->Queue = nullptr; 1435f44e41afSSri Hari Krishna Narayanan } 1436f44e41afSSri Hari Krishna Narayanan 1437f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS; 1438f44e41afSSri Hari Krishna Narayanan } 1439f44e41afSSri Hari Krishna Narayanan 1440f44e41afSSri Hari Krishna Narayanan int initAsyncInfo(int DeviceId, __tgt_async_info **AsyncInfo) const { 1441f44e41afSSri Hari Krishna Narayanan *AsyncInfo = new __tgt_async_info; 1442f44e41afSSri Hari Krishna Narayanan getStream(DeviceId, *AsyncInfo); 1443f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS; 1444f44e41afSSri Hari Krishna Narayanan } 1445f44e41afSSri Hari Krishna Narayanan 1446f44e41afSSri Hari Krishna Narayanan int initDeviceInfo(int DeviceId, __tgt_device_info *DeviceInfo, 1447f44e41afSSri Hari Krishna Narayanan const char **ErrStr) const { 1448f44e41afSSri Hari Krishna Narayanan assert(DeviceInfo && "DeviceInfo is nullptr"); 1449f44e41afSSri Hari Krishna Narayanan 1450f44e41afSSri Hari Krishna Narayanan if (!DeviceInfo->Context) 1451f44e41afSSri Hari Krishna Narayanan DeviceInfo->Context = DeviceData[DeviceId].Context; 1452f44e41afSSri Hari Krishna Narayanan if (!DeviceInfo->Device) { 1453f44e41afSSri Hari Krishna Narayanan CUdevice Dev; 1454f44e41afSSri Hari Krishna Narayanan CUresult Err = cuDeviceGet(&Dev, DeviceId); 1455f44e41afSSri Hari Krishna Narayanan if (Err == CUDA_SUCCESS) { 1456f44e41afSSri Hari Krishna Narayanan DeviceInfo->Device = reinterpret_cast<void *>(Dev); 1457f44e41afSSri Hari Krishna Narayanan } else { 1458f44e41afSSri Hari Krishna Narayanan cuGetErrorString(Err, ErrStr); 1459f44e41afSSri Hari Krishna Narayanan return OFFLOAD_FAIL; 1460f44e41afSSri Hari Krishna Narayanan } 1461f44e41afSSri Hari Krishna Narayanan } 1462f44e41afSSri Hari Krishna Narayanan return OFFLOAD_SUCCESS; 1463f44e41afSSri Hari Krishna Narayanan } 146439d3283aSShilei Tian 146539d3283aSShilei Tian int setContext(int DeviceId) { 146639d3283aSShilei Tian assert(InitializedFlags[DeviceId] && "Device is not initialized"); 146739d3283aSShilei Tian 146839d3283aSShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 146939d3283aSShilei Tian if (!checkResult(Err, "error returned from cuCtxSetCurrent")) 147039d3283aSShilei Tian return OFFLOAD_FAIL; 147139d3283aSShilei Tian 147239d3283aSShilei Tian return OFFLOAD_SUCCESS; 147339d3283aSShilei Tian } 14744031bb98SShilei Tian }; 14754031bb98SShilei Tian 14764031bb98SShilei Tian DeviceRTLTy DeviceRTL; 14774031bb98SShilei Tian } // namespace 14784031bb98SShilei Tian 14794031bb98SShilei Tian // Exposed library API function 14804031bb98SShilei Tian #ifdef __cplusplus 14814031bb98SShilei Tian extern "C" { 14824031bb98SShilei Tian #endif 14834031bb98SShilei Tian 14844031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) { 14854031bb98SShilei Tian return elf_check_machine(image, /* EM_CUDA */ 190); 14864031bb98SShilei Tian } 14874031bb98SShilei Tian 14884031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); } 14894031bb98SShilei Tian 14904031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) { 149140470eb2SGeorge Rokos DP("Init requires flags to %" PRId64 "\n", RequiresFlags); 14924031bb98SShilei Tian DeviceRTL.setRequiresFlag(RequiresFlags); 14934031bb98SShilei Tian return RequiresFlags; 14944031bb98SShilei Tian } 14954031bb98SShilei Tian 1496a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) { 1497a014fbbcSShilei Tian if (DeviceRTL.isValidDeviceId(src_dev_id) && 1498a014fbbcSShilei Tian DeviceRTL.isValidDeviceId(dst_dev_id)) 1499a014fbbcSShilei Tian return 1; 1500a014fbbcSShilei Tian 1501a014fbbcSShilei Tian return 0; 1502a014fbbcSShilei Tian } 1503a014fbbcSShilei Tian 15044031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) { 15054031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 150639d3283aSShilei Tian // Context is set when init the device. 15074031bb98SShilei Tian 15084031bb98SShilei Tian return DeviceRTL.initDevice(device_id); 15094031bb98SShilei Tian } 15104031bb98SShilei Tian 151110aa83ffSJohannes Doerfert int32_t __tgt_rtl_deinit_device(int32_t device_id) { 151210aa83ffSJohannes Doerfert assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 151339d3283aSShilei Tian // Context is set when deinit the device. 151410aa83ffSJohannes Doerfert 151510aa83ffSJohannes Doerfert return DeviceRTL.deinitDevice(device_id); 151610aa83ffSJohannes Doerfert } 151710aa83ffSJohannes Doerfert 15184031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id, 15194031bb98SShilei Tian __tgt_device_image *image) { 15204031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 15214031bb98SShilei Tian 1522f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 152339d3283aSShilei Tian return nullptr; 152439d3283aSShilei Tian 15254031bb98SShilei Tian return DeviceRTL.loadBinary(device_id, image); 15264031bb98SShilei Tian } 15274031bb98SShilei Tian 15282468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *, 15292468fdd9SGeorge Rokos int32_t kind) { 15304031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 15314031bb98SShilei Tian 1532f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 153339d3283aSShilei Tian return nullptr; 153439d3283aSShilei Tian 1535a15f8589SJoseph Huber return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind); 15364031bb98SShilei Tian } 15374031bb98SShilei Tian 15384031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr, 15394031bb98SShilei Tian int64_t size) { 15404031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 154139d3283aSShilei Tian // Context is set in __tgt_rtl_data_submit_async. 15424031bb98SShilei Tian 15435449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 15444031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr, 15455449fbb5SJohannes Doerfert size, &AsyncInfo); 15464031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 15474031bb98SShilei Tian return OFFLOAD_FAIL; 15484031bb98SShilei Tian 15495449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 15504031bb98SShilei Tian } 15514031bb98SShilei Tian 15524031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr, 15534031bb98SShilei Tian void *hst_ptr, int64_t size, 15544031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 15554031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 15564031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 15574031bb98SShilei Tian 1558f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 155939d3283aSShilei Tian return OFFLOAD_FAIL; 156039d3283aSShilei Tian 15614031bb98SShilei Tian return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size, 15624031bb98SShilei Tian async_info_ptr); 15634031bb98SShilei Tian } 15644031bb98SShilei Tian 15654031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr, 15664031bb98SShilei Tian int64_t size) { 15674031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 156839d3283aSShilei Tian // Context is set in __tgt_rtl_data_retrieve_async. 15694031bb98SShilei Tian 15705449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 15714031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr, 15725449fbb5SJohannes Doerfert size, &AsyncInfo); 15734031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 15744031bb98SShilei Tian return OFFLOAD_FAIL; 15754031bb98SShilei Tian 15765449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 15774031bb98SShilei Tian } 15784031bb98SShilei Tian 15794031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr, 15804031bb98SShilei Tian void *tgt_ptr, int64_t size, 15814031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 15824031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 15834031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 15844031bb98SShilei Tian 1585f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 158639d3283aSShilei Tian return OFFLOAD_FAIL; 158739d3283aSShilei Tian 15884031bb98SShilei Tian return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size, 15894031bb98SShilei Tian async_info_ptr); 15904031bb98SShilei Tian } 15914031bb98SShilei Tian 1592a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr, 1593a014fbbcSShilei Tian int dst_dev_id, void *dst_ptr, 1594a014fbbcSShilei Tian int64_t size, 15955449fbb5SJohannes Doerfert __tgt_async_info *AsyncInfo) { 1596a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1597a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 15985449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 159939d3283aSShilei Tian // NOTE: We don't need to set context for data exchange as the device contexts 160039d3283aSShilei Tian // are passed to CUDA function directly. 1601a014fbbcSShilei Tian return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, 16025449fbb5SJohannes Doerfert AsyncInfo); 1603a014fbbcSShilei Tian } 1604a014fbbcSShilei Tian 1605a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr, 1606a014fbbcSShilei Tian int32_t dst_dev_id, void *dst_ptr, 1607a014fbbcSShilei Tian int64_t size) { 1608a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1609a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 161039d3283aSShilei Tian // Context is set in __tgt_rtl_data_exchange_async. 1611a014fbbcSShilei Tian 16125449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 1613a014fbbcSShilei Tian const int32_t rc = __tgt_rtl_data_exchange_async( 16145449fbb5SJohannes Doerfert src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo); 1615a014fbbcSShilei Tian if (rc != OFFLOAD_SUCCESS) 1616a014fbbcSShilei Tian return OFFLOAD_FAIL; 1617a014fbbcSShilei Tian 16185449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo); 1619a014fbbcSShilei Tian } 1620a014fbbcSShilei Tian 16214031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) { 16224031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 16234031bb98SShilei Tian 1624f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 162539d3283aSShilei Tian return OFFLOAD_FAIL; 162639d3283aSShilei Tian 16274031bb98SShilei Tian return DeviceRTL.dataDelete(device_id, tgt_ptr); 16284031bb98SShilei Tian } 16294031bb98SShilei Tian 16304031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr, 16314031bb98SShilei Tian void **tgt_args, 16324031bb98SShilei Tian ptrdiff_t *tgt_offsets, 16334031bb98SShilei Tian int32_t arg_num, int32_t team_num, 16344031bb98SShilei Tian int32_t thread_limit, 16354031bb98SShilei Tian uint64_t loop_tripcount) { 16364031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 163739d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_team_region_async. 16384031bb98SShilei Tian 16395449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 16404031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_team_region_async( 16414031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 16425449fbb5SJohannes Doerfert thread_limit, loop_tripcount, &AsyncInfo); 16434031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 16444031bb98SShilei Tian return OFFLOAD_FAIL; 16454031bb98SShilei Tian 16465449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 16474031bb98SShilei Tian } 16484031bb98SShilei Tian 16494031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async( 16504031bb98SShilei Tian int32_t device_id, void *tgt_entry_ptr, void **tgt_args, 16514031bb98SShilei Tian ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num, 16524031bb98SShilei Tian int32_t thread_limit, uint64_t loop_tripcount, 16534031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 16544031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 16554031bb98SShilei Tian 1656f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 165739d3283aSShilei Tian return OFFLOAD_FAIL; 165839d3283aSShilei Tian 16594031bb98SShilei Tian return DeviceRTL.runTargetTeamRegion( 16604031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 16614031bb98SShilei Tian thread_limit, loop_tripcount, async_info_ptr); 16624031bb98SShilei Tian } 16633de4cd12SGeorge Rokos 16643de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr, 166532ed2927SShilei Tian void **tgt_args, ptrdiff_t *tgt_offsets, 166603ff643dSShilei Tian int32_t arg_num) { 16674031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 166839d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_region_async. 16694031bb98SShilei Tian 16705449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 16714031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_region_async( 16725449fbb5SJohannes Doerfert device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo); 167303ff643dSShilei Tian if (rc != OFFLOAD_SUCCESS) 167403ff643dSShilei Tian return OFFLOAD_FAIL; 167503ff643dSShilei Tian 16765449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 167703ff643dSShilei Tian } 167803ff643dSShilei Tian 167903ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id, 168003ff643dSShilei Tian void *tgt_entry_ptr, void **tgt_args, 168103ff643dSShilei Tian ptrdiff_t *tgt_offsets, 168232ed2927SShilei Tian int32_t arg_num, 16834031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 16844031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 168539d3283aSShilei Tian // Context is set in __tgt_rtl_run_target_team_region_async. 168603ff643dSShilei Tian return __tgt_rtl_run_target_team_region_async( 16874031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, 16884031bb98SShilei Tian /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0, 16894031bb98SShilei Tian async_info_ptr); 169032ed2927SShilei Tian } 169132ed2927SShilei Tian 16924031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id, 16934031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 16944031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 16954031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 16964031bb98SShilei Tian assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr"); 169739d3283aSShilei Tian // NOTE: We don't need to set context for stream sync. 16984031bb98SShilei Tian return DeviceRTL.synchronize(device_id, async_info_ptr); 16993de4cd12SGeorge Rokos } 17003de4cd12SGeorge Rokos 17012b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) { 170259b68490SJoseph Huber std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal(); 17032b6f2008SJoseph Huber InfoLevel.store(NewInfoLevel); 17042b6f2008SJoseph Huber } 17052b6f2008SJoseph Huber 1706d2f85d09SJose M Monsalve Diaz void __tgt_rtl_print_device_info(int32_t device_id) { 1707d2f85d09SJose M Monsalve Diaz assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 170839d3283aSShilei Tian // NOTE: We don't need to set context for print device info. 1709d2f85d09SJose M Monsalve Diaz DeviceRTL.printDeviceInfo(device_id); 1710d2f85d09SJose M Monsalve Diaz } 1711d2f85d09SJose M Monsalve Diaz 171229df4ab3SShilei Tian int32_t __tgt_rtl_create_event(int32_t device_id, void **event) { 171329df4ab3SShilei Tian assert(event && "event is nullptr"); 171439d3283aSShilei Tian 1715f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 171639d3283aSShilei Tian return OFFLOAD_FAIL; 171739d3283aSShilei Tian 17181660288bSJohannes Doerfert return DeviceRTL.createEvent(device_id, event); 171929df4ab3SShilei Tian } 172029df4ab3SShilei Tian 172129df4ab3SShilei Tian int32_t __tgt_rtl_record_event(int32_t device_id, void *event_ptr, 172229df4ab3SShilei Tian __tgt_async_info *async_info_ptr) { 172329df4ab3SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 172429df4ab3SShilei Tian assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr"); 172529df4ab3SShilei Tian assert(event_ptr && "event_ptr is nullptr"); 172639d3283aSShilei Tian // NOTE: We might not need to set context for event record. 172729df4ab3SShilei Tian return recordEvent(event_ptr, async_info_ptr); 172829df4ab3SShilei Tian } 172929df4ab3SShilei Tian 173029df4ab3SShilei Tian int32_t __tgt_rtl_wait_event(int32_t device_id, void *event_ptr, 173129df4ab3SShilei Tian __tgt_async_info *async_info_ptr) { 173229df4ab3SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 173329df4ab3SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 173429df4ab3SShilei Tian assert(event_ptr && "event is nullptr"); 173539d3283aSShilei Tian // NOTE: We might not need to set context for event sync. 173629df4ab3SShilei Tian return DeviceRTL.waitEvent(device_id, async_info_ptr, event_ptr); 173729df4ab3SShilei Tian } 173829df4ab3SShilei Tian 173929df4ab3SShilei Tian int32_t __tgt_rtl_sync_event(int32_t device_id, void *event_ptr) { 174029df4ab3SShilei Tian assert(event_ptr && "event is nullptr"); 174139d3283aSShilei Tian // NOTE: We might not need to set context for event sync. 174229df4ab3SShilei Tian return syncEvent(event_ptr); 174329df4ab3SShilei Tian } 174429df4ab3SShilei Tian 174529df4ab3SShilei Tian int32_t __tgt_rtl_destroy_event(int32_t device_id, void *event_ptr) { 174629df4ab3SShilei Tian assert(event_ptr && "event is nullptr"); 174729df4ab3SShilei Tian 1748f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 174939d3283aSShilei Tian return OFFLOAD_FAIL; 175039d3283aSShilei Tian 17511660288bSJohannes Doerfert return DeviceRTL.destroyEvent(device_id, event_ptr); 175229df4ab3SShilei Tian } 175329df4ab3SShilei Tian 1754f44e41afSSri Hari Krishna Narayanan int32_t __tgt_rtl_release_async_info(int32_t device_id, 1755f44e41afSSri Hari Krishna Narayanan __tgt_async_info *async_info) { 1756f44e41afSSri Hari Krishna Narayanan assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 1757f44e41afSSri Hari Krishna Narayanan assert(async_info && "async_info is nullptr"); 1758f44e41afSSri Hari Krishna Narayanan 1759f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 176039d3283aSShilei Tian return OFFLOAD_FAIL; 176139d3283aSShilei Tian 1762f44e41afSSri Hari Krishna Narayanan return DeviceRTL.releaseAsyncInfo(device_id, async_info); 1763f44e41afSSri Hari Krishna Narayanan } 1764f44e41afSSri Hari Krishna Narayanan 1765f44e41afSSri Hari Krishna Narayanan int32_t __tgt_rtl_init_async_info(int32_t device_id, 1766f44e41afSSri Hari Krishna Narayanan __tgt_async_info **async_info) { 1767f44e41afSSri Hari Krishna Narayanan assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 1768f44e41afSSri Hari Krishna Narayanan assert(async_info && "async_info is nullptr"); 1769f44e41afSSri Hari Krishna Narayanan 1770f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 177139d3283aSShilei Tian return OFFLOAD_FAIL; 177239d3283aSShilei Tian 1773f44e41afSSri Hari Krishna Narayanan return DeviceRTL.initAsyncInfo(device_id, async_info); 1774f44e41afSSri Hari Krishna Narayanan } 1775f44e41afSSri Hari Krishna Narayanan 1776f44e41afSSri Hari Krishna Narayanan int32_t __tgt_rtl_init_device_info(int32_t device_id, 1777f44e41afSSri Hari Krishna Narayanan __tgt_device_info *device_info_ptr, 1778f44e41afSSri Hari Krishna Narayanan const char **err_str) { 1779f44e41afSSri Hari Krishna Narayanan assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 1780f44e41afSSri Hari Krishna Narayanan assert(device_info_ptr && "device_info_ptr is nullptr"); 1781f44e41afSSri Hari Krishna Narayanan 1782f6639a42SShilei Tian if (DeviceRTL.setContext(device_id) != OFFLOAD_SUCCESS) 178339d3283aSShilei Tian return OFFLOAD_FAIL; 178439d3283aSShilei Tian 1785f44e41afSSri Hari Krishna Narayanan return DeviceRTL.initDeviceInfo(device_id, device_info_ptr, err_str); 1786f44e41afSSri Hari Krishna Narayanan } 1787f44e41afSSri Hari Krishna Narayanan 17883de4cd12SGeorge Rokos #ifdef __cplusplus 17893de4cd12SGeorge Rokos } 17903de4cd12SGeorge Rokos #endif 1791