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