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