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