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