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