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