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