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