1 //===--- amdgpu/src/rtl.cpp --------------------------------------- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // RTL for AMD hsa machine 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include <algorithm> 14 #include <assert.h> 15 #include <cstdio> 16 #include <cstdlib> 17 #include <cstring> 18 #include <functional> 19 #include <libelf.h> 20 #include <list> 21 #include <memory> 22 #include <mutex> 23 #include <shared_mutex> 24 #include <unordered_map> 25 #include <vector> 26 27 #include "interop_hsa.h" 28 #include "impl_runtime.h" 29 30 #include "internal.h" 31 #include "rt.h" 32 33 #include "DeviceEnvironment.h" 34 #include "get_elf_mach_gfx_name.h" 35 #include "omptargetplugin.h" 36 #include "print_tracing.h" 37 38 #include "llvm/Frontend/OpenMP/OMPConstants.h" 39 #include "llvm/Frontend/OpenMP/OMPGridValues.h" 40 41 // hostrpc interface, FIXME: consider moving to its own include these are 42 // statically linked into amdgpu/plugin if present from hostrpc_services.a, 43 // linked as --whole-archive to override the weak symbols that are used to 44 // implement a fallback for toolchains that do not yet have a hostrpc library. 45 extern "C" { 46 unsigned long hostrpc_assign_buffer(hsa_agent_t agent, hsa_queue_t *this_Q, 47 uint32_t device_id); 48 hsa_status_t hostrpc_init(); 49 hsa_status_t hostrpc_terminate(); 50 51 __attribute__((weak)) hsa_status_t hostrpc_init() { return HSA_STATUS_SUCCESS; } 52 __attribute__((weak)) hsa_status_t hostrpc_terminate() { 53 return HSA_STATUS_SUCCESS; 54 } 55 __attribute__((weak)) unsigned long 56 hostrpc_assign_buffer(hsa_agent_t, hsa_queue_t *, uint32_t device_id) { 57 DP("Warning: Attempting to assign hostrpc to device %u, but hostrpc library " 58 "missing\n", 59 device_id); 60 return 0; 61 } 62 } 63 64 // Heuristic parameters used for kernel launch 65 // Number of teams per CU to allow scheduling flexibility 66 static const unsigned DefaultTeamsPerCU = 4; 67 68 int print_kernel_trace; 69 70 #ifdef OMPTARGET_DEBUG 71 #define check(msg, status) \ 72 if (status != HSA_STATUS_SUCCESS) { \ 73 DP(#msg " failed\n"); \ 74 } else { \ 75 DP(#msg " succeeded\n"); \ 76 } 77 #else 78 #define check(msg, status) \ 79 {} 80 #endif 81 82 #include "elf_common.h" 83 84 namespace hsa { 85 template <typename C> hsa_status_t iterate_agents(C cb) { 86 auto L = [](hsa_agent_t agent, void *data) -> hsa_status_t { 87 C *unwrapped = static_cast<C *>(data); 88 return (*unwrapped)(agent); 89 }; 90 return hsa_iterate_agents(L, static_cast<void *>(&cb)); 91 } 92 93 template <typename C> 94 hsa_status_t amd_agent_iterate_memory_pools(hsa_agent_t Agent, C cb) { 95 auto L = [](hsa_amd_memory_pool_t MemoryPool, void *data) -> hsa_status_t { 96 C *unwrapped = static_cast<C *>(data); 97 return (*unwrapped)(MemoryPool); 98 }; 99 100 return hsa_amd_agent_iterate_memory_pools(Agent, L, static_cast<void *>(&cb)); 101 } 102 103 } // namespace hsa 104 105 /// Keep entries table per device 106 struct FuncOrGblEntryTy { 107 __tgt_target_table Table; 108 std::vector<__tgt_offload_entry> Entries; 109 }; 110 111 struct KernelArgPool { 112 private: 113 static pthread_mutex_t mutex; 114 115 public: 116 uint32_t kernarg_segment_size; 117 void *kernarg_region = nullptr; 118 std::queue<int> free_kernarg_segments; 119 120 uint32_t kernarg_size_including_implicit() { 121 return kernarg_segment_size + sizeof(impl_implicit_args_t); 122 } 123 124 ~KernelArgPool() { 125 if (kernarg_region) { 126 auto r = hsa_amd_memory_pool_free(kernarg_region); 127 if (r != HSA_STATUS_SUCCESS) { 128 DP("hsa_amd_memory_pool_free failed: %s\n", get_error_string(r)); 129 } 130 } 131 } 132 133 // Can't really copy or move a mutex 134 KernelArgPool() = default; 135 KernelArgPool(const KernelArgPool &) = delete; 136 KernelArgPool(KernelArgPool &&) = delete; 137 138 KernelArgPool(uint32_t kernarg_segment_size, 139 hsa_amd_memory_pool_t &memory_pool) 140 : kernarg_segment_size(kernarg_segment_size) { 141 142 // impl uses one pool per kernel for all gpus, with a fixed upper size 143 // preserving that exact scheme here, including the queue<int> 144 145 hsa_status_t err = hsa_amd_memory_pool_allocate( 146 memory_pool, kernarg_size_including_implicit() * MAX_NUM_KERNELS, 0, 147 &kernarg_region); 148 149 if (err != HSA_STATUS_SUCCESS) { 150 DP("hsa_amd_memory_pool_allocate failed: %s\n", get_error_string(err)); 151 kernarg_region = nullptr; // paranoid 152 return; 153 } 154 155 err = core::allow_access_to_all_gpu_agents(kernarg_region); 156 if (err != HSA_STATUS_SUCCESS) { 157 DP("hsa allow_access_to_all_gpu_agents failed: %s\n", 158 get_error_string(err)); 159 auto r = hsa_amd_memory_pool_free(kernarg_region); 160 if (r != HSA_STATUS_SUCCESS) { 161 // if free failed, can't do anything more to resolve it 162 DP("hsa memory poll free failed: %s\n", get_error_string(err)); 163 } 164 kernarg_region = nullptr; 165 return; 166 } 167 168 for (int i = 0; i < MAX_NUM_KERNELS; i++) { 169 free_kernarg_segments.push(i); 170 } 171 } 172 173 void *allocate(uint64_t arg_num) { 174 assert((arg_num * sizeof(void *)) == kernarg_segment_size); 175 lock l(&mutex); 176 void *res = nullptr; 177 if (!free_kernarg_segments.empty()) { 178 179 int free_idx = free_kernarg_segments.front(); 180 res = static_cast<void *>(static_cast<char *>(kernarg_region) + 181 (free_idx * kernarg_size_including_implicit())); 182 assert(free_idx == pointer_to_index(res)); 183 free_kernarg_segments.pop(); 184 } 185 return res; 186 } 187 188 void deallocate(void *ptr) { 189 lock l(&mutex); 190 int idx = pointer_to_index(ptr); 191 free_kernarg_segments.push(idx); 192 } 193 194 private: 195 int pointer_to_index(void *ptr) { 196 ptrdiff_t bytes = 197 static_cast<char *>(ptr) - static_cast<char *>(kernarg_region); 198 assert(bytes >= 0); 199 assert(bytes % kernarg_size_including_implicit() == 0); 200 return bytes / kernarg_size_including_implicit(); 201 } 202 struct lock { 203 lock(pthread_mutex_t *m) : m(m) { pthread_mutex_lock(m); } 204 ~lock() { pthread_mutex_unlock(m); } 205 pthread_mutex_t *m; 206 }; 207 }; 208 pthread_mutex_t KernelArgPool::mutex = PTHREAD_MUTEX_INITIALIZER; 209 210 std::unordered_map<std::string /*kernel*/, std::unique_ptr<KernelArgPool>> 211 KernelArgPoolMap; 212 213 /// Use a single entity to encode a kernel and a set of flags 214 struct KernelTy { 215 llvm::omp::OMPTgtExecModeFlags ExecutionMode; 216 int16_t ConstWGSize; 217 int32_t device_id; 218 void *CallStackAddr = nullptr; 219 const char *Name; 220 221 KernelTy(llvm::omp::OMPTgtExecModeFlags _ExecutionMode, int16_t _ConstWGSize, 222 int32_t _device_id, void *_CallStackAddr, const char *_Name, 223 uint32_t _kernarg_segment_size, 224 hsa_amd_memory_pool_t &KernArgMemoryPool) 225 : ExecutionMode(_ExecutionMode), ConstWGSize(_ConstWGSize), 226 device_id(_device_id), CallStackAddr(_CallStackAddr), Name(_Name) { 227 DP("Construct kernelinfo: ExecMode %d\n", ExecutionMode); 228 229 std::string N(_Name); 230 if (KernelArgPoolMap.find(N) == KernelArgPoolMap.end()) { 231 KernelArgPoolMap.insert( 232 std::make_pair(N, std::unique_ptr<KernelArgPool>(new KernelArgPool( 233 _kernarg_segment_size, KernArgMemoryPool)))); 234 } 235 } 236 }; 237 238 /// List that contains all the kernels. 239 /// FIXME: we may need this to be per device and per library. 240 std::list<KernelTy> KernelsList; 241 242 template <typename Callback> static hsa_status_t FindAgents(Callback CB) { 243 244 hsa_status_t err = 245 hsa::iterate_agents([&](hsa_agent_t agent) -> hsa_status_t { 246 hsa_device_type_t device_type; 247 // get_info fails iff HSA runtime not yet initialized 248 hsa_status_t err = 249 hsa_agent_get_info(agent, HSA_AGENT_INFO_DEVICE, &device_type); 250 251 if (err != HSA_STATUS_SUCCESS) { 252 if (print_kernel_trace > 0) 253 DP("rtl.cpp: err %s\n", get_error_string(err)); 254 255 return err; 256 } 257 258 CB(device_type, agent); 259 return HSA_STATUS_SUCCESS; 260 }); 261 262 // iterate_agents fails iff HSA runtime not yet initialized 263 if (print_kernel_trace > 0 && err != HSA_STATUS_SUCCESS) { 264 DP("rtl.cpp: err %s\n", get_error_string(err)); 265 } 266 267 return err; 268 } 269 270 static void callbackQueue(hsa_status_t status, hsa_queue_t *source, 271 void *data) { 272 if (status != HSA_STATUS_SUCCESS) { 273 const char *status_string; 274 if (hsa_status_string(status, &status_string) != HSA_STATUS_SUCCESS) { 275 status_string = "unavailable"; 276 } 277 DP("[%s:%d] GPU error in queue %p %d (%s)\n", __FILE__, __LINE__, source, 278 status, status_string); 279 abort(); 280 } 281 } 282 283 namespace core { 284 namespace { 285 void packet_store_release(uint32_t *packet, uint16_t header, uint16_t rest) { 286 __atomic_store_n(packet, header | (rest << 16), __ATOMIC_RELEASE); 287 } 288 289 uint16_t create_header() { 290 uint16_t header = HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE; 291 header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE; 292 header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE; 293 return header; 294 } 295 296 hsa_status_t isValidMemoryPool(hsa_amd_memory_pool_t MemoryPool) { 297 bool AllocAllowed = false; 298 hsa_status_t Err = hsa_amd_memory_pool_get_info( 299 MemoryPool, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED, 300 &AllocAllowed); 301 if (Err != HSA_STATUS_SUCCESS) { 302 DP("Alloc allowed in memory pool check failed: %s\n", 303 get_error_string(Err)); 304 return Err; 305 } 306 307 size_t Size = 0; 308 Err = hsa_amd_memory_pool_get_info(MemoryPool, HSA_AMD_MEMORY_POOL_INFO_SIZE, 309 &Size); 310 if (Err != HSA_STATUS_SUCCESS) { 311 DP("Get memory pool size failed: %s\n", get_error_string(Err)); 312 return Err; 313 } 314 315 return (AllocAllowed && Size > 0) ? HSA_STATUS_SUCCESS : HSA_STATUS_ERROR; 316 } 317 318 hsa_status_t addMemoryPool(hsa_amd_memory_pool_t MemoryPool, void *Data) { 319 std::vector<hsa_amd_memory_pool_t> *Result = 320 static_cast<std::vector<hsa_amd_memory_pool_t> *>(Data); 321 322 hsa_status_t err; 323 if ((err = isValidMemoryPool(MemoryPool)) != HSA_STATUS_SUCCESS) { 324 return err; 325 } 326 327 Result->push_back(MemoryPool); 328 return HSA_STATUS_SUCCESS; 329 } 330 331 } // namespace 332 } // namespace core 333 334 struct EnvironmentVariables { 335 int NumTeams; 336 int TeamLimit; 337 int TeamThreadLimit; 338 int MaxTeamsDefault; 339 }; 340 341 template <uint32_t wavesize> 342 static constexpr const llvm::omp::GV &getGridValue() { 343 return llvm::omp::getAMDGPUGridValues<wavesize>(); 344 } 345 346 struct HSALifetime { 347 // Wrapper around HSA used to ensure it is constructed before other types 348 // and destructed after, which means said other types can use raii for 349 // cleanup without risking running outside of the lifetime of HSA 350 const hsa_status_t S; 351 352 bool HSAInitSuccess() { return S == HSA_STATUS_SUCCESS; } 353 HSALifetime() : S(hsa_init()) {} 354 355 ~HSALifetime() { 356 if (S == HSA_STATUS_SUCCESS) { 357 hsa_status_t Err = hsa_shut_down(); 358 if (Err != HSA_STATUS_SUCCESS) { 359 // Can't call into HSA to get a string from the integer 360 DP("Shutting down HSA failed: %d\n", Err); 361 } 362 } 363 } 364 }; 365 366 // Handle scheduling of multiple hsa_queue's per device to 367 // multiple threads (one scheduler per device) 368 class HSAQueueScheduler { 369 public: 370 HSAQueueScheduler() : current(0) {} 371 372 HSAQueueScheduler(const HSAQueueScheduler &) = delete; 373 374 HSAQueueScheduler(HSAQueueScheduler &&q) { 375 current = q.current.load(); 376 for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) { 377 HSAQueues[i] = q.HSAQueues[i]; 378 q.HSAQueues[i] = nullptr; 379 } 380 } 381 382 // \return false if any HSA queue creation fails 383 bool CreateQueues(hsa_agent_t HSAAgent, uint32_t queue_size) { 384 for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) { 385 hsa_queue_t *Q = nullptr; 386 hsa_status_t rc = 387 hsa_queue_create(HSAAgent, queue_size, HSA_QUEUE_TYPE_MULTI, 388 callbackQueue, NULL, UINT32_MAX, UINT32_MAX, &Q); 389 if (rc != HSA_STATUS_SUCCESS) { 390 DP("Failed to create HSA queue %d\n", i); 391 return false; 392 } 393 HSAQueues[i] = Q; 394 } 395 return true; 396 } 397 398 ~HSAQueueScheduler() { 399 for (uint8_t i = 0; i < NUM_QUEUES_PER_DEVICE; i++) { 400 if (HSAQueues[i]) { 401 hsa_status_t err = hsa_queue_destroy(HSAQueues[i]); 402 if (err != HSA_STATUS_SUCCESS) 403 DP("Error destroying HSA queue"); 404 } 405 } 406 } 407 408 // \return next queue to use for device 409 hsa_queue_t *Next() { 410 return HSAQueues[(current.fetch_add(1, std::memory_order_relaxed)) % 411 NUM_QUEUES_PER_DEVICE]; 412 } 413 414 private: 415 // Number of queues per device 416 enum : uint8_t { NUM_QUEUES_PER_DEVICE = 4 }; 417 hsa_queue_t *HSAQueues[NUM_QUEUES_PER_DEVICE] = {}; 418 std::atomic<uint8_t> current; 419 }; 420 421 /// Class containing all the device information 422 class RTLDeviceInfoTy : HSALifetime { 423 std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries; 424 425 struct QueueDeleter { 426 void operator()(hsa_queue_t *Q) { 427 if (Q) { 428 hsa_status_t Err = hsa_queue_destroy(Q); 429 if (Err != HSA_STATUS_SUCCESS) { 430 DP("Error destroying hsa queue: %s\n", get_error_string(Err)); 431 } 432 } 433 } 434 }; 435 436 public: 437 bool ConstructionSucceeded = false; 438 439 // load binary populates symbol tables and mutates various global state 440 // run uses those symbol tables 441 std::shared_timed_mutex load_run_lock; 442 443 int NumberOfDevices = 0; 444 445 // GPU devices 446 std::vector<hsa_agent_t> HSAAgents; 447 std::vector<HSAQueueScheduler> HSAQueueSchedulers; // one per gpu 448 449 // CPUs 450 std::vector<hsa_agent_t> CPUAgents; 451 452 // Device properties 453 std::vector<int> ComputeUnits; 454 std::vector<int> GroupsPerDevice; 455 std::vector<int> ThreadsPerGroup; 456 std::vector<int> WarpSize; 457 std::vector<std::string> GPUName; 458 459 // OpenMP properties 460 std::vector<int> NumTeams; 461 std::vector<int> NumThreads; 462 463 // OpenMP Environment properties 464 EnvironmentVariables Env; 465 466 // OpenMP Requires Flags 467 int64_t RequiresFlags; 468 469 // Resource pools 470 SignalPoolT FreeSignalPool; 471 472 bool hostcall_required = false; 473 474 std::vector<hsa_executable_t> HSAExecutables; 475 476 std::vector<std::map<std::string, atl_kernel_info_t>> KernelInfoTable; 477 std::vector<std::map<std::string, atl_symbol_info_t>> SymbolInfoTable; 478 479 hsa_amd_memory_pool_t KernArgPool; 480 481 // fine grained memory pool for host allocations 482 hsa_amd_memory_pool_t HostFineGrainedMemoryPool; 483 484 // fine and coarse-grained memory pools per offloading device 485 std::vector<hsa_amd_memory_pool_t> DeviceFineGrainedMemoryPools; 486 std::vector<hsa_amd_memory_pool_t> DeviceCoarseGrainedMemoryPools; 487 488 struct implFreePtrDeletor { 489 void operator()(void *p) { 490 core::Runtime::Memfree(p); // ignore failure to free 491 } 492 }; 493 494 // device_State shared across loaded binaries, error if inconsistent size 495 std::vector<std::pair<std::unique_ptr<void, implFreePtrDeletor>, uint64_t>> 496 deviceStateStore; 497 498 static const unsigned HardTeamLimit = 499 (1 << 16) - 1; // 64K needed to fit in uint16 500 static const int DefaultNumTeams = 128; 501 502 // These need to be per-device since different devices can have different 503 // wave sizes, but are currently the same number for each so that refactor 504 // can be postponed. 505 static_assert(getGridValue<32>().GV_Max_Teams == 506 getGridValue<64>().GV_Max_Teams, 507 ""); 508 static const int Max_Teams = getGridValue<64>().GV_Max_Teams; 509 510 static_assert(getGridValue<32>().GV_Max_WG_Size == 511 getGridValue<64>().GV_Max_WG_Size, 512 ""); 513 static const int Max_WG_Size = getGridValue<64>().GV_Max_WG_Size; 514 515 static_assert(getGridValue<32>().GV_Default_WG_Size == 516 getGridValue<64>().GV_Default_WG_Size, 517 ""); 518 static const int Default_WG_Size = getGridValue<64>().GV_Default_WG_Size; 519 520 using MemcpyFunc = hsa_status_t (*)(hsa_signal_t, void *, void *, size_t size, 521 hsa_agent_t, hsa_amd_memory_pool_t); 522 hsa_status_t freesignalpool_memcpy(void *dest, void *src, size_t size, 523 MemcpyFunc Func, int32_t deviceId) { 524 hsa_agent_t agent = HSAAgents[deviceId]; 525 hsa_signal_t s = FreeSignalPool.pop(); 526 if (s.handle == 0) { 527 return HSA_STATUS_ERROR; 528 } 529 hsa_status_t r = Func(s, dest, src, size, agent, HostFineGrainedMemoryPool); 530 FreeSignalPool.push(s); 531 return r; 532 } 533 534 hsa_status_t freesignalpool_memcpy_d2h(void *dest, void *src, size_t size, 535 int32_t deviceId) { 536 return freesignalpool_memcpy(dest, src, size, impl_memcpy_d2h, deviceId); 537 } 538 539 hsa_status_t freesignalpool_memcpy_h2d(void *dest, void *src, size_t size, 540 int32_t deviceId) { 541 return freesignalpool_memcpy(dest, src, size, impl_memcpy_h2d, deviceId); 542 } 543 544 // Record entry point associated with device 545 void addOffloadEntry(int32_t device_id, __tgt_offload_entry entry) { 546 assert(device_id < (int32_t)FuncGblEntries.size() && 547 "Unexpected device id!"); 548 FuncOrGblEntryTy &E = FuncGblEntries[device_id].back(); 549 550 E.Entries.push_back(entry); 551 } 552 553 // Return true if the entry is associated with device 554 bool findOffloadEntry(int32_t device_id, void *addr) { 555 assert(device_id < (int32_t)FuncGblEntries.size() && 556 "Unexpected device id!"); 557 FuncOrGblEntryTy &E = FuncGblEntries[device_id].back(); 558 559 for (auto &it : E.Entries) { 560 if (it.addr == addr) 561 return true; 562 } 563 564 return false; 565 } 566 567 // Return the pointer to the target entries table 568 __tgt_target_table *getOffloadEntriesTable(int32_t device_id) { 569 assert(device_id < (int32_t)FuncGblEntries.size() && 570 "Unexpected device id!"); 571 FuncOrGblEntryTy &E = FuncGblEntries[device_id].back(); 572 573 int32_t size = E.Entries.size(); 574 575 // Table is empty 576 if (!size) 577 return 0; 578 579 __tgt_offload_entry *begin = &E.Entries[0]; 580 __tgt_offload_entry *end = &E.Entries[size - 1]; 581 582 // Update table info according to the entries and return the pointer 583 E.Table.EntriesBegin = begin; 584 E.Table.EntriesEnd = ++end; 585 586 return &E.Table; 587 } 588 589 // Clear entries table for a device 590 void clearOffloadEntriesTable(int device_id) { 591 assert(device_id < (int32_t)FuncGblEntries.size() && 592 "Unexpected device id!"); 593 FuncGblEntries[device_id].emplace_back(); 594 FuncOrGblEntryTy &E = FuncGblEntries[device_id].back(); 595 // KernelArgPoolMap.clear(); 596 E.Entries.clear(); 597 E.Table.EntriesBegin = E.Table.EntriesEnd = 0; 598 } 599 600 hsa_status_t addDeviceMemoryPool(hsa_amd_memory_pool_t MemoryPool, 601 int DeviceId) { 602 assert(DeviceId < DeviceFineGrainedMemoryPools.size() && "Error here."); 603 uint32_t GlobalFlags = 0; 604 hsa_status_t Err = hsa_amd_memory_pool_get_info( 605 MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags); 606 607 if (Err != HSA_STATUS_SUCCESS) { 608 return Err; 609 } 610 611 if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) { 612 DeviceFineGrainedMemoryPools[DeviceId] = MemoryPool; 613 } else if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) { 614 DeviceCoarseGrainedMemoryPools[DeviceId] = MemoryPool; 615 } 616 617 return HSA_STATUS_SUCCESS; 618 } 619 620 hsa_status_t setupDevicePools(const std::vector<hsa_agent_t> &Agents) { 621 for (int DeviceId = 0; DeviceId < Agents.size(); DeviceId++) { 622 hsa_status_t Err = hsa::amd_agent_iterate_memory_pools( 623 Agents[DeviceId], [&](hsa_amd_memory_pool_t MemoryPool) { 624 hsa_status_t ValidStatus = core::isValidMemoryPool(MemoryPool); 625 if (ValidStatus != HSA_STATUS_SUCCESS) { 626 DP("Alloc allowed in memory pool check failed: %s\n", 627 get_error_string(ValidStatus)); 628 return HSA_STATUS_SUCCESS; 629 } 630 return addDeviceMemoryPool(MemoryPool, DeviceId); 631 }); 632 633 if (Err != HSA_STATUS_SUCCESS) { 634 DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__, 635 "Iterate all memory pools", get_error_string(Err)); 636 return Err; 637 } 638 } 639 return HSA_STATUS_SUCCESS; 640 } 641 642 hsa_status_t setupHostMemoryPools(std::vector<hsa_agent_t> &Agents) { 643 std::vector<hsa_amd_memory_pool_t> HostPools; 644 645 // collect all the "valid" pools for all the given agents. 646 for (const auto &Agent : Agents) { 647 hsa_status_t Err = hsa_amd_agent_iterate_memory_pools( 648 Agent, core::addMemoryPool, static_cast<void *>(&HostPools)); 649 if (Err != HSA_STATUS_SUCCESS) { 650 DP("addMemoryPool returned %s, continuing\n", get_error_string(Err)); 651 } 652 } 653 654 // We need two fine-grained pools. 655 // 1. One with kernarg flag set for storing kernel arguments 656 // 2. Second for host allocations 657 bool FineGrainedMemoryPoolSet = false; 658 bool KernArgPoolSet = false; 659 for (const auto &MemoryPool : HostPools) { 660 hsa_status_t Err = HSA_STATUS_SUCCESS; 661 uint32_t GlobalFlags = 0; 662 Err = hsa_amd_memory_pool_get_info( 663 MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags); 664 if (Err != HSA_STATUS_SUCCESS) { 665 DP("Get memory pool info failed: %s\n", get_error_string(Err)); 666 return Err; 667 } 668 669 if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) { 670 if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT) { 671 KernArgPool = MemoryPool; 672 KernArgPoolSet = true; 673 } 674 HostFineGrainedMemoryPool = MemoryPool; 675 FineGrainedMemoryPoolSet = true; 676 } 677 } 678 679 if (FineGrainedMemoryPoolSet && KernArgPoolSet) 680 return HSA_STATUS_SUCCESS; 681 682 return HSA_STATUS_ERROR; 683 } 684 685 hsa_amd_memory_pool_t getDeviceMemoryPool(int DeviceId) { 686 assert(DeviceId >= 0 && DeviceId < DeviceCoarseGrainedMemoryPools.size() && 687 "Invalid device Id"); 688 return DeviceCoarseGrainedMemoryPools[DeviceId]; 689 } 690 691 hsa_amd_memory_pool_t getHostMemoryPool() { 692 return HostFineGrainedMemoryPool; 693 } 694 695 static int readEnvElseMinusOne(const char *Env) { 696 const char *envStr = getenv(Env); 697 int res = -1; 698 if (envStr) { 699 res = std::stoi(envStr); 700 DP("Parsed %s=%d\n", Env, res); 701 } 702 return res; 703 } 704 705 RTLDeviceInfoTy() { 706 DP("Start initializing " GETNAME(TARGET_NAME) "\n"); 707 708 // LIBOMPTARGET_KERNEL_TRACE provides a kernel launch trace to stderr 709 // anytime. You do not need a debug library build. 710 // 0 => no tracing 711 // 1 => tracing dispatch only 712 // >1 => verbosity increase 713 714 if (!HSAInitSuccess()) { 715 DP("Error when initializing HSA in " GETNAME(TARGET_NAME) "\n"); 716 return; 717 } 718 719 if (char *envStr = getenv("LIBOMPTARGET_KERNEL_TRACE")) 720 print_kernel_trace = atoi(envStr); 721 else 722 print_kernel_trace = 0; 723 724 hsa_status_t err = core::atl_init_gpu_context(); 725 if (err != HSA_STATUS_SUCCESS) { 726 DP("Error when initializing " GETNAME(TARGET_NAME) "\n"); 727 return; 728 } 729 730 // Init hostcall soon after initializing hsa 731 hostrpc_init(); 732 733 err = FindAgents([&](hsa_device_type_t DeviceType, hsa_agent_t Agent) { 734 if (DeviceType == HSA_DEVICE_TYPE_CPU) { 735 CPUAgents.push_back(Agent); 736 } else { 737 HSAAgents.push_back(Agent); 738 } 739 }); 740 if (err != HSA_STATUS_SUCCESS) 741 return; 742 743 NumberOfDevices = (int)HSAAgents.size(); 744 745 if (NumberOfDevices == 0) { 746 DP("There are no devices supporting HSA.\n"); 747 return; 748 } else { 749 DP("There are %d devices supporting HSA.\n", NumberOfDevices); 750 } 751 752 // Init the device info 753 HSAQueueSchedulers.reserve(NumberOfDevices); 754 FuncGblEntries.resize(NumberOfDevices); 755 ThreadsPerGroup.resize(NumberOfDevices); 756 ComputeUnits.resize(NumberOfDevices); 757 GPUName.resize(NumberOfDevices); 758 GroupsPerDevice.resize(NumberOfDevices); 759 WarpSize.resize(NumberOfDevices); 760 NumTeams.resize(NumberOfDevices); 761 NumThreads.resize(NumberOfDevices); 762 deviceStateStore.resize(NumberOfDevices); 763 KernelInfoTable.resize(NumberOfDevices); 764 SymbolInfoTable.resize(NumberOfDevices); 765 DeviceCoarseGrainedMemoryPools.resize(NumberOfDevices); 766 DeviceFineGrainedMemoryPools.resize(NumberOfDevices); 767 768 err = setupDevicePools(HSAAgents); 769 if (err != HSA_STATUS_SUCCESS) { 770 DP("Setup for Device Memory Pools failed\n"); 771 return; 772 } 773 774 err = setupHostMemoryPools(CPUAgents); 775 if (err != HSA_STATUS_SUCCESS) { 776 DP("Setup for Host Memory Pools failed\n"); 777 return; 778 } 779 780 for (int i = 0; i < NumberOfDevices; i++) { 781 uint32_t queue_size = 0; 782 { 783 hsa_status_t err = hsa_agent_get_info( 784 HSAAgents[i], HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size); 785 if (err != HSA_STATUS_SUCCESS) { 786 DP("HSA query QUEUE_MAX_SIZE failed for agent %d\n", i); 787 return; 788 } 789 enum { MaxQueueSize = 4096 }; 790 if (queue_size > MaxQueueSize) { 791 queue_size = MaxQueueSize; 792 } 793 } 794 795 { 796 HSAQueueScheduler QSched; 797 if (!QSched.CreateQueues(HSAAgents[i], queue_size)) 798 return; 799 HSAQueueSchedulers.emplace_back(std::move(QSched)); 800 } 801 802 deviceStateStore[i] = {nullptr, 0}; 803 } 804 805 for (int i = 0; i < NumberOfDevices; i++) { 806 ThreadsPerGroup[i] = RTLDeviceInfoTy::Default_WG_Size; 807 GroupsPerDevice[i] = RTLDeviceInfoTy::DefaultNumTeams; 808 ComputeUnits[i] = 1; 809 DP("Device %d: Initial groupsPerDevice %d & threadsPerGroup %d\n", i, 810 GroupsPerDevice[i], ThreadsPerGroup[i]); 811 } 812 813 // Get environment variables regarding teams 814 Env.TeamLimit = readEnvElseMinusOne("OMP_TEAM_LIMIT"); 815 Env.NumTeams = readEnvElseMinusOne("OMP_NUM_TEAMS"); 816 Env.MaxTeamsDefault = readEnvElseMinusOne("OMP_MAX_TEAMS_DEFAULT"); 817 Env.TeamThreadLimit = readEnvElseMinusOne("OMP_TEAMS_THREAD_LIMIT"); 818 819 // Default state. 820 RequiresFlags = OMP_REQ_UNDEFINED; 821 822 ConstructionSucceeded = true; 823 } 824 825 ~RTLDeviceInfoTy() { 826 DP("Finalizing the " GETNAME(TARGET_NAME) " DeviceInfo.\n"); 827 if (!HSAInitSuccess()) { 828 // Then none of these can have been set up and they can't be torn down 829 return; 830 } 831 // Run destructors on types that use HSA before 832 // impl_finalize removes access to it 833 deviceStateStore.clear(); 834 KernelArgPoolMap.clear(); 835 // Terminate hostrpc before finalizing hsa 836 hostrpc_terminate(); 837 838 hsa_status_t Err; 839 for (uint32_t I = 0; I < HSAExecutables.size(); I++) { 840 Err = hsa_executable_destroy(HSAExecutables[I]); 841 if (Err != HSA_STATUS_SUCCESS) { 842 DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__, 843 "Destroying executable", get_error_string(Err)); 844 } 845 } 846 } 847 }; 848 849 pthread_mutex_t SignalPoolT::mutex = PTHREAD_MUTEX_INITIALIZER; 850 851 static RTLDeviceInfoTy DeviceInfo; 852 853 namespace { 854 855 int32_t dataRetrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr, int64_t Size, 856 __tgt_async_info *AsyncInfo) { 857 assert(AsyncInfo && "AsyncInfo is nullptr"); 858 assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large"); 859 // Return success if we are not copying back to host from target. 860 if (!HstPtr) 861 return OFFLOAD_SUCCESS; 862 hsa_status_t err; 863 DP("Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size, 864 (long long unsigned)(Elf64_Addr)TgtPtr, 865 (long long unsigned)(Elf64_Addr)HstPtr); 866 867 err = DeviceInfo.freesignalpool_memcpy_d2h(HstPtr, TgtPtr, (size_t)Size, 868 DeviceId); 869 870 if (err != HSA_STATUS_SUCCESS) { 871 DP("Error when copying data from device to host. Pointers: " 872 "host = 0x%016lx, device = 0x%016lx, size = %lld\n", 873 (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size); 874 return OFFLOAD_FAIL; 875 } 876 DP("DONE Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size, 877 (long long unsigned)(Elf64_Addr)TgtPtr, 878 (long long unsigned)(Elf64_Addr)HstPtr); 879 return OFFLOAD_SUCCESS; 880 } 881 882 int32_t dataSubmit(int32_t DeviceId, void *TgtPtr, void *HstPtr, int64_t Size, 883 __tgt_async_info *AsyncInfo) { 884 assert(AsyncInfo && "AsyncInfo is nullptr"); 885 hsa_status_t err; 886 assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large"); 887 // Return success if we are not doing host to target. 888 if (!HstPtr) 889 return OFFLOAD_SUCCESS; 890 891 DP("Submit data %ld bytes, (hst:%016llx) -> (tgt:%016llx).\n", Size, 892 (long long unsigned)(Elf64_Addr)HstPtr, 893 (long long unsigned)(Elf64_Addr)TgtPtr); 894 err = DeviceInfo.freesignalpool_memcpy_h2d(TgtPtr, HstPtr, (size_t)Size, 895 DeviceId); 896 if (err != HSA_STATUS_SUCCESS) { 897 DP("Error when copying data from host to device. Pointers: " 898 "host = 0x%016lx, device = 0x%016lx, size = %lld\n", 899 (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size); 900 return OFFLOAD_FAIL; 901 } 902 return OFFLOAD_SUCCESS; 903 } 904 905 // Async. 906 // The implementation was written with cuda streams in mind. The semantics of 907 // that are to execute kernels on a queue in order of insertion. A synchronise 908 // call then makes writes visible between host and device. This means a series 909 // of N data_submit_async calls are expected to execute serially. HSA offers 910 // various options to run the data copies concurrently. This may require changes 911 // to libomptarget. 912 913 // __tgt_async_info* contains a void * Queue. Queue = 0 is used to indicate that 914 // there are no outstanding kernels that need to be synchronized. Any async call 915 // may be passed a Queue==0, at which point the cuda implementation will set it 916 // to non-null (see getStream). The cuda streams are per-device. Upstream may 917 // change this interface to explicitly initialize the AsyncInfo_pointer, but 918 // until then hsa lazily initializes it as well. 919 920 void initAsyncInfo(__tgt_async_info *AsyncInfo) { 921 // set non-null while using async calls, return to null to indicate completion 922 assert(AsyncInfo); 923 if (!AsyncInfo->Queue) { 924 AsyncInfo->Queue = reinterpret_cast<void *>(UINT64_MAX); 925 } 926 } 927 void finiAsyncInfo(__tgt_async_info *AsyncInfo) { 928 assert(AsyncInfo); 929 assert(AsyncInfo->Queue); 930 AsyncInfo->Queue = 0; 931 } 932 933 // Determine launch values for kernel. 934 struct launchVals { 935 int WorkgroupSize; 936 int GridSize; 937 }; 938 launchVals getLaunchVals(int WarpSize, EnvironmentVariables Env, 939 int ConstWGSize, 940 llvm::omp::OMPTgtExecModeFlags ExecutionMode, 941 int num_teams, int thread_limit, 942 uint64_t loop_tripcount, int DeviceNumTeams) { 943 944 int threadsPerGroup = RTLDeviceInfoTy::Default_WG_Size; 945 int num_groups = 0; 946 947 int Max_Teams = 948 Env.MaxTeamsDefault > 0 ? Env.MaxTeamsDefault : DeviceNumTeams; 949 if (Max_Teams > RTLDeviceInfoTy::HardTeamLimit) 950 Max_Teams = RTLDeviceInfoTy::HardTeamLimit; 951 952 if (print_kernel_trace & STARTUP_DETAILS) { 953 DP("RTLDeviceInfoTy::Max_Teams: %d\n", RTLDeviceInfoTy::Max_Teams); 954 DP("Max_Teams: %d\n", Max_Teams); 955 DP("RTLDeviceInfoTy::Warp_Size: %d\n", WarpSize); 956 DP("RTLDeviceInfoTy::Max_WG_Size: %d\n", RTLDeviceInfoTy::Max_WG_Size); 957 DP("RTLDeviceInfoTy::Default_WG_Size: %d\n", 958 RTLDeviceInfoTy::Default_WG_Size); 959 DP("thread_limit: %d\n", thread_limit); 960 DP("threadsPerGroup: %d\n", threadsPerGroup); 961 DP("ConstWGSize: %d\n", ConstWGSize); 962 } 963 // check for thread_limit() clause 964 if (thread_limit > 0) { 965 threadsPerGroup = thread_limit; 966 DP("Setting threads per block to requested %d\n", thread_limit); 967 // Add master warp for GENERIC 968 if (ExecutionMode == 969 llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) { 970 threadsPerGroup += WarpSize; 971 DP("Adding master wavefront: +%d threads\n", WarpSize); 972 } 973 if (threadsPerGroup > RTLDeviceInfoTy::Max_WG_Size) { // limit to max 974 threadsPerGroup = RTLDeviceInfoTy::Max_WG_Size; 975 DP("Setting threads per block to maximum %d\n", threadsPerGroup); 976 } 977 } 978 // check flat_max_work_group_size attr here 979 if (threadsPerGroup > ConstWGSize) { 980 threadsPerGroup = ConstWGSize; 981 DP("Reduced threadsPerGroup to flat-attr-group-size limit %d\n", 982 threadsPerGroup); 983 } 984 if (print_kernel_trace & STARTUP_DETAILS) 985 DP("threadsPerGroup: %d\n", threadsPerGroup); 986 DP("Preparing %d threads\n", threadsPerGroup); 987 988 // Set default num_groups (teams) 989 if (Env.TeamLimit > 0) 990 num_groups = (Max_Teams < Env.TeamLimit) ? Max_Teams : Env.TeamLimit; 991 else 992 num_groups = Max_Teams; 993 DP("Set default num of groups %d\n", num_groups); 994 995 if (print_kernel_trace & STARTUP_DETAILS) { 996 DP("num_groups: %d\n", num_groups); 997 DP("num_teams: %d\n", num_teams); 998 } 999 1000 // Reduce num_groups if threadsPerGroup exceeds RTLDeviceInfoTy::Max_WG_Size 1001 // This reduction is typical for default case (no thread_limit clause). 1002 // or when user goes crazy with num_teams clause. 1003 // FIXME: We cant distinguish between a constant or variable thread limit. 1004 // So we only handle constant thread_limits. 1005 if (threadsPerGroup > 1006 RTLDeviceInfoTy::Default_WG_Size) // 256 < threadsPerGroup <= 1024 1007 // Should we round threadsPerGroup up to nearest WarpSize 1008 // here? 1009 num_groups = (Max_Teams * RTLDeviceInfoTy::Max_WG_Size) / threadsPerGroup; 1010 1011 // check for num_teams() clause 1012 if (num_teams > 0) { 1013 num_groups = (num_teams < num_groups) ? num_teams : num_groups; 1014 } 1015 if (print_kernel_trace & STARTUP_DETAILS) { 1016 DP("num_groups: %d\n", num_groups); 1017 DP("Env.NumTeams %d\n", Env.NumTeams); 1018 DP("Env.TeamLimit %d\n", Env.TeamLimit); 1019 } 1020 1021 if (Env.NumTeams > 0) { 1022 num_groups = (Env.NumTeams < num_groups) ? Env.NumTeams : num_groups; 1023 DP("Modifying teams based on Env.NumTeams %d\n", Env.NumTeams); 1024 } else if (Env.TeamLimit > 0) { 1025 num_groups = (Env.TeamLimit < num_groups) ? Env.TeamLimit : num_groups; 1026 DP("Modifying teams based on Env.TeamLimit%d\n", Env.TeamLimit); 1027 } else { 1028 if (num_teams <= 0) { 1029 if (loop_tripcount > 0) { 1030 if (ExecutionMode == 1031 llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_SPMD) { 1032 // round up to the nearest integer 1033 num_groups = ((loop_tripcount - 1) / threadsPerGroup) + 1; 1034 } else if (ExecutionMode == 1035 llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC) { 1036 num_groups = loop_tripcount; 1037 } else /* OMP_TGT_EXEC_MODE_GENERIC_SPMD */ { 1038 // This is a generic kernel that was transformed to use SPMD-mode 1039 // execution but uses Generic-mode semantics for scheduling. 1040 num_groups = loop_tripcount; 1041 } 1042 DP("Using %d teams due to loop trip count %" PRIu64 " and number of " 1043 "threads per block %d\n", 1044 num_groups, loop_tripcount, threadsPerGroup); 1045 } 1046 } else { 1047 num_groups = num_teams; 1048 } 1049 if (num_groups > Max_Teams) { 1050 num_groups = Max_Teams; 1051 if (print_kernel_trace & STARTUP_DETAILS) 1052 DP("Limiting num_groups %d to Max_Teams %d \n", num_groups, Max_Teams); 1053 } 1054 if (num_groups > num_teams && num_teams > 0) { 1055 num_groups = num_teams; 1056 if (print_kernel_trace & STARTUP_DETAILS) 1057 DP("Limiting num_groups %d to clause num_teams %d \n", num_groups, 1058 num_teams); 1059 } 1060 } 1061 1062 // num_teams clause always honored, no matter what, unless DEFAULT is active. 1063 if (num_teams > 0) { 1064 num_groups = num_teams; 1065 // Cap num_groups to EnvMaxTeamsDefault if set. 1066 if (Env.MaxTeamsDefault > 0 && num_groups > Env.MaxTeamsDefault) 1067 num_groups = Env.MaxTeamsDefault; 1068 } 1069 if (print_kernel_trace & STARTUP_DETAILS) { 1070 DP("threadsPerGroup: %d\n", threadsPerGroup); 1071 DP("num_groups: %d\n", num_groups); 1072 DP("loop_tripcount: %ld\n", loop_tripcount); 1073 } 1074 DP("Final %d num_groups and %d threadsPerGroup\n", num_groups, 1075 threadsPerGroup); 1076 1077 launchVals res; 1078 res.WorkgroupSize = threadsPerGroup; 1079 res.GridSize = threadsPerGroup * num_groups; 1080 return res; 1081 } 1082 1083 static uint64_t acquire_available_packet_id(hsa_queue_t *queue) { 1084 uint64_t packet_id = hsa_queue_add_write_index_relaxed(queue, 1); 1085 bool full = true; 1086 while (full) { 1087 full = 1088 packet_id >= (queue->size + hsa_queue_load_read_index_scacquire(queue)); 1089 } 1090 return packet_id; 1091 } 1092 1093 int32_t runRegionLocked(int32_t device_id, void *tgt_entry_ptr, void **tgt_args, 1094 ptrdiff_t *tgt_offsets, int32_t arg_num, 1095 int32_t num_teams, int32_t thread_limit, 1096 uint64_t loop_tripcount) { 1097 // Set the context we are using 1098 // update thread limit content in gpu memory if un-initialized or specified 1099 // from host 1100 1101 DP("Run target team region thread_limit %d\n", thread_limit); 1102 1103 // All args are references. 1104 std::vector<void *> args(arg_num); 1105 std::vector<void *> ptrs(arg_num); 1106 1107 DP("Arg_num: %d\n", arg_num); 1108 for (int32_t i = 0; i < arg_num; ++i) { 1109 ptrs[i] = (void *)((intptr_t)tgt_args[i] + tgt_offsets[i]); 1110 args[i] = &ptrs[i]; 1111 DP("Offseted base: arg[%d]:" DPxMOD "\n", i, DPxPTR(ptrs[i])); 1112 } 1113 1114 KernelTy *KernelInfo = (KernelTy *)tgt_entry_ptr; 1115 1116 std::string kernel_name = std::string(KernelInfo->Name); 1117 auto &KernelInfoTable = DeviceInfo.KernelInfoTable; 1118 if (KernelInfoTable[device_id].find(kernel_name) == 1119 KernelInfoTable[device_id].end()) { 1120 DP("Kernel %s not found\n", kernel_name.c_str()); 1121 return OFFLOAD_FAIL; 1122 } 1123 1124 const atl_kernel_info_t KernelInfoEntry = 1125 KernelInfoTable[device_id][kernel_name]; 1126 const uint32_t group_segment_size = KernelInfoEntry.group_segment_size; 1127 const uint32_t sgpr_count = KernelInfoEntry.sgpr_count; 1128 const uint32_t vgpr_count = KernelInfoEntry.vgpr_count; 1129 const uint32_t sgpr_spill_count = KernelInfoEntry.sgpr_spill_count; 1130 const uint32_t vgpr_spill_count = KernelInfoEntry.vgpr_spill_count; 1131 1132 assert(arg_num == (int)KernelInfoEntry.explicit_argument_count); 1133 1134 /* 1135 * Set limit based on ThreadsPerGroup and GroupsPerDevice 1136 */ 1137 launchVals LV = 1138 getLaunchVals(DeviceInfo.WarpSize[device_id], DeviceInfo.Env, 1139 KernelInfo->ConstWGSize, KernelInfo->ExecutionMode, 1140 num_teams, // From run_region arg 1141 thread_limit, // From run_region arg 1142 loop_tripcount, // From run_region arg 1143 DeviceInfo.NumTeams[KernelInfo->device_id]); 1144 const int GridSize = LV.GridSize; 1145 const int WorkgroupSize = LV.WorkgroupSize; 1146 1147 if (print_kernel_trace >= LAUNCH) { 1148 int num_groups = GridSize / WorkgroupSize; 1149 // enum modes are SPMD, GENERIC, NONE 0,1,2 1150 // if doing rtl timing, print to stderr, unless stdout requested. 1151 bool traceToStdout = print_kernel_trace & (RTL_TO_STDOUT | RTL_TIMING); 1152 fprintf(traceToStdout ? stdout : stderr, 1153 "DEVID:%2d SGN:%1d ConstWGSize:%-4d args:%2d teamsXthrds:(%4dX%4d) " 1154 "reqd:(%4dX%4d) lds_usage:%uB sgpr_count:%u vgpr_count:%u " 1155 "sgpr_spill_count:%u vgpr_spill_count:%u tripcount:%lu n:%s\n", 1156 device_id, KernelInfo->ExecutionMode, KernelInfo->ConstWGSize, 1157 arg_num, num_groups, WorkgroupSize, num_teams, thread_limit, 1158 group_segment_size, sgpr_count, vgpr_count, sgpr_spill_count, 1159 vgpr_spill_count, loop_tripcount, KernelInfo->Name); 1160 } 1161 1162 // Run on the device. 1163 { 1164 hsa_queue_t *queue = DeviceInfo.HSAQueueSchedulers[device_id].Next(); 1165 if (!queue) { 1166 return OFFLOAD_FAIL; 1167 } 1168 uint64_t packet_id = acquire_available_packet_id(queue); 1169 1170 const uint32_t mask = queue->size - 1; // size is a power of 2 1171 hsa_kernel_dispatch_packet_t *packet = 1172 (hsa_kernel_dispatch_packet_t *)queue->base_address + 1173 (packet_id & mask); 1174 1175 // packet->header is written last 1176 packet->setup = UINT16_C(1) << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS; 1177 packet->workgroup_size_x = WorkgroupSize; 1178 packet->workgroup_size_y = 1; 1179 packet->workgroup_size_z = 1; 1180 packet->reserved0 = 0; 1181 packet->grid_size_x = GridSize; 1182 packet->grid_size_y = 1; 1183 packet->grid_size_z = 1; 1184 packet->private_segment_size = KernelInfoEntry.private_segment_size; 1185 packet->group_segment_size = KernelInfoEntry.group_segment_size; 1186 packet->kernel_object = KernelInfoEntry.kernel_object; 1187 packet->kernarg_address = 0; // use the block allocator 1188 packet->reserved2 = 0; // impl writes id_ here 1189 packet->completion_signal = {0}; // may want a pool of signals 1190 1191 KernelArgPool *ArgPool = nullptr; 1192 void *kernarg = nullptr; 1193 { 1194 auto it = KernelArgPoolMap.find(std::string(KernelInfo->Name)); 1195 if (it != KernelArgPoolMap.end()) { 1196 ArgPool = (it->second).get(); 1197 } 1198 } 1199 if (!ArgPool) { 1200 DP("Warning: No ArgPool for %s on device %d\n", KernelInfo->Name, 1201 device_id); 1202 } 1203 { 1204 if (ArgPool) { 1205 assert(ArgPool->kernarg_segment_size == (arg_num * sizeof(void *))); 1206 kernarg = ArgPool->allocate(arg_num); 1207 } 1208 if (!kernarg) { 1209 DP("Allocate kernarg failed\n"); 1210 return OFFLOAD_FAIL; 1211 } 1212 1213 // Copy explicit arguments 1214 for (int i = 0; i < arg_num; i++) { 1215 memcpy((char *)kernarg + sizeof(void *) * i, args[i], sizeof(void *)); 1216 } 1217 1218 // Initialize implicit arguments. TODO: Which of these can be dropped 1219 impl_implicit_args_t *impl_args = 1220 reinterpret_cast<impl_implicit_args_t *>( 1221 static_cast<char *>(kernarg) + ArgPool->kernarg_segment_size); 1222 memset(impl_args, 0, 1223 sizeof(impl_implicit_args_t)); // may not be necessary 1224 impl_args->offset_x = 0; 1225 impl_args->offset_y = 0; 1226 impl_args->offset_z = 0; 1227 1228 // assign a hostcall buffer for the selected Q 1229 if (__atomic_load_n(&DeviceInfo.hostcall_required, __ATOMIC_ACQUIRE)) { 1230 // hostrpc_assign_buffer is not thread safe, and this function is 1231 // under a multiple reader lock, not a writer lock. 1232 static pthread_mutex_t hostcall_init_lock = PTHREAD_MUTEX_INITIALIZER; 1233 pthread_mutex_lock(&hostcall_init_lock); 1234 unsigned long buffer = hostrpc_assign_buffer( 1235 DeviceInfo.HSAAgents[device_id], queue, device_id); 1236 pthread_mutex_unlock(&hostcall_init_lock); 1237 if (!buffer) { 1238 DP("hostrpc_assign_buffer failed, gpu would dereference null and " 1239 "error\n"); 1240 return OFFLOAD_FAIL; 1241 } 1242 1243 if (KernelInfoEntry.implicit_argument_count >= 4) { 1244 // Initialise pointer for implicit_argument_count != 0 ABI 1245 // Guess that the right implicit argument is at offset 24 after 1246 // the explicit arguments. In the future, should be able to read 1247 // the offset from msgpack. Clang is not annotating it at present. 1248 uint64_t Offset = 1249 sizeof(void *) * (KernelInfoEntry.explicit_argument_count + 3); 1250 if ((Offset + 8) > (ArgPool->kernarg_segment_size)) { 1251 DP("Bad offset of hostcall, exceeds kernarg segment size\n"); 1252 } else { 1253 memcpy(static_cast<char *>(kernarg) + Offset, &buffer, 8); 1254 } 1255 } 1256 1257 // initialise pointer for implicit_argument_count == 0 ABI 1258 impl_args->hostcall_ptr = buffer; 1259 } 1260 1261 packet->kernarg_address = kernarg; 1262 } 1263 1264 hsa_signal_t s = DeviceInfo.FreeSignalPool.pop(); 1265 if (s.handle == 0) { 1266 DP("Failed to get signal instance\n"); 1267 return OFFLOAD_FAIL; 1268 } 1269 packet->completion_signal = s; 1270 hsa_signal_store_relaxed(packet->completion_signal, 1); 1271 1272 // Publish the packet indicating it is ready to be processed 1273 core::packet_store_release(reinterpret_cast<uint32_t *>(packet), 1274 core::create_header(), packet->setup); 1275 1276 // Since the packet is already published, its contents must not be 1277 // accessed any more 1278 hsa_signal_store_relaxed(queue->doorbell_signal, packet_id); 1279 1280 while (hsa_signal_wait_scacquire(s, HSA_SIGNAL_CONDITION_EQ, 0, UINT64_MAX, 1281 HSA_WAIT_STATE_BLOCKED) != 0) 1282 ; 1283 1284 assert(ArgPool); 1285 ArgPool->deallocate(kernarg); 1286 DeviceInfo.FreeSignalPool.push(s); 1287 } 1288 1289 DP("Kernel completed\n"); 1290 return OFFLOAD_SUCCESS; 1291 } 1292 1293 bool elf_machine_id_is_amdgcn(__tgt_device_image *image) { 1294 const uint16_t amdgcnMachineID = 224; // EM_AMDGPU may not be in system elf.h 1295 int32_t r = elf_check_machine(image, amdgcnMachineID); 1296 if (!r) { 1297 DP("Supported machine ID not found\n"); 1298 } 1299 return r; 1300 } 1301 1302 uint32_t elf_e_flags(__tgt_device_image *image) { 1303 char *img_begin = (char *)image->ImageStart; 1304 size_t img_size = (char *)image->ImageEnd - img_begin; 1305 1306 Elf *e = elf_memory(img_begin, img_size); 1307 if (!e) { 1308 DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1)); 1309 return 0; 1310 } 1311 1312 Elf64_Ehdr *eh64 = elf64_getehdr(e); 1313 1314 if (!eh64) { 1315 DP("Unable to get machine ID from ELF file!\n"); 1316 elf_end(e); 1317 return 0; 1318 } 1319 1320 uint32_t Flags = eh64->e_flags; 1321 1322 elf_end(e); 1323 DP("ELF Flags: 0x%x\n", Flags); 1324 return Flags; 1325 } 1326 } // namespace 1327 1328 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) { 1329 return elf_machine_id_is_amdgcn(image); 1330 } 1331 1332 int __tgt_rtl_number_of_devices() { 1333 // If the construction failed, no methods are safe to call 1334 if (DeviceInfo.ConstructionSucceeded) { 1335 return DeviceInfo.NumberOfDevices; 1336 } else { 1337 DP("AMDGPU plugin construction failed. Zero devices available\n"); 1338 return 0; 1339 } 1340 } 1341 1342 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) { 1343 DP("Init requires flags to %ld\n", RequiresFlags); 1344 DeviceInfo.RequiresFlags = RequiresFlags; 1345 return RequiresFlags; 1346 } 1347 1348 namespace { 1349 template <typename T> bool enforce_upper_bound(T *value, T upper) { 1350 bool changed = *value > upper; 1351 if (changed) { 1352 *value = upper; 1353 } 1354 return changed; 1355 } 1356 } // namespace 1357 1358 int32_t __tgt_rtl_init_device(int device_id) { 1359 hsa_status_t err; 1360 1361 // this is per device id init 1362 DP("Initialize the device id: %d\n", device_id); 1363 1364 hsa_agent_t agent = DeviceInfo.HSAAgents[device_id]; 1365 1366 // Get number of Compute Unit 1367 uint32_t compute_units = 0; 1368 err = hsa_agent_get_info( 1369 agent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT, 1370 &compute_units); 1371 if (err != HSA_STATUS_SUCCESS) { 1372 DeviceInfo.ComputeUnits[device_id] = 1; 1373 DP("Error getting compute units : settiing to 1\n"); 1374 } else { 1375 DeviceInfo.ComputeUnits[device_id] = compute_units; 1376 DP("Using %d compute unis per grid\n", DeviceInfo.ComputeUnits[device_id]); 1377 } 1378 1379 char GetInfoName[64]; // 64 max size returned by get info 1380 err = hsa_agent_get_info(agent, (hsa_agent_info_t)HSA_AGENT_INFO_NAME, 1381 (void *)GetInfoName); 1382 if (err) 1383 DeviceInfo.GPUName[device_id] = "--unknown gpu--"; 1384 else { 1385 DeviceInfo.GPUName[device_id] = GetInfoName; 1386 } 1387 1388 if (print_kernel_trace & STARTUP_DETAILS) 1389 DP("Device#%-2d CU's: %2d %s\n", device_id, 1390 DeviceInfo.ComputeUnits[device_id], 1391 DeviceInfo.GPUName[device_id].c_str()); 1392 1393 // Query attributes to determine number of threads/block and blocks/grid. 1394 uint16_t workgroup_max_dim[3]; 1395 err = hsa_agent_get_info(agent, HSA_AGENT_INFO_WORKGROUP_MAX_DIM, 1396 &workgroup_max_dim); 1397 if (err != HSA_STATUS_SUCCESS) { 1398 DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::DefaultNumTeams; 1399 DP("Error getting grid dims: num groups : %d\n", 1400 RTLDeviceInfoTy::DefaultNumTeams); 1401 } else if (workgroup_max_dim[0] <= RTLDeviceInfoTy::HardTeamLimit) { 1402 DeviceInfo.GroupsPerDevice[device_id] = workgroup_max_dim[0]; 1403 DP("Using %d ROCm blocks per grid\n", 1404 DeviceInfo.GroupsPerDevice[device_id]); 1405 } else { 1406 DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::HardTeamLimit; 1407 DP("Max ROCm blocks per grid %d exceeds the hard team limit %d, capping " 1408 "at the hard limit\n", 1409 workgroup_max_dim[0], RTLDeviceInfoTy::HardTeamLimit); 1410 } 1411 1412 // Get thread limit 1413 hsa_dim3_t grid_max_dim; 1414 err = hsa_agent_get_info(agent, HSA_AGENT_INFO_GRID_MAX_DIM, &grid_max_dim); 1415 if (err == HSA_STATUS_SUCCESS) { 1416 DeviceInfo.ThreadsPerGroup[device_id] = 1417 reinterpret_cast<uint32_t *>(&grid_max_dim)[0] / 1418 DeviceInfo.GroupsPerDevice[device_id]; 1419 1420 if (DeviceInfo.ThreadsPerGroup[device_id] == 0) { 1421 DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size; 1422 DP("Default thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size); 1423 } else if (enforce_upper_bound(&DeviceInfo.ThreadsPerGroup[device_id], 1424 RTLDeviceInfoTy::Max_WG_Size)) { 1425 DP("Capped thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size); 1426 } else { 1427 DP("Using ROCm Queried thread limit: %d\n", 1428 DeviceInfo.ThreadsPerGroup[device_id]); 1429 } 1430 } else { 1431 DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size; 1432 DP("Error getting max block dimension, use default:%d \n", 1433 RTLDeviceInfoTy::Max_WG_Size); 1434 } 1435 1436 // Get wavefront size 1437 uint32_t wavefront_size = 0; 1438 err = 1439 hsa_agent_get_info(agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size); 1440 if (err == HSA_STATUS_SUCCESS) { 1441 DP("Queried wavefront size: %d\n", wavefront_size); 1442 DeviceInfo.WarpSize[device_id] = wavefront_size; 1443 } else { 1444 // TODO: Burn the wavefront size into the code object 1445 DP("Warning: Unknown wavefront size, assuming 64\n"); 1446 DeviceInfo.WarpSize[device_id] = 64; 1447 } 1448 1449 // Adjust teams to the env variables 1450 1451 if (DeviceInfo.Env.TeamLimit > 0 && 1452 (enforce_upper_bound(&DeviceInfo.GroupsPerDevice[device_id], 1453 DeviceInfo.Env.TeamLimit))) { 1454 DP("Capping max groups per device to OMP_TEAM_LIMIT=%d\n", 1455 DeviceInfo.Env.TeamLimit); 1456 } 1457 1458 // Set default number of teams 1459 if (DeviceInfo.Env.NumTeams > 0) { 1460 DeviceInfo.NumTeams[device_id] = DeviceInfo.Env.NumTeams; 1461 DP("Default number of teams set according to environment %d\n", 1462 DeviceInfo.Env.NumTeams); 1463 } else { 1464 char *TeamsPerCUEnvStr = getenv("OMP_TARGET_TEAMS_PER_PROC"); 1465 int TeamsPerCU = DefaultTeamsPerCU; 1466 if (TeamsPerCUEnvStr) { 1467 TeamsPerCU = std::stoi(TeamsPerCUEnvStr); 1468 } 1469 1470 DeviceInfo.NumTeams[device_id] = 1471 TeamsPerCU * DeviceInfo.ComputeUnits[device_id]; 1472 DP("Default number of teams = %d * number of compute units %d\n", 1473 TeamsPerCU, DeviceInfo.ComputeUnits[device_id]); 1474 } 1475 1476 if (enforce_upper_bound(&DeviceInfo.NumTeams[device_id], 1477 DeviceInfo.GroupsPerDevice[device_id])) { 1478 DP("Default number of teams exceeds device limit, capping at %d\n", 1479 DeviceInfo.GroupsPerDevice[device_id]); 1480 } 1481 1482 // Adjust threads to the env variables 1483 if (DeviceInfo.Env.TeamThreadLimit > 0 && 1484 (enforce_upper_bound(&DeviceInfo.NumThreads[device_id], 1485 DeviceInfo.Env.TeamThreadLimit))) { 1486 DP("Capping max number of threads to OMP_TEAMS_THREAD_LIMIT=%d\n", 1487 DeviceInfo.Env.TeamThreadLimit); 1488 } 1489 1490 // Set default number of threads 1491 DeviceInfo.NumThreads[device_id] = RTLDeviceInfoTy::Default_WG_Size; 1492 DP("Default number of threads set according to library's default %d\n", 1493 RTLDeviceInfoTy::Default_WG_Size); 1494 if (enforce_upper_bound(&DeviceInfo.NumThreads[device_id], 1495 DeviceInfo.ThreadsPerGroup[device_id])) { 1496 DP("Default number of threads exceeds device limit, capping at %d\n", 1497 DeviceInfo.ThreadsPerGroup[device_id]); 1498 } 1499 1500 DP("Device %d: default limit for groupsPerDevice %d & threadsPerGroup %d\n", 1501 device_id, DeviceInfo.GroupsPerDevice[device_id], 1502 DeviceInfo.ThreadsPerGroup[device_id]); 1503 1504 DP("Device %d: wavefront size %d, total threads %d x %d = %d\n", device_id, 1505 DeviceInfo.WarpSize[device_id], DeviceInfo.ThreadsPerGroup[device_id], 1506 DeviceInfo.GroupsPerDevice[device_id], 1507 DeviceInfo.GroupsPerDevice[device_id] * 1508 DeviceInfo.ThreadsPerGroup[device_id]); 1509 1510 return OFFLOAD_SUCCESS; 1511 } 1512 1513 namespace { 1514 Elf64_Shdr *find_only_SHT_HASH(Elf *elf) { 1515 size_t N; 1516 int rc = elf_getshdrnum(elf, &N); 1517 if (rc != 0) { 1518 return nullptr; 1519 } 1520 1521 Elf64_Shdr *result = nullptr; 1522 for (size_t i = 0; i < N; i++) { 1523 Elf_Scn *scn = elf_getscn(elf, i); 1524 if (scn) { 1525 Elf64_Shdr *shdr = elf64_getshdr(scn); 1526 if (shdr) { 1527 if (shdr->sh_type == SHT_HASH) { 1528 if (result == nullptr) { 1529 result = shdr; 1530 } else { 1531 // multiple SHT_HASH sections not handled 1532 return nullptr; 1533 } 1534 } 1535 } 1536 } 1537 } 1538 return result; 1539 } 1540 1541 const Elf64_Sym *elf_lookup(Elf *elf, char *base, Elf64_Shdr *section_hash, 1542 const char *symname) { 1543 1544 assert(section_hash); 1545 size_t section_symtab_index = section_hash->sh_link; 1546 Elf64_Shdr *section_symtab = 1547 elf64_getshdr(elf_getscn(elf, section_symtab_index)); 1548 size_t section_strtab_index = section_symtab->sh_link; 1549 1550 const Elf64_Sym *symtab = 1551 reinterpret_cast<const Elf64_Sym *>(base + section_symtab->sh_offset); 1552 1553 const uint32_t *hashtab = 1554 reinterpret_cast<const uint32_t *>(base + section_hash->sh_offset); 1555 1556 // Layout: 1557 // nbucket 1558 // nchain 1559 // bucket[nbucket] 1560 // chain[nchain] 1561 uint32_t nbucket = hashtab[0]; 1562 const uint32_t *bucket = &hashtab[2]; 1563 const uint32_t *chain = &hashtab[nbucket + 2]; 1564 1565 const size_t max = strlen(symname) + 1; 1566 const uint32_t hash = elf_hash(symname); 1567 for (uint32_t i = bucket[hash % nbucket]; i != 0; i = chain[i]) { 1568 char *n = elf_strptr(elf, section_strtab_index, symtab[i].st_name); 1569 if (strncmp(symname, n, max) == 0) { 1570 return &symtab[i]; 1571 } 1572 } 1573 1574 return nullptr; 1575 } 1576 1577 struct symbol_info { 1578 void *addr = nullptr; 1579 uint32_t size = UINT32_MAX; 1580 uint32_t sh_type = SHT_NULL; 1581 }; 1582 1583 int get_symbol_info_without_loading(Elf *elf, char *base, const char *symname, 1584 symbol_info *res) { 1585 if (elf_kind(elf) != ELF_K_ELF) { 1586 return 1; 1587 } 1588 1589 Elf64_Shdr *section_hash = find_only_SHT_HASH(elf); 1590 if (!section_hash) { 1591 return 1; 1592 } 1593 1594 const Elf64_Sym *sym = elf_lookup(elf, base, section_hash, symname); 1595 if (!sym) { 1596 return 1; 1597 } 1598 1599 if (sym->st_size > UINT32_MAX) { 1600 return 1; 1601 } 1602 1603 if (sym->st_shndx == SHN_UNDEF) { 1604 return 1; 1605 } 1606 1607 Elf_Scn *section = elf_getscn(elf, sym->st_shndx); 1608 if (!section) { 1609 return 1; 1610 } 1611 1612 Elf64_Shdr *header = elf64_getshdr(section); 1613 if (!header) { 1614 return 1; 1615 } 1616 1617 res->addr = sym->st_value + base; 1618 res->size = static_cast<uint32_t>(sym->st_size); 1619 res->sh_type = header->sh_type; 1620 return 0; 1621 } 1622 1623 int get_symbol_info_without_loading(char *base, size_t img_size, 1624 const char *symname, symbol_info *res) { 1625 Elf *elf = elf_memory(base, img_size); 1626 if (elf) { 1627 int rc = get_symbol_info_without_loading(elf, base, symname, res); 1628 elf_end(elf); 1629 return rc; 1630 } 1631 return 1; 1632 } 1633 1634 hsa_status_t interop_get_symbol_info(char *base, size_t img_size, 1635 const char *symname, void **var_addr, 1636 uint32_t *var_size) { 1637 symbol_info si; 1638 int rc = get_symbol_info_without_loading(base, img_size, symname, &si); 1639 if (rc == 0) { 1640 *var_addr = si.addr; 1641 *var_size = si.size; 1642 return HSA_STATUS_SUCCESS; 1643 } else { 1644 return HSA_STATUS_ERROR; 1645 } 1646 } 1647 1648 template <typename C> 1649 hsa_status_t module_register_from_memory_to_place( 1650 std::map<std::string, atl_kernel_info_t> &KernelInfoTable, 1651 std::map<std::string, atl_symbol_info_t> &SymbolInfoTable, 1652 void *module_bytes, size_t module_size, int DeviceId, C cb, 1653 std::vector<hsa_executable_t> &HSAExecutables) { 1654 auto L = [](void *data, size_t size, void *cb_state) -> hsa_status_t { 1655 C *unwrapped = static_cast<C *>(cb_state); 1656 return (*unwrapped)(data, size); 1657 }; 1658 return core::RegisterModuleFromMemory( 1659 KernelInfoTable, SymbolInfoTable, module_bytes, module_size, 1660 DeviceInfo.HSAAgents[DeviceId], L, static_cast<void *>(&cb), 1661 HSAExecutables); 1662 } 1663 } // namespace 1664 1665 static uint64_t get_device_State_bytes(char *ImageStart, size_t img_size) { 1666 uint64_t device_State_bytes = 0; 1667 { 1668 // If this is the deviceRTL, get the state variable size 1669 symbol_info size_si; 1670 int rc = get_symbol_info_without_loading( 1671 ImageStart, img_size, "omptarget_nvptx_device_State_size", &size_si); 1672 1673 if (rc == 0) { 1674 if (size_si.size != sizeof(uint64_t)) { 1675 DP("Found device_State_size variable with wrong size\n"); 1676 return 0; 1677 } 1678 1679 // Read number of bytes directly from the elf 1680 memcpy(&device_State_bytes, size_si.addr, sizeof(uint64_t)); 1681 } 1682 } 1683 return device_State_bytes; 1684 } 1685 1686 static __tgt_target_table * 1687 __tgt_rtl_load_binary_locked(int32_t device_id, __tgt_device_image *image); 1688 1689 static __tgt_target_table * 1690 __tgt_rtl_load_binary_locked(int32_t device_id, __tgt_device_image *image); 1691 1692 __tgt_target_table *__tgt_rtl_load_binary(int32_t device_id, 1693 __tgt_device_image *image) { 1694 DeviceInfo.load_run_lock.lock(); 1695 __tgt_target_table *res = __tgt_rtl_load_binary_locked(device_id, image); 1696 DeviceInfo.load_run_lock.unlock(); 1697 return res; 1698 } 1699 1700 struct device_environment { 1701 // initialise an DeviceEnvironmentTy in the deviceRTL 1702 // patches around differences in the deviceRTL between trunk, aomp, 1703 // rocmcc. Over time these differences will tend to zero and this class 1704 // simplified. 1705 // Symbol may be in .data or .bss, and may be missing fields, todo: 1706 // review aomp/trunk/rocm and simplify the following 1707 1708 // The symbol may also have been deadstripped because the device side 1709 // accessors were unused. 1710 1711 // If the symbol is in .data (aomp, rocm) it can be written directly. 1712 // If it is in .bss, we must wait for it to be allocated space on the 1713 // gpu (trunk) and initialize after loading. 1714 const char *sym() { return "omptarget_device_environment"; } 1715 1716 DeviceEnvironmentTy host_device_env; 1717 symbol_info si; 1718 bool valid = false; 1719 1720 __tgt_device_image *image; 1721 const size_t img_size; 1722 1723 device_environment(int device_id, int number_devices, 1724 __tgt_device_image *image, const size_t img_size) 1725 : image(image), img_size(img_size) { 1726 1727 host_device_env.NumDevices = number_devices; 1728 host_device_env.DeviceNum = device_id; 1729 host_device_env.DebugKind = 0; 1730 host_device_env.DynamicMemSize = 0; 1731 if (char *envStr = getenv("LIBOMPTARGET_DEVICE_RTL_DEBUG")) { 1732 host_device_env.DebugKind = std::stoi(envStr); 1733 } 1734 1735 int rc = get_symbol_info_without_loading((char *)image->ImageStart, 1736 img_size, sym(), &si); 1737 if (rc != 0) { 1738 DP("Finding global device environment '%s' - symbol missing.\n", sym()); 1739 return; 1740 } 1741 1742 if (si.size > sizeof(host_device_env)) { 1743 DP("Symbol '%s' has size %u, expected at most %zu.\n", sym(), si.size, 1744 sizeof(host_device_env)); 1745 return; 1746 } 1747 1748 valid = true; 1749 } 1750 1751 bool in_image() { return si.sh_type != SHT_NOBITS; } 1752 1753 hsa_status_t before_loading(void *data, size_t size) { 1754 if (valid) { 1755 if (in_image()) { 1756 DP("Setting global device environment before load (%u bytes)\n", 1757 si.size); 1758 uint64_t offset = (char *)si.addr - (char *)image->ImageStart; 1759 void *pos = (char *)data + offset; 1760 memcpy(pos, &host_device_env, si.size); 1761 } 1762 } 1763 return HSA_STATUS_SUCCESS; 1764 } 1765 1766 hsa_status_t after_loading() { 1767 if (valid) { 1768 if (!in_image()) { 1769 DP("Setting global device environment after load (%u bytes)\n", 1770 si.size); 1771 int device_id = host_device_env.DeviceNum; 1772 auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id]; 1773 void *state_ptr; 1774 uint32_t state_ptr_size; 1775 hsa_status_t err = interop_hsa_get_symbol_info( 1776 SymbolInfo, device_id, sym(), &state_ptr, &state_ptr_size); 1777 if (err != HSA_STATUS_SUCCESS) { 1778 DP("failed to find %s in loaded image\n", sym()); 1779 return err; 1780 } 1781 1782 if (state_ptr_size != si.size) { 1783 DP("Symbol had size %u before loading, %u after\n", state_ptr_size, 1784 si.size); 1785 return HSA_STATUS_ERROR; 1786 } 1787 1788 return DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &host_device_env, 1789 state_ptr_size, device_id); 1790 } 1791 } 1792 return HSA_STATUS_SUCCESS; 1793 } 1794 }; 1795 1796 static hsa_status_t impl_calloc(void **ret_ptr, size_t size, int DeviceId) { 1797 uint64_t rounded = 4 * ((size + 3) / 4); 1798 void *ptr; 1799 hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(DeviceId); 1800 hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, rounded, 0, &ptr); 1801 if (err != HSA_STATUS_SUCCESS) { 1802 return err; 1803 } 1804 1805 hsa_status_t rc = hsa_amd_memory_fill(ptr, 0, rounded / 4); 1806 if (rc != HSA_STATUS_SUCCESS) { 1807 DP("zero fill device_state failed with %u\n", rc); 1808 core::Runtime::Memfree(ptr); 1809 return HSA_STATUS_ERROR; 1810 } 1811 1812 *ret_ptr = ptr; 1813 return HSA_STATUS_SUCCESS; 1814 } 1815 1816 static bool image_contains_symbol(void *data, size_t size, const char *sym) { 1817 symbol_info si; 1818 int rc = get_symbol_info_without_loading((char *)data, size, sym, &si); 1819 return (rc == 0) && (si.addr != nullptr); 1820 } 1821 1822 __tgt_target_table *__tgt_rtl_load_binary_locked(int32_t device_id, 1823 __tgt_device_image *image) { 1824 // This function loads the device image onto gpu[device_id] and does other 1825 // per-image initialization work. Specifically: 1826 // 1827 // - Initialize an DeviceEnvironmentTy instance embedded in the 1828 // image at the symbol "omptarget_device_environment" 1829 // Fields DebugKind, DeviceNum, NumDevices. Used by the deviceRTL. 1830 // 1831 // - Allocate a large array per-gpu (could be moved to init_device) 1832 // - Read a uint64_t at symbol omptarget_nvptx_device_State_size 1833 // - Allocate at least that many bytes of gpu memory 1834 // - Zero initialize it 1835 // - Write the pointer to the symbol omptarget_nvptx_device_State 1836 // 1837 // - Pulls some per-kernel information together from various sources and 1838 // records it in the KernelsList for quicker access later 1839 // 1840 // The initialization can be done before or after loading the image onto the 1841 // gpu. This function presently does a mixture. Using the hsa api to get/set 1842 // the information is simpler to implement, in exchange for more complicated 1843 // runtime behaviour. E.g. launching a kernel or using dma to get eight bytes 1844 // back from the gpu vs a hashtable lookup on the host. 1845 1846 const size_t img_size = (char *)image->ImageEnd - (char *)image->ImageStart; 1847 1848 DeviceInfo.clearOffloadEntriesTable(device_id); 1849 1850 // We do not need to set the ELF version because the caller of this function 1851 // had to do that to decide the right runtime to use 1852 1853 if (!elf_machine_id_is_amdgcn(image)) { 1854 return NULL; 1855 } 1856 1857 { 1858 auto env = device_environment(device_id, DeviceInfo.NumberOfDevices, image, 1859 img_size); 1860 1861 auto &KernelInfo = DeviceInfo.KernelInfoTable[device_id]; 1862 auto &SymbolInfo = DeviceInfo.SymbolInfoTable[device_id]; 1863 hsa_status_t err = module_register_from_memory_to_place( 1864 KernelInfo, SymbolInfo, (void *)image->ImageStart, img_size, device_id, 1865 [&](void *data, size_t size) { 1866 if (image_contains_symbol(data, size, "needs_hostcall_buffer")) { 1867 __atomic_store_n(&DeviceInfo.hostcall_required, true, 1868 __ATOMIC_RELEASE); 1869 } 1870 return env.before_loading(data, size); 1871 }, 1872 DeviceInfo.HSAExecutables); 1873 1874 check("Module registering", err); 1875 if (err != HSA_STATUS_SUCCESS) { 1876 const char *DeviceName = DeviceInfo.GPUName[device_id].c_str(); 1877 const char *ElfName = get_elf_mach_gfx_name(elf_e_flags(image)); 1878 1879 if (strcmp(DeviceName, ElfName) != 0) { 1880 DP("Possible gpu arch mismatch: device:%s, image:%s please check" 1881 " compiler flag: -march=<gpu>\n", 1882 DeviceName, ElfName); 1883 } else { 1884 DP("Error loading image onto GPU: %s\n", get_error_string(err)); 1885 } 1886 1887 return NULL; 1888 } 1889 1890 err = env.after_loading(); 1891 if (err != HSA_STATUS_SUCCESS) { 1892 return NULL; 1893 } 1894 } 1895 1896 DP("AMDGPU module successfully loaded!\n"); 1897 1898 { 1899 // the device_State array is either large value in bss or a void* that 1900 // needs to be assigned to a pointer to an array of size device_state_bytes 1901 // If absent, it has been deadstripped and needs no setup. 1902 1903 void *state_ptr; 1904 uint32_t state_ptr_size; 1905 auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id]; 1906 hsa_status_t err = interop_hsa_get_symbol_info( 1907 SymbolInfoMap, device_id, "omptarget_nvptx_device_State", &state_ptr, 1908 &state_ptr_size); 1909 1910 if (err != HSA_STATUS_SUCCESS) { 1911 DP("No device_state symbol found, skipping initialization\n"); 1912 } else { 1913 if (state_ptr_size < sizeof(void *)) { 1914 DP("unexpected size of state_ptr %u != %zu\n", state_ptr_size, 1915 sizeof(void *)); 1916 return NULL; 1917 } 1918 1919 // if it's larger than a void*, assume it's a bss array and no further 1920 // initialization is required. Only try to set up a pointer for 1921 // sizeof(void*) 1922 if (state_ptr_size == sizeof(void *)) { 1923 uint64_t device_State_bytes = 1924 get_device_State_bytes((char *)image->ImageStart, img_size); 1925 if (device_State_bytes == 0) { 1926 DP("Can't initialize device_State, missing size information\n"); 1927 return NULL; 1928 } 1929 1930 auto &dss = DeviceInfo.deviceStateStore[device_id]; 1931 if (dss.first.get() == nullptr) { 1932 assert(dss.second == 0); 1933 void *ptr = NULL; 1934 hsa_status_t err = impl_calloc(&ptr, device_State_bytes, device_id); 1935 if (err != HSA_STATUS_SUCCESS) { 1936 DP("Failed to allocate device_state array\n"); 1937 return NULL; 1938 } 1939 dss = { 1940 std::unique_ptr<void, RTLDeviceInfoTy::implFreePtrDeletor>{ptr}, 1941 device_State_bytes, 1942 }; 1943 } 1944 1945 void *ptr = dss.first.get(); 1946 if (device_State_bytes != dss.second) { 1947 DP("Inconsistent sizes of device_State unsupported\n"); 1948 return NULL; 1949 } 1950 1951 // write ptr to device memory so it can be used by later kernels 1952 err = DeviceInfo.freesignalpool_memcpy_h2d(state_ptr, &ptr, 1953 sizeof(void *), device_id); 1954 if (err != HSA_STATUS_SUCCESS) { 1955 DP("memcpy install of state_ptr failed\n"); 1956 return NULL; 1957 } 1958 } 1959 } 1960 } 1961 1962 // Here, we take advantage of the data that is appended after img_end to get 1963 // the symbols' name we need to load. This data consist of the host entries 1964 // begin and end as well as the target name (see the offloading linker script 1965 // creation in clang compiler). 1966 1967 // Find the symbols in the module by name. The name can be obtain by 1968 // concatenating the host entry name with the target name 1969 1970 __tgt_offload_entry *HostBegin = image->EntriesBegin; 1971 __tgt_offload_entry *HostEnd = image->EntriesEnd; 1972 1973 for (__tgt_offload_entry *e = HostBegin; e != HostEnd; ++e) { 1974 1975 if (!e->addr) { 1976 // The host should have always something in the address to 1977 // uniquely identify the target region. 1978 DP("Analyzing host entry '<null>' (size = %lld)...\n", 1979 (unsigned long long)e->size); 1980 return NULL; 1981 } 1982 1983 if (e->size) { 1984 __tgt_offload_entry entry = *e; 1985 1986 void *varptr; 1987 uint32_t varsize; 1988 1989 auto &SymbolInfoMap = DeviceInfo.SymbolInfoTable[device_id]; 1990 hsa_status_t err = interop_hsa_get_symbol_info( 1991 SymbolInfoMap, device_id, e->name, &varptr, &varsize); 1992 1993 if (err != HSA_STATUS_SUCCESS) { 1994 // Inform the user what symbol prevented offloading 1995 DP("Loading global '%s' (Failed)\n", e->name); 1996 return NULL; 1997 } 1998 1999 if (varsize != e->size) { 2000 DP("Loading global '%s' - size mismatch (%u != %lu)\n", e->name, 2001 varsize, e->size); 2002 return NULL; 2003 } 2004 2005 DP("Entry point " DPxMOD " maps to global %s (" DPxMOD ")\n", 2006 DPxPTR(e - HostBegin), e->name, DPxPTR(varptr)); 2007 entry.addr = (void *)varptr; 2008 2009 DeviceInfo.addOffloadEntry(device_id, entry); 2010 2011 if (DeviceInfo.RequiresFlags & OMP_REQ_UNIFIED_SHARED_MEMORY && 2012 e->flags & OMP_DECLARE_TARGET_LINK) { 2013 // If unified memory is present any target link variables 2014 // can access host addresses directly. There is no longer a 2015 // need for device copies. 2016 err = DeviceInfo.freesignalpool_memcpy_h2d(varptr, e->addr, 2017 sizeof(void *), device_id); 2018 if (err != HSA_STATUS_SUCCESS) 2019 DP("Error when copying USM\n"); 2020 DP("Copy linked variable host address (" DPxMOD ")" 2021 "to device address (" DPxMOD ")\n", 2022 DPxPTR(*((void **)e->addr)), DPxPTR(varptr)); 2023 } 2024 2025 continue; 2026 } 2027 2028 DP("to find the kernel name: %s size: %lu\n", e->name, strlen(e->name)); 2029 2030 // errors in kernarg_segment_size previously treated as = 0 (or as undef) 2031 uint32_t kernarg_segment_size = 0; 2032 auto &KernelInfoMap = DeviceInfo.KernelInfoTable[device_id]; 2033 hsa_status_t err = HSA_STATUS_SUCCESS; 2034 if (!e->name) { 2035 err = HSA_STATUS_ERROR; 2036 } else { 2037 std::string kernelStr = std::string(e->name); 2038 auto It = KernelInfoMap.find(kernelStr); 2039 if (It != KernelInfoMap.end()) { 2040 atl_kernel_info_t info = It->second; 2041 kernarg_segment_size = info.kernel_segment_size; 2042 } else { 2043 err = HSA_STATUS_ERROR; 2044 } 2045 } 2046 2047 // default value GENERIC (in case symbol is missing from cubin file) 2048 llvm::omp::OMPTgtExecModeFlags ExecModeVal = 2049 llvm::omp::OMPTgtExecModeFlags::OMP_TGT_EXEC_MODE_GENERIC; 2050 2051 // get flat group size if present, else Default_WG_Size 2052 int16_t WGSizeVal = RTLDeviceInfoTy::Default_WG_Size; 2053 2054 // get Kernel Descriptor if present. 2055 // Keep struct in sync wih getTgtAttributeStructQTy in CGOpenMPRuntime.cpp 2056 struct KernDescValType { 2057 uint16_t Version; 2058 uint16_t TSize; 2059 uint16_t WG_Size; 2060 }; 2061 struct KernDescValType KernDescVal; 2062 std::string KernDescNameStr(e->name); 2063 KernDescNameStr += "_kern_desc"; 2064 const char *KernDescName = KernDescNameStr.c_str(); 2065 2066 void *KernDescPtr; 2067 uint32_t KernDescSize; 2068 void *CallStackAddr = nullptr; 2069 err = interop_get_symbol_info((char *)image->ImageStart, img_size, 2070 KernDescName, &KernDescPtr, &KernDescSize); 2071 2072 if (err == HSA_STATUS_SUCCESS) { 2073 if ((size_t)KernDescSize != sizeof(KernDescVal)) 2074 DP("Loading global computation properties '%s' - size mismatch (%u != " 2075 "%lu)\n", 2076 KernDescName, KernDescSize, sizeof(KernDescVal)); 2077 2078 memcpy(&KernDescVal, KernDescPtr, (size_t)KernDescSize); 2079 2080 // Check structure size against recorded size. 2081 if ((size_t)KernDescSize != KernDescVal.TSize) 2082 DP("KernDescVal size %lu does not match advertized size %d for '%s'\n", 2083 sizeof(KernDescVal), KernDescVal.TSize, KernDescName); 2084 2085 DP("After loading global for %s KernDesc \n", KernDescName); 2086 DP("KernDesc: Version: %d\n", KernDescVal.Version); 2087 DP("KernDesc: TSize: %d\n", KernDescVal.TSize); 2088 DP("KernDesc: WG_Size: %d\n", KernDescVal.WG_Size); 2089 2090 if (KernDescVal.WG_Size == 0) { 2091 KernDescVal.WG_Size = RTLDeviceInfoTy::Default_WG_Size; 2092 DP("Setting KernDescVal.WG_Size to default %d\n", KernDescVal.WG_Size); 2093 } 2094 WGSizeVal = KernDescVal.WG_Size; 2095 DP("WGSizeVal %d\n", WGSizeVal); 2096 check("Loading KernDesc computation property", err); 2097 } else { 2098 DP("Warning: Loading KernDesc '%s' - symbol not found, ", KernDescName); 2099 2100 // Flat group size 2101 std::string WGSizeNameStr(e->name); 2102 WGSizeNameStr += "_wg_size"; 2103 const char *WGSizeName = WGSizeNameStr.c_str(); 2104 2105 void *WGSizePtr; 2106 uint32_t WGSize; 2107 err = interop_get_symbol_info((char *)image->ImageStart, img_size, 2108 WGSizeName, &WGSizePtr, &WGSize); 2109 2110 if (err == HSA_STATUS_SUCCESS) { 2111 if ((size_t)WGSize != sizeof(int16_t)) { 2112 DP("Loading global computation properties '%s' - size mismatch (%u " 2113 "!= " 2114 "%lu)\n", 2115 WGSizeName, WGSize, sizeof(int16_t)); 2116 return NULL; 2117 } 2118 2119 memcpy(&WGSizeVal, WGSizePtr, (size_t)WGSize); 2120 2121 DP("After loading global for %s WGSize = %d\n", WGSizeName, WGSizeVal); 2122 2123 if (WGSizeVal < RTLDeviceInfoTy::Default_WG_Size || 2124 WGSizeVal > RTLDeviceInfoTy::Max_WG_Size) { 2125 DP("Error wrong WGSize value specified in HSA code object file: " 2126 "%d\n", 2127 WGSizeVal); 2128 WGSizeVal = RTLDeviceInfoTy::Default_WG_Size; 2129 } 2130 } else { 2131 DP("Warning: Loading WGSize '%s' - symbol not found, " 2132 "using default value %d\n", 2133 WGSizeName, WGSizeVal); 2134 } 2135 2136 check("Loading WGSize computation property", err); 2137 } 2138 2139 // Read execution mode from global in binary 2140 std::string ExecModeNameStr(e->name); 2141 ExecModeNameStr += "_exec_mode"; 2142 const char *ExecModeName = ExecModeNameStr.c_str(); 2143 2144 void *ExecModePtr; 2145 uint32_t varsize; 2146 err = interop_get_symbol_info((char *)image->ImageStart, img_size, 2147 ExecModeName, &ExecModePtr, &varsize); 2148 2149 if (err == HSA_STATUS_SUCCESS) { 2150 if ((size_t)varsize != sizeof(llvm::omp::OMPTgtExecModeFlags)) { 2151 DP("Loading global computation properties '%s' - size mismatch(%u != " 2152 "%lu)\n", 2153 ExecModeName, varsize, sizeof(llvm::omp::OMPTgtExecModeFlags)); 2154 return NULL; 2155 } 2156 2157 memcpy(&ExecModeVal, ExecModePtr, (size_t)varsize); 2158 2159 DP("After loading global for %s ExecMode = %d\n", ExecModeName, 2160 ExecModeVal); 2161 2162 if (ExecModeVal < 0 || 2163 ExecModeVal > llvm::omp::OMP_TGT_EXEC_MODE_GENERIC_SPMD) { 2164 DP("Error wrong exec_mode value specified in HSA code object file: " 2165 "%d\n", 2166 ExecModeVal); 2167 return NULL; 2168 } 2169 } else { 2170 DP("Loading global exec_mode '%s' - symbol missing, using default " 2171 "value " 2172 "GENERIC (1)\n", 2173 ExecModeName); 2174 } 2175 check("Loading computation property", err); 2176 2177 KernelsList.push_back(KernelTy(ExecModeVal, WGSizeVal, device_id, 2178 CallStackAddr, e->name, kernarg_segment_size, 2179 DeviceInfo.KernArgPool)); 2180 __tgt_offload_entry entry = *e; 2181 entry.addr = (void *)&KernelsList.back(); 2182 DeviceInfo.addOffloadEntry(device_id, entry); 2183 DP("Entry point %ld maps to %s\n", e - HostBegin, e->name); 2184 } 2185 2186 return DeviceInfo.getOffloadEntriesTable(device_id); 2187 } 2188 2189 void *__tgt_rtl_data_alloc(int device_id, int64_t size, void *, int32_t kind) { 2190 void *ptr = NULL; 2191 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2192 2193 if (kind != TARGET_ALLOC_DEFAULT) { 2194 REPORT("Invalid target data allocation kind or requested allocator not " 2195 "implemented yet\n"); 2196 return NULL; 2197 } 2198 2199 hsa_amd_memory_pool_t MemoryPool = DeviceInfo.getDeviceMemoryPool(device_id); 2200 hsa_status_t err = hsa_amd_memory_pool_allocate(MemoryPool, size, 0, &ptr); 2201 DP("Tgt alloc data %ld bytes, (tgt:%016llx).\n", size, 2202 (long long unsigned)(Elf64_Addr)ptr); 2203 ptr = (err == HSA_STATUS_SUCCESS) ? ptr : NULL; 2204 return ptr; 2205 } 2206 2207 int32_t __tgt_rtl_data_submit(int device_id, void *tgt_ptr, void *hst_ptr, 2208 int64_t size) { 2209 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2210 __tgt_async_info AsyncInfo; 2211 int32_t rc = dataSubmit(device_id, tgt_ptr, hst_ptr, size, &AsyncInfo); 2212 if (rc != OFFLOAD_SUCCESS) 2213 return OFFLOAD_FAIL; 2214 2215 return __tgt_rtl_synchronize(device_id, &AsyncInfo); 2216 } 2217 2218 int32_t __tgt_rtl_data_submit_async(int device_id, void *tgt_ptr, void *hst_ptr, 2219 int64_t size, __tgt_async_info *AsyncInfo) { 2220 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2221 if (AsyncInfo) { 2222 initAsyncInfo(AsyncInfo); 2223 return dataSubmit(device_id, tgt_ptr, hst_ptr, size, AsyncInfo); 2224 } else { 2225 return __tgt_rtl_data_submit(device_id, tgt_ptr, hst_ptr, size); 2226 } 2227 } 2228 2229 int32_t __tgt_rtl_data_retrieve(int device_id, void *hst_ptr, void *tgt_ptr, 2230 int64_t size) { 2231 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2232 __tgt_async_info AsyncInfo; 2233 int32_t rc = dataRetrieve(device_id, hst_ptr, tgt_ptr, size, &AsyncInfo); 2234 if (rc != OFFLOAD_SUCCESS) 2235 return OFFLOAD_FAIL; 2236 2237 return __tgt_rtl_synchronize(device_id, &AsyncInfo); 2238 } 2239 2240 int32_t __tgt_rtl_data_retrieve_async(int device_id, void *hst_ptr, 2241 void *tgt_ptr, int64_t size, 2242 __tgt_async_info *AsyncInfo) { 2243 assert(AsyncInfo && "AsyncInfo is nullptr"); 2244 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2245 initAsyncInfo(AsyncInfo); 2246 return dataRetrieve(device_id, hst_ptr, tgt_ptr, size, AsyncInfo); 2247 } 2248 2249 int32_t __tgt_rtl_data_delete(int device_id, void *tgt_ptr) { 2250 assert(device_id < DeviceInfo.NumberOfDevices && "Device ID too large"); 2251 hsa_status_t err; 2252 DP("Tgt free data (tgt:%016llx).\n", (long long unsigned)(Elf64_Addr)tgt_ptr); 2253 err = core::Runtime::Memfree(tgt_ptr); 2254 if (err != HSA_STATUS_SUCCESS) { 2255 DP("Error when freeing CUDA memory\n"); 2256 return OFFLOAD_FAIL; 2257 } 2258 return OFFLOAD_SUCCESS; 2259 } 2260 2261 int32_t __tgt_rtl_run_target_team_region(int32_t device_id, void *tgt_entry_ptr, 2262 void **tgt_args, 2263 ptrdiff_t *tgt_offsets, 2264 int32_t arg_num, int32_t num_teams, 2265 int32_t thread_limit, 2266 uint64_t loop_tripcount) { 2267 2268 DeviceInfo.load_run_lock.lock_shared(); 2269 int32_t res = 2270 runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, 2271 num_teams, thread_limit, loop_tripcount); 2272 2273 DeviceInfo.load_run_lock.unlock_shared(); 2274 return res; 2275 } 2276 2277 int32_t __tgt_rtl_run_target_region(int32_t device_id, void *tgt_entry_ptr, 2278 void **tgt_args, ptrdiff_t *tgt_offsets, 2279 int32_t arg_num) { 2280 // use one team and one thread 2281 // fix thread num 2282 int32_t team_num = 1; 2283 int32_t thread_limit = 0; // use default 2284 return __tgt_rtl_run_target_team_region(device_id, tgt_entry_ptr, tgt_args, 2285 tgt_offsets, arg_num, team_num, 2286 thread_limit, 0); 2287 } 2288 2289 int32_t __tgt_rtl_run_target_team_region_async( 2290 int32_t device_id, void *tgt_entry_ptr, void **tgt_args, 2291 ptrdiff_t *tgt_offsets, int32_t arg_num, int32_t num_teams, 2292 int32_t thread_limit, uint64_t loop_tripcount, 2293 __tgt_async_info *AsyncInfo) { 2294 assert(AsyncInfo && "AsyncInfo is nullptr"); 2295 initAsyncInfo(AsyncInfo); 2296 2297 DeviceInfo.load_run_lock.lock_shared(); 2298 int32_t res = 2299 runRegionLocked(device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, 2300 num_teams, thread_limit, loop_tripcount); 2301 2302 DeviceInfo.load_run_lock.unlock_shared(); 2303 return res; 2304 } 2305 2306 int32_t __tgt_rtl_run_target_region_async(int32_t device_id, 2307 void *tgt_entry_ptr, void **tgt_args, 2308 ptrdiff_t *tgt_offsets, 2309 int32_t arg_num, 2310 __tgt_async_info *AsyncInfo) { 2311 // use one team and one thread 2312 // fix thread num 2313 int32_t team_num = 1; 2314 int32_t thread_limit = 0; // use default 2315 return __tgt_rtl_run_target_team_region_async( 2316 device_id, tgt_entry_ptr, tgt_args, tgt_offsets, arg_num, team_num, 2317 thread_limit, 0, AsyncInfo); 2318 } 2319 2320 int32_t __tgt_rtl_synchronize(int32_t device_id, __tgt_async_info *AsyncInfo) { 2321 assert(AsyncInfo && "AsyncInfo is nullptr"); 2322 2323 // Cuda asserts that AsyncInfo->Queue is non-null, but this invariant 2324 // is not ensured by devices.cpp for amdgcn 2325 // assert(AsyncInfo->Queue && "AsyncInfo->Queue is nullptr"); 2326 if (AsyncInfo->Queue) { 2327 finiAsyncInfo(AsyncInfo); 2328 } 2329 return OFFLOAD_SUCCESS; 2330 } 2331 2332 namespace core { 2333 hsa_status_t allow_access_to_all_gpu_agents(void *ptr) { 2334 return hsa_amd_agents_allow_access(DeviceInfo.HSAAgents.size(), 2335 &DeviceInfo.HSAAgents[0], NULL, ptr); 2336 } 2337 2338 } // namespace core 2339