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