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