xref: /llvm-project/libc/utils/gpu/loader/amdgpu/amdhsa-loader.cpp (revision b4d49fb52e2068cdf4944dc0783c3ef691c946c4)
1 //===-- Loader Implementation for AMDHSA devices --------------------------===//
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 // This file impelements a simple loader to run images supporting the AMDHSA
10 // architecture. The file launches the '_start' kernel which should be provided
11 // by the device application start code and call ultimately call the 'main'
12 // function.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "Loader.h"
17 
18 #if defined(__has_include)
19 #if __has_include("hsa/hsa.h")
20 #include "hsa/hsa.h"
21 #include "hsa/hsa_ext_amd.h"
22 #elif __has_include("hsa.h")
23 #include "hsa.h"
24 #include "hsa_ext_amd.h"
25 #endif
26 #else
27 #include "hsa/hsa.h"
28 #include "hsa/hsa_ext_amd.h"
29 #endif
30 
31 #include <atomic>
32 #include <cstdio>
33 #include <cstdlib>
34 #include <cstring>
35 #include <thread>
36 #include <tuple>
37 #include <utility>
38 
39 // The implicit arguments of COV5 AMDGPU kernels.
40 struct implicit_args_t {
41   uint32_t grid_size_x;
42   uint32_t grid_size_y;
43   uint32_t grid_size_z;
44   uint16_t workgroup_size_x;
45   uint16_t workgroup_size_y;
46   uint16_t workgroup_size_z;
47   uint8_t Unused0[46];
48   uint16_t grid_dims;
49   uint8_t Unused1[190];
50 };
51 
52 /// Print the error code and exit if \p code indicates an error.
53 static void handle_error_impl(const char *file, int32_t line,
54                               hsa_status_t code) {
55   if (code == HSA_STATUS_SUCCESS || code == HSA_STATUS_INFO_BREAK)
56     return;
57 
58   const char *desc;
59   if (hsa_status_string(code, &desc) != HSA_STATUS_SUCCESS)
60     desc = "Unknown error";
61   fprintf(stderr, "%s:%d:0: Error: %s\n", file, line, desc);
62   exit(EXIT_FAILURE);
63 }
64 
65 /// Generic interface for iterating using the HSA callbacks.
66 template <typename elem_ty, typename func_ty, typename callback_ty>
67 hsa_status_t iterate(func_ty func, callback_ty cb) {
68   auto l = [](elem_ty elem, void *data) -> hsa_status_t {
69     callback_ty *unwrapped = static_cast<callback_ty *>(data);
70     return (*unwrapped)(elem);
71   };
72   return func(l, static_cast<void *>(&cb));
73 }
74 
75 /// Generic interface for iterating using the HSA callbacks.
76 template <typename elem_ty, typename func_ty, typename func_arg_ty,
77           typename callback_ty>
78 hsa_status_t iterate(func_ty func, func_arg_ty func_arg, callback_ty cb) {
79   auto l = [](elem_ty elem, void *data) -> hsa_status_t {
80     callback_ty *unwrapped = static_cast<callback_ty *>(data);
81     return (*unwrapped)(elem);
82   };
83   return func(func_arg, l, static_cast<void *>(&cb));
84 }
85 
86 /// Iterate through all availible agents.
87 template <typename callback_ty>
88 hsa_status_t iterate_agents(callback_ty callback) {
89   return iterate<hsa_agent_t>(hsa_iterate_agents, callback);
90 }
91 
92 /// Iterate through all availible memory pools.
93 template <typename callback_ty>
94 hsa_status_t iterate_agent_memory_pools(hsa_agent_t agent, callback_ty cb) {
95   return iterate<hsa_amd_memory_pool_t>(hsa_amd_agent_iterate_memory_pools,
96                                         agent, cb);
97 }
98 
99 template <hsa_device_type_t flag>
100 hsa_status_t get_agent(hsa_agent_t *output_agent) {
101   // Find the first agent with a matching device type.
102   auto cb = [&](hsa_agent_t hsa_agent) -> hsa_status_t {
103     hsa_device_type_t type;
104     hsa_status_t status =
105         hsa_agent_get_info(hsa_agent, HSA_AGENT_INFO_DEVICE, &type);
106     if (status != HSA_STATUS_SUCCESS)
107       return status;
108 
109     if (type == flag) {
110       // Ensure that a GPU agent supports kernel dispatch packets.
111       if (type == HSA_DEVICE_TYPE_GPU) {
112         hsa_agent_feature_t features;
113         status =
114             hsa_agent_get_info(hsa_agent, HSA_AGENT_INFO_FEATURE, &features);
115         if (status != HSA_STATUS_SUCCESS)
116           return status;
117         if (features & HSA_AGENT_FEATURE_KERNEL_DISPATCH)
118           *output_agent = hsa_agent;
119       } else {
120         *output_agent = hsa_agent;
121       }
122       return HSA_STATUS_INFO_BREAK;
123     }
124     return HSA_STATUS_SUCCESS;
125   };
126 
127   return iterate_agents(cb);
128 }
129 
130 void print_kernel_resources(const char *kernel_name) {
131   fprintf(stderr, "Kernel resources on AMDGPU is not supported yet.\n");
132 }
133 
134 /// Retrieve a global memory pool with a \p flag from the agent.
135 template <hsa_amd_memory_pool_global_flag_t flag>
136 hsa_status_t get_agent_memory_pool(hsa_agent_t agent,
137                                    hsa_amd_memory_pool_t *output_pool) {
138   auto cb = [&](hsa_amd_memory_pool_t memory_pool) {
139     uint32_t flags;
140     hsa_amd_segment_t segment;
141     if (auto err = hsa_amd_memory_pool_get_info(
142             memory_pool, HSA_AMD_MEMORY_POOL_INFO_SEGMENT, &segment))
143       return err;
144     if (auto err = hsa_amd_memory_pool_get_info(
145             memory_pool, HSA_AMD_MEMORY_POOL_INFO_GLOBAL_FLAGS, &flags))
146       return err;
147 
148     if (segment != HSA_AMD_SEGMENT_GLOBAL)
149       return HSA_STATUS_SUCCESS;
150 
151     if (flags & flag)
152       *output_pool = memory_pool;
153 
154     return HSA_STATUS_SUCCESS;
155   };
156   return iterate_agent_memory_pools(agent, cb);
157 }
158 
159 template <typename args_t>
160 hsa_status_t launch_kernel(hsa_agent_t dev_agent, hsa_executable_t executable,
161                            hsa_amd_memory_pool_t kernargs_pool,
162                            hsa_amd_memory_pool_t coarsegrained_pool,
163                            hsa_queue_t *queue, rpc::Server &server,
164                            const LaunchParameters &params,
165                            const char *kernel_name, args_t kernel_args,
166                            bool print_resource_usage) {
167   // Look up the kernel in the loaded executable.
168   hsa_executable_symbol_t symbol;
169   if (hsa_status_t err = hsa_executable_get_symbol_by_name(
170           executable, kernel_name, &dev_agent, &symbol))
171     return err;
172 
173   uint32_t wavefront_size = 0;
174   if (hsa_status_t err = hsa_agent_get_info(
175           dev_agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size))
176     handle_error(err);
177   // Retrieve different properties of the kernel symbol used for launch.
178   uint64_t kernel;
179   uint32_t args_size;
180   uint32_t group_size;
181   uint32_t private_size;
182   bool dynamic_stack;
183 
184   std::pair<hsa_executable_symbol_info_t, void *> symbol_infos[] = {
185       {HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &kernel},
186       {HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE, &args_size},
187       {HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE, &group_size},
188       {HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_DYNAMIC_CALLSTACK, &dynamic_stack},
189       {HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE, &private_size}};
190 
191   for (auto &[info, value] : symbol_infos)
192     if (hsa_status_t err = hsa_executable_symbol_get_info(symbol, info, value))
193       return err;
194 
195   // Allocate space for the kernel arguments on the host and allow the GPU agent
196   // to access it.
197   void *args;
198   if (hsa_status_t err = hsa_amd_memory_pool_allocate(kernargs_pool, args_size,
199                                                       /*flags=*/0, &args))
200     handle_error(err);
201   hsa_amd_agents_allow_access(1, &dev_agent, nullptr, args);
202 
203   // Initialize all the arguments (explicit and implicit) to zero, then set the
204   // explicit arguments to the values created above.
205   std::memset(args, 0, args_size);
206   std::memcpy(args, &kernel_args, sizeof(args_t));
207 
208   // Initialize the necessary implicit arguments to the proper values.
209   int dims = 1 + (params.num_blocks_y * params.num_threads_y != 1) +
210              (params.num_blocks_z * params.num_threads_z != 1);
211   implicit_args_t *implicit_args = reinterpret_cast<implicit_args_t *>(
212       reinterpret_cast<uint8_t *>(args) + sizeof(args_t));
213   implicit_args->grid_dims = dims;
214   implicit_args->grid_size_x = params.num_blocks_x;
215   implicit_args->grid_size_y = params.num_blocks_y;
216   implicit_args->grid_size_z = params.num_blocks_z;
217   implicit_args->workgroup_size_x = params.num_threads_x;
218   implicit_args->workgroup_size_y = params.num_threads_y;
219   implicit_args->workgroup_size_z = params.num_threads_z;
220 
221   // Obtain a packet from the queue.
222   uint64_t packet_id = hsa_queue_add_write_index_relaxed(queue, 1);
223   while (packet_id - hsa_queue_load_read_index_scacquire(queue) >= queue->size)
224     ;
225 
226   const uint32_t mask = queue->size - 1;
227   hsa_kernel_dispatch_packet_t *packet =
228       static_cast<hsa_kernel_dispatch_packet_t *>(queue->base_address) +
229       (packet_id & mask);
230 
231   // Set up the packet for exeuction on the device. We currently only launch
232   // with one thread on the device, forcing the rest of the wavefront to be
233   // masked off.
234   uint16_t setup = (dims) << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS;
235   packet->workgroup_size_x = params.num_threads_x;
236   packet->workgroup_size_y = params.num_threads_y;
237   packet->workgroup_size_z = params.num_threads_z;
238   packet->reserved0 = 0;
239   packet->grid_size_x = params.num_blocks_x * params.num_threads_x;
240   packet->grid_size_y = params.num_blocks_y * params.num_threads_y;
241   packet->grid_size_z = params.num_blocks_z * params.num_threads_z;
242   packet->private_segment_size =
243       dynamic_stack ? 16 * 1024 /* 16 KB */ : private_size;
244   packet->group_segment_size = group_size;
245   packet->kernel_object = kernel;
246   packet->kernarg_address = args;
247   packet->reserved2 = 0;
248   // Create a signal to indicate when this packet has been completed.
249   if (hsa_status_t err =
250           hsa_signal_create(1, 0, nullptr, &packet->completion_signal))
251     handle_error(err);
252 
253   if (print_resource_usage)
254     print_kernel_resources(kernel_name);
255 
256   // Initialize the packet header and set the doorbell signal to begin execution
257   // by the HSA runtime.
258   uint16_t header =
259       1u << HSA_PACKET_HEADER_BARRIER |
260       (HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE) |
261       (HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_SCACQUIRE_FENCE_SCOPE) |
262       (HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_SCRELEASE_FENCE_SCOPE);
263   uint32_t header_word = header | (setup << 16u);
264   __atomic_store_n((uint32_t *)&packet->header, header_word, __ATOMIC_RELEASE);
265   hsa_signal_store_relaxed(queue->doorbell_signal, packet_id);
266 
267   std::atomic<bool> finished = false;
268   std::thread server_thread(
269       [](std::atomic<bool> *finished, rpc::Server *server,
270          uint32_t wavefront_size, hsa_agent_t dev_agent,
271          hsa_amd_memory_pool_t coarsegrained_pool) {
272         // Register RPC callbacks for the malloc and free functions on HSA.
273         auto malloc_handler = [&](size_t size) -> void * {
274           void *dev_ptr = nullptr;
275           if (hsa_status_t err =
276                   hsa_amd_memory_pool_allocate(coarsegrained_pool, size,
277                                                /*flags=*/0, &dev_ptr))
278             dev_ptr = nullptr;
279           hsa_amd_agents_allow_access(1, &dev_agent, nullptr, dev_ptr);
280           return dev_ptr;
281         };
282 
283         auto free_handler = [](void *ptr) -> void {
284           if (hsa_status_t err =
285                   hsa_amd_memory_pool_free(reinterpret_cast<void *>(ptr)))
286             handle_error(err);
287         };
288 
289         uint32_t index = 0;
290         while (!*finished) {
291           if (wavefront_size == 32)
292             index =
293                 handle_server<32>(*server, index, malloc_handler, free_handler);
294           else
295             index =
296                 handle_server<64>(*server, index, malloc_handler, free_handler);
297         }
298       },
299       &finished, &server, wavefront_size, dev_agent, coarsegrained_pool);
300 
301   // Wait until the kernel has completed execution on the device. Periodically
302   // check the RPC client for work to be performed on the server.
303   while (hsa_signal_wait_scacquire(packet->completion_signal,
304                                    HSA_SIGNAL_CONDITION_EQ, 0, UINT64_MAX,
305                                    HSA_WAIT_STATE_BLOCKED) != 0)
306     ;
307 
308   finished = true;
309   if (server_thread.joinable())
310     server_thread.join();
311 
312   // Destroy the resources acquired to launch the kernel and return.
313   if (hsa_status_t err = hsa_amd_memory_pool_free(args))
314     handle_error(err);
315   if (hsa_status_t err = hsa_signal_destroy(packet->completion_signal))
316     handle_error(err);
317 
318   return HSA_STATUS_SUCCESS;
319 }
320 
321 /// Copies data from the source agent to the destination agent. The source
322 /// memory must first be pinned explicitly or allocated via HSA.
323 static hsa_status_t hsa_memcpy(void *dst, hsa_agent_t dst_agent,
324                                const void *src, hsa_agent_t src_agent,
325                                uint64_t size) {
326   // Create a memory signal to copy information between the host and device.
327   hsa_signal_t memory_signal;
328   if (hsa_status_t err = hsa_signal_create(1, 0, nullptr, &memory_signal))
329     return err;
330 
331   if (hsa_status_t err = hsa_amd_memory_async_copy(
332           dst, dst_agent, src, src_agent, size, 0, nullptr, memory_signal))
333     return err;
334 
335   while (hsa_signal_wait_scacquire(memory_signal, HSA_SIGNAL_CONDITION_EQ, 0,
336                                    UINT64_MAX, HSA_WAIT_STATE_ACTIVE) != 0)
337     ;
338 
339   if (hsa_status_t err = hsa_signal_destroy(memory_signal))
340     return err;
341 
342   return HSA_STATUS_SUCCESS;
343 }
344 
345 int load(int argc, const char **argv, const char **envp, void *image,
346          size_t size, const LaunchParameters &params,
347          bool print_resource_usage) {
348   // Initialize the HSA runtime used to communicate with the device.
349   if (hsa_status_t err = hsa_init())
350     handle_error(err);
351 
352   // Register a callback when the device encounters a memory fault.
353   if (hsa_status_t err = hsa_amd_register_system_event_handler(
354           [](const hsa_amd_event_t *event, void *) -> hsa_status_t {
355             if (event->event_type == HSA_AMD_GPU_MEMORY_FAULT_EVENT)
356               return HSA_STATUS_ERROR;
357             return HSA_STATUS_SUCCESS;
358           },
359           nullptr))
360     handle_error(err);
361 
362   // Obtain a single agent for the device and host to use the HSA memory model.
363   hsa_agent_t dev_agent;
364   hsa_agent_t host_agent;
365   if (hsa_status_t err = get_agent<HSA_DEVICE_TYPE_GPU>(&dev_agent))
366     handle_error(err);
367   if (hsa_status_t err = get_agent<HSA_DEVICE_TYPE_CPU>(&host_agent))
368     handle_error(err);
369 
370   // Load the code object's ISA information and executable data segments.
371   hsa_code_object_reader_t reader;
372   if (hsa_status_t err =
373           hsa_code_object_reader_create_from_memory(image, size, &reader))
374     handle_error(err);
375 
376   hsa_executable_t executable;
377   if (hsa_status_t err = hsa_executable_create_alt(
378           HSA_PROFILE_FULL, HSA_DEFAULT_FLOAT_ROUNDING_MODE_ZERO, "",
379           &executable))
380     handle_error(err);
381 
382   hsa_loaded_code_object_t object;
383   if (hsa_status_t err = hsa_executable_load_agent_code_object(
384           executable, dev_agent, reader, "", &object))
385     handle_error(err);
386 
387   // No modifications to the executable are allowed  after this point.
388   if (hsa_status_t err = hsa_executable_freeze(executable, ""))
389     handle_error(err);
390 
391   // Check the validity of the loaded executable. If the agents ISA features do
392   // not match the executable's code object it will fail here.
393   uint32_t result;
394   if (hsa_status_t err = hsa_executable_validate(executable, &result))
395     handle_error(err);
396   if (result)
397     handle_error(HSA_STATUS_ERROR);
398 
399   if (hsa_status_t err = hsa_code_object_reader_destroy(reader))
400     handle_error(err);
401 
402   // Obtain memory pools to exchange data between the host and the device. The
403   // fine-grained pool acts as pinned memory on the host for DMA transfers to
404   // the device, the coarse-grained pool is for allocations directly on the
405   // device, and the kernerl-argument pool is for executing the kernel.
406   hsa_amd_memory_pool_t kernargs_pool;
407   hsa_amd_memory_pool_t finegrained_pool;
408   hsa_amd_memory_pool_t coarsegrained_pool;
409   if (hsa_status_t err =
410           get_agent_memory_pool<HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_KERNARG_INIT>(
411               host_agent, &kernargs_pool))
412     handle_error(err);
413   if (hsa_status_t err =
414           get_agent_memory_pool<HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_FINE_GRAINED>(
415               host_agent, &finegrained_pool))
416     handle_error(err);
417   if (hsa_status_t err =
418           get_agent_memory_pool<HSA_AMD_MEMORY_POOL_GLOBAL_FLAG_COARSE_GRAINED>(
419               dev_agent, &coarsegrained_pool))
420     handle_error(err);
421 
422   // Allocate fine-grained memory on the host to hold the pointer array for the
423   // copied argv and allow the GPU agent to access it.
424   auto allocator = [&](uint64_t size) -> void * {
425     void *dev_ptr = nullptr;
426     if (hsa_status_t err = hsa_amd_memory_pool_allocate(finegrained_pool, size,
427                                                         /*flags=*/0, &dev_ptr))
428       handle_error(err);
429     hsa_amd_agents_allow_access(1, &dev_agent, nullptr, dev_ptr);
430     return dev_ptr;
431   };
432   void *dev_argv = copy_argument_vector(argc, argv, allocator);
433   if (!dev_argv)
434     handle_error("Failed to allocate device argv");
435 
436   // Allocate fine-grained memory on the host to hold the pointer array for the
437   // copied environment array and allow the GPU agent to access it.
438   void *dev_envp = copy_environment(envp, allocator);
439   if (!dev_envp)
440     handle_error("Failed to allocate device environment");
441 
442   // Allocate space for the return pointer and initialize it to zero.
443   void *dev_ret;
444   if (hsa_status_t err =
445           hsa_amd_memory_pool_allocate(coarsegrained_pool, sizeof(int),
446                                        /*flags=*/0, &dev_ret))
447     handle_error(err);
448   hsa_amd_memory_fill(dev_ret, 0, /*count=*/1);
449 
450   // Allocate finegrained memory for the RPC server and client to share.
451   uint32_t wavefront_size = 0;
452   if (hsa_status_t err = hsa_agent_get_info(
453           dev_agent, HSA_AGENT_INFO_WAVEFRONT_SIZE, &wavefront_size))
454     handle_error(err);
455 
456   // Set up the RPC server.
457   void *rpc_buffer;
458   if (hsa_status_t err = hsa_amd_memory_pool_allocate(
459           finegrained_pool,
460           rpc::Server::allocation_size(wavefront_size, rpc::MAX_PORT_COUNT),
461           /*flags=*/0, &rpc_buffer))
462     handle_error(err);
463   hsa_amd_agents_allow_access(1, &dev_agent, nullptr, rpc_buffer);
464 
465   rpc::Server server(rpc::MAX_PORT_COUNT, rpc_buffer);
466   rpc::Client client(rpc::MAX_PORT_COUNT, rpc_buffer);
467 
468   // Initialize the RPC client on the device by copying the local data to the
469   // device's internal pointer.
470   hsa_executable_symbol_t rpc_client_sym;
471   if (hsa_status_t err = hsa_executable_get_symbol_by_name(
472           executable, "__llvm_libc_rpc_client", &dev_agent, &rpc_client_sym))
473     handle_error(err);
474 
475   void *rpc_client_host;
476   if (hsa_status_t err =
477           hsa_amd_memory_pool_allocate(finegrained_pool, sizeof(void *),
478                                        /*flags=*/0, &rpc_client_host))
479     handle_error(err);
480   hsa_amd_agents_allow_access(1, &dev_agent, nullptr, rpc_client_host);
481 
482   void *rpc_client_dev;
483   if (hsa_status_t err = hsa_executable_symbol_get_info(
484           rpc_client_sym, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
485           &rpc_client_dev))
486     handle_error(err);
487 
488   // Copy the address of the client buffer from the device to the host.
489   if (hsa_status_t err = hsa_memcpy(rpc_client_host, host_agent, rpc_client_dev,
490                                     dev_agent, sizeof(void *)))
491     handle_error(err);
492 
493   void *rpc_client_buffer;
494   if (hsa_status_t err =
495           hsa_amd_memory_lock(&client, sizeof(rpc::Client),
496                               /*agents=*/nullptr, 0, &rpc_client_buffer))
497     handle_error(err);
498 
499   // Copy the RPC client buffer to the address pointed to by the symbol.
500   if (hsa_status_t err =
501           hsa_memcpy(*reinterpret_cast<void **>(rpc_client_host), dev_agent,
502                      rpc_client_buffer, host_agent, sizeof(rpc::Client)))
503     handle_error(err);
504 
505   if (hsa_status_t err = hsa_amd_memory_unlock(&client))
506     handle_error(err);
507   if (hsa_status_t err = hsa_amd_memory_pool_free(rpc_client_host))
508     handle_error(err);
509 
510   // Obtain the GPU's fixed-frequency clock rate and copy it to the GPU.
511   // If the clock_freq symbol is missing, no work to do.
512   hsa_executable_symbol_t freq_sym;
513   if (HSA_STATUS_SUCCESS ==
514       hsa_executable_get_symbol_by_name(executable, "__llvm_libc_clock_freq",
515                                         &dev_agent, &freq_sym)) {
516 
517     void *host_clock_freq;
518     if (hsa_status_t err =
519             hsa_amd_memory_pool_allocate(finegrained_pool, sizeof(uint64_t),
520                                          /*flags=*/0, &host_clock_freq))
521       handle_error(err);
522     hsa_amd_agents_allow_access(1, &dev_agent, nullptr, host_clock_freq);
523 
524     if (HSA_STATUS_SUCCESS ==
525         hsa_agent_get_info(dev_agent,
526                            static_cast<hsa_agent_info_t>(
527                                HSA_AMD_AGENT_INFO_TIMESTAMP_FREQUENCY),
528                            host_clock_freq)) {
529 
530       void *freq_addr;
531       if (hsa_status_t err = hsa_executable_symbol_get_info(
532               freq_sym, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
533               &freq_addr))
534         handle_error(err);
535 
536       if (hsa_status_t err = hsa_memcpy(freq_addr, dev_agent, host_clock_freq,
537                                         host_agent, sizeof(uint64_t)))
538         handle_error(err);
539     }
540   }
541 
542   // Obtain a queue with the maximum (power of two) size, used to send commands
543   // to the HSA runtime and launch execution on the device.
544   uint64_t queue_size;
545   if (hsa_status_t err = hsa_agent_get_info(
546           dev_agent, HSA_AGENT_INFO_QUEUE_MAX_SIZE, &queue_size))
547     handle_error(err);
548   hsa_queue_t *queue = nullptr;
549   if (hsa_status_t err =
550           hsa_queue_create(dev_agent, queue_size, HSA_QUEUE_TYPE_MULTI, nullptr,
551                            nullptr, UINT32_MAX, UINT32_MAX, &queue))
552     handle_error(err);
553 
554   LaunchParameters single_threaded_params = {1, 1, 1, 1, 1, 1};
555   begin_args_t init_args = {argc, dev_argv, dev_envp};
556   if (hsa_status_t err = launch_kernel(dev_agent, executable, kernargs_pool,
557                                        coarsegrained_pool, queue, server,
558                                        single_threaded_params, "_begin.kd",
559                                        init_args, print_resource_usage))
560     handle_error(err);
561 
562   start_args_t args = {argc, dev_argv, dev_envp, dev_ret};
563   if (hsa_status_t err = launch_kernel(
564           dev_agent, executable, kernargs_pool, coarsegrained_pool, queue,
565           server, params, "_start.kd", args, print_resource_usage))
566     handle_error(err);
567 
568   void *host_ret;
569   if (hsa_status_t err =
570           hsa_amd_memory_pool_allocate(finegrained_pool, sizeof(int),
571                                        /*flags=*/0, &host_ret))
572     handle_error(err);
573   hsa_amd_agents_allow_access(1, &dev_agent, nullptr, host_ret);
574 
575   if (hsa_status_t err =
576           hsa_memcpy(host_ret, host_agent, dev_ret, dev_agent, sizeof(int)))
577     handle_error(err);
578 
579   // Save the return value and perform basic clean-up.
580   int ret = *static_cast<int *>(host_ret);
581 
582   end_args_t fini_args = {ret};
583   if (hsa_status_t err = launch_kernel(dev_agent, executable, kernargs_pool,
584                                        coarsegrained_pool, queue, server,
585                                        single_threaded_params, "_end.kd",
586                                        fini_args, print_resource_usage))
587     handle_error(err);
588 
589   if (hsa_status_t err = hsa_amd_memory_pool_free(rpc_buffer))
590     handle_error(err);
591 
592   // Free the memory allocated for the device.
593   if (hsa_status_t err = hsa_amd_memory_pool_free(dev_argv))
594     handle_error(err);
595   if (hsa_status_t err = hsa_amd_memory_pool_free(dev_ret))
596     handle_error(err);
597   if (hsa_status_t err = hsa_amd_memory_pool_free(host_ret))
598     handle_error(err);
599 
600   if (hsa_status_t err = hsa_queue_destroy(queue))
601     handle_error(err);
602 
603   if (hsa_status_t err = hsa_executable_destroy(executable))
604     handle_error(err);
605 
606   if (hsa_status_t err = hsa_shut_down())
607     handle_error(err);
608 
609   return ret;
610 }
611