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