13de4cd12SGeorge Rokos //===----RTLs/cuda/src/rtl.cpp - Target RTLs Implementation ------- C++ -*-===// 23de4cd12SGeorge Rokos // 357b08b09SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 457b08b09SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 557b08b09SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 63de4cd12SGeorge Rokos // 73de4cd12SGeorge Rokos //===----------------------------------------------------------------------===// 83de4cd12SGeorge Rokos // 93de4cd12SGeorge Rokos // RTL for CUDA machine 103de4cd12SGeorge Rokos // 113de4cd12SGeorge Rokos //===----------------------------------------------------------------------===// 123de4cd12SGeorge Rokos 133de4cd12SGeorge Rokos #include <cassert> 143de4cd12SGeorge Rokos #include <cstddef> 153de4cd12SGeorge Rokos #include <cuda.h> 163de4cd12SGeorge Rokos #include <list> 17a5153dbcSJohannes Doerfert #include <memory> 18feed674dSShilei Tian #include <mutex> 193de4cd12SGeorge Rokos #include <string> 20a15f8589SJoseph Huber #include <unordered_map> 213de4cd12SGeorge Rokos #include <vector> 223de4cd12SGeorge Rokos 23ae95ceebSJoseph Huber #include "Debug.h" 241546d319SGeorge Rokos #include "omptargetplugin.h" 253de4cd12SGeorge Rokos 263de4cd12SGeorge Rokos #define TARGET_NAME CUDA 27ae95ceebSJoseph Huber #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL" 2878769ec4SMichael Kruse 290871d6d5SShilei Tian #include "MemoryManager.h" 300871d6d5SShilei Tian 3178769ec4SMichael Kruse // Utility for retrieving and printing CUDA error string. 32ae95ceebSJoseph Huber #ifdef OMPTARGET_DEBUG 3378769ec4SMichael Kruse #define CUDA_ERR_STRING(err) \ 3478769ec4SMichael Kruse do { \ 35ae95ceebSJoseph Huber if (getDebugLevel() > 0) { \ 3603111e5eSYe Luo const char *errStr = nullptr; \ 3703111e5eSYe Luo CUresult errStr_status = cuGetErrorString(err, &errStr); \ 3803111e5eSYe Luo if (errStr_status == CUDA_ERROR_INVALID_VALUE) \ 392ce16810SJoseph Huber REPORT("Unrecognized CUDA error code: %d\n", err); \ 4003111e5eSYe Luo else if (errStr_status == CUDA_SUCCESS) \ 412ce16810SJoseph Huber REPORT("CUDA error is: %s\n", errStr); \ 4203111e5eSYe Luo else { \ 432ce16810SJoseph Huber REPORT("Unresolved CUDA error code: %d\n", err); \ 442ce16810SJoseph Huber REPORT("Unsuccessful cuGetErrorString return status: %d\n", \ 4503111e5eSYe Luo errStr_status); \ 4603111e5eSYe Luo } \ 472ce16810SJoseph Huber } else { \ 482ce16810SJoseph Huber const char *errStr = nullptr; \ 492ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \ 502ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \ 512ce16810SJoseph Huber REPORT("%s \n", errStr); \ 5278769ec4SMichael Kruse } \ 5378769ec4SMichael Kruse } while (false) 54b305d26bSSergey Dmitriev #else // OMPTARGET_DEBUG 552ce16810SJoseph Huber #define CUDA_ERR_STRING(err) \ 562ce16810SJoseph Huber do { \ 572ce16810SJoseph Huber const char *errStr = nullptr; \ 582ce16810SJoseph Huber CUresult errStr_status = cuGetErrorString(err, &errStr); \ 592ce16810SJoseph Huber if (errStr_status == CUDA_SUCCESS) \ 602ce16810SJoseph Huber REPORT("%s \n", errStr); \ 612ce16810SJoseph Huber } while (false) 62b305d26bSSergey Dmitriev #endif // OMPTARGET_DEBUG 633de4cd12SGeorge Rokos 64a81c68aeSShilei Tian #include "elf_common.h" 653de4cd12SGeorge Rokos 663de4cd12SGeorge Rokos /// Keep entries table per device. 673de4cd12SGeorge Rokos struct FuncOrGblEntryTy { 683de4cd12SGeorge Rokos __tgt_target_table Table; 693de4cd12SGeorge Rokos std::vector<__tgt_offload_entry> Entries; 703de4cd12SGeorge Rokos }; 713de4cd12SGeorge Rokos 723de4cd12SGeorge Rokos enum ExecutionModeType { 73c13df8e5SGeorge Rokos SPMD, // constructors, destructors, 74c13df8e5SGeorge Rokos // combined constructs (`teams distribute parallel for [simd]`) 75c13df8e5SGeorge Rokos GENERIC, // everything else 763de4cd12SGeorge Rokos NONE 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 843de4cd12SGeorge Rokos // 0 - SPMD mode (without master warp) 853de4cd12SGeorge Rokos // 1 - Generic mode (with master warp) 863de4cd12SGeorge Rokos int8_t ExecutionMode; 873de4cd12SGeorge Rokos 88aa27cfc1SJohannes Doerfert /// Maximal number of threads per block for this kernel. 89aa27cfc1SJohannes Doerfert int MaxThreadsPerBlock = 0; 90aa27cfc1SJohannes Doerfert 913de4cd12SGeorge Rokos KernelTy(CUfunction _Func, int8_t _ExecutionMode) 923de4cd12SGeorge Rokos : Func(_Func), ExecutionMode(_ExecutionMode) {} 933de4cd12SGeorge Rokos }; 943de4cd12SGeorge Rokos 954c6a098aSKazuaki Ishizaki /// Device environment data 96feed674dSShilei Tian /// Manually sync with the deviceRTL side for now, move to a dedicated header 97feed674dSShilei Tian /// file later. 98e1c7a46dSGuansong Zhang struct omptarget_device_environmentTy { 99e1c7a46dSGuansong Zhang int32_t debug_level; 100e1c7a46dSGuansong Zhang }; 101e1c7a46dSGuansong Zhang 102feed674dSShilei Tian namespace { 103feed674dSShilei Tian bool checkResult(CUresult Err, const char *ErrMsg) { 104feed674dSShilei Tian if (Err == CUDA_SUCCESS) 105feed674dSShilei Tian return true; 106feed674dSShilei Tian 1072ce16810SJoseph Huber REPORT("%s", ErrMsg); 108feed674dSShilei Tian CUDA_ERR_STRING(Err); 109feed674dSShilei Tian return false; 110feed674dSShilei Tian } 1114031bb98SShilei Tian 112a014fbbcSShilei Tian int memcpyDtoD(const void *SrcPtr, void *DstPtr, int64_t Size, 113a014fbbcSShilei Tian CUstream Stream) { 11495f0d1edSJon Chesterfield CUresult Err = 11595f0d1edSJon Chesterfield cuMemcpyDtoDAsync((CUdeviceptr)DstPtr, (CUdeviceptr)SrcPtr, Size, Stream); 116a014fbbcSShilei Tian 117a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 11829338459SJoseph Huber DP("Error when copying data from device to device. Pointers: src " 119a014fbbcSShilei Tian "= " DPxMOD ", dst = " DPxMOD ", size = %" PRId64 "\n", 120a014fbbcSShilei Tian DPxPTR(SrcPtr), DPxPTR(DstPtr), Size); 121a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 122a014fbbcSShilei Tian return OFFLOAD_FAIL; 123a014fbbcSShilei Tian } 124a014fbbcSShilei Tian 125a014fbbcSShilei Tian return OFFLOAD_SUCCESS; 126a014fbbcSShilei Tian } 127a014fbbcSShilei Tian 1284031bb98SShilei Tian // Structure contains per-device data 1294031bb98SShilei Tian struct DeviceDataTy { 1305272d29eSJohannes Doerfert /// List that contains all the kernels. 1315272d29eSJohannes Doerfert std::list<KernelTy> KernelsList; 1325272d29eSJohannes Doerfert 1334031bb98SShilei Tian std::list<FuncOrGblEntryTy> FuncGblEntries; 1345272d29eSJohannes Doerfert 1354031bb98SShilei Tian CUcontext Context = nullptr; 1364031bb98SShilei Tian // Device properties 1374031bb98SShilei Tian int ThreadsPerBlock = 0; 1384031bb98SShilei Tian int BlocksPerGrid = 0; 1394031bb98SShilei Tian int WarpSize = 0; 1404031bb98SShilei Tian // OpenMP properties 1414031bb98SShilei Tian int NumTeams = 0; 1424031bb98SShilei Tian int NumThreads = 0; 1434031bb98SShilei Tian }; 144feed674dSShilei Tian 145feed674dSShilei Tian class StreamManagerTy { 146feed674dSShilei Tian int NumberOfDevices; 1474031bb98SShilei Tian // The initial size of stream pool 1484031bb98SShilei Tian int EnvNumInitialStreams; 149feed674dSShilei Tian // Per-device stream mutex 150feed674dSShilei Tian std::vector<std::unique_ptr<std::mutex>> StreamMtx; 151feed674dSShilei Tian // Per-device stream Id indicates the next available stream in the pool 152feed674dSShilei Tian std::vector<int> NextStreamId; 153feed674dSShilei Tian // Per-device stream pool 154feed674dSShilei Tian std::vector<std::vector<CUstream>> StreamPool; 1554031bb98SShilei Tian // Reference to per-device data 1564031bb98SShilei Tian std::vector<DeviceDataTy> &DeviceData; 157feed674dSShilei Tian 158feed674dSShilei Tian // If there is no CUstream left in the pool, we will resize the pool to 159feed674dSShilei Tian // allocate more CUstream. This function should be called with device mutex, 160feed674dSShilei Tian // and we do not resize to smaller one. 161feed674dSShilei Tian void resizeStreamPool(const int DeviceId, const size_t NewSize) { 162feed674dSShilei Tian std::vector<CUstream> &Pool = StreamPool[DeviceId]; 163feed674dSShilei Tian const size_t CurrentSize = Pool.size(); 164feed674dSShilei Tian assert(NewSize > CurrentSize && "new size is not larger than current size"); 165feed674dSShilei Tian 1664031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 1674031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) { 168feed674dSShilei Tian // We will return if cannot switch to the right context in case of 169feed674dSShilei Tian // creating bunch of streams that are not corresponding to the right 170feed674dSShilei Tian // device. The offloading will fail later because selected CUstream is 171feed674dSShilei Tian // nullptr. 172feed674dSShilei Tian return; 173feed674dSShilei Tian } 174feed674dSShilei Tian 1754031bb98SShilei Tian Pool.resize(NewSize, nullptr); 1764031bb98SShilei Tian 177feed674dSShilei Tian for (size_t I = CurrentSize; I < NewSize; ++I) { 1784031bb98SShilei Tian checkResult(cuStreamCreate(&Pool[I], CU_STREAM_NON_BLOCKING), 1794031bb98SShilei Tian "Error returned from cuStreamCreate\n"); 180feed674dSShilei Tian } 181feed674dSShilei Tian } 182feed674dSShilei Tian 183feed674dSShilei Tian public: 1844031bb98SShilei Tian StreamManagerTy(const int NumberOfDevices, 1854031bb98SShilei Tian std::vector<DeviceDataTy> &DeviceData) 1864031bb98SShilei Tian : NumberOfDevices(NumberOfDevices), EnvNumInitialStreams(32), 1874031bb98SShilei Tian DeviceData(DeviceData) { 188feed674dSShilei Tian StreamPool.resize(NumberOfDevices); 189feed674dSShilei Tian NextStreamId.resize(NumberOfDevices); 190feed674dSShilei Tian StreamMtx.resize(NumberOfDevices); 191feed674dSShilei Tian 1924031bb98SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_NUM_INITIAL_STREAMS")) 1934031bb98SShilei Tian EnvNumInitialStreams = std::stoi(EnvStr); 194feed674dSShilei Tian 195feed674dSShilei Tian // Initialize the next stream id 196feed674dSShilei Tian std::fill(NextStreamId.begin(), NextStreamId.end(), 0); 197feed674dSShilei Tian 198feed674dSShilei Tian // Initialize stream mutex 199feed674dSShilei Tian for (std::unique_ptr<std::mutex> &Ptr : StreamMtx) 200feed674dSShilei Tian Ptr = std::make_unique<std::mutex>(); 201feed674dSShilei Tian } 202feed674dSShilei Tian 203feed674dSShilei Tian ~StreamManagerTy() { 204feed674dSShilei Tian // Destroy streams 205feed674dSShilei Tian for (int I = 0; I < NumberOfDevices; ++I) { 2064031bb98SShilei Tian checkResult(cuCtxSetCurrent(DeviceData[I].Context), 2074031bb98SShilei Tian "Error returned from cuCtxSetCurrent\n"); 208feed674dSShilei Tian 209feed674dSShilei Tian for (CUstream &S : StreamPool[I]) { 2104031bb98SShilei Tian if (S) 21195f0d1edSJon Chesterfield checkResult(cuStreamDestroy(S), 21295f0d1edSJon Chesterfield "Error returned from cuStreamDestroy\n"); 213feed674dSShilei Tian } 214feed674dSShilei Tian } 215feed674dSShilei Tian } 216feed674dSShilei Tian 217feed674dSShilei Tian // Get a CUstream from pool. Per-device next stream id always points to the 218feed674dSShilei Tian // next available CUstream. That means, CUstreams [0, id-1] have been 219feed674dSShilei Tian // assigned, and [id,] are still available. If there is no CUstream left, we 220feed674dSShilei Tian // will ask more CUstreams from CUDA RT. Each time a CUstream is assigned, 221feed674dSShilei Tian // the id will increase one. 222feed674dSShilei Tian // xxxxxs+++++++++ 223feed674dSShilei Tian // ^ 224feed674dSShilei Tian // id 225feed674dSShilei Tian // After assignment, the pool becomes the following and s is assigned. 226feed674dSShilei Tian // xxxxxs+++++++++ 227feed674dSShilei Tian // ^ 228feed674dSShilei Tian // id 229feed674dSShilei Tian CUstream getStream(const int DeviceId) { 230feed674dSShilei Tian const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]); 231feed674dSShilei Tian int &Id = NextStreamId[DeviceId]; 232feed674dSShilei Tian // No CUstream left in the pool, we need to request from CUDA RT 233ad94fce8SJohannes Doerfert if (Id == static_cast<int>(StreamPool[DeviceId].size())) { 234feed674dSShilei Tian // By default we double the stream pool every time 235feed674dSShilei Tian resizeStreamPool(DeviceId, Id * 2); 236feed674dSShilei Tian } 237feed674dSShilei Tian return StreamPool[DeviceId][Id++]; 238feed674dSShilei Tian } 239feed674dSShilei Tian 240feed674dSShilei Tian // Return a CUstream back to pool. As mentioned above, per-device next 241feed674dSShilei Tian // stream is always points to the next available CUstream, so when we return 242feed674dSShilei Tian // a CUstream, we need to first decrease the id, and then copy the CUstream 243feed674dSShilei Tian // back. 244feed674dSShilei Tian // It is worth noting that, the order of streams return might be different 245feed674dSShilei Tian // from that they're assigned, that saying, at some point, there might be 246feed674dSShilei Tian // two identical CUstreams. 247feed674dSShilei Tian // xxax+a+++++ 248feed674dSShilei Tian // ^ 249feed674dSShilei Tian // id 250feed674dSShilei Tian // However, it doesn't matter, because they're always on the two sides of 251feed674dSShilei Tian // id. The left one will in the end be overwritten by another CUstream. 252feed674dSShilei Tian // Therefore, after several execution, the order of pool might be different 253feed674dSShilei Tian // from its initial state. 254feed674dSShilei Tian void returnStream(const int DeviceId, CUstream Stream) { 255feed674dSShilei Tian const std::lock_guard<std::mutex> Lock(*StreamMtx[DeviceId]); 256feed674dSShilei Tian int &Id = NextStreamId[DeviceId]; 257feed674dSShilei Tian assert(Id > 0 && "Wrong stream ID"); 258feed674dSShilei Tian StreamPool[DeviceId][--Id] = Stream; 259feed674dSShilei Tian } 260feed674dSShilei Tian 2614031bb98SShilei Tian bool initializeDeviceStreamPool(const int DeviceId) { 2624031bb98SShilei Tian assert(StreamPool[DeviceId].empty() && "stream pool has been initialized"); 2634031bb98SShilei Tian 2644031bb98SShilei Tian resizeStreamPool(DeviceId, EnvNumInitialStreams); 2654031bb98SShilei Tian 2664031bb98SShilei Tian // Check the size of stream pool 267ad94fce8SJohannes Doerfert if (static_cast<int>(StreamPool[DeviceId].size()) != EnvNumInitialStreams) 2684031bb98SShilei Tian return false; 2694031bb98SShilei Tian 2704031bb98SShilei Tian // Check whether each stream is valid 2714031bb98SShilei Tian for (CUstream &S : StreamPool[DeviceId]) 2724031bb98SShilei Tian if (!S) 2734031bb98SShilei Tian return false; 2744031bb98SShilei Tian 2754031bb98SShilei Tian return true; 276feed674dSShilei Tian } 277feed674dSShilei Tian }; 278feed674dSShilei Tian 2794031bb98SShilei Tian class DeviceRTLTy { 2803de4cd12SGeorge Rokos int NumberOfDevices; 2814031bb98SShilei Tian // OpenMP environment properties 2823de4cd12SGeorge Rokos int EnvNumTeams; 2833de4cd12SGeorge Rokos int EnvTeamLimit; 284*422adaa8SJoseph Huber int EnvTeamThreadLimit; 2854031bb98SShilei Tian // OpenMP requires flags 286c5fe030cSGheorghe-Teodor Bercea int64_t RequiresFlags; 287c5fe030cSGheorghe-Teodor Bercea 2884031bb98SShilei Tian static constexpr const int HardTeamLimit = 1U << 16U; // 64k 2894031bb98SShilei Tian static constexpr const int HardThreadLimit = 1024; 2904031bb98SShilei Tian static constexpr const int DefaultNumTeams = 128; 2914031bb98SShilei Tian static constexpr const int DefaultNumThreads = 128; 2923de4cd12SGeorge Rokos 2934031bb98SShilei Tian std::unique_ptr<StreamManagerTy> StreamManager; 2944031bb98SShilei Tian std::vector<DeviceDataTy> DeviceData; 2954031bb98SShilei Tian std::vector<CUmodule> Modules; 296feed674dSShilei Tian 2970871d6d5SShilei Tian /// A class responsible for interacting with device native runtime library to 2980871d6d5SShilei Tian /// allocate and free memory. 2990871d6d5SShilei Tian class CUDADeviceAllocatorTy : public DeviceAllocatorTy { 3000871d6d5SShilei Tian const int DeviceId; 3010871d6d5SShilei Tian const std::vector<DeviceDataTy> &DeviceData; 302a15f8589SJoseph Huber std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs; 3030871d6d5SShilei Tian 3040871d6d5SShilei Tian public: 3050871d6d5SShilei Tian CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData) 3060871d6d5SShilei Tian : DeviceId(DeviceId), DeviceData(DeviceData) {} 3070871d6d5SShilei Tian 308a15f8589SJoseph Huber void *allocate(size_t Size, void *, TargetAllocTy Kind) override { 3090871d6d5SShilei Tian if (Size == 0) 3100871d6d5SShilei Tian return nullptr; 3110871d6d5SShilei Tian 3120871d6d5SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 3130871d6d5SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 3140871d6d5SShilei Tian return nullptr; 3150871d6d5SShilei Tian 316a15f8589SJoseph Huber void *MemAlloc = nullptr; 317a15f8589SJoseph Huber switch (Kind) { 318a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 319a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 3200871d6d5SShilei Tian CUdeviceptr DevicePtr; 32195f0d1edSJon Chesterfield Err = cuMemAlloc(&DevicePtr, Size); 322a15f8589SJoseph Huber MemAlloc = (void *)DevicePtr; 32395f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemAlloc\n")) 3240871d6d5SShilei Tian return nullptr; 325a15f8589SJoseph Huber break; 326a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 327a15f8589SJoseph Huber void *HostPtr; 328a15f8589SJoseph Huber Err = cuMemAllocHost(&HostPtr, Size); 329a15f8589SJoseph Huber MemAlloc = HostPtr; 330a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocHost\n")) 331a15f8589SJoseph Huber return nullptr; 332a15f8589SJoseph Huber HostPinnedAllocs[MemAlloc] = Kind; 333a15f8589SJoseph Huber break; 334a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 335a15f8589SJoseph Huber CUdeviceptr SharedPtr; 336a15f8589SJoseph Huber Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL); 337a15f8589SJoseph Huber MemAlloc = (void *)SharedPtr; 338a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocManaged\n")) 339a15f8589SJoseph Huber return nullptr; 340a15f8589SJoseph Huber break; 341a15f8589SJoseph Huber } 3420871d6d5SShilei Tian 343a15f8589SJoseph Huber return MemAlloc; 3440871d6d5SShilei Tian } 3450871d6d5SShilei Tian 3460871d6d5SShilei Tian int free(void *TgtPtr) override { 3470871d6d5SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 3480871d6d5SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 3490871d6d5SShilei Tian return OFFLOAD_FAIL; 3500871d6d5SShilei Tian 351a15f8589SJoseph Huber // Host pinned memory must be freed differently. 352a15f8589SJoseph Huber TargetAllocTy Kind = 353a15f8589SJoseph Huber (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end()) 354a15f8589SJoseph Huber ? TARGET_ALLOC_DEFAULT 355a15f8589SJoseph Huber : TARGET_ALLOC_HOST; 356a15f8589SJoseph Huber switch (Kind) { 357a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 358a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 359a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 36095f0d1edSJon Chesterfield Err = cuMemFree((CUdeviceptr)TgtPtr); 36195f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemFree\n")) 3620871d6d5SShilei Tian return OFFLOAD_FAIL; 363a15f8589SJoseph Huber break; 364a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 365a15f8589SJoseph Huber Err = cuMemFreeHost(TgtPtr); 366a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemFreeHost\n")) 367a15f8589SJoseph Huber return OFFLOAD_FAIL; 368a15f8589SJoseph Huber break; 369a15f8589SJoseph Huber } 3700871d6d5SShilei Tian 3710871d6d5SShilei Tian return OFFLOAD_SUCCESS; 3720871d6d5SShilei Tian } 3730871d6d5SShilei Tian }; 3740871d6d5SShilei Tian 3750871d6d5SShilei Tian /// A vector of device allocators 3760871d6d5SShilei Tian std::vector<CUDADeviceAllocatorTy> DeviceAllocators; 3770871d6d5SShilei Tian 3780871d6d5SShilei Tian /// A vector of memory managers. Since the memory manager is non-copyable and 3790871d6d5SShilei Tian // non-removable, we wrap them into std::unique_ptr. 3800871d6d5SShilei Tian std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers; 3810871d6d5SShilei Tian 3820871d6d5SShilei Tian /// Whether use memory manager 3830871d6d5SShilei Tian bool UseMemoryManager = true; 3840871d6d5SShilei Tian 3853de4cd12SGeorge Rokos // Record entry point associated with device 3864031bb98SShilei Tian void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) { 3874031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 3883de4cd12SGeorge Rokos E.Entries.push_back(entry); 3893de4cd12SGeorge Rokos } 3903de4cd12SGeorge Rokos 391ae209397SJoseph Huber // Return a pointer to the entry associated with the pointer 392ae209397SJoseph Huber const __tgt_offload_entry *getOffloadEntry(const int DeviceId, 393ae209397SJoseph Huber const void *Addr) const { 3944031bb98SShilei Tian for (const __tgt_offload_entry &Itr : 3954031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.back().Entries) 3964031bb98SShilei Tian if (Itr.addr == Addr) 397ae209397SJoseph Huber return &Itr; 3983de4cd12SGeorge Rokos 399ae209397SJoseph Huber return nullptr; 4003de4cd12SGeorge Rokos } 4013de4cd12SGeorge Rokos 4023de4cd12SGeorge Rokos // Return the pointer to the target entries table 4034031bb98SShilei Tian __tgt_target_table *getOffloadEntriesTable(const int DeviceId) { 4044031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4053de4cd12SGeorge Rokos 4064031bb98SShilei Tian if (E.Entries.empty()) 4074031bb98SShilei Tian return nullptr; 4083de4cd12SGeorge Rokos 4093de4cd12SGeorge Rokos // Update table info according to the entries and return the pointer 4104031bb98SShilei Tian E.Table.EntriesBegin = E.Entries.data(); 4114031bb98SShilei Tian E.Table.EntriesEnd = E.Entries.data() + E.Entries.size(); 4123de4cd12SGeorge Rokos 4133de4cd12SGeorge Rokos return &E.Table; 4143de4cd12SGeorge Rokos } 4153de4cd12SGeorge Rokos 4163de4cd12SGeorge Rokos // Clear entries table for a device 4174031bb98SShilei Tian void clearOffloadEntriesTable(const int DeviceId) { 4184031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.emplace_back(); 4194031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4203de4cd12SGeorge Rokos E.Entries.clear(); 4214031bb98SShilei Tian E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr; 4223de4cd12SGeorge Rokos } 4233de4cd12SGeorge Rokos 4245449fbb5SJohannes Doerfert CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const { 4255449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 4264031bb98SShilei Tian 4275449fbb5SJohannes Doerfert if (!AsyncInfo->Queue) 4285449fbb5SJohannes Doerfert AsyncInfo->Queue = StreamManager->getStream(DeviceId); 4294031bb98SShilei Tian 4305449fbb5SJohannes Doerfert return reinterpret_cast<CUstream>(AsyncInfo->Queue); 431b305d26bSSergey Dmitriev } 4324031bb98SShilei Tian 4334031bb98SShilei Tian public: 4344031bb98SShilei Tian // This class should not be copied 4354031bb98SShilei Tian DeviceRTLTy(const DeviceRTLTy &) = delete; 4364031bb98SShilei Tian DeviceRTLTy(DeviceRTLTy &&) = delete; 4374031bb98SShilei Tian 4384031bb98SShilei Tian DeviceRTLTy() 4394031bb98SShilei Tian : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1), 440*422adaa8SJoseph Huber EnvTeamThreadLimit(-1), RequiresFlags(OMP_REQ_UNDEFINED) { 441b305d26bSSergey Dmitriev 4423de4cd12SGeorge Rokos DP("Start initializing CUDA\n"); 4433de4cd12SGeorge Rokos 4444031bb98SShilei Tian CUresult Err = cuInit(0); 4457baff00eSJon Chesterfield if (Err == CUDA_ERROR_INVALID_HANDLE) { 4467baff00eSJon Chesterfield // Can't call cuGetErrorString if dlsym failed 4477baff00eSJon Chesterfield DP("Failed to load CUDA shared library\n"); 4487baff00eSJon Chesterfield return; 4497baff00eSJon Chesterfield } 4504031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuInit\n")) { 4513de4cd12SGeorge Rokos return; 4523de4cd12SGeorge Rokos } 4533de4cd12SGeorge Rokos 4544031bb98SShilei Tian Err = cuDeviceGetCount(&NumberOfDevices); 4554031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGetCount\n")) 4563de4cd12SGeorge Rokos return; 4573de4cd12SGeorge Rokos 4583de4cd12SGeorge Rokos if (NumberOfDevices == 0) { 4593de4cd12SGeorge Rokos DP("There are no devices supporting CUDA.\n"); 4603de4cd12SGeorge Rokos return; 4613de4cd12SGeorge Rokos } 4623de4cd12SGeorge Rokos 4634031bb98SShilei Tian DeviceData.resize(NumberOfDevices); 4643de4cd12SGeorge Rokos 4653de4cd12SGeorge Rokos // Get environment variables regarding teams 4664031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) { 4673de4cd12SGeorge Rokos // OMP_TEAM_LIMIT has been set 4684031bb98SShilei Tian EnvTeamLimit = std::stoi(EnvStr); 4693de4cd12SGeorge Rokos DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit); 4703de4cd12SGeorge Rokos } 471*422adaa8SJoseph Huber if (const char *EnvStr = getenv("OMP_TEAMS_THREAD_LIMIT")) { 472*422adaa8SJoseph Huber // OMP_TEAMS_THREAD_LIMIT has been set 473*422adaa8SJoseph Huber EnvTeamThreadLimit = std::stoi(EnvStr); 474*422adaa8SJoseph Huber DP("Parsed OMP_TEAMS_THREAD_LIMIT=%d\n", EnvTeamThreadLimit); 475*422adaa8SJoseph Huber } 4764031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) { 4773de4cd12SGeorge Rokos // OMP_NUM_TEAMS has been set 4784031bb98SShilei Tian EnvNumTeams = std::stoi(EnvStr); 4793de4cd12SGeorge Rokos DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams); 4803de4cd12SGeorge Rokos } 481c5fe030cSGheorghe-Teodor Bercea 482feed674dSShilei Tian StreamManager = 4834031bb98SShilei Tian std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData); 4840871d6d5SShilei Tian 4850871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 4860871d6d5SShilei Tian DeviceAllocators.emplace_back(I, DeviceData); 4870871d6d5SShilei Tian 4880871d6d5SShilei Tian // Get the size threshold from environment variable 4890871d6d5SShilei Tian std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv(); 4900871d6d5SShilei Tian UseMemoryManager = Res.second; 4910871d6d5SShilei Tian size_t MemoryManagerThreshold = Res.first; 4920871d6d5SShilei Tian 4930871d6d5SShilei Tian if (UseMemoryManager) 4940871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 4950871d6d5SShilei Tian MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>( 4960871d6d5SShilei Tian DeviceAllocators[I], MemoryManagerThreshold)); 4973de4cd12SGeorge Rokos } 4983de4cd12SGeorge Rokos 4994031bb98SShilei Tian ~DeviceRTLTy() { 5000871d6d5SShilei Tian // We first destruct memory managers in case that its dependent data are 5010871d6d5SShilei Tian // destroyed before it. 5020871d6d5SShilei Tian for (auto &M : MemoryManagers) 5030871d6d5SShilei Tian M.release(); 5040871d6d5SShilei Tian 505feed674dSShilei Tian StreamManager = nullptr; 506feed674dSShilei Tian 5074031bb98SShilei Tian for (CUmodule &M : Modules) 5084031bb98SShilei Tian // Close module 5094031bb98SShilei Tian if (M) 5104031bb98SShilei Tian checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n"); 5114031bb98SShilei Tian 5124031bb98SShilei Tian for (DeviceDataTy &D : DeviceData) { 5134031bb98SShilei Tian // Destroy context 514c5348aecSYe Luo if (D.Context) { 515c5348aecSYe Luo checkResult(cuCtxSetCurrent(D.Context), 516c5348aecSYe Luo "Error returned from cuCtxSetCurrent\n"); 517c5348aecSYe Luo CUdevice Device; 518c5348aecSYe Luo checkResult(cuCtxGetDevice(&Device), 519c5348aecSYe Luo "Error returned from cuCtxGetDevice\n"); 52095f0d1edSJon Chesterfield checkResult(cuDevicePrimaryCtxRelease(Device), 52195f0d1edSJon Chesterfield "Error returned from cuDevicePrimaryCtxRelease\n"); 522c5348aecSYe Luo } 5233de4cd12SGeorge Rokos } 5243de4cd12SGeorge Rokos } 5253de4cd12SGeorge Rokos 5264031bb98SShilei Tian // Check whether a given DeviceId is valid 5274031bb98SShilei Tian bool isValidDeviceId(const int DeviceId) const { 5284031bb98SShilei Tian return DeviceId >= 0 && DeviceId < NumberOfDevices; 52932ed2927SShilei Tian } 53032ed2927SShilei Tian 531cb038927SShilei Tian int getNumOfDevices() const { return NumberOfDevices; } 5324031bb98SShilei Tian 5334031bb98SShilei Tian void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; } 5344031bb98SShilei Tian 5354031bb98SShilei Tian int initDevice(const int DeviceId) { 5364031bb98SShilei Tian CUdevice Device; 5374031bb98SShilei Tian 5384031bb98SShilei Tian DP("Getting device %d\n", DeviceId); 5394031bb98SShilei Tian CUresult Err = cuDeviceGet(&Device, DeviceId); 5404031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGet\n")) 54132ed2927SShilei Tian return OFFLOAD_FAIL; 5423de4cd12SGeorge Rokos 543c5348aecSYe Luo // Query the current flags of the primary context and set its flags if 544c5348aecSYe Luo // it is inactive 545c5348aecSYe Luo unsigned int FormerPrimaryCtxFlags = 0; 546c5348aecSYe Luo int FormerPrimaryCtxIsActive = 0; 547c5348aecSYe Luo Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags, 548c5348aecSYe Luo &FormerPrimaryCtxIsActive); 549c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n")) 550c5348aecSYe Luo return OFFLOAD_FAIL; 551c5348aecSYe Luo 552c5348aecSYe Luo if (FormerPrimaryCtxIsActive) { 553c5348aecSYe Luo DP("The primary context is active, no change to its flags\n"); 554c5348aecSYe Luo if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) != 555c5348aecSYe Luo CU_CTX_SCHED_BLOCKING_SYNC) 556c5348aecSYe Luo DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n"); 557c5348aecSYe Luo } else { 558c5348aecSYe Luo DP("The primary context is inactive, set its flags to " 559c5348aecSYe Luo "CU_CTX_SCHED_BLOCKING_SYNC\n"); 56095f0d1edSJon Chesterfield Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC); 56195f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n")) 562c5348aecSYe Luo return OFFLOAD_FAIL; 563c5348aecSYe Luo } 564c5348aecSYe Luo 565c5348aecSYe Luo // Retain the per device primary context and save it to use whenever this 566c5348aecSYe Luo // device is selected. 567c5348aecSYe Luo Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device); 568c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n")) 5693de4cd12SGeorge Rokos return OFFLOAD_FAIL; 5703de4cd12SGeorge Rokos 5714031bb98SShilei Tian Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 5724031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 5734031bb98SShilei Tian return OFFLOAD_FAIL; 574a5153dbcSJohannes Doerfert 575feed674dSShilei Tian // Initialize stream pool 5764031bb98SShilei Tian if (!StreamManager->initializeDeviceStreamPool(DeviceId)) 5774031bb98SShilei Tian return OFFLOAD_FAIL; 578a5153dbcSJohannes Doerfert 579bb51d398SJonas Hahnfeld // Query attributes to determine number of threads/block and blocks/grid. 5804031bb98SShilei Tian int MaxGridDimX; 5814031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, 5824031bb98SShilei Tian Device); 5834031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 5844031bb98SShilei Tian DP("Error getting max grid dimension, use default value %d\n", 5854031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 5864031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams; 5874031bb98SShilei Tian } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) { 5884031bb98SShilei Tian DP("Using %d CUDA blocks per grid\n", MaxGridDimX); 5894031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX; 5903de4cd12SGeorge Rokos } else { 5913de4cd12SGeorge Rokos DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping " 592bb51d398SJonas Hahnfeld "at the hard limit\n", 5934031bb98SShilei Tian MaxGridDimX, DeviceRTLTy::HardTeamLimit); 5944031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit; 5953de4cd12SGeorge Rokos } 5963de4cd12SGeorge Rokos 597bb51d398SJonas Hahnfeld // We are only exploiting threads along the x axis. 5984031bb98SShilei Tian int MaxBlockDimX; 5994031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxBlockDimX, 6004031bb98SShilei Tian CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device); 6014031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6024031bb98SShilei Tian DP("Error getting max block dimension, use default value %d\n", 6034031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 6044031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads; 605*422adaa8SJoseph Huber } else { 6064031bb98SShilei Tian DP("Using %d CUDA threads per block\n", MaxBlockDimX); 6074031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX; 608*422adaa8SJoseph Huber 609*422adaa8SJoseph Huber if (EnvTeamThreadLimit > 0 && 610*422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock > EnvTeamThreadLimit) { 611*422adaa8SJoseph Huber DP("Max CUDA threads per block %d exceeds the thread limit %d set by " 612*422adaa8SJoseph Huber "OMP_TEAMS_THREAD_LIMIT, capping at the limit\n", 613*422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, EnvTeamThreadLimit); 614*422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock = EnvTeamThreadLimit; 615*422adaa8SJoseph Huber } 616*422adaa8SJoseph Huber if (DeviceData[DeviceId].ThreadsPerBlock > DeviceRTLTy::HardThreadLimit) { 6174031bb98SShilei Tian DP("Max CUDA threads per block %d exceeds the hard thread limit %d, " 6184031bb98SShilei Tian "capping at the hard limit\n", 619*422adaa8SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceRTLTy::HardThreadLimit); 6204031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit; 6213de4cd12SGeorge Rokos } 622*422adaa8SJoseph Huber } 6233de4cd12SGeorge Rokos 6244031bb98SShilei Tian // Get and set warp size 6254031bb98SShilei Tian int WarpSize; 6264031bb98SShilei Tian Err = 6274031bb98SShilei Tian cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device); 6284031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6294031bb98SShilei Tian DP("Error getting warp size, assume default value 32\n"); 6304031bb98SShilei Tian DeviceData[DeviceId].WarpSize = 32; 631bb51d398SJonas Hahnfeld } else { 6324031bb98SShilei Tian DP("Using warp size %d\n", WarpSize); 6334031bb98SShilei Tian DeviceData[DeviceId].WarpSize = WarpSize; 6343de4cd12SGeorge Rokos } 6353de4cd12SGeorge Rokos 6363de4cd12SGeorge Rokos // Adjust teams to the env variables 6374031bb98SShilei Tian if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) { 6383de4cd12SGeorge Rokos DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n", 6394031bb98SShilei Tian EnvTeamLimit); 6404031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit; 6413de4cd12SGeorge Rokos } 6423de4cd12SGeorge Rokos 643119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 644ae209397SJoseph Huber "Device supports up to %d CUDA blocks and %d threads with a " 645ae209397SJoseph Huber "warp size of %d\n", 646ae209397SJoseph Huber DeviceData[DeviceId].BlocksPerGrid, 647ae209397SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize); 6483de4cd12SGeorge Rokos 6493de4cd12SGeorge Rokos // Set default number of teams 6504031bb98SShilei Tian if (EnvNumTeams > 0) { 6513de4cd12SGeorge Rokos DP("Default number of teams set according to environment %d\n", 6524031bb98SShilei Tian EnvNumTeams); 6534031bb98SShilei Tian DeviceData[DeviceId].NumTeams = EnvNumTeams; 6543de4cd12SGeorge Rokos } else { 6554031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams; 6563de4cd12SGeorge Rokos DP("Default number of teams set according to library's default %d\n", 6574031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 6583de4cd12SGeorge Rokos } 6594031bb98SShilei Tian 6604031bb98SShilei Tian if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) { 6613de4cd12SGeorge Rokos DP("Default number of teams exceeds device limit, capping at %d\n", 6624031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 6634031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid; 6643de4cd12SGeorge Rokos } 6653de4cd12SGeorge Rokos 6663de4cd12SGeorge Rokos // Set default number of threads 6674031bb98SShilei Tian DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads; 6683de4cd12SGeorge Rokos DP("Default number of threads set according to library's default %d\n", 6694031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 6704031bb98SShilei Tian if (DeviceData[DeviceId].NumThreads > 6714031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock) { 6723de4cd12SGeorge Rokos DP("Default number of threads exceeds device limit, capping at %d\n", 6734031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 6744031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock; 6753de4cd12SGeorge Rokos } 6763de4cd12SGeorge Rokos 6773de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 6783de4cd12SGeorge Rokos } 6793de4cd12SGeorge Rokos 6804031bb98SShilei Tian __tgt_target_table *loadBinary(const int DeviceId, 6814031bb98SShilei Tian const __tgt_device_image *Image) { 6824031bb98SShilei Tian // Set the context we are using 6834031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 6844031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 6854031bb98SShilei Tian return nullptr; 6863de4cd12SGeorge Rokos 6873de4cd12SGeorge Rokos // Clear the offload table as we are going to create a new one. 6884031bb98SShilei Tian clearOffloadEntriesTable(DeviceId); 6893de4cd12SGeorge Rokos 6903de4cd12SGeorge Rokos // Create the module and extract the function pointers. 6914031bb98SShilei Tian CUmodule Module; 6924031bb98SShilei Tian DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart)); 6934031bb98SShilei Tian Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr); 6944031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n")) 6954031bb98SShilei Tian return nullptr; 6963de4cd12SGeorge Rokos 6973de4cd12SGeorge Rokos DP("CUDA module successfully loaded!\n"); 6984031bb98SShilei Tian 6994031bb98SShilei Tian Modules.push_back(Module); 7003de4cd12SGeorge Rokos 7013de4cd12SGeorge Rokos // Find the symbols in the module by name. 7024031bb98SShilei Tian const __tgt_offload_entry *HostBegin = Image->EntriesBegin; 7034031bb98SShilei Tian const __tgt_offload_entry *HostEnd = Image->EntriesEnd; 7043de4cd12SGeorge Rokos 7055272d29eSJohannes Doerfert std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList; 7064031bb98SShilei Tian for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) { 7074031bb98SShilei Tian if (!E->addr) { 7084031bb98SShilei Tian // We return nullptr when something like this happens, the host should 7094031bb98SShilei Tian // have always something in the address to uniquely identify the target 7104031bb98SShilei Tian // region. 7114031bb98SShilei Tian DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size); 7124031bb98SShilei Tian return nullptr; 7133de4cd12SGeorge Rokos } 7143de4cd12SGeorge Rokos 7154031bb98SShilei Tian if (E->size) { 7164031bb98SShilei Tian __tgt_offload_entry Entry = *E; 7174031bb98SShilei Tian CUdeviceptr CUPtr; 7184031bb98SShilei Tian size_t CUSize; 71995f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name); 7204031bb98SShilei Tian // We keep this style here because we need the name 7214031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7222ce16810SJoseph Huber REPORT("Loading global '%s' Failed\n", E->name); 7234031bb98SShilei Tian CUDA_ERR_STRING(Err); 7244031bb98SShilei Tian return nullptr; 7253de4cd12SGeorge Rokos } 7263de4cd12SGeorge Rokos 7274031bb98SShilei Tian if (CUSize != E->size) { 7284031bb98SShilei Tian DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name, 7294031bb98SShilei Tian CUSize, E->size); 7304031bb98SShilei Tian return nullptr; 7313de4cd12SGeorge Rokos } 7323de4cd12SGeorge Rokos 7333de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n", 7344031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr)); 7354031bb98SShilei Tian 7364031bb98SShilei Tian Entry.addr = (void *)(CUPtr); 7373de4cd12SGeorge Rokos 738aace6d28SGheorghe-Teodor Bercea // Note: In the current implementation declare target variables 739aace6d28SGheorghe-Teodor Bercea // can either be link or to. This means that once unified 740aace6d28SGheorghe-Teodor Bercea // memory is activated via the requires directive, the variable 741aace6d28SGheorghe-Teodor Bercea // can be used directly from the host in both cases. 742aace6d28SGheorghe-Teodor Bercea // TODO: when variables types other than to or link are added, 7434c6a098aSKazuaki Ishizaki // the below condition should be changed to explicitly 744aace6d28SGheorghe-Teodor Bercea // check for to and link variables types: 7454031bb98SShilei Tian // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags & 7464031bb98SShilei Tian // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO)) 7474031bb98SShilei Tian if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) { 748aace6d28SGheorghe-Teodor Bercea // If unified memory is present any target link or to variables 749c5fe030cSGheorghe-Teodor Bercea // can access host addresses directly. There is no longer a 750c5fe030cSGheorghe-Teodor Bercea // need for device copies. 75195f0d1edSJon Chesterfield cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *)); 7524031bb98SShilei Tian DP("Copy linked variable host address (" DPxMOD 7534031bb98SShilei Tian ") to device address (" DPxMOD ")\n", 7544031bb98SShilei Tian DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr)); 755c5fe030cSGheorghe-Teodor Bercea } 756c5fe030cSGheorghe-Teodor Bercea 7574031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 7583de4cd12SGeorge Rokos 7593de4cd12SGeorge Rokos continue; 7603de4cd12SGeorge Rokos } 7613de4cd12SGeorge Rokos 7624031bb98SShilei Tian CUfunction Func; 7634031bb98SShilei Tian Err = cuModuleGetFunction(&Func, Module, E->name); 7644031bb98SShilei Tian // We keep this style here because we need the name 7654031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7662ce16810SJoseph Huber REPORT("Loading '%s' Failed\n", E->name); 7674031bb98SShilei Tian CUDA_ERR_STRING(Err); 7684031bb98SShilei Tian return nullptr; 7693de4cd12SGeorge Rokos } 7703de4cd12SGeorge Rokos 7713de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n", 7724031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(Func)); 7733de4cd12SGeorge Rokos 7743de4cd12SGeorge Rokos // default value GENERIC (in case symbol is missing from cubin file) 7753de4cd12SGeorge Rokos int8_t ExecModeVal = ExecutionModeType::GENERIC; 7764031bb98SShilei Tian std::string ExecModeNameStr(E->name); 7773de4cd12SGeorge Rokos ExecModeNameStr += "_exec_mode"; 7783de4cd12SGeorge Rokos const char *ExecModeName = ExecModeNameStr.c_str(); 7793de4cd12SGeorge Rokos 7803de4cd12SGeorge Rokos CUdeviceptr ExecModePtr; 7814031bb98SShilei Tian size_t CUSize; 78295f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName); 7834031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 7844031bb98SShilei Tian if (CUSize != sizeof(int8_t)) { 7853de4cd12SGeorge Rokos DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n", 7864031bb98SShilei Tian ExecModeName, CUSize, sizeof(int8_t)); 7874031bb98SShilei Tian return nullptr; 7883de4cd12SGeorge Rokos } 7893de4cd12SGeorge Rokos 79095f0d1edSJon Chesterfield Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize); 7914031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7922ce16810SJoseph Huber REPORT("Error when copying data from device to host. Pointers: " 7933de4cd12SGeorge Rokos "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n", 7944031bb98SShilei Tian DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize); 7954031bb98SShilei Tian CUDA_ERR_STRING(Err); 7964031bb98SShilei Tian return nullptr; 7973de4cd12SGeorge Rokos } 7983de4cd12SGeorge Rokos 7993de4cd12SGeorge Rokos if (ExecModeVal < 0 || ExecModeVal > 1) { 8003de4cd12SGeorge Rokos DP("Error wrong exec_mode value specified in cubin file: %d\n", 8013de4cd12SGeorge Rokos ExecModeVal); 8024031bb98SShilei Tian return nullptr; 8033de4cd12SGeorge Rokos } 8043de4cd12SGeorge Rokos } else { 8052ce16810SJoseph Huber REPORT("Loading global exec_mode '%s' - symbol missing, using default " 8064031bb98SShilei Tian "value GENERIC (1)\n", 8074031bb98SShilei Tian ExecModeName); 8084031bb98SShilei Tian CUDA_ERR_STRING(Err); 8093de4cd12SGeorge Rokos } 8103de4cd12SGeorge Rokos 8114031bb98SShilei Tian KernelsList.emplace_back(Func, ExecModeVal); 8123de4cd12SGeorge Rokos 8134031bb98SShilei Tian __tgt_offload_entry Entry = *E; 8144031bb98SShilei Tian Entry.addr = &KernelsList.back(); 8154031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 8163de4cd12SGeorge Rokos } 8173de4cd12SGeorge Rokos 818e1c7a46dSGuansong Zhang // send device environment data to the device 819e1c7a46dSGuansong Zhang { 8204031bb98SShilei Tian omptarget_device_environmentTy DeviceEnv{0}; 821e1c7a46dSGuansong Zhang 822e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG 8234031bb98SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) 8244031bb98SShilei Tian DeviceEnv.debug_level = std::stoi(EnvStr); 825e1c7a46dSGuansong Zhang #endif 826e1c7a46dSGuansong Zhang 8274031bb98SShilei Tian const char *DeviceEnvName = "omptarget_device_environment"; 8284031bb98SShilei Tian CUdeviceptr DeviceEnvPtr; 8294031bb98SShilei Tian size_t CUSize; 830e1c7a46dSGuansong Zhang 83195f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName); 8324031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 8334031bb98SShilei Tian if (CUSize != sizeof(DeviceEnv)) { 8342ce16810SJoseph Huber REPORT( 8352ce16810SJoseph Huber "Global device_environment '%s' - size mismatch (%zu != %zu)\n", 8364031bb98SShilei Tian DeviceEnvName, CUSize, sizeof(int32_t)); 8374031bb98SShilei Tian CUDA_ERR_STRING(Err); 8384031bb98SShilei Tian return nullptr; 839e1c7a46dSGuansong Zhang } 840e1c7a46dSGuansong Zhang 84195f0d1edSJon Chesterfield Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize); 8424031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 8432ce16810SJoseph Huber REPORT("Error when copying data from host to device. Pointers: " 844e1c7a46dSGuansong Zhang "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n", 8454031bb98SShilei Tian DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize); 8464031bb98SShilei Tian CUDA_ERR_STRING(Err); 8474031bb98SShilei Tian return nullptr; 848e1c7a46dSGuansong Zhang } 849e1c7a46dSGuansong Zhang 8504031bb98SShilei Tian DP("Sending global device environment data %zu bytes\n", CUSize); 851e1c7a46dSGuansong Zhang } else { 8524031bb98SShilei Tian DP("Finding global device environment '%s' - symbol missing.\n", 8534031bb98SShilei Tian DeviceEnvName); 8544031bb98SShilei Tian DP("Continue, considering this is a device RTL which does not accept " 8554031bb98SShilei Tian "environment setting.\n"); 856e1c7a46dSGuansong Zhang } 857e1c7a46dSGuansong Zhang } 858e1c7a46dSGuansong Zhang 8594031bb98SShilei Tian return getOffloadEntriesTable(DeviceId); 8603de4cd12SGeorge Rokos } 8613de4cd12SGeorge Rokos 862a15f8589SJoseph Huber void *dataAlloc(const int DeviceId, const int64_t Size, 863a15f8589SJoseph Huber const TargetAllocTy Kind) { 864a15f8589SJoseph Huber switch (Kind) { 865a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 866a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 8670871d6d5SShilei Tian if (UseMemoryManager) 8680871d6d5SShilei Tian return MemoryManagers[DeviceId]->allocate(Size, nullptr); 869a15f8589SJoseph Huber else 870a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 871a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 872a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 873a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 874a15f8589SJoseph Huber } 8754031bb98SShilei Tian 876a15f8589SJoseph Huber REPORT("Invalid target data allocation kind or requested allocator not " 877a15f8589SJoseph Huber "implemented yet\n"); 878a15f8589SJoseph Huber 879a15f8589SJoseph Huber return nullptr; 8803de4cd12SGeorge Rokos } 8813de4cd12SGeorge Rokos 8824031bb98SShilei Tian int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr, 8835449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 8845449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 8853de4cd12SGeorge Rokos 8864031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 8874031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 8883de4cd12SGeorge Rokos return OFFLOAD_FAIL; 8893de4cd12SGeorge Rokos 8905449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 8913de4cd12SGeorge Rokos 89295f0d1edSJon Chesterfield Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream); 8934031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 89429338459SJoseph Huber DP("Error when copying data from host to device. Pointers: host " 8952ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n", 8964031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size); 8974031bb98SShilei Tian CUDA_ERR_STRING(Err); 8983de4cd12SGeorge Rokos return OFFLOAD_FAIL; 8993de4cd12SGeorge Rokos } 9003de4cd12SGeorge Rokos 9013de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 9023de4cd12SGeorge Rokos } 9033de4cd12SGeorge Rokos 9044031bb98SShilei Tian int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr, 9055449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 9065449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 9074031bb98SShilei Tian 9084031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 9094031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 91003ff643dSShilei Tian return OFFLOAD_FAIL; 91103ff643dSShilei Tian 9125449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 91303ff643dSShilei Tian 91495f0d1edSJon Chesterfield Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream); 9154031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 91629338459SJoseph Huber DP("Error when copying data from device to host. Pointers: host " 9172ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n", 9184031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size); 9194031bb98SShilei Tian CUDA_ERR_STRING(Err); 9203de4cd12SGeorge Rokos return OFFLOAD_FAIL; 9213de4cd12SGeorge Rokos } 9223de4cd12SGeorge Rokos 9234031bb98SShilei Tian return OFFLOAD_SUCCESS; 9244031bb98SShilei Tian } 9254031bb98SShilei Tian 926a014fbbcSShilei Tian int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr, 9275449fbb5SJohannes Doerfert int64_t Size, __tgt_async_info *AsyncInfo) const { 9285449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 929a014fbbcSShilei Tian 930a014fbbcSShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context); 931a014fbbcSShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 932a014fbbcSShilei Tian return OFFLOAD_FAIL; 933a014fbbcSShilei Tian 9345449fbb5SJohannes Doerfert CUstream Stream = getStream(SrcDevId, AsyncInfo); 935a014fbbcSShilei Tian 936a014fbbcSShilei Tian // If they are two devices, we try peer to peer copy first 937a014fbbcSShilei Tian if (SrcDevId != DstDevId) { 938a014fbbcSShilei Tian int CanAccessPeer = 0; 939a014fbbcSShilei Tian Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId); 940a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 9412ce16810SJoseph Huber REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32 942a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 943a014fbbcSShilei Tian SrcDevId, DstDevId); 944a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 945a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 946a014fbbcSShilei Tian } 947a014fbbcSShilei Tian 948a014fbbcSShilei Tian if (!CanAccessPeer) { 949a014fbbcSShilei Tian DP("P2P memcpy not supported so fall back to D2D memcpy"); 950a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 951a014fbbcSShilei Tian } 952a014fbbcSShilei Tian 953a014fbbcSShilei Tian Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0); 954a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 9552ce16810SJoseph Huber REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32 956a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 957a014fbbcSShilei Tian SrcDevId, DstDevId); 958a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 959a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 960a014fbbcSShilei Tian } 961a014fbbcSShilei Tian 962a014fbbcSShilei Tian Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context, 963a014fbbcSShilei Tian (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context, 964a014fbbcSShilei Tian Size, Stream); 965a014fbbcSShilei Tian if (Err == CUDA_SUCCESS) 966a014fbbcSShilei Tian return OFFLOAD_SUCCESS; 967a014fbbcSShilei Tian 96829338459SJoseph Huber DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD 96929338459SJoseph Huber ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n", 97045bb073dSYe Luo DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId); 971a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 972a014fbbcSShilei Tian } 973a014fbbcSShilei Tian 974a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 975a014fbbcSShilei Tian } 976a014fbbcSShilei Tian 9770871d6d5SShilei Tian int dataDelete(const int DeviceId, void *TgtPtr) { 9780871d6d5SShilei Tian if (UseMemoryManager) 9790871d6d5SShilei Tian return MemoryManagers[DeviceId]->free(TgtPtr); 9804031bb98SShilei Tian 9810871d6d5SShilei Tian return DeviceAllocators[DeviceId].free(TgtPtr); 9824031bb98SShilei Tian } 9834031bb98SShilei Tian 984aa27cfc1SJohannes Doerfert int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs, 985aa27cfc1SJohannes Doerfert ptrdiff_t *TgtOffsets, const int ArgNum, 986aa27cfc1SJohannes Doerfert const int TeamNum, const int ThreadLimit, 9874031bb98SShilei Tian const unsigned int LoopTripCount, 9884031bb98SShilei Tian __tgt_async_info *AsyncInfo) const { 9894031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 9904031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 9914031bb98SShilei Tian return OFFLOAD_FAIL; 9924031bb98SShilei Tian 9933de4cd12SGeorge Rokos // All args are references. 9944031bb98SShilei Tian std::vector<void *> Args(ArgNum); 9954031bb98SShilei Tian std::vector<void *> Ptrs(ArgNum); 9963de4cd12SGeorge Rokos 9974031bb98SShilei Tian for (int I = 0; I < ArgNum; ++I) { 9984031bb98SShilei Tian Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]); 9994031bb98SShilei Tian Args[I] = &Ptrs[I]; 10001546d319SGeorge Rokos } 10013de4cd12SGeorge Rokos 1002aa27cfc1SJohannes Doerfert KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr); 10033de4cd12SGeorge Rokos 1004aa27cfc1SJohannes Doerfert int CudaThreadsPerBlock; 10054031bb98SShilei Tian if (ThreadLimit > 0) { 10064031bb98SShilei Tian DP("Setting CUDA threads per block to requested %d\n", ThreadLimit); 10074031bb98SShilei Tian CudaThreadsPerBlock = ThreadLimit; 10083de4cd12SGeorge Rokos // Add master warp if necessary 10093de4cd12SGeorge Rokos if (KernelInfo->ExecutionMode == GENERIC) { 10104031bb98SShilei Tian DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize); 10114031bb98SShilei Tian CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize; 10123de4cd12SGeorge Rokos } 1013c13df8e5SGeorge Rokos } else { 1014c13df8e5SGeorge Rokos DP("Setting CUDA threads per block to default %d\n", 10154031bb98SShilei Tian DeviceData[DeviceId].NumThreads); 10164031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads; 1017c13df8e5SGeorge Rokos } 10183de4cd12SGeorge Rokos 10194031bb98SShilei Tian if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) { 10203de4cd12SGeorge Rokos DP("Threads per block capped at device limit %d\n", 10214031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 10224031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock; 10233de4cd12SGeorge Rokos } 10243de4cd12SGeorge Rokos 1025aa27cfc1SJohannes Doerfert if (!KernelInfo->MaxThreadsPerBlock) { 1026aa27cfc1SJohannes Doerfert Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock, 10274031bb98SShilei Tian CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, 10284031bb98SShilei Tian KernelInfo->Func); 1029aa27cfc1SJohannes Doerfert if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n")) 1030aa27cfc1SJohannes Doerfert return OFFLOAD_FAIL; 1031aa27cfc1SJohannes Doerfert } 1032aa27cfc1SJohannes Doerfert 1033aa27cfc1SJohannes Doerfert if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) { 1034aa27cfc1SJohannes Doerfert DP("Threads per block capped at kernel limit %d\n", 1035aa27cfc1SJohannes Doerfert KernelInfo->MaxThreadsPerBlock); 1036aa27cfc1SJohannes Doerfert CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock; 10373de4cd12SGeorge Rokos } 10383de4cd12SGeorge Rokos 10394031bb98SShilei Tian unsigned int CudaBlocksPerGrid; 10404031bb98SShilei Tian if (TeamNum <= 0) { 10414031bb98SShilei Tian if (LoopTripCount > 0 && EnvNumTeams < 0) { 1042c13df8e5SGeorge Rokos if (KernelInfo->ExecutionMode == SPMD) { 10434031bb98SShilei Tian // We have a combined construct, i.e. `target teams distribute 10444031bb98SShilei Tian // parallel for [simd]`. We launch so many teams so that each thread 10454031bb98SShilei Tian // will execute one iteration of the loop. round up to the nearest 10464031bb98SShilei Tian // integer 10474031bb98SShilei Tian CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1; 1048c13df8e5SGeorge Rokos } else { 1049c13df8e5SGeorge Rokos // If we reach this point, then we have a non-combined construct, i.e. 1050c13df8e5SGeorge Rokos // `teams distribute` with a nested `parallel for` and each team is 1051c13df8e5SGeorge Rokos // assigned one iteration of the `distribute` loop. E.g.: 1052c13df8e5SGeorge Rokos // 1053c13df8e5SGeorge Rokos // #pragma omp target teams distribute 1054c13df8e5SGeorge Rokos // for(...loop_tripcount...) { 1055c13df8e5SGeorge Rokos // #pragma omp parallel for 1056c13df8e5SGeorge Rokos // for(...) {} 1057c13df8e5SGeorge Rokos // } 1058c13df8e5SGeorge Rokos // 1059c13df8e5SGeorge Rokos // Threads within a team will execute the iterations of the `parallel` 1060c13df8e5SGeorge Rokos // loop. 10614031bb98SShilei Tian CudaBlocksPerGrid = LoopTripCount; 1062c13df8e5SGeorge Rokos } 106345bb073dSYe Luo DP("Using %d teams due to loop trip count %" PRIu32 10644031bb98SShilei Tian " and number of threads per block %d\n", 10654031bb98SShilei Tian CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock); 10663de4cd12SGeorge Rokos } else { 10674031bb98SShilei Tian DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams); 10684031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams; 10693de4cd12SGeorge Rokos } 10704031bb98SShilei Tian } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) { 10713de4cd12SGeorge Rokos DP("Capping number of teams to team limit %d\n", 10724031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 10734031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid; 10743de4cd12SGeorge Rokos } else { 10754031bb98SShilei Tian DP("Using requested number of teams %d\n", TeamNum); 10764031bb98SShilei Tian CudaBlocksPerGrid = TeamNum; 10773de4cd12SGeorge Rokos } 10783de4cd12SGeorge Rokos 1079119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 1080ae209397SJoseph Huber "Launching kernel %s with %d blocks and %d threads in %s " 1081ae209397SJoseph Huber "mode\n", 1082ae209397SJoseph Huber (getOffloadEntry(DeviceId, TgtEntryPtr)) 1083ae209397SJoseph Huber ? getOffloadEntry(DeviceId, TgtEntryPtr)->name 1084ae209397SJoseph Huber : "(null)", 1085ae209397SJoseph Huber CudaBlocksPerGrid, CudaThreadsPerBlock, 1086ae209397SJoseph Huber (KernelInfo->ExecutionMode == SPMD) ? "SPMD" : "Generic"); 10873de4cd12SGeorge Rokos 10884031bb98SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo); 10894031bb98SShilei Tian Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1, 10904031bb98SShilei Tian /* gridDimZ */ 1, CudaThreadsPerBlock, 10914031bb98SShilei Tian /* blockDimY */ 1, /* blockDimZ */ 1, 10924031bb98SShilei Tian /* sharedMemBytes */ 0, Stream, &Args[0], nullptr); 10934031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuLaunchKernel\n")) 10944031bb98SShilei Tian return OFFLOAD_FAIL; 10954031bb98SShilei Tian 10964031bb98SShilei Tian DP("Launch of entry point at " DPxMOD " successful!\n", 10974031bb98SShilei Tian DPxPTR(TgtEntryPtr)); 10984031bb98SShilei Tian 10994031bb98SShilei Tian return OFFLOAD_SUCCESS; 11004031bb98SShilei Tian } 11014031bb98SShilei Tian 11025449fbb5SJohannes Doerfert int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const { 11035449fbb5SJohannes Doerfert CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue); 11044031bb98SShilei Tian CUresult Err = cuStreamSynchronize(Stream); 11053de4cd12SGeorge Rokos 11064031bb98SShilei Tian // Once the stream is synchronized, return it to stream pool and reset 11075449fbb5SJohannes Doerfert // AsyncInfo. This is to make sure the synchronization only works for its 11084031bb98SShilei Tian // own tasks. 11095449fbb5SJohannes Doerfert StreamManager->returnStream(DeviceId, 11105449fbb5SJohannes Doerfert reinterpret_cast<CUstream>(AsyncInfo->Queue)); 11115449fbb5SJohannes Doerfert AsyncInfo->Queue = nullptr; 11123de4cd12SGeorge Rokos 111316064e71SJoseph Huber if (Err != CUDA_SUCCESS) { 111429338459SJoseph Huber DP("Error when synchronizing stream. stream = " DPxMOD 111516064e71SJoseph Huber ", async info ptr = " DPxMOD "\n", 111616064e71SJoseph Huber DPxPTR(Stream), DPxPTR(AsyncInfo)); 111716064e71SJoseph Huber CUDA_ERR_STRING(Err); 111816064e71SJoseph Huber } 111916064e71SJoseph Huber return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL; 11203de4cd12SGeorge Rokos } 11214031bb98SShilei Tian }; 11224031bb98SShilei Tian 11234031bb98SShilei Tian DeviceRTLTy DeviceRTL; 11244031bb98SShilei Tian } // namespace 11254031bb98SShilei Tian 11264031bb98SShilei Tian // Exposed library API function 11274031bb98SShilei Tian #ifdef __cplusplus 11284031bb98SShilei Tian extern "C" { 11294031bb98SShilei Tian #endif 11304031bb98SShilei Tian 11314031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) { 11324031bb98SShilei Tian return elf_check_machine(image, /* EM_CUDA */ 190); 11334031bb98SShilei Tian } 11344031bb98SShilei Tian 11354031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); } 11364031bb98SShilei Tian 11374031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) { 113840470eb2SGeorge Rokos DP("Init requires flags to %" PRId64 "\n", RequiresFlags); 11394031bb98SShilei Tian DeviceRTL.setRequiresFlag(RequiresFlags); 11404031bb98SShilei Tian return RequiresFlags; 11414031bb98SShilei Tian } 11424031bb98SShilei Tian 1143a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) { 1144a014fbbcSShilei Tian if (DeviceRTL.isValidDeviceId(src_dev_id) && 1145a014fbbcSShilei Tian DeviceRTL.isValidDeviceId(dst_dev_id)) 1146a014fbbcSShilei Tian return 1; 1147a014fbbcSShilei Tian 1148a014fbbcSShilei Tian return 0; 1149a014fbbcSShilei Tian } 1150a014fbbcSShilei Tian 11514031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) { 11524031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11534031bb98SShilei Tian 11544031bb98SShilei Tian return DeviceRTL.initDevice(device_id); 11554031bb98SShilei Tian } 11564031bb98SShilei Tian 11574031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id, 11584031bb98SShilei Tian __tgt_device_image *image) { 11594031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11604031bb98SShilei Tian 11614031bb98SShilei Tian return DeviceRTL.loadBinary(device_id, image); 11624031bb98SShilei Tian } 11634031bb98SShilei Tian 11642468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *, 11652468fdd9SGeorge Rokos int32_t kind) { 11664031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11674031bb98SShilei Tian 1168a15f8589SJoseph Huber return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind); 11694031bb98SShilei Tian } 11704031bb98SShilei Tian 11714031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr, 11724031bb98SShilei Tian int64_t size) { 11734031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11744031bb98SShilei Tian 11755449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 11764031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr, 11775449fbb5SJohannes Doerfert size, &AsyncInfo); 11784031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 11794031bb98SShilei Tian return OFFLOAD_FAIL; 11804031bb98SShilei Tian 11815449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 11824031bb98SShilei Tian } 11834031bb98SShilei Tian 11844031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr, 11854031bb98SShilei Tian void *hst_ptr, int64_t size, 11864031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 11874031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11884031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 11894031bb98SShilei Tian 11904031bb98SShilei Tian return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size, 11914031bb98SShilei Tian async_info_ptr); 11924031bb98SShilei Tian } 11934031bb98SShilei Tian 11944031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr, 11954031bb98SShilei Tian int64_t size) { 11964031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11974031bb98SShilei Tian 11985449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 11994031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr, 12005449fbb5SJohannes Doerfert size, &AsyncInfo); 12014031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 12024031bb98SShilei Tian return OFFLOAD_FAIL; 12034031bb98SShilei Tian 12045449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 12054031bb98SShilei Tian } 12064031bb98SShilei Tian 12074031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr, 12084031bb98SShilei Tian void *tgt_ptr, int64_t size, 12094031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12104031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12114031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 12124031bb98SShilei Tian 12134031bb98SShilei Tian return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size, 12144031bb98SShilei Tian async_info_ptr); 12154031bb98SShilei Tian } 12164031bb98SShilei Tian 1217a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr, 1218a014fbbcSShilei Tian int dst_dev_id, void *dst_ptr, 1219a014fbbcSShilei Tian int64_t size, 12205449fbb5SJohannes Doerfert __tgt_async_info *AsyncInfo) { 1221a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1222a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 12235449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 1224a014fbbcSShilei Tian 1225a014fbbcSShilei Tian return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, 12265449fbb5SJohannes Doerfert AsyncInfo); 1227a014fbbcSShilei Tian } 1228a014fbbcSShilei Tian 1229a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr, 1230a014fbbcSShilei Tian int32_t dst_dev_id, void *dst_ptr, 1231a014fbbcSShilei Tian int64_t size) { 1232a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1233a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 1234a014fbbcSShilei Tian 12355449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 1236a014fbbcSShilei Tian const int32_t rc = __tgt_rtl_data_exchange_async( 12375449fbb5SJohannes Doerfert src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo); 1238a014fbbcSShilei Tian if (rc != OFFLOAD_SUCCESS) 1239a014fbbcSShilei Tian return OFFLOAD_FAIL; 1240a014fbbcSShilei Tian 12415449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo); 1242a014fbbcSShilei Tian } 1243a014fbbcSShilei Tian 12444031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) { 12454031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12464031bb98SShilei Tian 12474031bb98SShilei Tian return DeviceRTL.dataDelete(device_id, tgt_ptr); 12484031bb98SShilei Tian } 12494031bb98SShilei Tian 12504031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr, 12514031bb98SShilei Tian void **tgt_args, 12524031bb98SShilei Tian ptrdiff_t *tgt_offsets, 12534031bb98SShilei Tian int32_t arg_num, int32_t team_num, 12544031bb98SShilei Tian int32_t thread_limit, 12554031bb98SShilei Tian uint64_t loop_tripcount) { 12564031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12574031bb98SShilei Tian 12585449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 12594031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_team_region_async( 12604031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 12615449fbb5SJohannes Doerfert thread_limit, loop_tripcount, &AsyncInfo); 12624031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 12634031bb98SShilei Tian return OFFLOAD_FAIL; 12644031bb98SShilei Tian 12655449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 12664031bb98SShilei Tian } 12674031bb98SShilei Tian 12684031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async( 12694031bb98SShilei Tian int32_t device_id, void *tgt_entry_ptr, void **tgt_args, 12704031bb98SShilei Tian ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num, 12714031bb98SShilei Tian int32_t thread_limit, uint64_t loop_tripcount, 12724031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12734031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12744031bb98SShilei Tian 12754031bb98SShilei Tian return DeviceRTL.runTargetTeamRegion( 12764031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 12774031bb98SShilei Tian thread_limit, loop_tripcount, async_info_ptr); 12784031bb98SShilei Tian } 12793de4cd12SGeorge Rokos 12803de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr, 128132ed2927SShilei Tian void **tgt_args, ptrdiff_t *tgt_offsets, 128203ff643dSShilei Tian int32_t arg_num) { 12834031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12844031bb98SShilei Tian 12855449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 12864031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_region_async( 12875449fbb5SJohannes Doerfert device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo); 128803ff643dSShilei Tian if (rc != OFFLOAD_SUCCESS) 128903ff643dSShilei Tian return OFFLOAD_FAIL; 129003ff643dSShilei Tian 12915449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 129203ff643dSShilei Tian } 129303ff643dSShilei Tian 129403ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id, 129503ff643dSShilei Tian void *tgt_entry_ptr, void **tgt_args, 129603ff643dSShilei Tian ptrdiff_t *tgt_offsets, 129732ed2927SShilei Tian int32_t arg_num, 12984031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12994031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 13004031bb98SShilei Tian 130103ff643dSShilei Tian return __tgt_rtl_run_target_team_region_async( 13024031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, 13034031bb98SShilei Tian /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0, 13044031bb98SShilei Tian async_info_ptr); 130532ed2927SShilei Tian } 130632ed2927SShilei Tian 13074031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id, 13084031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 13094031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 13104031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 13114031bb98SShilei Tian assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr"); 131232ed2927SShilei Tian 13134031bb98SShilei Tian return DeviceRTL.synchronize(device_id, async_info_ptr); 13143de4cd12SGeorge Rokos } 13153de4cd12SGeorge Rokos 13162b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) { 131759b68490SJoseph Huber std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal(); 13182b6f2008SJoseph Huber InfoLevel.store(NewInfoLevel); 13192b6f2008SJoseph Huber } 13202b6f2008SJoseph Huber 13213de4cd12SGeorge Rokos #ifdef __cplusplus 13223de4cd12SGeorge Rokos } 13233de4cd12SGeorge Rokos #endif 1324