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