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