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