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