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