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