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