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