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