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