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