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 // Header from ATMI interface
28 #include "atmi_interop_hsa.h"
29 #include "atmi_runtime.h"
30 
31 #include "internal.h"
32 
33 #include "Debug.h"
34 #include "get_elf_mach_gfx_name.h"
35 #include "machine.h"
36 #include "omptargetplugin.h"
37 #include "print_tracing.h"
38 
39 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
40 
41 #ifndef TARGET_NAME
42 #error "Missing TARGET_NAME macro"
43 #endif
44 #define DEBUG_PREFIX "Target " GETNAME(TARGET_NAME) " RTL"
45 
46 // hostrpc interface, FIXME: consider moving to its own include these are
47 // statically linked into amdgpu/plugin if present from hostrpc_services.a,
48 // linked as --whole-archive to override the weak symbols that are used to
49 // implement a fallback for toolchains that do not yet have a hostrpc library.
50 extern "C" {
51 unsigned long hostrpc_assign_buffer(hsa_agent_t agent, hsa_queue_t *this_Q,
52                                     uint32_t device_id);
53 hsa_status_t hostrpc_init();
54 hsa_status_t hostrpc_terminate();
55 
56 __attribute__((weak)) hsa_status_t hostrpc_init() { return HSA_STATUS_SUCCESS; }
57 __attribute__((weak)) hsa_status_t hostrpc_terminate() {
58   return HSA_STATUS_SUCCESS;
59 }
60 __attribute__((weak)) unsigned long
61 hostrpc_assign_buffer(hsa_agent_t, hsa_queue_t *, uint32_t device_id) {
62   DP("Warning: Attempting to assign hostrpc to device %u, but hostrpc library "
63      "missing\n",
64      device_id);
65   return 0;
66 }
67 }
68 
69 // Heuristic parameters used for kernel launch
70 // Number of teams per CU to allow scheduling flexibility
71 static const unsigned DefaultTeamsPerCU = 4;
72 
73 int print_kernel_trace;
74 
75 #ifdef OMPTARGET_DEBUG
76 #define check(msg, status)                                                     \
77   if (status != HSA_STATUS_SUCCESS) {                                          \
78     DP(#msg " failed\n");                                                      \
79   } else {                                                                     \
80     DP(#msg " succeeded\n");                                                   \
81   }
82 #else
83 #define check(msg, status)                                                     \
84   {}
85 #endif
86 
87 #include "elf_common.h"
88 
89 namespace core {
90 hsa_status_t RegisterModuleFromMemory(
91     std::map<std::string, atl_kernel_info_t> &KernelInfo,
92     std::map<std::string, atl_symbol_info_t> &SymbolInfoTable, void *, size_t,
93     hsa_agent_t agent,
94     hsa_status_t (*on_deserialized_data)(void *data, size_t size,
95                                          void *cb_state),
96     void *cb_state, std::vector<hsa_executable_t> &HSAExecutables);
97 }
98 
99 namespace hsa {
100 template <typename C> hsa_status_t iterate_agents(C cb) {
101   auto L = [](hsa_agent_t agent, void *data) -> hsa_status_t {
102     C *unwrapped = static_cast<C *>(data);
103     return (*unwrapped)(agent);
104   };
105   return hsa_iterate_agents(L, static_cast<void *>(&cb));
106 }
107 
108 template <typename C>
109 hsa_status_t amd_agent_iterate_memory_pools(hsa_agent_t Agent, C cb) {
110   auto L = [](hsa_amd_memory_pool_t MemoryPool, void *data) -> hsa_status_t {
111     C *unwrapped = static_cast<C *>(data);
112     return (*unwrapped)(MemoryPool);
113   };
114 
115   return hsa_amd_agent_iterate_memory_pools(Agent, L, static_cast<void *>(&cb));
116 }
117 
118 } // namespace hsa
119 
120 /// Keep entries table per device
121 struct FuncOrGblEntryTy {
122   __tgt_target_table Table;
123   std::vector<__tgt_offload_entry> Entries;
124 };
125 
126 enum ExecutionModeType {
127   SPMD,         // constructors, destructors,
128                 // combined constructs (`teams distribute parallel for [simd]`)
129   GENERIC,      // everything else
130   SPMD_GENERIC, // Generic kernel with SPMD execution
131   NONE
132 };
133 
134 struct KernelArgPool {
135 private:
136   static pthread_mutex_t mutex;
137 
138 public:
139   uint32_t kernarg_segment_size;
140   void *kernarg_region = nullptr;
141   std::queue<int> free_kernarg_segments;
142 
143   uint32_t kernarg_size_including_implicit() {
144     return kernarg_segment_size + sizeof(atmi_implicit_args_t);
145   }
146 
147   ~KernelArgPool() {
148     if (kernarg_region) {
149       auto r = hsa_amd_memory_pool_free(kernarg_region);
150       if (r != HSA_STATUS_SUCCESS) {
151         DP("hsa_amd_memory_pool_free failed: %s\n", get_error_string(r));
152       }
153     }
154   }
155 
156   // Can't really copy or move a mutex
157   KernelArgPool() = default;
158   KernelArgPool(const KernelArgPool &) = delete;
159   KernelArgPool(KernelArgPool &&) = delete;
160 
161   KernelArgPool(uint32_t kernarg_segment_size,
162                 hsa_amd_memory_pool_t &memory_pool)
163       : kernarg_segment_size(kernarg_segment_size) {
164 
165     // atmi uses one pool per kernel for all gpus, with a fixed upper size
166     // preserving that exact scheme here, including the queue<int>
167 
168     hsa_status_t err = hsa_amd_memory_pool_allocate(
169         memory_pool, kernarg_size_including_implicit() * MAX_NUM_KERNELS, 0,
170         &kernarg_region);
171 
172     if (err != HSA_STATUS_SUCCESS) {
173       DP("hsa_amd_memory_pool_allocate failed: %s\n", get_error_string(err));
174       kernarg_region = nullptr; // paranoid
175       return;
176     }
177 
178     err = core::allow_access_to_all_gpu_agents(kernarg_region);
179     if (err != HSA_STATUS_SUCCESS) {
180       DP("hsa allow_access_to_all_gpu_agents failed: %s\n",
181          get_error_string(err));
182       auto r = hsa_amd_memory_pool_free(kernarg_region);
183       if (r != HSA_STATUS_SUCCESS) {
184         // if free failed, can't do anything more to resolve it
185         DP("hsa memory poll free failed: %s\n", get_error_string(err));
186       }
187       kernarg_region = nullptr;
188       return;
189     }
190 
191     for (int i = 0; i < MAX_NUM_KERNELS; i++) {
192       free_kernarg_segments.push(i);
193     }
194   }
195 
196   void *allocate(uint64_t arg_num) {
197     assert((arg_num * sizeof(void *)) == kernarg_segment_size);
198     lock l(&mutex);
199     void *res = nullptr;
200     if (!free_kernarg_segments.empty()) {
201 
202       int free_idx = free_kernarg_segments.front();
203       res = static_cast<void *>(static_cast<char *>(kernarg_region) +
204                                 (free_idx * kernarg_size_including_implicit()));
205       assert(free_idx == pointer_to_index(res));
206       free_kernarg_segments.pop();
207     }
208     return res;
209   }
210 
211   void deallocate(void *ptr) {
212     lock l(&mutex);
213     int idx = pointer_to_index(ptr);
214     free_kernarg_segments.push(idx);
215   }
216 
217 private:
218   int pointer_to_index(void *ptr) {
219     ptrdiff_t bytes =
220         static_cast<char *>(ptr) - static_cast<char *>(kernarg_region);
221     assert(bytes >= 0);
222     assert(bytes % kernarg_size_including_implicit() == 0);
223     return bytes / kernarg_size_including_implicit();
224   }
225   struct lock {
226     lock(pthread_mutex_t *m) : m(m) { pthread_mutex_lock(m); }
227     ~lock() { pthread_mutex_unlock(m); }
228     pthread_mutex_t *m;
229   };
230 };
231 pthread_mutex_t KernelArgPool::mutex = PTHREAD_MUTEX_INITIALIZER;
232 
233 std::unordered_map<std::string /*kernel*/, std::unique_ptr<KernelArgPool>>
234     KernelArgPoolMap;
235 
236 /// Use a single entity to encode a kernel and a set of flags
237 struct KernelTy {
238   // execution mode of kernel
239   // 0 - SPMD mode (without master warp)
240   // 1 - Generic mode (with master warp)
241   // 2 - SPMD mode execution with Generic mode semantics.
242   int8_t ExecutionMode;
243   int16_t ConstWGSize;
244   int32_t device_id;
245   void *CallStackAddr = nullptr;
246   const char *Name;
247 
248   KernelTy(int8_t _ExecutionMode, int16_t _ConstWGSize, int32_t _device_id,
249            void *_CallStackAddr, const char *_Name,
250            uint32_t _kernarg_segment_size,
251            hsa_amd_memory_pool_t &KernArgMemoryPool)
252       : ExecutionMode(_ExecutionMode), ConstWGSize(_ConstWGSize),
253         device_id(_device_id), CallStackAddr(_CallStackAddr), Name(_Name) {
254     DP("Construct kernelinfo: ExecMode %d\n", ExecutionMode);
255 
256     std::string N(_Name);
257     if (KernelArgPoolMap.find(N) == KernelArgPoolMap.end()) {
258       KernelArgPoolMap.insert(
259           std::make_pair(N, std::unique_ptr<KernelArgPool>(new KernelArgPool(
260                                 _kernarg_segment_size, KernArgMemoryPool))));
261     }
262   }
263 };
264 
265 /// List that contains all the kernels.
266 /// FIXME: we may need this to be per device and per library.
267 std::list<KernelTy> KernelsList;
268 
269 template <typename Callback> static hsa_status_t FindAgents(Callback CB) {
270 
271   hsa_status_t err =
272       hsa::iterate_agents([&](hsa_agent_t agent) -> hsa_status_t {
273         hsa_device_type_t device_type;
274         // get_info fails iff HSA runtime not yet initialized
275         hsa_status_t err =
276             hsa_agent_get_info(agent, HSA_AGENT_INFO_DEVICE, &device_type);
277         if (print_kernel_trace > 0 && err != HSA_STATUS_SUCCESS)
278           printf("rtl.cpp: err %d\n", err);
279         assert(err == HSA_STATUS_SUCCESS);
280 
281         CB(device_type, agent);
282         return HSA_STATUS_SUCCESS;
283       });
284 
285   // iterate_agents fails iff HSA runtime not yet initialized
286   if (print_kernel_trace > 0 && err != HSA_STATUS_SUCCESS) {
287     printf("rtl.cpp: err %d\n", err);
288   }
289 
290   return err;
291 }
292 
293 static void callbackQueue(hsa_status_t status, hsa_queue_t *source,
294                           void *data) {
295   if (status != HSA_STATUS_SUCCESS) {
296     const char *status_string;
297     if (hsa_status_string(status, &status_string) != HSA_STATUS_SUCCESS) {
298       status_string = "unavailable";
299     }
300     fprintf(stderr, "[%s:%d] GPU error in queue %p %d (%s)\n", __FILE__,
301             __LINE__, source, status, status_string);
302     abort();
303   }
304 }
305 
306 namespace core {
307 namespace {
308 void packet_store_release(uint32_t *packet, uint16_t header, uint16_t rest) {
309   __atomic_store_n(packet, header | (rest << 16), __ATOMIC_RELEASE);
310 }
311 
312 uint16_t create_header() {
313   uint16_t header = HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE;
314   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE;
315   header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE;
316   return header;
317 }
318 
319 hsa_status_t addKernArgPool(hsa_amd_memory_pool_t MemoryPool, void *Data) {
320   std::vector<hsa_amd_memory_pool_t> *Result =
321       static_cast<std::vector<hsa_amd_memory_pool_t> *>(Data);
322   bool AllocAllowed = false;
323   hsa_status_t err = hsa_amd_memory_pool_get_info(
324       MemoryPool, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED,
325       &AllocAllowed);
326   if (err != HSA_STATUS_SUCCESS) {
327     fprintf(stderr, "Alloc allowed in memory pool check failed: %s\n",
328             get_error_string(err));
329     return err;
330   }
331 
332   if (!AllocAllowed) {
333     // nothing needs to be done here.
334     return HSA_STATUS_SUCCESS;
335   }
336 
337   uint32_t GlobalFlags = 0;
338   err = hsa_amd_memory_pool_get_info(
339       MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
340   if (err != HSA_STATUS_SUCCESS) {
341     fprintf(stderr, "Get memory pool info failed: %s\n", get_error_string(err));
342     return err;
343   }
344 
345   size_t size = 0;
346   err = hsa_amd_memory_pool_get_info(MemoryPool, HSA_AMD_MEMORY_POOL_INFO_SIZE,
347                                      &size);
348   if (err != HSA_STATUS_SUCCESS) {
349     fprintf(stderr, "Get memory pool size failed: %s\n", get_error_string(err));
350     return err;
351   }
352 
353   if ((GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) &&
354       (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT) &&
355       size > 0) {
356     Result->push_back(MemoryPool);
357   }
358 
359   return HSA_STATUS_SUCCESS;
360 }
361 
362 std::pair<hsa_status_t, bool>
363 isValidMemoryPool(hsa_amd_memory_pool_t MemoryPool) {
364   bool AllocAllowed = false;
365   hsa_status_t Err = hsa_amd_memory_pool_get_info(
366       MemoryPool, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_ALLOWED,
367       &AllocAllowed);
368   if (Err != HSA_STATUS_SUCCESS) {
369     fprintf(stderr, "Alloc allowed in memory pool check failed: %s\n",
370             get_error_string(Err));
371     return {Err, false};
372   }
373 
374   return {HSA_STATUS_SUCCESS, AllocAllowed};
375 }
376 
377 template <typename AccumulatorFunc>
378 hsa_status_t collectMemoryPools(const std::vector<hsa_agent_t> &Agents,
379                                 AccumulatorFunc Func) {
380   for (int DeviceId = 0; DeviceId < Agents.size(); DeviceId++) {
381     hsa_status_t Err = hsa::amd_agent_iterate_memory_pools(
382         Agents[DeviceId], [&](hsa_amd_memory_pool_t MemoryPool) {
383           hsa_status_t Err;
384           bool Valid = false;
385           std::tie(Err, Valid) = isValidMemoryPool(MemoryPool);
386           if (Err != HSA_STATUS_SUCCESS) {
387             return Err;
388           }
389           if (Valid)
390             Func(MemoryPool, DeviceId);
391           return HSA_STATUS_SUCCESS;
392         });
393 
394     if (Err != HSA_STATUS_SUCCESS) {
395       printf("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
396              "Iterate all memory pools", get_error_string(Err));
397       return Err;
398     }
399   }
400 
401   return HSA_STATUS_SUCCESS;
402 }
403 
404 std::pair<hsa_status_t, hsa_amd_memory_pool_t>
405 FindKernargPool(const std::vector<hsa_agent_t> &HSAAgents) {
406   std::vector<hsa_amd_memory_pool_t> KernArgPools;
407   for (const auto &Agent : HSAAgents) {
408     hsa_status_t err = HSA_STATUS_SUCCESS;
409     err = hsa_amd_agent_iterate_memory_pools(
410         Agent, addKernArgPool, static_cast<void *>(&KernArgPools));
411     if (err != HSA_STATUS_SUCCESS) {
412       printf("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
413              "Iterate all memory pools", get_error_string(err));
414       return {err, hsa_amd_memory_pool_t{}};
415     }
416   }
417 
418   if (KernArgPools.empty()) {
419     fprintf(stderr, "Unable to find any valid kernarg pool\n");
420     return {HSA_STATUS_ERROR, hsa_amd_memory_pool_t{}};
421   }
422 
423   return {HSA_STATUS_SUCCESS, KernArgPools[0]};
424 }
425 
426 } // namespace
427 } // namespace core
428 
429 struct EnvironmentVariables {
430   int NumTeams;
431   int TeamLimit;
432   int TeamThreadLimit;
433   int MaxTeamsDefault;
434 };
435 
436 /// Class containing all the device information
437 class RTLDeviceInfoTy {
438   std::vector<std::list<FuncOrGblEntryTy>> FuncGblEntries;
439   bool HSAInitializeSucceeded = false;
440 
441 public:
442   // load binary populates symbol tables and mutates various global state
443   // run uses those symbol tables
444   std::shared_timed_mutex load_run_lock;
445 
446   int NumberOfDevices = 0;
447 
448   // GPU devices
449   std::vector<hsa_agent_t> HSAAgents;
450   std::vector<hsa_queue_t *> HSAQueues; // one per gpu
451 
452   // CPUs
453   std::vector<hsa_agent_t> CPUAgents;
454 
455   // Device properties
456   std::vector<int> ComputeUnits;
457   std::vector<int> GroupsPerDevice;
458   std::vector<int> ThreadsPerGroup;
459   std::vector<int> WarpSize;
460   std::vector<std::string> GPUName;
461 
462   // OpenMP properties
463   std::vector<int> NumTeams;
464   std::vector<int> NumThreads;
465 
466   // OpenMP Environment properties
467   EnvironmentVariables Env;
468 
469   // OpenMP Requires Flags
470   int64_t RequiresFlags;
471 
472   // Resource pools
473   SignalPoolT FreeSignalPool;
474 
475   bool hostcall_required = false;
476 
477   std::vector<hsa_executable_t> HSAExecutables;
478 
479   std::vector<std::map<std::string, atl_kernel_info_t>> KernelInfoTable;
480   std::vector<std::map<std::string, atl_symbol_info_t>> SymbolInfoTable;
481 
482   hsa_amd_memory_pool_t KernArgPool;
483 
484   // fine grained memory pool for host allocations
485   hsa_amd_memory_pool_t HostFineGrainedMemoryPool;
486 
487   // fine and coarse-grained memory pools per offloading device
488   std::vector<hsa_amd_memory_pool_t> DeviceFineGrainedMemoryPools;
489   std::vector<hsa_amd_memory_pool_t> DeviceCoarseGrainedMemoryPools;
490 
491   struct atmiFreePtrDeletor {
492     void operator()(void *p) {
493       core::Runtime::Memfree(p); // ignore failure to free
494     }
495   };
496 
497   // device_State shared across loaded binaries, error if inconsistent size
498   std::vector<std::pair<std::unique_ptr<void, atmiFreePtrDeletor>, uint64_t>>
499       deviceStateStore;
500 
501   static const unsigned HardTeamLimit =
502       (1 << 16) - 1; // 64K needed to fit in uint16
503   static const int DefaultNumTeams = 128;
504   static const int Max_Teams = llvm::omp::AMDGPUGridValues.GV_Max_Teams;
505   static const int Warp_Size = llvm::omp::AMDGPUGridValues.GV_Warp_Size;
506   static const int Max_WG_Size = llvm::omp::AMDGPUGridValues.GV_Max_WG_Size;
507   static const int Default_WG_Size =
508       llvm::omp::AMDGPUGridValues.GV_Default_WG_Size;
509 
510   using MemcpyFunc = hsa_status_t (*)(hsa_signal_t, void *, const void *,
511                                       size_t size, hsa_agent_t);
512   hsa_status_t freesignalpool_memcpy(void *dest, const void *src, size_t size,
513                                      MemcpyFunc Func, int32_t deviceId) {
514     hsa_agent_t agent = HSAAgents[deviceId];
515     hsa_signal_t s = FreeSignalPool.pop();
516     if (s.handle == 0) {
517       return HSA_STATUS_ERROR;
518     }
519     hsa_status_t r = Func(s, dest, src, size, agent);
520     FreeSignalPool.push(s);
521     return r;
522   }
523 
524   hsa_status_t freesignalpool_memcpy_d2h(void *dest, const void *src,
525                                          size_t size, int32_t deviceId) {
526     return freesignalpool_memcpy(dest, src, size, atmi_memcpy_d2h, deviceId);
527   }
528 
529   hsa_status_t freesignalpool_memcpy_h2d(void *dest, const void *src,
530                                          size_t size, int32_t deviceId) {
531     return freesignalpool_memcpy(dest, src, size, atmi_memcpy_h2d, deviceId);
532   }
533 
534   // Record entry point associated with device
535   void addOffloadEntry(int32_t device_id, __tgt_offload_entry entry) {
536     assert(device_id < (int32_t)FuncGblEntries.size() &&
537            "Unexpected device id!");
538     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
539 
540     E.Entries.push_back(entry);
541   }
542 
543   // Return true if the entry is associated with device
544   bool findOffloadEntry(int32_t device_id, void *addr) {
545     assert(device_id < (int32_t)FuncGblEntries.size() &&
546            "Unexpected device id!");
547     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
548 
549     for (auto &it : E.Entries) {
550       if (it.addr == addr)
551         return true;
552     }
553 
554     return false;
555   }
556 
557   // Return the pointer to the target entries table
558   __tgt_target_table *getOffloadEntriesTable(int32_t device_id) {
559     assert(device_id < (int32_t)FuncGblEntries.size() &&
560            "Unexpected device id!");
561     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
562 
563     int32_t size = E.Entries.size();
564 
565     // Table is empty
566     if (!size)
567       return 0;
568 
569     __tgt_offload_entry *begin = &E.Entries[0];
570     __tgt_offload_entry *end = &E.Entries[size - 1];
571 
572     // Update table info according to the entries and return the pointer
573     E.Table.EntriesBegin = begin;
574     E.Table.EntriesEnd = ++end;
575 
576     return &E.Table;
577   }
578 
579   // Clear entries table for a device
580   void clearOffloadEntriesTable(int device_id) {
581     assert(device_id < (int32_t)FuncGblEntries.size() &&
582            "Unexpected device id!");
583     FuncGblEntries[device_id].emplace_back();
584     FuncOrGblEntryTy &E = FuncGblEntries[device_id].back();
585     // KernelArgPoolMap.clear();
586     E.Entries.clear();
587     E.Table.EntriesBegin = E.Table.EntriesEnd = 0;
588   }
589 
590   hsa_status_t addDeviceMemoryPool(hsa_amd_memory_pool_t MemoryPool,
591                                    int DeviceId) {
592     assert(DeviceId < DeviceFineGrainedMemoryPools.size() && "Error here.");
593     uint32_t GlobalFlags = 0;
594     hsa_status_t Err = hsa_amd_memory_pool_get_info(
595         MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
596 
597     if (Err != HSA_STATUS_SUCCESS) {
598       return Err;
599     }
600 
601     if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED) {
602       DeviceFineGrainedMemoryPools[DeviceId] = MemoryPool;
603     } else if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED) {
604       DeviceCoarseGrainedMemoryPools[DeviceId] = MemoryPool;
605     }
606 
607     return HSA_STATUS_SUCCESS;
608   }
609 
610   hsa_status_t addHostMemoryPool(hsa_amd_memory_pool_t MemoryPool,
611                                  int DeviceId) {
612     uint32_t GlobalFlags = 0;
613     hsa_status_t Err = hsa_amd_memory_pool_get_info(
614         MemoryPool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &GlobalFlags);
615 
616     if (Err != HSA_STATUS_SUCCESS) {
617       return Err;
618     }
619 
620     uint32_t Size;
621     Err = hsa_amd_memory_pool_get_info(MemoryPool,
622                                        HSA_AMD_MEMORY_POOL_INFO_SIZE, &Size);
623     if (Err != HSA_STATUS_SUCCESS) {
624       return Err;
625     }
626 
627     if (GlobalFlags & HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED &&
628         Size > 0) {
629       HostFineGrainedMemoryPool = MemoryPool;
630     }
631 
632     return HSA_STATUS_SUCCESS;
633   }
634 
635   hsa_status_t setupMemoryPools() {
636     using namespace std::placeholders;
637     hsa_status_t Err;
638     Err = core::collectMemoryPools(
639         CPUAgents, std::bind(&RTLDeviceInfoTy::addHostMemoryPool, this, _1, _2));
640     if (Err != HSA_STATUS_SUCCESS) {
641       fprintf(stderr, "HSA error in collecting memory pools for CPU: %s\n",
642               get_error_string(Err));
643       return Err;
644     }
645     Err = core::collectMemoryPools(
646         HSAAgents, std::bind(&RTLDeviceInfoTy::addDeviceMemoryPool, this, _1, _2));
647     if (Err != HSA_STATUS_SUCCESS) {
648       fprintf(stderr,
649               "HSA error in collecting memory pools for offload devices: %s\n",
650               get_error_string(Err));
651       return Err;
652     }
653     return HSA_STATUS_SUCCESS;
654   }
655 
656   hsa_amd_memory_pool_t getDeviceMemoryPool(int DeviceId) {
657     assert(DeviceId >= 0 && DeviceId < DeviceCoarseGrainedMemoryPools.size() &&
658            "Invalid device Id");
659     return DeviceCoarseGrainedMemoryPools[DeviceId];
660   }
661 
662   hsa_amd_memory_pool_t getHostMemoryPool() {
663     return HostFineGrainedMemoryPool;
664   }
665 
666   static int readEnvElseMinusOne(const char *Env) {
667     const char *envStr = getenv(Env);
668     int res = -1;
669     if (envStr) {
670       res = std::stoi(envStr);
671       DP("Parsed %s=%d\n", Env, res);
672     }
673     return res;
674   }
675 
676   RTLDeviceInfoTy() {
677     // LIBOMPTARGET_KERNEL_TRACE provides a kernel launch trace to stderr
678     // anytime. You do not need a debug library build.
679     //  0 => no tracing
680     //  1 => tracing dispatch only
681     // >1 => verbosity increase
682     if (char *envStr = getenv("LIBOMPTARGET_KERNEL_TRACE"))
683       print_kernel_trace = atoi(envStr);
684     else
685       print_kernel_trace = 0;
686 
687     DP("Start initializing " GETNAME(TARGET_NAME) "\n");
688     hsa_status_t err = core::atl_init_gpu_context();
689     if (err == HSA_STATUS_SUCCESS) {
690       HSAInitializeSucceeded = true;
691     } else {
692       DP("Error when initializing " GETNAME(TARGET_NAME) "\n");
693       return;
694     }
695 
696     // Init hostcall soon after initializing ATMI
697     hostrpc_init();
698 
699     err = FindAgents([&](hsa_device_type_t DeviceType, hsa_agent_t Agent) {
700       if (DeviceType == HSA_DEVICE_TYPE_CPU) {
701         CPUAgents.push_back(Agent);
702       } else {
703         HSAAgents.push_back(Agent);
704       }
705     });
706     if (err != HSA_STATUS_SUCCESS)
707       return;
708 
709     NumberOfDevices = (int)HSAAgents.size();
710 
711     if (NumberOfDevices == 0) {
712       DP("There are no devices supporting HSA.\n");
713       return;
714     } else {
715       DP("There are %d devices supporting HSA.\n", NumberOfDevices);
716     }
717     std::tie(err, KernArgPool) = core::FindKernargPool(CPUAgents);
718     if (err != HSA_STATUS_SUCCESS) {
719       DP("Error when reading memory pools\n");
720       return;
721     }
722 
723     // Init the device info
724     HSAQueues.resize(NumberOfDevices);
725     FuncGblEntries.resize(NumberOfDevices);
726     ThreadsPerGroup.resize(NumberOfDevices);
727     ComputeUnits.resize(NumberOfDevices);
728     GPUName.resize(NumberOfDevices);
729     GroupsPerDevice.resize(NumberOfDevices);
730     WarpSize.resize(NumberOfDevices);
731     NumTeams.resize(NumberOfDevices);
732     NumThreads.resize(NumberOfDevices);
733     deviceStateStore.resize(NumberOfDevices);
734     KernelInfoTable.resize(NumberOfDevices);
735     SymbolInfoTable.resize(NumberOfDevices);
736     DeviceCoarseGrainedMemoryPools.resize(NumberOfDevices);
737     DeviceFineGrainedMemoryPools.resize(NumberOfDevices);
738 
739     err = setupMemoryPools();
740     if (err != HSA_STATUS_SUCCESS) {
741       DP("Error when setting up memory pools");
742       return;
743     }
744 
745     for (int i = 0; i < NumberOfDevices; i++) {
746       HSAQueues[i] = nullptr;
747     }
748 
749     for (int i = 0; i < NumberOfDevices; i++) {
750       uint32_t queue_size = 0;
751       {
752         hsa_status_t err = hsa_agent_get_info(
753             HSAAgents[i], HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size);
754         if (err != HSA_STATUS_SUCCESS) {
755           DP("HSA query QUEUE_MAX_SIZE failed for agent %d\n", i);
756           return;
757         }
758         if (queue_size > core::Runtime::getInstance().getMaxQueueSize()) {
759           queue_size = core::Runtime::getInstance().getMaxQueueSize();
760         }
761       }
762 
763       hsa_status_t rc = hsa_queue_create(
764           HSAAgents[i], queue_size, HSA_QUEUE_TYPE_MULTI, callbackQueue, NULL,
765           UINT32_MAX, UINT32_MAX, &HSAQueues[i]);
766       if (rc != HSA_STATUS_SUCCESS) {
767         DP("Failed to create HSA queue %d\n", i);
768         return;
769       }
770 
771       deviceStateStore[i] = {nullptr, 0};
772     }
773 
774     for (int i = 0; i < NumberOfDevices; i++) {
775       ThreadsPerGroup[i] = RTLDeviceInfoTy::Default_WG_Size;
776       GroupsPerDevice[i] = RTLDeviceInfoTy::DefaultNumTeams;
777       ComputeUnits[i] = 1;
778       DP("Device %d: Initial groupsPerDevice %d & threadsPerGroup %d\n", i,
779          GroupsPerDevice[i], ThreadsPerGroup[i]);
780     }
781 
782     // Get environment variables regarding teams
783     Env.TeamLimit = readEnvElseMinusOne("OMP_TEAM_LIMIT");
784     Env.NumTeams = readEnvElseMinusOne("OMP_NUM_TEAMS");
785     Env.MaxTeamsDefault = readEnvElseMinusOne("OMP_MAX_TEAMS_DEFAULT");
786     Env.TeamThreadLimit = readEnvElseMinusOne("OMP_TEAMS_THREAD_LIMIT");
787 
788     // Default state.
789     RequiresFlags = OMP_REQ_UNDEFINED;
790   }
791 
792   ~RTLDeviceInfoTy() {
793     DP("Finalizing the " GETNAME(TARGET_NAME) " DeviceInfo.\n");
794     if (!HSAInitializeSucceeded) {
795       // Then none of these can have been set up and they can't be torn down
796       return;
797     }
798     // Run destructors on types that use HSA before
799     // atmi_finalize removes access to it
800     deviceStateStore.clear();
801     KernelArgPoolMap.clear();
802     // Terminate hostrpc before finalizing ATMI
803     hostrpc_terminate();
804 
805     hsa_status_t Err;
806     for (uint32_t I = 0; I < HSAExecutables.size(); I++) {
807       Err = hsa_executable_destroy(HSAExecutables[I]);
808       if (Err != HSA_STATUS_SUCCESS) {
809         DP("[%s:%d] %s failed: %s\n", __FILE__, __LINE__,
810            "Destroying executable", get_error_string(Err));
811       }
812     }
813 
814     Err = hsa_shut_down();
815     if (Err != HSA_STATUS_SUCCESS) {
816       printf("[%s:%d] %s failed: %s\n", __FILE__, __LINE__, "Shutting down HSA",
817              get_error_string(Err));
818     }
819   }
820 };
821 
822 pthread_mutex_t SignalPoolT::mutex = PTHREAD_MUTEX_INITIALIZER;
823 
824 // TODO: May need to drop the trailing to fields until deviceRTL is updated
825 struct omptarget_device_environmentTy {
826   int32_t debug_level; // gets value of envvar LIBOMPTARGET_DEVICE_RTL_DEBUG
827                        // only useful for Debug build of deviceRTLs
828   int32_t num_devices; // gets number of active offload devices
829   int32_t device_num;  // gets a value 0 to num_devices-1
830 };
831 
832 static RTLDeviceInfoTy DeviceInfo;
833 
834 namespace {
835 
836 int32_t dataRetrieve(int32_t DeviceId, void *HstPtr, void *TgtPtr, int64_t Size,
837                      __tgt_async_info *AsyncInfo) {
838   assert(AsyncInfo && "AsyncInfo is nullptr");
839   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
840   // Return success if we are not copying back to host from target.
841   if (!HstPtr)
842     return OFFLOAD_SUCCESS;
843   hsa_status_t err;
844   DP("Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
845      (long long unsigned)(Elf64_Addr)TgtPtr,
846      (long long unsigned)(Elf64_Addr)HstPtr);
847 
848   err = DeviceInfo.freesignalpool_memcpy_d2h(HstPtr, TgtPtr, (size_t)Size,
849                                              DeviceId);
850 
851   if (err != HSA_STATUS_SUCCESS) {
852     DP("Error when copying data from device to host. Pointers: "
853        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
854        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
855     return OFFLOAD_FAIL;
856   }
857   DP("DONE Retrieve data %ld bytes, (tgt:%016llx) -> (hst:%016llx).\n", Size,
858      (long long unsigned)(Elf64_Addr)TgtPtr,
859      (long long unsigned)(Elf64_Addr)HstPtr);
860   return OFFLOAD_SUCCESS;
861 }
862 
863 int32_t dataSubmit(int32_t DeviceId, void *TgtPtr, void *HstPtr, int64_t Size,
864                    __tgt_async_info *AsyncInfo) {
865   assert(AsyncInfo && "AsyncInfo is nullptr");
866   hsa_status_t err;
867   assert(DeviceId < DeviceInfo.NumberOfDevices && "Device ID too large");
868   // Return success if we are not doing host to target.
869   if (!HstPtr)
870     return OFFLOAD_SUCCESS;
871 
872   DP("Submit data %ld bytes, (hst:%016llx) -> (tgt:%016llx).\n", Size,
873      (long long unsigned)(Elf64_Addr)HstPtr,
874      (long long unsigned)(Elf64_Addr)TgtPtr);
875   err = DeviceInfo.freesignalpool_memcpy_h2d(TgtPtr, HstPtr, (size_t)Size,
876                                              DeviceId);
877   if (err != HSA_STATUS_SUCCESS) {
878     DP("Error when copying data from host to device. Pointers: "
879        "host = 0x%016lx, device = 0x%016lx, size = %lld\n",
880        (Elf64_Addr)HstPtr, (Elf64_Addr)TgtPtr, (unsigned long long)Size);
881     return OFFLOAD_FAIL;
882   }
883   return OFFLOAD_SUCCESS;
884 }
885 
886 // Async.
887 // The implementation was written with cuda streams in mind. The semantics of
888 // that are to execute kernels on a queue in order of insertion. A synchronise
889 // call then makes writes visible between host and device. This means a series
890 // of N data_submit_async calls are expected to execute serially. HSA offers
891 // various options to run the data copies concurrently. This may require changes
892 // to libomptarget.
893 
894 // __tgt_async_info* contains a void * Queue. Queue = 0 is used to indicate that
895 // there are no outstanding kernels that need to be synchronized. Any async call
896 // may be passed a Queue==0, at which point the cuda implementation will set it
897 // to non-null (see getStream). The cuda streams are per-device. Upstream may
898 // change this interface to explicitly initialize the AsyncInfo_pointer, but
899 // until then hsa lazily initializes it as well.
900 
901 void initAsyncInfo(__tgt_async_info *AsyncInfo) {
902   // set non-null while using async calls, return to null to indicate completion
903   assert(AsyncInfo);
904   if (!AsyncInfo->Queue) {
905     AsyncInfo->Queue = reinterpret_cast<void *>(UINT64_MAX);
906   }
907 }
908 void finiAsyncInfo(__tgt_async_info *AsyncInfo) {
909   assert(AsyncInfo);
910   assert(AsyncInfo->Queue);
911   AsyncInfo->Queue = 0;
912 }
913 
914 bool elf_machine_id_is_amdgcn(__tgt_device_image *image) {
915   const uint16_t amdgcnMachineID = 224; // EM_AMDGPU may not be in system elf.h
916   int32_t r = elf_check_machine(image, amdgcnMachineID);
917   if (!r) {
918     DP("Supported machine ID not found\n");
919   }
920   return r;
921 }
922 
923 uint32_t elf_e_flags(__tgt_device_image *image) {
924   char *img_begin = (char *)image->ImageStart;
925   size_t img_size = (char *)image->ImageEnd - img_begin;
926 
927   Elf *e = elf_memory(img_begin, img_size);
928   if (!e) {
929     DP("Unable to get ELF handle: %s!\n", elf_errmsg(-1));
930     return 0;
931   }
932 
933   Elf64_Ehdr *eh64 = elf64_getehdr(e);
934 
935   if (!eh64) {
936     DP("Unable to get machine ID from ELF file!\n");
937     elf_end(e);
938     return 0;
939   }
940 
941   uint32_t Flags = eh64->e_flags;
942 
943   elf_end(e);
944   DP("ELF Flags: 0x%x\n", Flags);
945   return Flags;
946 }
947 } // namespace
948 
949 int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *image) {
950   return elf_machine_id_is_amdgcn(image);
951 }
952 
953 int __tgt_rtl_number_of_devices() { return DeviceInfo.NumberOfDevices; }
954 
955 int64_t __tgt_rtl_init_requires(int64_t RequiresFlags) {
956   DP("Init requires flags to %ld\n", RequiresFlags);
957   DeviceInfo.RequiresFlags = RequiresFlags;
958   return RequiresFlags;
959 }
960 
961 namespace {
962 template <typename T> bool enforce_upper_bound(T *value, T upper) {
963   bool changed = *value > upper;
964   if (changed) {
965     *value = upper;
966   }
967   return changed;
968 }
969 } // namespace
970 
971 int32_t __tgt_rtl_init_device(int device_id) {
972   hsa_status_t err;
973 
974   // this is per device id init
975   DP("Initialize the device id: %d\n", device_id);
976 
977   hsa_agent_t agent = DeviceInfo.HSAAgents[device_id];
978 
979   // Get number of Compute Unit
980   uint32_t compute_units = 0;
981   err = hsa_agent_get_info(
982       agent, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT,
983       &compute_units);
984   if (err != HSA_STATUS_SUCCESS) {
985     DeviceInfo.ComputeUnits[device_id] = 1;
986     DP("Error getting compute units : settiing to 1\n");
987   } else {
988     DeviceInfo.ComputeUnits[device_id] = compute_units;
989     DP("Using %d compute unis per grid\n", DeviceInfo.ComputeUnits[device_id]);
990   }
991 
992   char GetInfoName[64]; // 64 max size returned by get info
993   err = hsa_agent_get_info(agent, (hsa_agent_info_t)HSA_AGENT_INFO_NAME,
994                            (void *)GetInfoName);
995   if (err)
996     DeviceInfo.GPUName[device_id] = "--unknown gpu--";
997   else {
998     DeviceInfo.GPUName[device_id] = GetInfoName;
999   }
1000 
1001   if (print_kernel_trace & STARTUP_DETAILS)
1002     fprintf(stderr, "Device#%-2d CU's: %2d %s\n", device_id,
1003             DeviceInfo.ComputeUnits[device_id],
1004             DeviceInfo.GPUName[device_id].c_str());
1005 
1006   // Query attributes to determine number of threads/block and blocks/grid.
1007   uint16_t workgroup_max_dim[3];
1008   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_WORKGROUP_MAX_DIM,
1009                            &workgroup_max_dim);
1010   if (err != HSA_STATUS_SUCCESS) {
1011     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::DefaultNumTeams;
1012     DP("Error getting grid dims: num groups : %d\n",
1013        RTLDeviceInfoTy::DefaultNumTeams);
1014   } else if (workgroup_max_dim[0] <= RTLDeviceInfoTy::HardTeamLimit) {
1015     DeviceInfo.GroupsPerDevice[device_id] = workgroup_max_dim[0];
1016     DP("Using %d ROCm blocks per grid\n",
1017        DeviceInfo.GroupsPerDevice[device_id]);
1018   } else {
1019     DeviceInfo.GroupsPerDevice[device_id] = RTLDeviceInfoTy::HardTeamLimit;
1020     DP("Max ROCm blocks per grid %d exceeds the hard team limit %d, capping "
1021        "at the hard limit\n",
1022        workgroup_max_dim[0], RTLDeviceInfoTy::HardTeamLimit);
1023   }
1024 
1025   // Get thread limit
1026   hsa_dim3_t grid_max_dim;
1027   err = hsa_agent_get_info(agent, HSA_AGENT_INFO_GRID_MAX_DIM, &grid_max_dim);
1028   if (err == HSA_STATUS_SUCCESS) {
1029     DeviceInfo.ThreadsPerGroup[device_id] =
1030         reinterpret_cast<uint32_t *>(&grid_max_dim)[0] /
1031         DeviceInfo.GroupsPerDevice[device_id];
1032 
1033     if (DeviceInfo.ThreadsPerGroup[device_id] == 0) {
1034       DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1035       DP("Default thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1036     } else if (enforce_upper_bound(&DeviceInfo.ThreadsPerGroup[device_id],
1037                                    RTLDeviceInfoTy::Max_WG_Size)) {
1038       DP("Capped thread limit: %d\n", RTLDeviceInfoTy::Max_WG_Size);
1039     } else {
1040       DP("Using ROCm Queried thread limit: %d\n",
1041          DeviceInfo.ThreadsPerGroup[device_id]);
1042     }
1043   } else {
1044     DeviceInfo.ThreadsPerGroup[device_id] = RTLDeviceInfoTy::Max_WG_Size;
1045     DP("Error getting max block dimension, use default:%d \n",
1046        RTLDeviceInfoTy::Max_WG_Size);
1047   }
1048 
1049   // Get wavefront size
1050   uint32_t wavefront_size = 0;
1051   err =
1052       hsa_agent_get_info(agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size);
1053   if (err == HSA_STATUS_SUCCESS) {
1054     DP("Queried wavefront size: %d\n", wavefront_size);
1055     DeviceInfo.WarpSize[device_id] = wavefront_size;
1056   } else {
1057     DP("Default wavefront size: %d\n",
1058        llvm::omp::AMDGPUGridValues.GV_Warp_Size);
1059     DeviceInfo.WarpSize[device_id] = llvm::omp::AMDGPUGridValues.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 /* 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