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