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