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