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