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