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