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