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> 20*a15f8589SJoseph 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; 2844031bb98SShilei Tian // OpenMP requires flags 285c5fe030cSGheorghe-Teodor Bercea int64_t RequiresFlags; 286c5fe030cSGheorghe-Teodor Bercea 2874031bb98SShilei Tian static constexpr const int HardTeamLimit = 1U << 16U; // 64k 2884031bb98SShilei Tian static constexpr const int HardThreadLimit = 1024; 2894031bb98SShilei Tian static constexpr const int DefaultNumTeams = 128; 2904031bb98SShilei Tian static constexpr const int DefaultNumThreads = 128; 2913de4cd12SGeorge Rokos 2924031bb98SShilei Tian std::unique_ptr<StreamManagerTy> StreamManager; 2934031bb98SShilei Tian std::vector<DeviceDataTy> DeviceData; 2944031bb98SShilei Tian std::vector<CUmodule> Modules; 295feed674dSShilei Tian 2960871d6d5SShilei Tian /// A class responsible for interacting with device native runtime library to 2970871d6d5SShilei Tian /// allocate and free memory. 2980871d6d5SShilei Tian class CUDADeviceAllocatorTy : public DeviceAllocatorTy { 2990871d6d5SShilei Tian const int DeviceId; 3000871d6d5SShilei Tian const std::vector<DeviceDataTy> &DeviceData; 301*a15f8589SJoseph Huber std::unordered_map<void *, TargetAllocTy> HostPinnedAllocs; 3020871d6d5SShilei Tian 3030871d6d5SShilei Tian public: 3040871d6d5SShilei Tian CUDADeviceAllocatorTy(int DeviceId, std::vector<DeviceDataTy> &DeviceData) 3050871d6d5SShilei Tian : DeviceId(DeviceId), DeviceData(DeviceData) {} 3060871d6d5SShilei Tian 307*a15f8589SJoseph Huber void *allocate(size_t Size, void *, TargetAllocTy Kind) override { 3080871d6d5SShilei Tian if (Size == 0) 3090871d6d5SShilei Tian return nullptr; 3100871d6d5SShilei Tian 3110871d6d5SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 3120871d6d5SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 3130871d6d5SShilei Tian return nullptr; 3140871d6d5SShilei Tian 315*a15f8589SJoseph Huber void *MemAlloc = nullptr; 316*a15f8589SJoseph Huber switch (Kind) { 317*a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 318*a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 3190871d6d5SShilei Tian CUdeviceptr DevicePtr; 32095f0d1edSJon Chesterfield Err = cuMemAlloc(&DevicePtr, Size); 321*a15f8589SJoseph Huber MemAlloc = (void *)DevicePtr; 32295f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemAlloc\n")) 3230871d6d5SShilei Tian return nullptr; 324*a15f8589SJoseph Huber break; 325*a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 326*a15f8589SJoseph Huber void *HostPtr; 327*a15f8589SJoseph Huber Err = cuMemAllocHost(&HostPtr, Size); 328*a15f8589SJoseph Huber MemAlloc = HostPtr; 329*a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocHost\n")) 330*a15f8589SJoseph Huber return nullptr; 331*a15f8589SJoseph Huber HostPinnedAllocs[MemAlloc] = Kind; 332*a15f8589SJoseph Huber break; 333*a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 334*a15f8589SJoseph Huber CUdeviceptr SharedPtr; 335*a15f8589SJoseph Huber Err = cuMemAllocManaged(&SharedPtr, Size, CU_MEM_ATTACH_GLOBAL); 336*a15f8589SJoseph Huber MemAlloc = (void *)SharedPtr; 337*a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemAllocManaged\n")) 338*a15f8589SJoseph Huber return nullptr; 339*a15f8589SJoseph Huber break; 340*a15f8589SJoseph Huber } 3410871d6d5SShilei Tian 342*a15f8589SJoseph Huber return MemAlloc; 3430871d6d5SShilei Tian } 3440871d6d5SShilei Tian 3450871d6d5SShilei Tian int free(void *TgtPtr) override { 3460871d6d5SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 3470871d6d5SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 3480871d6d5SShilei Tian return OFFLOAD_FAIL; 3490871d6d5SShilei Tian 350*a15f8589SJoseph Huber // Host pinned memory must be freed differently. 351*a15f8589SJoseph Huber TargetAllocTy Kind = 352*a15f8589SJoseph Huber (HostPinnedAllocs.find(TgtPtr) == HostPinnedAllocs.end()) 353*a15f8589SJoseph Huber ? TARGET_ALLOC_DEFAULT 354*a15f8589SJoseph Huber : TARGET_ALLOC_HOST; 355*a15f8589SJoseph Huber switch (Kind) { 356*a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 357*a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 358*a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 35995f0d1edSJon Chesterfield Err = cuMemFree((CUdeviceptr)TgtPtr); 36095f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuMemFree\n")) 3610871d6d5SShilei Tian return OFFLOAD_FAIL; 362*a15f8589SJoseph Huber break; 363*a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 364*a15f8589SJoseph Huber Err = cuMemFreeHost(TgtPtr); 365*a15f8589SJoseph Huber if (!checkResult(Err, "Error returned from cuMemFreeHost\n")) 366*a15f8589SJoseph Huber return OFFLOAD_FAIL; 367*a15f8589SJoseph Huber break; 368*a15f8589SJoseph Huber } 3690871d6d5SShilei Tian 3700871d6d5SShilei Tian return OFFLOAD_SUCCESS; 3710871d6d5SShilei Tian } 3720871d6d5SShilei Tian }; 3730871d6d5SShilei Tian 3740871d6d5SShilei Tian /// A vector of device allocators 3750871d6d5SShilei Tian std::vector<CUDADeviceAllocatorTy> DeviceAllocators; 3760871d6d5SShilei Tian 3770871d6d5SShilei Tian /// A vector of memory managers. Since the memory manager is non-copyable and 3780871d6d5SShilei Tian // non-removable, we wrap them into std::unique_ptr. 3790871d6d5SShilei Tian std::vector<std::unique_ptr<MemoryManagerTy>> MemoryManagers; 3800871d6d5SShilei Tian 3810871d6d5SShilei Tian /// Whether use memory manager 3820871d6d5SShilei Tian bool UseMemoryManager = true; 3830871d6d5SShilei Tian 3843de4cd12SGeorge Rokos // Record entry point associated with device 3854031bb98SShilei Tian void addOffloadEntry(const int DeviceId, const __tgt_offload_entry entry) { 3864031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 3873de4cd12SGeorge Rokos E.Entries.push_back(entry); 3883de4cd12SGeorge Rokos } 3893de4cd12SGeorge Rokos 390ae209397SJoseph Huber // Return a pointer to the entry associated with the pointer 391ae209397SJoseph Huber const __tgt_offload_entry *getOffloadEntry(const int DeviceId, 392ae209397SJoseph Huber const void *Addr) const { 3934031bb98SShilei Tian for (const __tgt_offload_entry &Itr : 3944031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.back().Entries) 3954031bb98SShilei Tian if (Itr.addr == Addr) 396ae209397SJoseph Huber return &Itr; 3973de4cd12SGeorge Rokos 398ae209397SJoseph Huber return nullptr; 3993de4cd12SGeorge Rokos } 4003de4cd12SGeorge Rokos 4013de4cd12SGeorge Rokos // Return the pointer to the target entries table 4024031bb98SShilei Tian __tgt_target_table *getOffloadEntriesTable(const int DeviceId) { 4034031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4043de4cd12SGeorge Rokos 4054031bb98SShilei Tian if (E.Entries.empty()) 4064031bb98SShilei Tian return nullptr; 4073de4cd12SGeorge Rokos 4083de4cd12SGeorge Rokos // Update table info according to the entries and return the pointer 4094031bb98SShilei Tian E.Table.EntriesBegin = E.Entries.data(); 4104031bb98SShilei Tian E.Table.EntriesEnd = E.Entries.data() + E.Entries.size(); 4113de4cd12SGeorge Rokos 4123de4cd12SGeorge Rokos return &E.Table; 4133de4cd12SGeorge Rokos } 4143de4cd12SGeorge Rokos 4153de4cd12SGeorge Rokos // Clear entries table for a device 4164031bb98SShilei Tian void clearOffloadEntriesTable(const int DeviceId) { 4174031bb98SShilei Tian DeviceData[DeviceId].FuncGblEntries.emplace_back(); 4184031bb98SShilei Tian FuncOrGblEntryTy &E = DeviceData[DeviceId].FuncGblEntries.back(); 4193de4cd12SGeorge Rokos E.Entries.clear(); 4204031bb98SShilei Tian E.Table.EntriesBegin = E.Table.EntriesEnd = nullptr; 4213de4cd12SGeorge Rokos } 4223de4cd12SGeorge Rokos 4235449fbb5SJohannes Doerfert CUstream getStream(const int DeviceId, __tgt_async_info *AsyncInfo) const { 4245449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 4254031bb98SShilei Tian 4265449fbb5SJohannes Doerfert if (!AsyncInfo->Queue) 4275449fbb5SJohannes Doerfert AsyncInfo->Queue = StreamManager->getStream(DeviceId); 4284031bb98SShilei Tian 4295449fbb5SJohannes Doerfert return reinterpret_cast<CUstream>(AsyncInfo->Queue); 430b305d26bSSergey Dmitriev } 4314031bb98SShilei Tian 4324031bb98SShilei Tian public: 4334031bb98SShilei Tian // This class should not be copied 4344031bb98SShilei Tian DeviceRTLTy(const DeviceRTLTy &) = delete; 4354031bb98SShilei Tian DeviceRTLTy(DeviceRTLTy &&) = delete; 4364031bb98SShilei Tian 4374031bb98SShilei Tian DeviceRTLTy() 4384031bb98SShilei Tian : NumberOfDevices(0), EnvNumTeams(-1), EnvTeamLimit(-1), 4394031bb98SShilei Tian RequiresFlags(OMP_REQ_UNDEFINED) { 440b305d26bSSergey Dmitriev 4413de4cd12SGeorge Rokos DP("Start initializing CUDA\n"); 4423de4cd12SGeorge Rokos 4434031bb98SShilei Tian CUresult Err = cuInit(0); 4447baff00eSJon Chesterfield if (Err == CUDA_ERROR_INVALID_HANDLE) { 4457baff00eSJon Chesterfield // Can't call cuGetErrorString if dlsym failed 4467baff00eSJon Chesterfield DP("Failed to load CUDA shared library\n"); 4477baff00eSJon Chesterfield return; 4487baff00eSJon Chesterfield } 4494031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuInit\n")) { 4503de4cd12SGeorge Rokos return; 4513de4cd12SGeorge Rokos } 4523de4cd12SGeorge Rokos 4534031bb98SShilei Tian Err = cuDeviceGetCount(&NumberOfDevices); 4544031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGetCount\n")) 4553de4cd12SGeorge Rokos return; 4563de4cd12SGeorge Rokos 4573de4cd12SGeorge Rokos if (NumberOfDevices == 0) { 4583de4cd12SGeorge Rokos DP("There are no devices supporting CUDA.\n"); 4593de4cd12SGeorge Rokos return; 4603de4cd12SGeorge Rokos } 4613de4cd12SGeorge Rokos 4624031bb98SShilei Tian DeviceData.resize(NumberOfDevices); 4633de4cd12SGeorge Rokos 4643de4cd12SGeorge Rokos // Get environment variables regarding teams 4654031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_TEAM_LIMIT")) { 4663de4cd12SGeorge Rokos // OMP_TEAM_LIMIT has been set 4674031bb98SShilei Tian EnvTeamLimit = std::stoi(EnvStr); 4683de4cd12SGeorge Rokos DP("Parsed OMP_TEAM_LIMIT=%d\n", EnvTeamLimit); 4693de4cd12SGeorge Rokos } 4704031bb98SShilei Tian if (const char *EnvStr = getenv("OMP_NUM_TEAMS")) { 4713de4cd12SGeorge Rokos // OMP_NUM_TEAMS has been set 4724031bb98SShilei Tian EnvNumTeams = std::stoi(EnvStr); 4733de4cd12SGeorge Rokos DP("Parsed OMP_NUM_TEAMS=%d\n", EnvNumTeams); 4743de4cd12SGeorge Rokos } 475c5fe030cSGheorghe-Teodor Bercea 476feed674dSShilei Tian StreamManager = 4774031bb98SShilei Tian std::make_unique<StreamManagerTy>(NumberOfDevices, DeviceData); 4780871d6d5SShilei Tian 4790871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 4800871d6d5SShilei Tian DeviceAllocators.emplace_back(I, DeviceData); 4810871d6d5SShilei Tian 4820871d6d5SShilei Tian // Get the size threshold from environment variable 4830871d6d5SShilei Tian std::pair<size_t, bool> Res = MemoryManagerTy::getSizeThresholdFromEnv(); 4840871d6d5SShilei Tian UseMemoryManager = Res.second; 4850871d6d5SShilei Tian size_t MemoryManagerThreshold = Res.first; 4860871d6d5SShilei Tian 4870871d6d5SShilei Tian if (UseMemoryManager) 4880871d6d5SShilei Tian for (int I = 0; I < NumberOfDevices; ++I) 4890871d6d5SShilei Tian MemoryManagers.emplace_back(std::make_unique<MemoryManagerTy>( 4900871d6d5SShilei Tian DeviceAllocators[I], MemoryManagerThreshold)); 4913de4cd12SGeorge Rokos } 4923de4cd12SGeorge Rokos 4934031bb98SShilei Tian ~DeviceRTLTy() { 4940871d6d5SShilei Tian // We first destruct memory managers in case that its dependent data are 4950871d6d5SShilei Tian // destroyed before it. 4960871d6d5SShilei Tian for (auto &M : MemoryManagers) 4970871d6d5SShilei Tian M.release(); 4980871d6d5SShilei Tian 499feed674dSShilei Tian StreamManager = nullptr; 500feed674dSShilei Tian 5014031bb98SShilei Tian for (CUmodule &M : Modules) 5024031bb98SShilei Tian // Close module 5034031bb98SShilei Tian if (M) 5044031bb98SShilei Tian checkResult(cuModuleUnload(M), "Error returned from cuModuleUnload\n"); 5054031bb98SShilei Tian 5064031bb98SShilei Tian for (DeviceDataTy &D : DeviceData) { 5074031bb98SShilei Tian // Destroy context 508c5348aecSYe Luo if (D.Context) { 509c5348aecSYe Luo checkResult(cuCtxSetCurrent(D.Context), 510c5348aecSYe Luo "Error returned from cuCtxSetCurrent\n"); 511c5348aecSYe Luo CUdevice Device; 512c5348aecSYe Luo checkResult(cuCtxGetDevice(&Device), 513c5348aecSYe Luo "Error returned from cuCtxGetDevice\n"); 51495f0d1edSJon Chesterfield checkResult(cuDevicePrimaryCtxRelease(Device), 51595f0d1edSJon Chesterfield "Error returned from cuDevicePrimaryCtxRelease\n"); 516c5348aecSYe Luo } 5173de4cd12SGeorge Rokos } 5183de4cd12SGeorge Rokos } 5193de4cd12SGeorge Rokos 5204031bb98SShilei Tian // Check whether a given DeviceId is valid 5214031bb98SShilei Tian bool isValidDeviceId(const int DeviceId) const { 5224031bb98SShilei Tian return DeviceId >= 0 && DeviceId < NumberOfDevices; 52332ed2927SShilei Tian } 52432ed2927SShilei Tian 525cb038927SShilei Tian int getNumOfDevices() const { return NumberOfDevices; } 5264031bb98SShilei Tian 5274031bb98SShilei Tian void setRequiresFlag(const int64_t Flags) { this->RequiresFlags = Flags; } 5284031bb98SShilei Tian 5294031bb98SShilei Tian int initDevice(const int DeviceId) { 5304031bb98SShilei Tian CUdevice Device; 5314031bb98SShilei Tian 5324031bb98SShilei Tian DP("Getting device %d\n", DeviceId); 5334031bb98SShilei Tian CUresult Err = cuDeviceGet(&Device, DeviceId); 5344031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuDeviceGet\n")) 53532ed2927SShilei Tian return OFFLOAD_FAIL; 5363de4cd12SGeorge Rokos 537c5348aecSYe Luo // Query the current flags of the primary context and set its flags if 538c5348aecSYe Luo // it is inactive 539c5348aecSYe Luo unsigned int FormerPrimaryCtxFlags = 0; 540c5348aecSYe Luo int FormerPrimaryCtxIsActive = 0; 541c5348aecSYe Luo Err = cuDevicePrimaryCtxGetState(Device, &FormerPrimaryCtxFlags, 542c5348aecSYe Luo &FormerPrimaryCtxIsActive); 543c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxGetState\n")) 544c5348aecSYe Luo return OFFLOAD_FAIL; 545c5348aecSYe Luo 546c5348aecSYe Luo if (FormerPrimaryCtxIsActive) { 547c5348aecSYe Luo DP("The primary context is active, no change to its flags\n"); 548c5348aecSYe Luo if ((FormerPrimaryCtxFlags & CU_CTX_SCHED_MASK) != 549c5348aecSYe Luo CU_CTX_SCHED_BLOCKING_SYNC) 550c5348aecSYe Luo DP("Warning the current flags are not CU_CTX_SCHED_BLOCKING_SYNC\n"); 551c5348aecSYe Luo } else { 552c5348aecSYe Luo DP("The primary context is inactive, set its flags to " 553c5348aecSYe Luo "CU_CTX_SCHED_BLOCKING_SYNC\n"); 55495f0d1edSJon Chesterfield Err = cuDevicePrimaryCtxSetFlags(Device, CU_CTX_SCHED_BLOCKING_SYNC); 55595f0d1edSJon Chesterfield if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxSetFlags\n")) 556c5348aecSYe Luo return OFFLOAD_FAIL; 557c5348aecSYe Luo } 558c5348aecSYe Luo 559c5348aecSYe Luo // Retain the per device primary context and save it to use whenever this 560c5348aecSYe Luo // device is selected. 561c5348aecSYe Luo Err = cuDevicePrimaryCtxRetain(&DeviceData[DeviceId].Context, Device); 562c5348aecSYe Luo if (!checkResult(Err, "Error returned from cuDevicePrimaryCtxRetain\n")) 5633de4cd12SGeorge Rokos return OFFLOAD_FAIL; 5643de4cd12SGeorge Rokos 5654031bb98SShilei Tian Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 5664031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 5674031bb98SShilei Tian return OFFLOAD_FAIL; 568a5153dbcSJohannes Doerfert 569feed674dSShilei Tian // Initialize stream pool 5704031bb98SShilei Tian if (!StreamManager->initializeDeviceStreamPool(DeviceId)) 5714031bb98SShilei Tian return OFFLOAD_FAIL; 572a5153dbcSJohannes Doerfert 573bb51d398SJonas Hahnfeld // Query attributes to determine number of threads/block and blocks/grid. 5744031bb98SShilei Tian int MaxGridDimX; 5754031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxGridDimX, CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X, 5764031bb98SShilei Tian Device); 5774031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 5784031bb98SShilei Tian DP("Error getting max grid dimension, use default value %d\n", 5794031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 5804031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::DefaultNumTeams; 5814031bb98SShilei Tian } else if (MaxGridDimX <= DeviceRTLTy::HardTeamLimit) { 5824031bb98SShilei Tian DP("Using %d CUDA blocks per grid\n", MaxGridDimX); 5834031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = MaxGridDimX; 5843de4cd12SGeorge Rokos } else { 5853de4cd12SGeorge Rokos DP("Max CUDA blocks per grid %d exceeds the hard team limit %d, capping " 586bb51d398SJonas Hahnfeld "at the hard limit\n", 5874031bb98SShilei Tian MaxGridDimX, DeviceRTLTy::HardTeamLimit); 5884031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = DeviceRTLTy::HardTeamLimit; 5893de4cd12SGeorge Rokos } 5903de4cd12SGeorge Rokos 591bb51d398SJonas Hahnfeld // We are only exploiting threads along the x axis. 5924031bb98SShilei Tian int MaxBlockDimX; 5934031bb98SShilei Tian Err = cuDeviceGetAttribute(&MaxBlockDimX, 5944031bb98SShilei Tian CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X, Device); 5954031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 5964031bb98SShilei Tian DP("Error getting max block dimension, use default value %d\n", 5974031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 5984031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::DefaultNumThreads; 5994031bb98SShilei Tian } else if (MaxBlockDimX <= DeviceRTLTy::HardThreadLimit) { 6004031bb98SShilei Tian DP("Using %d CUDA threads per block\n", MaxBlockDimX); 6014031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = MaxBlockDimX; 6023de4cd12SGeorge Rokos } else { 6034031bb98SShilei Tian DP("Max CUDA threads per block %d exceeds the hard thread limit %d, " 6044031bb98SShilei Tian "capping at the hard limit\n", 6054031bb98SShilei Tian MaxBlockDimX, DeviceRTLTy::HardThreadLimit); 6064031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock = DeviceRTLTy::HardThreadLimit; 6073de4cd12SGeorge Rokos } 6083de4cd12SGeorge Rokos 6094031bb98SShilei Tian // Get and set warp size 6104031bb98SShilei Tian int WarpSize; 6114031bb98SShilei Tian Err = 6124031bb98SShilei Tian cuDeviceGetAttribute(&WarpSize, CU_DEVICE_ATTRIBUTE_WARP_SIZE, Device); 6134031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 6144031bb98SShilei Tian DP("Error getting warp size, assume default value 32\n"); 6154031bb98SShilei Tian DeviceData[DeviceId].WarpSize = 32; 616bb51d398SJonas Hahnfeld } else { 6174031bb98SShilei Tian DP("Using warp size %d\n", WarpSize); 6184031bb98SShilei Tian DeviceData[DeviceId].WarpSize = WarpSize; 6193de4cd12SGeorge Rokos } 6203de4cd12SGeorge Rokos 6213de4cd12SGeorge Rokos // Adjust teams to the env variables 6224031bb98SShilei Tian if (EnvTeamLimit > 0 && DeviceData[DeviceId].BlocksPerGrid > EnvTeamLimit) { 6233de4cd12SGeorge Rokos DP("Capping max CUDA blocks per grid to OMP_TEAM_LIMIT=%d\n", 6244031bb98SShilei Tian EnvTeamLimit); 6254031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid = EnvTeamLimit; 6263de4cd12SGeorge Rokos } 6273de4cd12SGeorge Rokos 628119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 629ae209397SJoseph Huber "Device supports up to %d CUDA blocks and %d threads with a " 630ae209397SJoseph Huber "warp size of %d\n", 631ae209397SJoseph Huber DeviceData[DeviceId].BlocksPerGrid, 632ae209397SJoseph Huber DeviceData[DeviceId].ThreadsPerBlock, DeviceData[DeviceId].WarpSize); 6333de4cd12SGeorge Rokos 6343de4cd12SGeorge Rokos // Set default number of teams 6354031bb98SShilei Tian if (EnvNumTeams > 0) { 6363de4cd12SGeorge Rokos DP("Default number of teams set according to environment %d\n", 6374031bb98SShilei Tian EnvNumTeams); 6384031bb98SShilei Tian DeviceData[DeviceId].NumTeams = EnvNumTeams; 6393de4cd12SGeorge Rokos } else { 6404031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceRTLTy::DefaultNumTeams; 6413de4cd12SGeorge Rokos DP("Default number of teams set according to library's default %d\n", 6424031bb98SShilei Tian DeviceRTLTy::DefaultNumTeams); 6433de4cd12SGeorge Rokos } 6444031bb98SShilei Tian 6454031bb98SShilei Tian if (DeviceData[DeviceId].NumTeams > DeviceData[DeviceId].BlocksPerGrid) { 6463de4cd12SGeorge Rokos DP("Default number of teams exceeds device limit, capping at %d\n", 6474031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 6484031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].BlocksPerGrid; 6493de4cd12SGeorge Rokos } 6503de4cd12SGeorge Rokos 6513de4cd12SGeorge Rokos // Set default number of threads 6524031bb98SShilei Tian DeviceData[DeviceId].NumThreads = DeviceRTLTy::DefaultNumThreads; 6533de4cd12SGeorge Rokos DP("Default number of threads set according to library's default %d\n", 6544031bb98SShilei Tian DeviceRTLTy::DefaultNumThreads); 6554031bb98SShilei Tian if (DeviceData[DeviceId].NumThreads > 6564031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock) { 6573de4cd12SGeorge Rokos DP("Default number of threads exceeds device limit, capping at %d\n", 6584031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 6594031bb98SShilei Tian DeviceData[DeviceId].NumTeams = DeviceData[DeviceId].ThreadsPerBlock; 6603de4cd12SGeorge Rokos } 6613de4cd12SGeorge Rokos 6623de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 6633de4cd12SGeorge Rokos } 6643de4cd12SGeorge Rokos 6654031bb98SShilei Tian __tgt_target_table *loadBinary(const int DeviceId, 6664031bb98SShilei Tian const __tgt_device_image *Image) { 6674031bb98SShilei Tian // Set the context we are using 6684031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 6694031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 6704031bb98SShilei Tian return nullptr; 6713de4cd12SGeorge Rokos 6723de4cd12SGeorge Rokos // Clear the offload table as we are going to create a new one. 6734031bb98SShilei Tian clearOffloadEntriesTable(DeviceId); 6743de4cd12SGeorge Rokos 6753de4cd12SGeorge Rokos // Create the module and extract the function pointers. 6764031bb98SShilei Tian CUmodule Module; 6774031bb98SShilei Tian DP("Load data from image " DPxMOD "\n", DPxPTR(Image->ImageStart)); 6784031bb98SShilei Tian Err = cuModuleLoadDataEx(&Module, Image->ImageStart, 0, nullptr, nullptr); 6794031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuModuleLoadDataEx\n")) 6804031bb98SShilei Tian return nullptr; 6813de4cd12SGeorge Rokos 6823de4cd12SGeorge Rokos DP("CUDA module successfully loaded!\n"); 6834031bb98SShilei Tian 6844031bb98SShilei Tian Modules.push_back(Module); 6853de4cd12SGeorge Rokos 6863de4cd12SGeorge Rokos // Find the symbols in the module by name. 6874031bb98SShilei Tian const __tgt_offload_entry *HostBegin = Image->EntriesBegin; 6884031bb98SShilei Tian const __tgt_offload_entry *HostEnd = Image->EntriesEnd; 6893de4cd12SGeorge Rokos 6905272d29eSJohannes Doerfert std::list<KernelTy> &KernelsList = DeviceData[DeviceId].KernelsList; 6914031bb98SShilei Tian for (const __tgt_offload_entry *E = HostBegin; E != HostEnd; ++E) { 6924031bb98SShilei Tian if (!E->addr) { 6934031bb98SShilei Tian // We return nullptr when something like this happens, the host should 6944031bb98SShilei Tian // have always something in the address to uniquely identify the target 6954031bb98SShilei Tian // region. 6964031bb98SShilei Tian DP("Invalid binary: host entry '<null>' (size = %zd)...\n", E->size); 6974031bb98SShilei Tian return nullptr; 6983de4cd12SGeorge Rokos } 6993de4cd12SGeorge Rokos 7004031bb98SShilei Tian if (E->size) { 7014031bb98SShilei Tian __tgt_offload_entry Entry = *E; 7024031bb98SShilei Tian CUdeviceptr CUPtr; 7034031bb98SShilei Tian size_t CUSize; 70495f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&CUPtr, &CUSize, Module, E->name); 7054031bb98SShilei Tian // We keep this style here because we need the name 7064031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7072ce16810SJoseph Huber REPORT("Loading global '%s' Failed\n", E->name); 7084031bb98SShilei Tian CUDA_ERR_STRING(Err); 7094031bb98SShilei Tian return nullptr; 7103de4cd12SGeorge Rokos } 7113de4cd12SGeorge Rokos 7124031bb98SShilei Tian if (CUSize != E->size) { 7134031bb98SShilei Tian DP("Loading global '%s' - size mismatch (%zd != %zd)\n", E->name, 7144031bb98SShilei Tian CUSize, E->size); 7154031bb98SShilei Tian return nullptr; 7163de4cd12SGeorge Rokos } 7173de4cd12SGeorge Rokos 7183de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n", 7194031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(CUPtr)); 7204031bb98SShilei Tian 7214031bb98SShilei Tian Entry.addr = (void *)(CUPtr); 7223de4cd12SGeorge Rokos 723aace6d28SGheorghe-Teodor Bercea // Note: In the current implementation declare target variables 724aace6d28SGheorghe-Teodor Bercea // can either be link or to. This means that once unified 725aace6d28SGheorghe-Teodor Bercea // memory is activated via the requires directive, the variable 726aace6d28SGheorghe-Teodor Bercea // can be used directly from the host in both cases. 727aace6d28SGheorghe-Teodor Bercea // TODO: when variables types other than to or link are added, 7284c6a098aSKazuaki Ishizaki // the below condition should be changed to explicitly 729aace6d28SGheorghe-Teodor Bercea // check for to and link variables types: 7304031bb98SShilei Tian // (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && (e->flags & 7314031bb98SShilei Tian // OMP_DECLARE_TARGET_LINK || e->flags == OMP_DECLARE_TARGET_TO)) 7324031bb98SShilei Tian if (RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY) { 733aace6d28SGheorghe-Teodor Bercea // If unified memory is present any target link or to variables 734c5fe030cSGheorghe-Teodor Bercea // can access host addresses directly. There is no longer a 735c5fe030cSGheorghe-Teodor Bercea // need for device copies. 73695f0d1edSJon Chesterfield cuMemcpyHtoD(CUPtr, E->addr, sizeof(void *)); 7374031bb98SShilei Tian DP("Copy linked variable host address (" DPxMOD 7384031bb98SShilei Tian ") to device address (" DPxMOD ")\n", 7394031bb98SShilei Tian DPxPTR(*((void **)E->addr)), DPxPTR(CUPtr)); 740c5fe030cSGheorghe-Teodor Bercea } 741c5fe030cSGheorghe-Teodor Bercea 7424031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 7433de4cd12SGeorge Rokos 7443de4cd12SGeorge Rokos continue; 7453de4cd12SGeorge Rokos } 7463de4cd12SGeorge Rokos 7474031bb98SShilei Tian CUfunction Func; 7484031bb98SShilei Tian Err = cuModuleGetFunction(&Func, Module, E->name); 7494031bb98SShilei Tian // We keep this style here because we need the name 7504031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7512ce16810SJoseph Huber REPORT("Loading '%s' Failed\n", E->name); 7524031bb98SShilei Tian CUDA_ERR_STRING(Err); 7534031bb98SShilei Tian return nullptr; 7543de4cd12SGeorge Rokos } 7553de4cd12SGeorge Rokos 7563de4cd12SGeorge Rokos DP("Entry point " DPxMOD " maps to %s (" DPxMOD ")\n", 7574031bb98SShilei Tian DPxPTR(E - HostBegin), E->name, DPxPTR(Func)); 7583de4cd12SGeorge Rokos 7593de4cd12SGeorge Rokos // default value GENERIC (in case symbol is missing from cubin file) 7603de4cd12SGeorge Rokos int8_t ExecModeVal = ExecutionModeType::GENERIC; 7614031bb98SShilei Tian std::string ExecModeNameStr(E->name); 7623de4cd12SGeorge Rokos ExecModeNameStr += "_exec_mode"; 7633de4cd12SGeorge Rokos const char *ExecModeName = ExecModeNameStr.c_str(); 7643de4cd12SGeorge Rokos 7653de4cd12SGeorge Rokos CUdeviceptr ExecModePtr; 7664031bb98SShilei Tian size_t CUSize; 76795f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&ExecModePtr, &CUSize, Module, ExecModeName); 7684031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 7694031bb98SShilei Tian if (CUSize != sizeof(int8_t)) { 7703de4cd12SGeorge Rokos DP("Loading global exec_mode '%s' - size mismatch (%zd != %zd)\n", 7714031bb98SShilei Tian ExecModeName, CUSize, sizeof(int8_t)); 7724031bb98SShilei Tian return nullptr; 7733de4cd12SGeorge Rokos } 7743de4cd12SGeorge Rokos 77595f0d1edSJon Chesterfield Err = cuMemcpyDtoH(&ExecModeVal, ExecModePtr, CUSize); 7764031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 7772ce16810SJoseph Huber REPORT("Error when copying data from device to host. Pointers: " 7783de4cd12SGeorge Rokos "host = " DPxMOD ", device = " DPxMOD ", size = %zd\n", 7794031bb98SShilei Tian DPxPTR(&ExecModeVal), DPxPTR(ExecModePtr), CUSize); 7804031bb98SShilei Tian CUDA_ERR_STRING(Err); 7814031bb98SShilei Tian return nullptr; 7823de4cd12SGeorge Rokos } 7833de4cd12SGeorge Rokos 7843de4cd12SGeorge Rokos if (ExecModeVal < 0 || ExecModeVal > 1) { 7853de4cd12SGeorge Rokos DP("Error wrong exec_mode value specified in cubin file: %d\n", 7863de4cd12SGeorge Rokos ExecModeVal); 7874031bb98SShilei Tian return nullptr; 7883de4cd12SGeorge Rokos } 7893de4cd12SGeorge Rokos } else { 7902ce16810SJoseph Huber REPORT("Loading global exec_mode '%s' - symbol missing, using default " 7914031bb98SShilei Tian "value GENERIC (1)\n", 7924031bb98SShilei Tian ExecModeName); 7934031bb98SShilei Tian CUDA_ERR_STRING(Err); 7943de4cd12SGeorge Rokos } 7953de4cd12SGeorge Rokos 7964031bb98SShilei Tian KernelsList.emplace_back(Func, ExecModeVal); 7973de4cd12SGeorge Rokos 7984031bb98SShilei Tian __tgt_offload_entry Entry = *E; 7994031bb98SShilei Tian Entry.addr = &KernelsList.back(); 8004031bb98SShilei Tian addOffloadEntry(DeviceId, Entry); 8013de4cd12SGeorge Rokos } 8023de4cd12SGeorge Rokos 803e1c7a46dSGuansong Zhang // send device environment data to the device 804e1c7a46dSGuansong Zhang { 8054031bb98SShilei Tian omptarget_device_environmentTy DeviceEnv{0}; 806e1c7a46dSGuansong Zhang 807e1c7a46dSGuansong Zhang #ifdef OMPTARGET_DEBUG 8084031bb98SShilei Tian if (const char *EnvStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) 8094031bb98SShilei Tian DeviceEnv.debug_level = std::stoi(EnvStr); 810e1c7a46dSGuansong Zhang #endif 811e1c7a46dSGuansong Zhang 8124031bb98SShilei Tian const char *DeviceEnvName = "omptarget_device_environment"; 8134031bb98SShilei Tian CUdeviceptr DeviceEnvPtr; 8144031bb98SShilei Tian size_t CUSize; 815e1c7a46dSGuansong Zhang 81695f0d1edSJon Chesterfield Err = cuModuleGetGlobal(&DeviceEnvPtr, &CUSize, Module, DeviceEnvName); 8174031bb98SShilei Tian if (Err == CUDA_SUCCESS) { 8184031bb98SShilei Tian if (CUSize != sizeof(DeviceEnv)) { 8192ce16810SJoseph Huber REPORT( 8202ce16810SJoseph Huber "Global device_environment '%s' - size mismatch (%zu != %zu)\n", 8214031bb98SShilei Tian DeviceEnvName, CUSize, sizeof(int32_t)); 8224031bb98SShilei Tian CUDA_ERR_STRING(Err); 8234031bb98SShilei Tian return nullptr; 824e1c7a46dSGuansong Zhang } 825e1c7a46dSGuansong Zhang 82695f0d1edSJon Chesterfield Err = cuMemcpyHtoD(DeviceEnvPtr, &DeviceEnv, CUSize); 8274031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 8282ce16810SJoseph Huber REPORT("Error when copying data from host to device. Pointers: " 829e1c7a46dSGuansong Zhang "host = " DPxMOD ", device = " DPxMOD ", size = %zu\n", 8304031bb98SShilei Tian DPxPTR(&DeviceEnv), DPxPTR(DeviceEnvPtr), CUSize); 8314031bb98SShilei Tian CUDA_ERR_STRING(Err); 8324031bb98SShilei Tian return nullptr; 833e1c7a46dSGuansong Zhang } 834e1c7a46dSGuansong Zhang 8354031bb98SShilei Tian DP("Sending global device environment data %zu bytes\n", CUSize); 836e1c7a46dSGuansong Zhang } else { 8374031bb98SShilei Tian DP("Finding global device environment '%s' - symbol missing.\n", 8384031bb98SShilei Tian DeviceEnvName); 8394031bb98SShilei Tian DP("Continue, considering this is a device RTL which does not accept " 8404031bb98SShilei Tian "environment setting.\n"); 841e1c7a46dSGuansong Zhang } 842e1c7a46dSGuansong Zhang } 843e1c7a46dSGuansong Zhang 8444031bb98SShilei Tian return getOffloadEntriesTable(DeviceId); 8453de4cd12SGeorge Rokos } 8463de4cd12SGeorge Rokos 847*a15f8589SJoseph Huber void *dataAlloc(const int DeviceId, const int64_t Size, 848*a15f8589SJoseph Huber const TargetAllocTy Kind) { 849*a15f8589SJoseph Huber switch (Kind) { 850*a15f8589SJoseph Huber case TARGET_ALLOC_DEFAULT: 851*a15f8589SJoseph Huber case TARGET_ALLOC_DEVICE: 8520871d6d5SShilei Tian if (UseMemoryManager) 8530871d6d5SShilei Tian return MemoryManagers[DeviceId]->allocate(Size, nullptr); 854*a15f8589SJoseph Huber else 855*a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 856*a15f8589SJoseph Huber case TARGET_ALLOC_HOST: 857*a15f8589SJoseph Huber case TARGET_ALLOC_SHARED: 858*a15f8589SJoseph Huber return DeviceAllocators[DeviceId].allocate(Size, nullptr, Kind); 859*a15f8589SJoseph Huber } 8604031bb98SShilei Tian 861*a15f8589SJoseph Huber REPORT("Invalid target data allocation kind or requested allocator not " 862*a15f8589SJoseph Huber "implemented yet\n"); 863*a15f8589SJoseph Huber 864*a15f8589SJoseph Huber return nullptr; 8653de4cd12SGeorge Rokos } 8663de4cd12SGeorge Rokos 8674031bb98SShilei Tian int dataSubmit(const int DeviceId, const void *TgtPtr, const void *HstPtr, 8685449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 8695449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 8703de4cd12SGeorge Rokos 8714031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 8724031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 8733de4cd12SGeorge Rokos return OFFLOAD_FAIL; 8743de4cd12SGeorge Rokos 8755449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 8763de4cd12SGeorge Rokos 87795f0d1edSJon Chesterfield Err = cuMemcpyHtoDAsync((CUdeviceptr)TgtPtr, HstPtr, Size, Stream); 8784031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 87929338459SJoseph Huber DP("Error when copying data from host to device. Pointers: host " 8802ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n", 8814031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size); 8824031bb98SShilei Tian CUDA_ERR_STRING(Err); 8833de4cd12SGeorge Rokos return OFFLOAD_FAIL; 8843de4cd12SGeorge Rokos } 8853de4cd12SGeorge Rokos 8863de4cd12SGeorge Rokos return OFFLOAD_SUCCESS; 8873de4cd12SGeorge Rokos } 8883de4cd12SGeorge Rokos 8894031bb98SShilei Tian int dataRetrieve(const int DeviceId, void *HstPtr, const void *TgtPtr, 8905449fbb5SJohannes Doerfert const int64_t Size, __tgt_async_info *AsyncInfo) const { 8915449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 8924031bb98SShilei Tian 8934031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 8944031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 89503ff643dSShilei Tian return OFFLOAD_FAIL; 89603ff643dSShilei Tian 8975449fbb5SJohannes Doerfert CUstream Stream = getStream(DeviceId, AsyncInfo); 89803ff643dSShilei Tian 89995f0d1edSJon Chesterfield Err = cuMemcpyDtoHAsync(HstPtr, (CUdeviceptr)TgtPtr, Size, Stream); 9004031bb98SShilei Tian if (Err != CUDA_SUCCESS) { 90129338459SJoseph Huber DP("Error when copying data from device to host. Pointers: host " 9022ce16810SJoseph Huber "= " DPxMOD ", device = " DPxMOD ", size = %" PRId64 "\n", 9034031bb98SShilei Tian DPxPTR(HstPtr), DPxPTR(TgtPtr), Size); 9044031bb98SShilei Tian CUDA_ERR_STRING(Err); 9053de4cd12SGeorge Rokos return OFFLOAD_FAIL; 9063de4cd12SGeorge Rokos } 9073de4cd12SGeorge Rokos 9084031bb98SShilei Tian return OFFLOAD_SUCCESS; 9094031bb98SShilei Tian } 9104031bb98SShilei Tian 911a014fbbcSShilei Tian int dataExchange(int SrcDevId, const void *SrcPtr, int DstDevId, void *DstPtr, 9125449fbb5SJohannes Doerfert int64_t Size, __tgt_async_info *AsyncInfo) const { 9135449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 914a014fbbcSShilei Tian 915a014fbbcSShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[SrcDevId].Context); 916a014fbbcSShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 917a014fbbcSShilei Tian return OFFLOAD_FAIL; 918a014fbbcSShilei Tian 9195449fbb5SJohannes Doerfert CUstream Stream = getStream(SrcDevId, AsyncInfo); 920a014fbbcSShilei Tian 921a014fbbcSShilei Tian // If they are two devices, we try peer to peer copy first 922a014fbbcSShilei Tian if (SrcDevId != DstDevId) { 923a014fbbcSShilei Tian int CanAccessPeer = 0; 924a014fbbcSShilei Tian Err = cuDeviceCanAccessPeer(&CanAccessPeer, SrcDevId, DstDevId); 925a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 9262ce16810SJoseph Huber REPORT("Error returned from cuDeviceCanAccessPeer. src = %" PRId32 927a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 928a014fbbcSShilei Tian SrcDevId, DstDevId); 929a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 930a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 931a014fbbcSShilei Tian } 932a014fbbcSShilei Tian 933a014fbbcSShilei Tian if (!CanAccessPeer) { 934a014fbbcSShilei Tian DP("P2P memcpy not supported so fall back to D2D memcpy"); 935a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 936a014fbbcSShilei Tian } 937a014fbbcSShilei Tian 938a014fbbcSShilei Tian Err = cuCtxEnablePeerAccess(DeviceData[DstDevId].Context, 0); 939a014fbbcSShilei Tian if (Err != CUDA_SUCCESS) { 9402ce16810SJoseph Huber REPORT("Error returned from cuCtxEnablePeerAccess. src = %" PRId32 941a014fbbcSShilei Tian ", dst = %" PRId32 "\n", 942a014fbbcSShilei Tian SrcDevId, DstDevId); 943a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 944a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 945a014fbbcSShilei Tian } 946a014fbbcSShilei Tian 947a014fbbcSShilei Tian Err = cuMemcpyPeerAsync((CUdeviceptr)DstPtr, DeviceData[DstDevId].Context, 948a014fbbcSShilei Tian (CUdeviceptr)SrcPtr, DeviceData[SrcDevId].Context, 949a014fbbcSShilei Tian Size, Stream); 950a014fbbcSShilei Tian if (Err == CUDA_SUCCESS) 951a014fbbcSShilei Tian return OFFLOAD_SUCCESS; 952a014fbbcSShilei Tian 95329338459SJoseph Huber DP("Error returned from cuMemcpyPeerAsync. src_ptr = " DPxMOD 95429338459SJoseph Huber ", src_id =%" PRId32 ", dst_ptr = " DPxMOD ", dst_id =%" PRId32 "\n", 95545bb073dSYe Luo DPxPTR(SrcPtr), SrcDevId, DPxPTR(DstPtr), DstDevId); 956a014fbbcSShilei Tian CUDA_ERR_STRING(Err); 957a014fbbcSShilei Tian } 958a014fbbcSShilei Tian 959a014fbbcSShilei Tian return memcpyDtoD(SrcPtr, DstPtr, Size, Stream); 960a014fbbcSShilei Tian } 961a014fbbcSShilei Tian 9620871d6d5SShilei Tian int dataDelete(const int DeviceId, void *TgtPtr) { 9630871d6d5SShilei Tian if (UseMemoryManager) 9640871d6d5SShilei Tian return MemoryManagers[DeviceId]->free(TgtPtr); 9654031bb98SShilei Tian 9660871d6d5SShilei Tian return DeviceAllocators[DeviceId].free(TgtPtr); 9674031bb98SShilei Tian } 9684031bb98SShilei Tian 969aa27cfc1SJohannes Doerfert int runTargetTeamRegion(const int DeviceId, void *TgtEntryPtr, void **TgtArgs, 970aa27cfc1SJohannes Doerfert ptrdiff_t *TgtOffsets, const int ArgNum, 971aa27cfc1SJohannes Doerfert const int TeamNum, const int ThreadLimit, 9724031bb98SShilei Tian const unsigned int LoopTripCount, 9734031bb98SShilei Tian __tgt_async_info *AsyncInfo) const { 9744031bb98SShilei Tian CUresult Err = cuCtxSetCurrent(DeviceData[DeviceId].Context); 9754031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuCtxSetCurrent\n")) 9764031bb98SShilei Tian return OFFLOAD_FAIL; 9774031bb98SShilei Tian 9783de4cd12SGeorge Rokos // All args are references. 9794031bb98SShilei Tian std::vector<void *> Args(ArgNum); 9804031bb98SShilei Tian std::vector<void *> Ptrs(ArgNum); 9813de4cd12SGeorge Rokos 9824031bb98SShilei Tian for (int I = 0; I < ArgNum; ++I) { 9834031bb98SShilei Tian Ptrs[I] = (void *)((intptr_t)TgtArgs[I] + TgtOffsets[I]); 9844031bb98SShilei Tian Args[I] = &Ptrs[I]; 9851546d319SGeorge Rokos } 9863de4cd12SGeorge Rokos 987aa27cfc1SJohannes Doerfert KernelTy *KernelInfo = reinterpret_cast<KernelTy *>(TgtEntryPtr); 9883de4cd12SGeorge Rokos 989aa27cfc1SJohannes Doerfert int CudaThreadsPerBlock; 9904031bb98SShilei Tian if (ThreadLimit > 0) { 9914031bb98SShilei Tian DP("Setting CUDA threads per block to requested %d\n", ThreadLimit); 9924031bb98SShilei Tian CudaThreadsPerBlock = ThreadLimit; 9933de4cd12SGeorge Rokos // Add master warp if necessary 9943de4cd12SGeorge Rokos if (KernelInfo->ExecutionMode == GENERIC) { 9954031bb98SShilei Tian DP("Adding master warp: +%d threads\n", DeviceData[DeviceId].WarpSize); 9964031bb98SShilei Tian CudaThreadsPerBlock += DeviceData[DeviceId].WarpSize; 9973de4cd12SGeorge Rokos } 998c13df8e5SGeorge Rokos } else { 999c13df8e5SGeorge Rokos DP("Setting CUDA threads per block to default %d\n", 10004031bb98SShilei Tian DeviceData[DeviceId].NumThreads); 10014031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].NumThreads; 1002c13df8e5SGeorge Rokos } 10033de4cd12SGeorge Rokos 10044031bb98SShilei Tian if (CudaThreadsPerBlock > DeviceData[DeviceId].ThreadsPerBlock) { 10053de4cd12SGeorge Rokos DP("Threads per block capped at device limit %d\n", 10064031bb98SShilei Tian DeviceData[DeviceId].ThreadsPerBlock); 10074031bb98SShilei Tian CudaThreadsPerBlock = DeviceData[DeviceId].ThreadsPerBlock; 10083de4cd12SGeorge Rokos } 10093de4cd12SGeorge Rokos 1010aa27cfc1SJohannes Doerfert if (!KernelInfo->MaxThreadsPerBlock) { 1011aa27cfc1SJohannes Doerfert Err = cuFuncGetAttribute(&KernelInfo->MaxThreadsPerBlock, 10124031bb98SShilei Tian CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, 10134031bb98SShilei Tian KernelInfo->Func); 1014aa27cfc1SJohannes Doerfert if (!checkResult(Err, "Error returned from cuFuncGetAttribute\n")) 1015aa27cfc1SJohannes Doerfert return OFFLOAD_FAIL; 1016aa27cfc1SJohannes Doerfert } 1017aa27cfc1SJohannes Doerfert 1018aa27cfc1SJohannes Doerfert if (KernelInfo->MaxThreadsPerBlock < CudaThreadsPerBlock) { 1019aa27cfc1SJohannes Doerfert DP("Threads per block capped at kernel limit %d\n", 1020aa27cfc1SJohannes Doerfert KernelInfo->MaxThreadsPerBlock); 1021aa27cfc1SJohannes Doerfert CudaThreadsPerBlock = KernelInfo->MaxThreadsPerBlock; 10223de4cd12SGeorge Rokos } 10233de4cd12SGeorge Rokos 10244031bb98SShilei Tian unsigned int CudaBlocksPerGrid; 10254031bb98SShilei Tian if (TeamNum <= 0) { 10264031bb98SShilei Tian if (LoopTripCount > 0 && EnvNumTeams < 0) { 1027c13df8e5SGeorge Rokos if (KernelInfo->ExecutionMode == SPMD) { 10284031bb98SShilei Tian // We have a combined construct, i.e. `target teams distribute 10294031bb98SShilei Tian // parallel for [simd]`. We launch so many teams so that each thread 10304031bb98SShilei Tian // will execute one iteration of the loop. round up to the nearest 10314031bb98SShilei Tian // integer 10324031bb98SShilei Tian CudaBlocksPerGrid = ((LoopTripCount - 1) / CudaThreadsPerBlock) + 1; 1033c13df8e5SGeorge Rokos } else { 1034c13df8e5SGeorge Rokos // If we reach this point, then we have a non-combined construct, i.e. 1035c13df8e5SGeorge Rokos // `teams distribute` with a nested `parallel for` and each team is 1036c13df8e5SGeorge Rokos // assigned one iteration of the `distribute` loop. E.g.: 1037c13df8e5SGeorge Rokos // 1038c13df8e5SGeorge Rokos // #pragma omp target teams distribute 1039c13df8e5SGeorge Rokos // for(...loop_tripcount...) { 1040c13df8e5SGeorge Rokos // #pragma omp parallel for 1041c13df8e5SGeorge Rokos // for(...) {} 1042c13df8e5SGeorge Rokos // } 1043c13df8e5SGeorge Rokos // 1044c13df8e5SGeorge Rokos // Threads within a team will execute the iterations of the `parallel` 1045c13df8e5SGeorge Rokos // loop. 10464031bb98SShilei Tian CudaBlocksPerGrid = LoopTripCount; 1047c13df8e5SGeorge Rokos } 104845bb073dSYe Luo DP("Using %d teams due to loop trip count %" PRIu32 10494031bb98SShilei Tian " and number of threads per block %d\n", 10504031bb98SShilei Tian CudaBlocksPerGrid, LoopTripCount, CudaThreadsPerBlock); 10513de4cd12SGeorge Rokos } else { 10524031bb98SShilei Tian DP("Using default number of teams %d\n", DeviceData[DeviceId].NumTeams); 10534031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].NumTeams; 10543de4cd12SGeorge Rokos } 10554031bb98SShilei Tian } else if (TeamNum > DeviceData[DeviceId].BlocksPerGrid) { 10563de4cd12SGeorge Rokos DP("Capping number of teams to team limit %d\n", 10574031bb98SShilei Tian DeviceData[DeviceId].BlocksPerGrid); 10584031bb98SShilei Tian CudaBlocksPerGrid = DeviceData[DeviceId].BlocksPerGrid; 10593de4cd12SGeorge Rokos } else { 10604031bb98SShilei Tian DP("Using requested number of teams %d\n", TeamNum); 10614031bb98SShilei Tian CudaBlocksPerGrid = TeamNum; 10623de4cd12SGeorge Rokos } 10633de4cd12SGeorge Rokos 1064119a9ea1SJoseph Huber INFO(OMP_INFOTYPE_PLUGIN_KERNEL, DeviceId, 1065ae209397SJoseph Huber "Launching kernel %s with %d blocks and %d threads in %s " 1066ae209397SJoseph Huber "mode\n", 1067ae209397SJoseph Huber (getOffloadEntry(DeviceId, TgtEntryPtr)) 1068ae209397SJoseph Huber ? getOffloadEntry(DeviceId, TgtEntryPtr)->name 1069ae209397SJoseph Huber : "(null)", 1070ae209397SJoseph Huber CudaBlocksPerGrid, CudaThreadsPerBlock, 1071ae209397SJoseph Huber (KernelInfo->ExecutionMode == SPMD) ? "SPMD" : "Generic"); 10723de4cd12SGeorge Rokos 10734031bb98SShilei Tian CUstream Stream = getStream(DeviceId, AsyncInfo); 10744031bb98SShilei Tian Err = cuLaunchKernel(KernelInfo->Func, CudaBlocksPerGrid, /* gridDimY */ 1, 10754031bb98SShilei Tian /* gridDimZ */ 1, CudaThreadsPerBlock, 10764031bb98SShilei Tian /* blockDimY */ 1, /* blockDimZ */ 1, 10774031bb98SShilei Tian /* sharedMemBytes */ 0, Stream, &Args[0], nullptr); 10784031bb98SShilei Tian if (!checkResult(Err, "Error returned from cuLaunchKernel\n")) 10794031bb98SShilei Tian return OFFLOAD_FAIL; 10804031bb98SShilei Tian 10814031bb98SShilei Tian DP("Launch of entry point at " DPxMOD " successful!\n", 10824031bb98SShilei Tian DPxPTR(TgtEntryPtr)); 10834031bb98SShilei Tian 10844031bb98SShilei Tian return OFFLOAD_SUCCESS; 10854031bb98SShilei Tian } 10864031bb98SShilei Tian 10875449fbb5SJohannes Doerfert int synchronize(const int DeviceId, __tgt_async_info *AsyncInfo) const { 10885449fbb5SJohannes Doerfert CUstream Stream = reinterpret_cast<CUstream>(AsyncInfo->Queue); 10894031bb98SShilei Tian CUresult Err = cuStreamSynchronize(Stream); 10903de4cd12SGeorge Rokos 10914031bb98SShilei Tian // Once the stream is synchronized, return it to stream pool and reset 10925449fbb5SJohannes Doerfert // AsyncInfo. This is to make sure the synchronization only works for its 10934031bb98SShilei Tian // own tasks. 10945449fbb5SJohannes Doerfert StreamManager->returnStream(DeviceId, 10955449fbb5SJohannes Doerfert reinterpret_cast<CUstream>(AsyncInfo->Queue)); 10965449fbb5SJohannes Doerfert AsyncInfo->Queue = nullptr; 10973de4cd12SGeorge Rokos 109816064e71SJoseph Huber if (Err != CUDA_SUCCESS) { 109929338459SJoseph Huber DP("Error when synchronizing stream. stream = " DPxMOD 110016064e71SJoseph Huber ", async info ptr = " DPxMOD "\n", 110116064e71SJoseph Huber DPxPTR(Stream), DPxPTR(AsyncInfo)); 110216064e71SJoseph Huber CUDA_ERR_STRING(Err); 110316064e71SJoseph Huber } 110416064e71SJoseph Huber return (Err == CUDA_SUCCESS) ? OFFLOAD_SUCCESS : OFFLOAD_FAIL; 11053de4cd12SGeorge Rokos } 11064031bb98SShilei Tian }; 11074031bb98SShilei Tian 11084031bb98SShilei Tian DeviceRTLTy DeviceRTL; 11094031bb98SShilei Tian } // namespace 11104031bb98SShilei Tian 11114031bb98SShilei Tian // Exposed library API function 11124031bb98SShilei Tian #ifdef __cplusplus 11134031bb98SShilei Tian extern "C" { 11144031bb98SShilei Tian #endif 11154031bb98SShilei Tian 11164031bb98SShilei Tian int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) { 11174031bb98SShilei Tian return elf_check_machine(image, /* EM_CUDA */ 190); 11184031bb98SShilei Tian } 11194031bb98SShilei Tian 11204031bb98SShilei Tian int32_t __tgt_rtl_number_of_devices() { return DeviceRTL.getNumOfDevices(); } 11214031bb98SShilei Tian 11224031bb98SShilei Tian int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) { 112340470eb2SGeorge Rokos DP("Init requires flags to %" PRId64 "\n", RequiresFlags); 11244031bb98SShilei Tian DeviceRTL.setRequiresFlag(RequiresFlags); 11254031bb98SShilei Tian return RequiresFlags; 11264031bb98SShilei Tian } 11274031bb98SShilei Tian 1128a014fbbcSShilei Tian int32_t __tgt_rtl_is_data_exchangable(int32_t src_dev_id, int dst_dev_id) { 1129a014fbbcSShilei Tian if (DeviceRTL.isValidDeviceId(src_dev_id) && 1130a014fbbcSShilei Tian DeviceRTL.isValidDeviceId(dst_dev_id)) 1131a014fbbcSShilei Tian return 1; 1132a014fbbcSShilei Tian 1133a014fbbcSShilei Tian return 0; 1134a014fbbcSShilei Tian } 1135a014fbbcSShilei Tian 11364031bb98SShilei Tian int32_t __tgt_rtl_init_device(int32_t device_id) { 11374031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11384031bb98SShilei Tian 11394031bb98SShilei Tian return DeviceRTL.initDevice(device_id); 11404031bb98SShilei Tian } 11414031bb98SShilei Tian 11424031bb98SShilei Tian __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id, 11434031bb98SShilei Tian __tgt_device_image *image) { 11444031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11454031bb98SShilei Tian 11464031bb98SShilei Tian return DeviceRTL.loadBinary(device_id, image); 11474031bb98SShilei Tian } 11484031bb98SShilei Tian 11492468fdd9SGeorge Rokos void *__tgt_rtl_data_alloc(int32_t device_id, int64_t size, void *, 11502468fdd9SGeorge Rokos int32_t kind) { 11514031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11524031bb98SShilei Tian 1153*a15f8589SJoseph Huber return DeviceRTL.dataAlloc(device_id, size, (TargetAllocTy)kind); 11544031bb98SShilei Tian } 11554031bb98SShilei Tian 11564031bb98SShilei Tian int32_t __tgt_rtl_data_submit(int32_t device_id, void *tgt_ptr, void *hst_ptr, 11574031bb98SShilei Tian int64_t size) { 11584031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11594031bb98SShilei Tian 11605449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 11614031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_submit_async(device_id, tgt_ptr, hst_ptr, 11625449fbb5SJohannes Doerfert size, &AsyncInfo); 11634031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 11644031bb98SShilei Tian return OFFLOAD_FAIL; 11654031bb98SShilei Tian 11665449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 11674031bb98SShilei Tian } 11684031bb98SShilei Tian 11694031bb98SShilei Tian int32_t __tgt_rtl_data_submit_async(int32_t device_id, void *tgt_ptr, 11704031bb98SShilei Tian void *hst_ptr, int64_t size, 11714031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 11724031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11734031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 11744031bb98SShilei Tian 11754031bb98SShilei Tian return DeviceRTL.dataSubmit(device_id, tgt_ptr, hst_ptr, size, 11764031bb98SShilei Tian async_info_ptr); 11774031bb98SShilei Tian } 11784031bb98SShilei Tian 11794031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve(int32_t device_id, void *hst_ptr, void *tgt_ptr, 11804031bb98SShilei Tian int64_t size) { 11814031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11824031bb98SShilei Tian 11835449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 11844031bb98SShilei Tian const int32_t rc = __tgt_rtl_data_retrieve_async(device_id, hst_ptr, tgt_ptr, 11855449fbb5SJohannes Doerfert size, &AsyncInfo); 11864031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 11874031bb98SShilei Tian return OFFLOAD_FAIL; 11884031bb98SShilei Tian 11895449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 11904031bb98SShilei Tian } 11914031bb98SShilei Tian 11924031bb98SShilei Tian int32_t __tgt_rtl_data_retrieve_async(int32_t device_id, void *hst_ptr, 11934031bb98SShilei Tian void *tgt_ptr, int64_t size, 11944031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 11954031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 11964031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 11974031bb98SShilei Tian 11984031bb98SShilei Tian return DeviceRTL.dataRetrieve(device_id, hst_ptr, tgt_ptr, size, 11994031bb98SShilei Tian async_info_ptr); 12004031bb98SShilei Tian } 12014031bb98SShilei Tian 1202a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange_async(int32_t src_dev_id, void *src_ptr, 1203a014fbbcSShilei Tian int dst_dev_id, void *dst_ptr, 1204a014fbbcSShilei Tian int64_t size, 12055449fbb5SJohannes Doerfert __tgt_async_info *AsyncInfo) { 1206a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1207a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 12085449fbb5SJohannes Doerfert assert(AsyncInfo && "AsyncInfo is nullptr"); 1209a014fbbcSShilei Tian 1210a014fbbcSShilei Tian return DeviceRTL.dataExchange(src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, 12115449fbb5SJohannes Doerfert AsyncInfo); 1212a014fbbcSShilei Tian } 1213a014fbbcSShilei Tian 1214a014fbbcSShilei Tian int32_t __tgt_rtl_data_exchange(int32_t src_dev_id, void *src_ptr, 1215a014fbbcSShilei Tian int32_t dst_dev_id, void *dst_ptr, 1216a014fbbcSShilei Tian int64_t size) { 1217a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(src_dev_id) && "src_dev_id is invalid"); 1218a014fbbcSShilei Tian assert(DeviceRTL.isValidDeviceId(dst_dev_id) && "dst_dev_id is invalid"); 1219a014fbbcSShilei Tian 12205449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 1221a014fbbcSShilei Tian const int32_t rc = __tgt_rtl_data_exchange_async( 12225449fbb5SJohannes Doerfert src_dev_id, src_ptr, dst_dev_id, dst_ptr, size, &AsyncInfo); 1223a014fbbcSShilei Tian if (rc != OFFLOAD_SUCCESS) 1224a014fbbcSShilei Tian return OFFLOAD_FAIL; 1225a014fbbcSShilei Tian 12265449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(src_dev_id, &AsyncInfo); 1227a014fbbcSShilei Tian } 1228a014fbbcSShilei Tian 12294031bb98SShilei Tian int32_t __tgt_rtl_data_delete(int32_t device_id, void *tgt_ptr) { 12304031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12314031bb98SShilei Tian 12324031bb98SShilei Tian return DeviceRTL.dataDelete(device_id, tgt_ptr); 12334031bb98SShilei Tian } 12344031bb98SShilei Tian 12354031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr, 12364031bb98SShilei Tian void **tgt_args, 12374031bb98SShilei Tian ptrdiff_t *tgt_offsets, 12384031bb98SShilei Tian int32_t arg_num, int32_t team_num, 12394031bb98SShilei Tian int32_t thread_limit, 12404031bb98SShilei Tian uint64_t loop_tripcount) { 12414031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12424031bb98SShilei Tian 12435449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 12444031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_team_region_async( 12454031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 12465449fbb5SJohannes Doerfert thread_limit, loop_tripcount, &AsyncInfo); 12474031bb98SShilei Tian if (rc != OFFLOAD_SUCCESS) 12484031bb98SShilei Tian return OFFLOAD_FAIL; 12494031bb98SShilei Tian 12505449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 12514031bb98SShilei Tian } 12524031bb98SShilei Tian 12534031bb98SShilei Tian int32_t __tgt_rtl_run_target_team_region_async( 12544031bb98SShilei Tian int32_t device_id, void *tgt_entry_ptr, void **tgt_args, 12554031bb98SShilei Tian ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t team_num, 12564031bb98SShilei Tian int32_t thread_limit, uint64_t loop_tripcount, 12574031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12584031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12594031bb98SShilei Tian 12604031bb98SShilei Tian return DeviceRTL.runTargetTeamRegion( 12614031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 12624031bb98SShilei Tian thread_limit, loop_tripcount, async_info_ptr); 12634031bb98SShilei Tian } 12643de4cd12SGeorge Rokos 12653de4cd12SGeorge Rokos int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr, 126632ed2927SShilei Tian void **tgt_args, ptrdiff_t *tgt_offsets, 126703ff643dSShilei Tian int32_t arg_num) { 12684031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12694031bb98SShilei Tian 12705449fbb5SJohannes Doerfert __tgt_async_info AsyncInfo; 12714031bb98SShilei Tian const int32_t rc = __tgt_rtl_run_target_region_async( 12725449fbb5SJohannes Doerfert device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, &AsyncInfo); 127303ff643dSShilei Tian if (rc != OFFLOAD_SUCCESS) 127403ff643dSShilei Tian return OFFLOAD_FAIL; 127503ff643dSShilei Tian 12765449fbb5SJohannes Doerfert return __tgt_rtl_synchronize(device_id, &AsyncInfo); 127703ff643dSShilei Tian } 127803ff643dSShilei Tian 127903ff643dSShilei Tian int32_t __tgt_rtl_run_target_region_async(int32_t device_id, 128003ff643dSShilei Tian void *tgt_entry_ptr, void **tgt_args, 128103ff643dSShilei Tian ptrdiff_t *tgt_offsets, 128232ed2927SShilei Tian int32_t arg_num, 12834031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12844031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12854031bb98SShilei Tian 128603ff643dSShilei Tian return __tgt_rtl_run_target_team_region_async( 12874031bb98SShilei Tian device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, 12884031bb98SShilei Tian /* team num*/ 1, /* thread_limit */ 1, /* loop_tripcount */ 0, 12894031bb98SShilei Tian async_info_ptr); 129032ed2927SShilei Tian } 129132ed2927SShilei Tian 12924031bb98SShilei Tian int32_t __tgt_rtl_synchronize(int32_t device_id, 12934031bb98SShilei Tian __tgt_async_info *async_info_ptr) { 12944031bb98SShilei Tian assert(DeviceRTL.isValidDeviceId(device_id) && "device_id is invalid"); 12954031bb98SShilei Tian assert(async_info_ptr && "async_info_ptr is nullptr"); 12964031bb98SShilei Tian assert(async_info_ptr->Queue && "async_info_ptr->Queue is nullptr"); 129732ed2927SShilei Tian 12984031bb98SShilei Tian return DeviceRTL.synchronize(device_id, async_info_ptr); 12993de4cd12SGeorge Rokos } 13003de4cd12SGeorge Rokos 13012b6f2008SJoseph Huber void __tgt_rtl_set_info_flag(uint32_t NewInfoLevel) { 130259b68490SJoseph Huber std::atomic<uint32_t> &InfoLevel = getInfoLevelInternal(); 13032b6f2008SJoseph Huber InfoLevel.store(NewInfoLevel); 13042b6f2008SJoseph Huber } 13052b6f2008SJoseph Huber 13063de4cd12SGeorge Rokos #ifdef __cplusplus 13073de4cd12SGeorge Rokos } 13083de4cd12SGeorge Rokos #endif 1309