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