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