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