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