Debian Codegraph @

libgomp/plugin/plugin-gcn.c

raw
1 /* Plugin for AMD GCN execution.
2
3 Copyright (C) 2013-2025 Free Software Foundation, Inc.
4
5 Contributed by Mentor Embedded
6
7 This file is part of the GNU Offloading and Multi Processing Library
8 (libgomp).
9
10 Libgomp is free software; you can redistribute it and/or modify it
11 under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3, or (at your option)
13 any later version.
14
15 Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
16 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 FOR A PARTICULAR PURPOSE. See the GNU General Public License for
18 more details.
19
20 Under Section 7 of GPL version 3, you are granted additional
21 permissions described in the GCC Runtime Library Exception, version
22 3.1, as published by the Free Software Foundation.
23
24 You should have received a copy of the GNU General Public License and
25 a copy of the GCC Runtime Library Exception along with this program;
26 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
27 <http://www.gnu.org/licenses/>. */
28
29 /* {{{ Includes and defines */
30
31 #include "config.h"
32 #include "symcat.h"
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <pthread.h>
37 #include <inttypes.h>
38 #include <stdbool.h>
39 #include <limits.h>
40 #include <hsa.h>
41 #include <hsa_ext_amd.h>
42 #include <dlfcn.h>
43 #include <signal.h>
44 #define _LIBGOMP_PLUGIN_INCLUDE 1
45 #include "libgomp-plugin.h"
46 #undef _LIBGOMP_PLUGIN_INCLUDE
47 #include "config/gcn/libgomp-gcn.h" /* For struct output. */
48 #include "gomp-constants.h"
49 #include <elf.h>
50 #include "oacc-plugin.h"
51 #include "oacc-int.h"
52 #include <assert.h>
53
54 /* These probably won't be in elf.h for a while. */
55 #ifndef R_AMDGPU_NONE
56 #define R_AMDGPU_NONE 0
57 #define R_AMDGPU_ABS32_LO 1 /* (S + A) & 0xFFFFFFFF */
58 #define R_AMDGPU_ABS32_HI 2 /* (S + A) >> 32 */
59 #define R_AMDGPU_ABS64 3 /* S + A */
60 #define R_AMDGPU_REL32 4 /* S + A - P */
61 #define R_AMDGPU_REL64 5 /* S + A - P */
62 #define R_AMDGPU_ABS32 6 /* S + A */
63 #define R_AMDGPU_GOTPCREL 7 /* G + GOT + A - P */
64 #define R_AMDGPU_GOTPCREL32_LO 8 /* (G + GOT + A - P) & 0xFFFFFFFF */
65 #define R_AMDGPU_GOTPCREL32_HI 9 /* (G + GOT + A - P) >> 32 */
66 #define R_AMDGPU_REL32_LO 10 /* (S + A - P) & 0xFFFFFFFF */
67 #define R_AMDGPU_REL32_HI 11 /* (S + A - P) >> 32 */
68 #define R_AMDGPU_RELATIVE64 13 /* B + A */
69 #endif
70
71 #define ELFABIVERSION_AMDGPU_HSA_V6 4
72
73 #define EF_AMDGPU_GENERIC_VERSION_V 0xff000000 /* Mask. */
74 #define EF_AMDGPU_GENERIC_VERSION_OFFSET 24
75
76 #define GET_GENERIC_VERSION(VAR) ((VAR & EF_AMDGPU_GENERIC_VERSION_V) \
77 >> EF_AMDGPU_GENERIC_VERSION_OFFSET)
78
79 /* GCN specific definitions for asynchronous queues. */
80
81 #define ASYNC_QUEUE_SIZE 64
82 #define DRAIN_QUEUE_SYNCHRONOUS_P false
83 #define DEBUG_QUEUES 0
84 #define DEBUG_THREAD_SLEEP 0
85 #define DEBUG_THREAD_SIGNAL 0
86
87 /* Defaults. */
88 #define DEFAULT_GCN_HEAP_SIZE (100*1024*1024) /* 100MB. */
89
90 /* Secure getenv() which returns NULL if running as SUID/SGID. */
91 #ifndef HAVE_SECURE_GETENV
92 #ifdef HAVE___SECURE_GETENV
93 #define secure_getenv __secure_getenv
94 #elif defined (HAVE_UNISTD_H) && defined(HAVE_GETUID) && defined(HAVE_GETEUID) \
95 && defined(HAVE_GETGID) && defined(HAVE_GETEGID)
96
97 #include <unistd.h>
98
99 /* Implementation of secure_getenv() for targets where it is not provided but
100 we have at least means to test real and effective IDs. */
101
102 static char *
103 secure_getenv (const char *name)
104 {
105 if ((getuid () == geteuid ()) && (getgid () == getegid ()))
106 return getenv (name);
107 else
108 return NULL;
109 }
110
111 #else
112 #define secure_getenv getenv
113 #endif
114 #endif
115
116 /* }}} */
117 /* {{{ Types */
118
119 /* GCN-specific implementation of the GOMP_PLUGIN_acc_thread data. */
120
121 struct gcn_thread
122 {
123 /* The thread number from the async clause, or GOMP_ASYNC_SYNC. */
124 int async;
125 };
126
127 /* As an HSA runtime is dlopened, following structure defines function
128 pointers utilized by the HSA plug-in. */
129
130 struct hsa_runtime_fn_info
131 {
132 /* HSA runtime. */
133 hsa_status_t (*hsa_status_string_fn) (hsa_status_t status,
134 const char **status_string);
135 hsa_status_t (*hsa_system_get_info_fn) (hsa_system_info_t attribute,
136 void *value);
137 hsa_status_t (*hsa_agent_get_info_fn) (hsa_agent_t agent,
138 hsa_agent_info_t attribute,
139 void *value);
140 hsa_status_t (*hsa_isa_get_info_fn)(hsa_isa_t isa,
141 hsa_isa_info_t attribute,
142 uint32_t index,
143 void *value);
144 hsa_status_t (*hsa_init_fn) (void);
145 hsa_status_t (*hsa_iterate_agents_fn)
146 (hsa_status_t (*callback)(hsa_agent_t agent, void *data), void *data);
147 hsa_status_t (*hsa_region_get_info_fn) (hsa_region_t region,
148 hsa_region_info_t attribute,
149 void *value);
150 hsa_status_t (*hsa_queue_create_fn)
151 (hsa_agent_t agent, uint32_t size, hsa_queue_type_t type,
152 void (*callback)(hsa_status_t status, hsa_queue_t *source, void *data),
153 void *data, uint32_t private_segment_size,
154 uint32_t group_segment_size, hsa_queue_t **queue);
155 hsa_status_t (*hsa_agent_iterate_regions_fn)
156 (hsa_agent_t agent,
157 hsa_status_t (*callback)(hsa_region_t region, void *data), void *data);
158 hsa_status_t (*hsa_executable_destroy_fn) (hsa_executable_t executable);
159 hsa_status_t (*hsa_executable_create_fn)
160 (hsa_profile_t profile, hsa_executable_state_t executable_state,
161 const char *options, hsa_executable_t *executable);
162 hsa_status_t (*hsa_executable_global_variable_define_fn)
163 (hsa_executable_t executable, const char *variable_name, void *address);
164 hsa_status_t (*hsa_executable_load_code_object_fn)
165 (hsa_executable_t executable, hsa_agent_t agent,
166 hsa_code_object_t code_object, const char *options);
167 hsa_status_t (*hsa_executable_freeze_fn)(hsa_executable_t executable,
168 const char *options);
169 hsa_status_t (*hsa_signal_create_fn) (hsa_signal_value_t initial_value,
170 uint32_t num_consumers,
171 const hsa_agent_t *consumers,
172 hsa_signal_t *signal);
173 hsa_status_t (*hsa_memory_allocate_fn) (hsa_region_t region, size_t size,
174 void **ptr);
175 hsa_status_t (*hsa_memory_assign_agent_fn) (void *ptr, hsa_agent_t agent,
176 hsa_access_permission_t access);
177 hsa_status_t (*hsa_memory_copy_fn)(void *dst, const void *src, size_t size);
178 hsa_status_t (*hsa_memory_free_fn) (void *ptr);
179 hsa_status_t (*hsa_signal_destroy_fn) (hsa_signal_t signal);
180 hsa_status_t (*hsa_executable_get_symbol_fn)
181 (hsa_executable_t executable, const char *module_name,
182 const char *symbol_name, hsa_agent_t agent, int32_t call_convention,
183 hsa_executable_symbol_t *symbol);
184 hsa_status_t (*hsa_executable_symbol_get_info_fn)
185 (hsa_executable_symbol_t executable_symbol,
186 hsa_executable_symbol_info_t attribute, void *value);
187 hsa_status_t (*hsa_executable_iterate_symbols_fn)
188 (hsa_executable_t executable,
189 hsa_status_t (*callback)(hsa_executable_t executable,
190 hsa_executable_symbol_t symbol, void *data),
191 void *data);
192 uint64_t (*hsa_queue_add_write_index_release_fn) (const hsa_queue_t *queue,
193 uint64_t value);
194 uint64_t (*hsa_queue_load_read_index_acquire_fn) (const hsa_queue_t *queue);
195 uint64_t (*hsa_queue_load_read_index_relaxed_fn) (const hsa_queue_t *queue);
196 uint64_t (*hsa_queue_load_write_index_relaxed_fn) (const hsa_queue_t *queue);
197 void (*hsa_signal_store_relaxed_fn) (hsa_signal_t signal,
198 hsa_signal_value_t value);
199 void (*hsa_signal_store_release_fn) (hsa_signal_t signal,
200 hsa_signal_value_t value);
201 hsa_signal_value_t (*hsa_signal_wait_acquire_fn)
202 (hsa_signal_t signal, hsa_signal_condition_t condition,
203 hsa_signal_value_t compare_value, uint64_t timeout_hint,
204 hsa_wait_state_t wait_state_hint);
205 hsa_signal_value_t (*hsa_signal_load_acquire_fn) (hsa_signal_t signal);
206 hsa_status_t (*hsa_queue_destroy_fn) (hsa_queue_t *queue);
207
208 hsa_status_t (*hsa_code_object_deserialize_fn)
209 (void *serialized_code_object, size_t serialized_code_object_size,
210 const char *options, hsa_code_object_t *code_object);
211 hsa_status_t (*hsa_amd_memory_lock_fn)
212 (void *host_ptr, size_t size, hsa_agent_t *agents, int num_agent,
213 void **agent_ptr);
214 hsa_status_t (*hsa_amd_memory_unlock_fn) (void *host_ptr);
215 hsa_status_t (*hsa_amd_memory_async_copy_rect_fn)
216 (const hsa_pitched_ptr_t *dst, const hsa_dim3_t *dst_offset,
217 const hsa_pitched_ptr_t *src, const hsa_dim3_t *src_offset,
218 const hsa_dim3_t *range, hsa_agent_t copy_agent,
219 hsa_amd_copy_direction_t dir, uint32_t num_dep_signals,
220 const hsa_signal_t *dep_signals, hsa_signal_t completion_signal);
221 };
222
223 /* As an HIP runtime is dlopened, following structure defines function
224 pointers utilized by the interop feature of this plugin.
225 Add suffient type declarations to get this work. */
226
227 typedef int hipError_t; /* Actually an enum; 0 == success. */
228 typedef void* hipCtx_t;
229 struct hipStream_s;
230 typedef struct hipStream_s* hipStream_t;
231
232 struct hip_runtime_fn_info
233 {
234 hipError_t (*hipStreamCreate_fn) (hipStream_t *);
235 hipError_t (*hipStreamDestroy_fn) (hipStream_t);
236 hipError_t (*hipStreamSynchronize_fn) (hipStream_t);
237 hipError_t (*hipCtxGetCurrent_fn) (hipCtx_t *ctx);
238 hipError_t (*hipSetDevice_fn) (int deviceId);
239 hipError_t (*hipGetDevice_fn) (int *deviceId);
240 };
241
242 /* Structure describing the run-time and grid properties of an HSA kernel
243 lauch. This needs to match the format passed to GOMP_OFFLOAD_run. */
244
245 struct GOMP_kernel_launch_attributes
246 {
247 /* Number of dimensions the workload has. Maximum number is 3. */
248 uint32_t ndim;
249 /* Size of the grid in the three respective dimensions. */
250 uint32_t gdims[3];
251 /* Size of work-groups in the respective dimensions. */
252 uint32_t wdims[3];
253 };
254
255 /* Collection of information needed for a dispatch of a kernel from a
256 kernel. */
257
258 struct kernel_dispatch
259 {
260 struct agent_info *agent;
261 /* Pointer to a command queue associated with a kernel dispatch agent. */
262 void *queue;
263 /* Pointer to a memory space used for kernel arguments passing. */
264 void *kernarg_address;
265 /* Kernel object. */
266 uint64_t object;
267 /* Synchronization signal used for dispatch synchronization. */
268 uint64_t signal;
269 /* Private segment size. */
270 uint32_t private_segment_size;
271 /* Group segment size. */
272 uint32_t group_segment_size;
273 };
274
275 /* Structure of the kernargs segment, supporting console output.
276
277 This needs to match the definitions in Newlib, and the expectations
278 in libgomp target code. */
279
280 struct kernargs {
281 struct kernargs_abi abi;
282
283 /* Output data. */
284 struct output output_data;
285 };
286
287 /* A queue entry for a future asynchronous launch. */
288
289 struct kernel_launch
290 {
291 struct kernel_info *kernel;
292 void *vars;
293 struct GOMP_kernel_launch_attributes kla;
294 };
295
296 /* A queue entry for a future callback. */
297
298 struct callback
299 {
300 void (*fn)(void *);
301 void *data;
302 };
303
304 /* A data struct for the copy_data callback. */
305
306 struct copy_data
307 {
308 void *dst;
309 const void *src;
310 size_t len;
311 struct goacc_asyncqueue *aq;
312 };
313
314 /* A queue entry for a placeholder. These correspond to a wait event. */
315
316 struct placeholder
317 {
318 int executed;
319 pthread_cond_t cond;
320 pthread_mutex_t mutex;
321 };
322
323 /* A queue entry for a wait directive. */
324
325 struct asyncwait_info
326 {
327 struct placeholder *placeholderp;
328 };
329
330 /* Encode the type of an entry in an async queue. */
331
332 enum entry_type
333 {
334 KERNEL_LAUNCH,
335 CALLBACK,
336 ASYNC_WAIT,
337 ASYNC_PLACEHOLDER
338 };
339
340 /* An entry in an async queue. */
341
342 struct queue_entry
343 {
344 enum entry_type type;
345 union {
346 struct kernel_launch launch;
347 struct callback callback;
348 struct asyncwait_info asyncwait;
349 struct placeholder placeholder;
350 } u;
351 };
352
353 /* An async queue header.
354
355 OpenMP may create one of these.
356 OpenACC may create many. */
357
358 struct goacc_asyncqueue
359 {
360 struct agent_info *agent;
361 hsa_queue_t *hsa_queue;
362
363 pthread_t thread_drain_queue;
364 pthread_mutex_t mutex;
365 pthread_cond_t queue_cond_in;
366 pthread_cond_t queue_cond_out;
367 struct queue_entry queue[ASYNC_QUEUE_SIZE];
368 int queue_first;
369 int queue_n;
370 int drain_queue_stop;
371
372 int id;
373 struct goacc_asyncqueue *prev;
374 struct goacc_asyncqueue *next;
375 };
376
377 /* Mkoffload uses this structure to describe a kernel.
378
379 OpenMP kernel dimensions are passed at runtime.
380 OpenACC kernel dimensions are passed at compile time, here. */
381
382 struct hsa_kernel_description
383 {
384 const char *name;
385 int oacc_dims[3]; /* Only present for GCN kernels. */
386 int sgpr_count;
387 int vpgr_count;
388 };
389
390 /* Mkoffload uses this structure to describe an offload variable. */
391
392 struct global_var_info
393 {
394 const char *name;
395 void *address;
396 };
397
398 /* Mkoffload uses this structure to describe all the kernels in a
399 loadable module. These are passed the libgomp via static constructors. */
400
401 struct gcn_image_desc
402 {
403 struct gcn_image {
404 size_t size;
405 void *image;
406 } *gcn_image;
407 const unsigned kernel_count;
408 struct hsa_kernel_description *kernel_infos;
409 const unsigned ind_func_count;
410 const unsigned global_variable_count;
411 };
412
413 /* Enum values corresponding to the the ELF architecture codes.
414 Only 'special' values are actually referenced in this file, but having them
415 all may aid debugging. */
416
417 typedef enum {
418 EF_AMDGPU_MACH_UNSUPPORTED = -1,
419 #define GCN_DEVICE(name, NAME, ELF, ...) \
420 EF_AMDGPU_MACH_AMDGCN_ ## NAME = ELF,
421 #include "../../gcc/config/gcn/gcn-devices.def"
422 } EF_AMDGPU_MACH;
423
424 const static int EF_AMDGPU_MACH_MASK = 0x000000ff;
425 typedef EF_AMDGPU_MACH gcn_isa;
426
427 /* Description of an HSA GPU agent (device) and the program associated with
428 it. */
429
430 struct agent_info
431 {
432 /* The HSA ID of the agent. Assigned when hsa_context is initialized. */
433 hsa_agent_t id;
434 /* The user-visible device number. */
435 int device_id;
436 /* Whether the agent has been initialized. The fields below are usable only
437 if it has been. */
438 bool initialized;
439
440 /* The instruction set architecture of the device. */
441 gcn_isa device_isa;
442 /* Name of the agent. */
443 char name[64];
444 /* Name of the vendor of the agent. */
445 char vendor_name[64];
446 /* Command queues of the agent. */
447 hsa_queue_t *sync_queue;
448 struct goacc_asyncqueue *async_queues, *omp_async_queue;
449 pthread_mutex_t async_queues_mutex;
450
451 /* The HSA memory region from which to allocate kernel arguments. */
452 hsa_region_t kernarg_region;
453
454 /* The HSA memory region from which to allocate device data. */
455 hsa_region_t data_region;
456
457 /* Allocated ephemeral memories (team arena and stack space). */
458 struct ephemeral_memories_list *ephemeral_memories_list;
459 pthread_mutex_t ephemeral_memories_write_lock;
460
461 /* Read-write lock that protects kernels which are running or about to be run
462 from interference with loading and unloading of images. Needs to be
463 locked for reading while a kernel is being run, and for writing if the
464 list of modules is manipulated (and thus the HSA program invalidated). */
465 pthread_rwlock_t module_rwlock;
466
467 /* The module associated with this kernel. */
468 struct module_info *module;
469
470 /* Mutex enforcing that only one thread will finalize the HSA program. A
471 thread should have locked agent->module_rwlock for reading before
472 acquiring it. */
473 pthread_mutex_t prog_mutex;
474 /* Flag whether the HSA program that consists of all the modules has been
475 finalized. */
476 bool prog_finalized;
477 /* HSA executable - the finalized program that is used to locate kernels. */
478 hsa_executable_t executable;
479 };
480
481 /* Information required to identify, finalize and run any given kernel. */
482
483 enum offload_kind {KIND_UNKNOWN, KIND_OPENMP, KIND_OPENACC};
484
485 struct kernel_info
486 {
487 /* Name of the kernel, required to locate it within the GCN object-code
488 module. */
489 const char *name;
490 /* The specific agent the kernel has been or will be finalized for and run
491 on. */
492 struct agent_info *agent;
493 /* The specific module where the kernel takes place. */
494 struct module_info *module;
495 /* Information provided by mkoffload associated with the kernel. */
496 struct hsa_kernel_description *description;
497 /* Mutex enforcing that at most once thread ever initializes a kernel for
498 use. A thread should have locked agent->module_rwlock for reading before
499 acquiring it. */
500 pthread_mutex_t init_mutex;
501 /* Flag indicating whether the kernel has been initialized and all fields
502 below it contain valid data. */
503 bool initialized;
504 /* Flag indicating that the kernel has a problem that blocks an execution. */
505 bool initialization_failed;
506 /* The object to be put into the dispatch queue. */
507 uint64_t object;
508 /* Required size of kernel arguments. */
509 uint32_t kernarg_segment_size;
510 /* Required size of group segment. */
511 uint32_t group_segment_size;
512 /* Required size of private segment. */
513 uint32_t private_segment_size;
514 /* Set up for OpenMP or OpenACC? */
515 enum offload_kind kind;
516 };
517
518 /* Information about a particular GCN module, its image and kernels. */
519
520 struct module_info
521 {
522 /* The description with which the program has registered the image. */
523 struct gcn_image_desc *image_desc;
524 /* GCN heap allocation. */
525 struct heap *heap;
526 /* Physical boundaries of the loaded module. */
527 Elf64_Addr phys_address_start;
528 Elf64_Addr phys_address_end;
529
530 bool constructors_run_p;
531 struct kernel_info *init_array_func, *fini_array_func;
532
533 /* Number of kernels in this module. */
534 int kernel_count;
535 /* An array of kernel_info structures describing each kernel in this
536 module. */
537 struct kernel_info kernels[];
538 };
539
540 /* A linked list of memory arenas allocated on the device.
541 These are used by OpenMP, as a means to optimize per-team malloc,
542 and for host-accessible stack space. */
543
544 struct ephemeral_memories_list
545 {
546 struct ephemeral_memories_list *next;
547
548 /* The size is determined by the number of teams and threads. */
549 size_t size;
550 /* The device address allocated memory. */
551 void *address;
552 /* A flag to prevent two asynchronous kernels trying to use the same memory.
553 The mutex is locked until the kernel exits. */
554 pthread_mutex_t in_use;
555 };
556
557 /* Information about the whole HSA environment and all of its agents. */
558
559 struct hsa_context_info
560 {
561 /* Whether the structure has been initialized. */
562 bool initialized;
563 /* Number of usable GPU HSA agents in the system. */
564 int agent_count;
565 /* Array of agent_info structures describing the individual HSA agents. */
566 struct agent_info *agents;
567 /* Driver version string. */
568 char driver_version_s[30];
569 };
570
571 /* }}} */
572 /* {{{ Global variables */
573
574 /* Information about the whole HSA environment and all of its agents. */
575
576 static struct hsa_context_info hsa_context;
577
578 /* HSA runtime functions that are initialized in init_hsa_context. */
579 static struct hsa_runtime_fn_info hsa_fns;
580
581 /* HIP runtime functions that are initialized in init_hip_runtime_functions. */
582 static struct hip_runtime_fn_info hip_fns;
583
584 /* Heap space, allocated target-side, provided for use of newlib malloc.
585 Each module should have it's own heap allocated.
586 Beware that heap usage increases with OpenMP teams. See also arenas. */
587
588 static size_t gcn_kernel_heap_size = DEFAULT_GCN_HEAP_SIZE;
589
590 /* Ephemeral memory sizes for each kernel launch. */
591
592 static int team_arena_size = DEFAULT_TEAM_ARENA_SIZE;
593 static int stack_size = DEFAULT_GCN_STACK_SIZE;
594 static int lowlat_size = -1;
595
596 /* Flag to decide whether print to stderr information about what is going on.
597 Set in init_debug depending on environment variables. */
598
599 static bool debug;
600
601 /* Flag to decide if the runtime should suppress a possible fallback to host
602 execution. */
603
604 static bool suppress_host_fallback;
605
606 /* Flag to locate HSA and HIP runtime shared libraries that are dlopened
607 by this plug-in. */
608
609 static const char *hsa_runtime_lib;
610 static const char *hip_runtime_lib;
611
612 /* Flag to decide if the runtime should support also CPU devices (can be
613 a simulator). */
614
615 static bool support_cpu_devices;
616
617 /* Runtime dimension overrides. Zero indicates default. */
618
619 static int override_x_dim = 0;
620 static int override_z_dim = 0;
621
622 /* }}} */
623 /* {{{ Debug & Diagnostic */
624
625 /* Print a message to stderr if GCN_DEBUG value is set to true. */
626
627 #define DEBUG_PRINT(...) \
628 do \
629 { \
630 if (debug) \
631 { \
632 fprintf (stderr, __VA_ARGS__); \
633 } \
634 } \
635 while (false);
636
637 /* Flush stderr if GCN_DEBUG value is set to true. */
638
639 #define DEBUG_FLUSH() \
640 do { \
641 if (debug) \
642 fflush (stderr); \
643 } while (false)
644
645 /* Print a logging message with PREFIX to stderr if GCN_DEBUG value
646 is set to true. */
647
648 #define DEBUG_LOG(prefix, ...) \
649 do \
650 { \
651 DEBUG_PRINT (prefix); \
652 DEBUG_PRINT (__VA_ARGS__); \
653 DEBUG_FLUSH (); \
654 } while (false)
655
656 /* Print a debugging message to stderr. */
657
658 #define GCN_DEBUG(...) DEBUG_LOG ("GCN debug: ", __VA_ARGS__)
659
660 /* Print a warning message to stderr. */
661
662 #define GCN_WARNING(...) DEBUG_LOG ("GCN warning: ", __VA_ARGS__)
663
664 /* Print HSA warning STR with an HSA STATUS code. */
665
666 static void
667 hsa_warn (const char *str, hsa_status_t status)
668 {
669 if (!debug)
670 return;
671
672 const char *hsa_error_msg = "[unknown]";
673 hsa_fns.hsa_status_string_fn (status, &hsa_error_msg);
674
675 fprintf (stderr, "GCN warning: %s\nRuntime message: %s\n", str,
676 hsa_error_msg);
677 }
678
679 /* Report a fatal error STR together with the HSA error corresponding to STATUS
680 and terminate execution of the current process. */
681
682 static void
683 hsa_fatal (const char *str, hsa_status_t status)
684 {
685 const char *hsa_error_msg = "[unknown]";
686 hsa_fns.hsa_status_string_fn (status, &hsa_error_msg);
687 GOMP_PLUGIN_fatal ("GCN fatal error: %s\nRuntime message: %s\n", str,
688 hsa_error_msg);
689 }
690
691 /* Like hsa_fatal, except only report error message, and return FALSE
692 for propagating error processing to outside of plugin. */
693
694 static bool
695 hsa_error (const char *str, hsa_status_t status)
696 {
697 const char *hsa_error_msg = "[unknown]";
698 hsa_fns.hsa_status_string_fn (status, &hsa_error_msg);
699 GOMP_PLUGIN_error ("GCN fatal error: %s\nRuntime message: %s\n", str,
700 hsa_error_msg);
701 return false;
702 }
703
704 /* Dump information about the available hardware. */
705
706 static void
707 dump_hsa_system_info (void)
708 {
709 hsa_status_t status;
710
711 hsa_endianness_t endianness;
712 status = hsa_fns.hsa_system_get_info_fn (HSA_SYSTEM_INFO_ENDIANNESS,
713 &endianness);
714 if (status == HSA_STATUS_SUCCESS)
715 switch (endianness)
716 {
717 case HSA_ENDIANNESS_LITTLE:
718 GCN_DEBUG ("HSA_SYSTEM_INFO_ENDIANNESS: LITTLE\n");
719 break;
720 case HSA_ENDIANNESS_BIG:
721 GCN_DEBUG ("HSA_SYSTEM_INFO_ENDIANNESS: BIG\n");
722 break;
723 default:
724 GCN_WARNING ("HSA_SYSTEM_INFO_ENDIANNESS: UNKNOWN\n");
725 }
726 else
727 GCN_WARNING ("HSA_SYSTEM_INFO_ENDIANNESS: FAILED\n");
728
729 uint8_t extensions[128];
730 status = hsa_fns.hsa_system_get_info_fn (HSA_SYSTEM_INFO_EXTENSIONS,
731 &extensions);
732 if (status == HSA_STATUS_SUCCESS)
733 {
734 if (extensions[0] & (1 << HSA_EXTENSION_IMAGES))
735 GCN_DEBUG ("HSA_SYSTEM_INFO_EXTENSIONS: IMAGES\n");
736 }
737 else
738 GCN_WARNING ("HSA_SYSTEM_INFO_EXTENSIONS: FAILED\n");
739 }
740
741 /* Dump information about the available hardware. */
742
743 static void
744 dump_machine_model (hsa_machine_model_t machine_model, const char *s)
745 {
746 switch (machine_model)
747 {
748 case HSA_MACHINE_MODEL_SMALL:
749 GCN_DEBUG ("%s: SMALL\n", s);
750 break;
751 case HSA_MACHINE_MODEL_LARGE:
752 GCN_DEBUG ("%s: LARGE\n", s);
753 break;
754 default:
755 GCN_WARNING ("%s: UNKNOWN\n", s);
756 break;
757 }
758 }
759
760 /* Dump information about the available hardware. */
761
762 static void
763 dump_profile (hsa_profile_t profile, const char *s)
764 {
765 switch (profile)
766 {
767 case HSA_PROFILE_FULL:
768 GCN_DEBUG ("%s: FULL\n", s);
769 break;
770 case HSA_PROFILE_BASE:
771 GCN_DEBUG ("%s: BASE\n", s);
772 break;
773 default:
774 GCN_WARNING ("%s: UNKNOWN\n", s);
775 break;
776 }
777 }
778
779 /* Dump information about a device memory region. */
780
781 static hsa_status_t
782 dump_hsa_region (hsa_region_t region, void *data __attribute__((unused)))
783 {
784 hsa_status_t status;
785
786 hsa_region_segment_t segment;
787 status = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_SEGMENT,
788 &segment);
789 if (status == HSA_STATUS_SUCCESS)
790 {
791 if (segment == HSA_REGION_SEGMENT_GLOBAL)
792 GCN_DEBUG ("HSA_REGION_INFO_SEGMENT: GLOBAL\n");
793 else if (segment == HSA_REGION_SEGMENT_READONLY)
794 GCN_DEBUG ("HSA_REGION_INFO_SEGMENT: READONLY\n");
795 else if (segment == HSA_REGION_SEGMENT_PRIVATE)
796 GCN_DEBUG ("HSA_REGION_INFO_SEGMENT: PRIVATE\n");
797 else if (segment == HSA_REGION_SEGMENT_GROUP)
798 GCN_DEBUG ("HSA_REGION_INFO_SEGMENT: GROUP\n");
799 else
800 GCN_WARNING ("HSA_REGION_INFO_SEGMENT: UNKNOWN\n");
801 }
802 else
803 GCN_WARNING ("HSA_REGION_INFO_SEGMENT: FAILED\n");
804
805 if (segment == HSA_REGION_SEGMENT_GLOBAL)
806 {
807 uint32_t flags;
808 status
809 = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_GLOBAL_FLAGS,
810 &flags);
811 if (status == HSA_STATUS_SUCCESS)
812 {
813 if (flags & HSA_REGION_GLOBAL_FLAG_KERNARG)
814 GCN_DEBUG ("HSA_REGION_INFO_GLOBAL_FLAGS: KERNARG\n");
815 if (flags & HSA_REGION_GLOBAL_FLAG_FINE_GRAINED)
816 GCN_DEBUG ("HSA_REGION_INFO_GLOBAL_FLAGS: FINE_GRAINED\n");
817 if (flags & HSA_REGION_GLOBAL_FLAG_COARSE_GRAINED)
818 GCN_DEBUG ("HSA_REGION_INFO_GLOBAL_FLAGS: COARSE_GRAINED\n");
819 }
820 else
821 GCN_WARNING ("HSA_REGION_INFO_GLOBAL_FLAGS: FAILED\n");
822 }
823
824 size_t size;
825 status = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_SIZE, &size);
826 if (status == HSA_STATUS_SUCCESS)
827 GCN_DEBUG ("HSA_REGION_INFO_SIZE: %zu\n", size);
828 else
829 GCN_WARNING ("HSA_REGION_INFO_SIZE: FAILED\n");
830
831 status
832 = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_ALLOC_MAX_SIZE,
833 &size);
834 if (status == HSA_STATUS_SUCCESS)
835 GCN_DEBUG ("HSA_REGION_INFO_ALLOC_MAX_SIZE: %zu\n", size);
836 else
837 GCN_WARNING ("HSA_REGION_INFO_ALLOC_MAX_SIZE: FAILED\n");
838
839 bool alloc_allowed;
840 status
841 = hsa_fns.hsa_region_get_info_fn (region,
842 HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED,
843 &alloc_allowed);
844 if (status == HSA_STATUS_SUCCESS)
845 GCN_DEBUG ("HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED: %u\n", alloc_allowed);
846 else
847 GCN_WARNING ("HSA_REGION_INFO_RUNTIME_ALLOC_ALLOWED: FAILED\n");
848
849 if (status != HSA_STATUS_SUCCESS || !alloc_allowed)
850 return HSA_STATUS_SUCCESS;
851
852 status
853 = hsa_fns.hsa_region_get_info_fn (region,
854 HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE,
855 &size);
856 if (status == HSA_STATUS_SUCCESS)
857 GCN_DEBUG ("HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE: %zu\n", size);
858 else
859 GCN_WARNING ("HSA_REGION_INFO_RUNTIME_ALLOC_GRANULE: FAILED\n");
860
861 size_t align;
862 status
863 = hsa_fns.hsa_region_get_info_fn (region,
864 HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT,
865 &align);
866 if (status == HSA_STATUS_SUCCESS)
867 GCN_DEBUG ("HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT: %zu\n", align);
868 else
869 GCN_WARNING ("HSA_REGION_INFO_RUNTIME_ALLOC_ALIGNMENT: FAILED\n");
870
871 return HSA_STATUS_SUCCESS;
872 }
873
874 /* Dump information about all the device memory regions. */
875
876 static void
877 dump_hsa_regions (hsa_agent_t agent)
878 {
879 hsa_status_t status;
880 status = hsa_fns.hsa_agent_iterate_regions_fn (agent,
881 dump_hsa_region,
882 NULL);
883 if (status != HSA_STATUS_SUCCESS)
884 hsa_error ("Dumping hsa regions failed", status);
885 }
886
887 /* Dump information about the available devices. */
888
889 static hsa_status_t
890 dump_hsa_agent_info (hsa_agent_t agent, void *data __attribute__((unused)))
891 {
892 hsa_status_t status;
893
894 char buf[64];
895 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_NAME,
896 &buf);
897 if (status == HSA_STATUS_SUCCESS)
898 GCN_DEBUG ("HSA_AGENT_INFO_NAME: %s\n", buf);
899 else
900 GCN_WARNING ("HSA_AGENT_INFO_NAME: FAILED\n");
901
902 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_VENDOR_NAME,
903 &buf);
904 if (status == HSA_STATUS_SUCCESS)
905 GCN_DEBUG ("HSA_AGENT_INFO_VENDOR_NAME: %s\n", buf);
906 else
907 GCN_WARNING ("HSA_AGENT_INFO_VENDOR_NAME: FAILED\n");
908
909 hsa_machine_model_t machine_model;
910 status
911 = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_MACHINE_MODEL,
912 &machine_model);
913 if (status == HSA_STATUS_SUCCESS)
914 dump_machine_model (machine_model, "HSA_AGENT_INFO_MACHINE_MODEL");
915 else
916 GCN_WARNING ("HSA_AGENT_INFO_MACHINE_MODEL: FAILED\n");
917
918 hsa_profile_t profile;
919 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_PROFILE,
920 &profile);
921 if (status == HSA_STATUS_SUCCESS)
922 dump_profile (profile, "HSA_AGENT_INFO_PROFILE");
923 else
924 GCN_WARNING ("HSA_AGENT_INFO_PROFILE: FAILED\n");
925
926 hsa_device_type_t device_type;
927 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_DEVICE,
928 &device_type);
929 if (status == HSA_STATUS_SUCCESS)
930 {
931 switch (device_type)
932 {
933 case HSA_DEVICE_TYPE_CPU:
934 GCN_DEBUG ("HSA_AGENT_INFO_DEVICE: CPU\n");
935 break;
936 case HSA_DEVICE_TYPE_GPU:
937 GCN_DEBUG ("HSA_AGENT_INFO_DEVICE: GPU\n");
938 break;
939 case HSA_DEVICE_TYPE_DSP:
940 GCN_DEBUG ("HSA_AGENT_INFO_DEVICE: DSP\n");
941 break;
942 default:
943 GCN_WARNING ("HSA_AGENT_INFO_DEVICE: UNKNOWN\n");
944 break;
945 }
946 }
947 else
948 GCN_WARNING ("HSA_AGENT_INFO_DEVICE: FAILED\n");
949
950 uint32_t cu_count;
951 status = hsa_fns.hsa_agent_get_info_fn
952 (agent, HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT, &cu_count);
953 if (status == HSA_STATUS_SUCCESS)
954 GCN_DEBUG ("HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT: %u\n", cu_count);
955 else
956 GCN_WARNING ("HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT: FAILED\n");
957
958 uint32_t size;
959 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_WAVEFRONT_SIZE,
960 &size);
961 if (status == HSA_STATUS_SUCCESS)
962 GCN_DEBUG ("HSA_AGENT_INFO_WAVEFRONT_SIZE: %u\n", size);
963 else
964 GCN_WARNING ("HSA_AGENT_INFO_WAVEFRONT_SIZE: FAILED\n");
965
966 uint32_t max_dim;
967 status = hsa_fns.hsa_agent_get_info_fn (agent,
968 HSA_AGENT_INFO_WORKGROUP_MAX_DIM,
969 &max_dim);
970 if (status == HSA_STATUS_SUCCESS)
971 GCN_DEBUG ("HSA_AGENT_INFO_WORKGROUP_MAX_DIM: %u\n", max_dim);
972 else
973 GCN_WARNING ("HSA_AGENT_INFO_WORKGROUP_MAX_DIM: FAILED\n");
974
975 uint32_t max_size;
976 status = hsa_fns.hsa_agent_get_info_fn (agent,
977 HSA_AGENT_INFO_WORKGROUP_MAX_SIZE,
978 &max_size);
979 if (status == HSA_STATUS_SUCCESS)
980 GCN_DEBUG ("HSA_AGENT_INFO_WORKGROUP_MAX_SIZE: %u\n", max_size);
981 else
982 GCN_WARNING ("HSA_AGENT_INFO_WORKGROUP_MAX_SIZE: FAILED\n");
983
984 uint32_t grid_max_dim;
985 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_GRID_MAX_DIM,
986 &grid_max_dim);
987 if (status == HSA_STATUS_SUCCESS)
988 GCN_DEBUG ("HSA_AGENT_INFO_GRID_MAX_DIM: %u\n", grid_max_dim);
989 else
990 GCN_WARNING ("HSA_AGENT_INFO_GRID_MAX_DIM: FAILED\n");
991
992 uint32_t grid_max_size;
993 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_GRID_MAX_SIZE,
994 &grid_max_size);
995 if (status == HSA_STATUS_SUCCESS)
996 GCN_DEBUG ("HSA_AGENT_INFO_GRID_MAX_SIZE: %u\n", grid_max_size);
997 else
998 GCN_WARNING ("HSA_AGENT_INFO_GRID_MAX_SIZE: FAILED\n");
999
1000 dump_hsa_regions (agent);
1001
1002 return HSA_STATUS_SUCCESS;
1003 }
1004
1005 /* Forward reference. */
1006
1007 static char *get_executable_symbol_name (hsa_executable_symbol_t symbol);
1008
1009 /* Helper function for dump_executable_symbols. */
1010
1011 static hsa_status_t
1012 dump_executable_symbol (hsa_executable_t executable,
1013 hsa_executable_symbol_t symbol,
1014 void *data __attribute__((unused)))
1015 {
1016 char *name = get_executable_symbol_name (symbol);
1017
1018 if (name)
1019 {
1020 GCN_DEBUG ("executable symbol: %s\n", name);
1021 free (name);
1022 }
1023
1024 return HSA_STATUS_SUCCESS;
1025 }
1026
1027 /* Dump all global symbol in an executable. */
1028
1029 static void
1030 dump_executable_symbols (hsa_executable_t executable)
1031 {
1032 hsa_status_t status;
1033 status
1034 = hsa_fns.hsa_executable_iterate_symbols_fn (executable,
1035 dump_executable_symbol,
1036 NULL);
1037 if (status != HSA_STATUS_SUCCESS)
1038 hsa_fatal ("Could not dump HSA executable symbols", status);
1039 }
1040
1041 /* Dump kernel DISPATCH data structure and indent it by INDENT spaces. */
1042
1043 static void
1044 print_kernel_dispatch (struct kernel_dispatch *dispatch, unsigned indent)
1045 {
1046 struct kernargs *kernargs = (struct kernargs *)dispatch->kernarg_address;
1047
1048 fprintf (stderr, "%*sthis: %p\n", indent, "", dispatch);
1049 fprintf (stderr, "%*squeue: %p\n", indent, "", dispatch->queue);
1050 fprintf (stderr, "%*skernarg_address: %p\n", indent, "", kernargs);
1051 fprintf (stderr, "%*sheap address: %p\n", indent, "",
1052 (void*)kernargs->abi.heap_ptr);
1053 fprintf (stderr, "%*sarena address: %p (%d bytes per workgroup)\n", indent,
1054 "", (void*)kernargs->abi.arena_ptr,
1055 kernargs->abi.arena_size_per_team);
1056 fprintf (stderr, "%*sstack address: %p (%d bytes per wavefront)\n", indent,
1057 "", (void*)kernargs->abi.stack_ptr,
1058 kernargs->abi.stack_size_per_thread);
1059 fprintf (stderr, "%*sobject: %lu\n", indent, "", dispatch->object);
1060 fprintf (stderr, "%*sprivate_segment_size: %u\n", indent, "",
1061 dispatch->private_segment_size);
1062 fprintf (stderr, "%*sgroup_segment_size: %u (low-latency pool)\n", indent,
1063 "", dispatch->group_segment_size);
1064 fprintf (stderr, "\n");
1065 }
1066
1067 /* }}} */
1068 /* {{{ Utility functions */
1069
1070 /* Cast the thread local storage to gcn_thread. */
1071
1072 static inline struct gcn_thread *
1073 gcn_thread (void)
1074 {
1075 return (struct gcn_thread *) GOMP_PLUGIN_acc_thread ();
1076 }
1077
1078 /* Initialize debug and suppress_host_fallback according to the environment. */
1079
1080 static void
1081 init_environment_variables (void)
1082 {
1083 if (secure_getenv ("GCN_DEBUG"))
1084 debug = true;
1085 else
1086 debug = false;
1087
1088 if (secure_getenv ("GCN_SUPPRESS_HOST_FALLBACK"))
1089 suppress_host_fallback = true;
1090 else
1091 suppress_host_fallback = false;
1092
1093 hsa_runtime_lib = secure_getenv ("HSA_RUNTIME_LIB");
1094 if (hsa_runtime_lib == NULL)
1095 hsa_runtime_lib = "libhsa-runtime64.so.1";
1096
1097 hip_runtime_lib = secure_getenv ("HIP_RUNTIME_LIB");
1098 if (hip_runtime_lib == NULL)
1099 hip_runtime_lib = "libamdhip64.so";
1100
1101 support_cpu_devices = secure_getenv ("GCN_SUPPORT_CPU_DEVICES");
1102
1103 const char *x = secure_getenv ("GCN_NUM_TEAMS");
1104 if (!x)
1105 x = secure_getenv ("GCN_NUM_GANGS");
1106 if (x)
1107 override_x_dim = atoi (x);
1108
1109 const char *z = secure_getenv ("GCN_NUM_THREADS");
1110 if (!z)
1111 z = secure_getenv ("GCN_NUM_WORKERS");
1112 if (z)
1113 override_z_dim = atoi (z);
1114
1115 const char *heap = secure_getenv ("GCN_HEAP_SIZE");
1116 if (heap)
1117 {
1118 size_t tmp = atol (heap);
1119 if (tmp)
1120 gcn_kernel_heap_size = tmp;
1121 }
1122
1123 const char *arena = secure_getenv ("GCN_TEAM_ARENA_SIZE");
1124 if (arena)
1125 {
1126 int tmp = atoi (arena);
1127 if (tmp)
1128 team_arena_size = tmp;;
1129 }
1130
1131 const char *stack = secure_getenv ("GCN_STACK_SIZE");
1132 if (stack)
1133 {
1134 int tmp = atoi (stack);
1135 if (tmp)
1136 stack_size = tmp;;
1137 }
1138
1139 const char *lowlat = secure_getenv ("GOMP_GCN_LOWLAT_POOL");
1140 if (lowlat)
1141 lowlat_size = atoi (lowlat);
1142 }
1143
1144 /* Return malloc'd string with name of SYMBOL. */
1145
1146 static char *
1147 get_executable_symbol_name (hsa_executable_symbol_t symbol)
1148 {
1149 hsa_status_t status;
1150 char *res;
1151 uint32_t len;
1152 const hsa_executable_symbol_info_t info_name_length
1153 = HSA_EXECUTABLE_SYMBOL_INFO_NAME_LENGTH;
1154
1155 status = hsa_fns.hsa_executable_symbol_get_info_fn (symbol, info_name_length,
1156 &len);
1157 if (status != HSA_STATUS_SUCCESS)
1158 {
1159 hsa_error ("Could not get length of symbol name", status);
1160 return NULL;
1161 }
1162
1163 res = GOMP_PLUGIN_malloc (len + 1);
1164
1165 const hsa_executable_symbol_info_t info_name
1166 = HSA_EXECUTABLE_SYMBOL_INFO_NAME;
1167
1168 status = hsa_fns.hsa_executable_symbol_get_info_fn (symbol, info_name, res);
1169
1170 if (status != HSA_STATUS_SUCCESS)
1171 {
1172 hsa_error ("Could not get symbol name", status);
1173 free (res);
1174 return NULL;
1175 }
1176
1177 res[len] = '\0';
1178
1179 return res;
1180 }
1181
1182 /* Get the number of GPU Compute Units. */
1183
1184 static int
1185 get_cu_count (struct agent_info *agent)
1186 {
1187 uint32_t cu_count;
1188 hsa_status_t status = hsa_fns.hsa_agent_get_info_fn
1189 (agent->id, HSA_AMD_AGENT_INFO_COMPUTE_UNIT_COUNT, &cu_count);
1190 if (status == HSA_STATUS_SUCCESS)
1191 return cu_count;
1192 else
1193 return 64; /* The usual number for older devices. */
1194 }
1195
1196 /* Calculate the maximum grid size for OMP threads / OACC workers.
1197 This depends on the kernel's resource usage levels. */
1198
1199 static int
1200 limit_worker_threads (int threads)
1201 {
1202 /* FIXME Do something more inteligent here.
1203 GCN can always run 4 threads within a Compute Unit, but
1204 more than that depends on register usage. */
1205 if (threads > 16)
1206 threads = 16;
1207 return threads;
1208 }
1209
1210 /* This sets the maximum number of teams to twice the number of GPU Compute
1211 Units to avoid memory waste and corresponding memory access faults. */
1212
1213 static int
1214 limit_teams (int teams, struct agent_info *agent)
1215 {
1216 int max_teams = 2 * get_cu_count (agent);
1217 if (teams > max_teams)
1218 teams = max_teams;
1219 return teams;
1220 }
1221
1222 /* Parse the target attributes INPUT provided by the compiler and return true
1223 if we should run anything all. If INPUT is NULL, fill DEF with default
1224 values, then store INPUT or DEF into *RESULT.
1225
1226 This is used for OpenMP only. */
1227
1228 static bool
1229 parse_target_attributes (void **input,
1230 struct GOMP_kernel_launch_attributes *def,
1231 struct GOMP_kernel_launch_attributes **result,
1232 struct agent_info *agent)
1233 {
1234 if (!input)
1235 GOMP_PLUGIN_fatal ("No target arguments provided");
1236
1237 bool grid_attrs_found = false;
1238 bool gcn_dims_found = false;
1239 int gcn_teams = 0;
1240 int gcn_threads = 0;
1241 while (*input)
1242 {
1243 intptr_t id = (intptr_t) *input++, val;
1244
1245 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
1246 val = (intptr_t) *input++;
1247 else
1248 val = id >> GOMP_TARGET_ARG_VALUE_SHIFT;
1249
1250 val = (val > INT_MAX) ? INT_MAX : val;
1251
1252 if ((id & GOMP_TARGET_ARG_DEVICE_MASK) == GOMP_DEVICE_GCN
1253 && ((id & GOMP_TARGET_ARG_ID_MASK)
1254 == GOMP_TARGET_ARG_HSA_KERNEL_ATTRIBUTES))
1255 {
1256 grid_attrs_found = true;
1257 break;
1258 }
1259 else if ((id & GOMP_TARGET_ARG_DEVICE_MASK)
1260 == GOMP_TARGET_ARG_DEVICE_ALL)
1261 {
1262 gcn_dims_found = true;
1263 switch (id & GOMP_TARGET_ARG_ID_MASK)
1264 {
1265 case GOMP_TARGET_ARG_NUM_TEAMS:
1266 gcn_teams = limit_teams (val, agent);
1267 break;
1268 case GOMP_TARGET_ARG_THREAD_LIMIT:
1269 gcn_threads = limit_worker_threads (val);
1270 break;
1271 default:
1272 ;
1273 }
1274 }
1275 }
1276
1277 if (gcn_dims_found)
1278 {
1279 bool gfx900_workaround_p = false;
1280
1281 if (agent->device_isa == EF_AMDGPU_MACH_AMDGCN_GFX900
1282 && gcn_threads == 0 && override_z_dim == 0)
1283 {
1284 gfx900_workaround_p = true;
1285 GCN_WARNING ("VEGA BUG WORKAROUND: reducing default number of "
1286 "threads to at most 4 per team.\n");
1287 GCN_WARNING (" - If this is not a Vega 10 device, please use "
1288 "GCN_NUM_THREADS=16\n");
1289 }
1290
1291 /* Ideally, when a dimension isn't explicitly specified, we should
1292 tune it to run 40 (or 32?) threads per CU with no threads getting queued.
1293 In practice, we tune for peak performance on BabelStream, which
1294 for OpenACC is currently 32 threads per CU. */
1295 def->ndim = 3;
1296 if (gcn_teams <= 0 && gcn_threads <= 0)
1297 {
1298 /* Set up a reasonable number of teams and threads. */
1299 gcn_threads = gfx900_workaround_p ? 4 : 16; // 8;
1300 def->gdims[0] = get_cu_count (agent); // * (40 / gcn_threads);
1301 def->gdims[2] = gcn_threads;
1302 }
1303 else if (gcn_teams <= 0 && gcn_threads > 0)
1304 {
1305 /* Auto-scale the number of teams with the number of threads. */
1306 def->gdims[0] = get_cu_count (agent); // * (40 / gcn_threads);
1307 def->gdims[2] = gcn_threads;
1308 }
1309 else if (gcn_teams > 0 && gcn_threads <= 0)
1310 {
1311 int max_threads = gfx900_workaround_p ? 4 : 16;
1312
1313 /* Auto-scale the number of threads with the number of teams. */
1314 def->gdims[0] = gcn_teams;
1315 def->gdims[2] = 16; // get_cu_count (agent) * 40 / gcn_teams;
1316 if (def->gdims[2] == 0)
1317 def->gdims[2] = 1;
1318 else if (def->gdims[2] > max_threads)
1319 def->gdims[2] = max_threads;
1320 }
1321 else
1322 {
1323 def->gdims[0] = gcn_teams;
1324 def->gdims[2] = gcn_threads;
1325 }
1326 def->gdims[1] = 64; /* Each thread is 64 work items wide. */
1327 def->wdims[0] = 1; /* Single team per work-group. */
1328 def->wdims[1] = 64;
1329 def->wdims[2] = 16;
1330 *result = def;
1331 return true;
1332 }
1333 else if (!grid_attrs_found)
1334 {
1335 def->ndim = 1;
1336 def->gdims[0] = 1;
1337 def->gdims[1] = 1;
1338 def->gdims[2] = 1;
1339 def->wdims[0] = 1;
1340 def->wdims[1] = 1;
1341 def->wdims[2] = 1;
1342 *result = def;
1343 GCN_WARNING ("GOMP_OFFLOAD_run called with no launch attributes\n");
1344 return true;
1345 }
1346
1347 struct GOMP_kernel_launch_attributes *kla;
1348 kla = (struct GOMP_kernel_launch_attributes *) *input;
1349 *result = kla;
1350 if (kla->ndim == 0 || kla->ndim > 3)
1351 GOMP_PLUGIN_fatal ("Invalid number of dimensions (%u)", kla->ndim);
1352
1353 GCN_DEBUG ("GOMP_OFFLOAD_run called with %u dimensions:\n", kla->ndim);
1354 unsigned i;
1355 for (i = 0; i < kla->ndim; i++)
1356 {
1357 GCN_DEBUG (" Dimension %u: grid size %u and group size %u\n", i,
1358 kla->gdims[i], kla->wdims[i]);
1359 if (kla->gdims[i] == 0)
1360 return false;
1361 }
1362 return true;
1363 }
1364
1365 /* Return the group size given the requested GROUP size, GRID size and number
1366 of grid dimensions NDIM. */
1367
1368 static uint32_t
1369 get_group_size (uint32_t ndim, uint32_t grid, uint32_t group)
1370 {
1371 if (group == 0)
1372 {
1373 /* TODO: Provide a default via environment or device characteristics. */
1374 if (ndim == 1)
1375 group = 64;
1376 else if (ndim == 2)
1377 group = 8;
1378 else
1379 group = 4;
1380 }
1381
1382 if (group > grid)
1383 group = grid;
1384 return group;
1385 }
1386
1387 /* Atomically store pair of uint16_t values (HEADER and REST) to a PACKET. */
1388
1389 static void
1390 packet_store_release (uint32_t* packet, uint16_t header, uint16_t rest)
1391 {
1392 __atomic_store_n (packet, header | (rest << 16), __ATOMIC_RELEASE);
1393 }
1394
1395 /* A never-called callback for the HSA command queues. These signal events
1396 that we don't use, so we trigger an error.
1397
1398 This "queue" is not to be confused with the async queues, below. */
1399
1400 static void
1401 hsa_queue_callback (hsa_status_t status,
1402 hsa_queue_t *queue __attribute__ ((unused)),
1403 void *data __attribute__ ((unused)))
1404 {
1405 hsa_fatal ("Asynchronous queue error", status);
1406 }
1407
1408 /* }}} */
1409 /* {{{ HSA initialization */
1410
1411 /* Populate hsa_fns with the function addresses from libhsa-runtime64.so. */
1412
1413 static bool
1414 init_hsa_runtime_functions (void)
1415 {
1416 #define DLSYM_FN(function) \
1417 hsa_fns.function##_fn = dlsym (handle, #function); \
1418 if (hsa_fns.function##_fn == NULL) \
1419 GOMP_PLUGIN_fatal ("'%s' is missing '%s'", hsa_runtime_lib, #function);
1420 #define DLSYM_OPT_FN(function) \
1421 hsa_fns.function##_fn = dlsym (handle, #function);
1422
1423 void *handle = dlopen (hsa_runtime_lib, RTLD_LAZY);
1424 if (handle == NULL)
1425 return false;
1426
1427 DLSYM_FN (hsa_status_string)
1428 DLSYM_FN (hsa_system_get_info)
1429 DLSYM_FN (hsa_agent_get_info)
1430 DLSYM_FN (hsa_init)
1431 DLSYM_FN (hsa_iterate_agents)
1432 DLSYM_FN (hsa_region_get_info)
1433 DLSYM_FN (hsa_queue_create)
1434 DLSYM_FN (hsa_agent_iterate_regions)
1435 DLSYM_FN (hsa_executable_destroy)
1436 DLSYM_FN (hsa_executable_create)
1437 DLSYM_FN (hsa_executable_global_variable_define)
1438 DLSYM_FN (hsa_executable_load_code_object)
1439 DLSYM_FN (hsa_executable_freeze)
1440 DLSYM_FN (hsa_signal_create)
1441 DLSYM_FN (hsa_memory_allocate)
1442 DLSYM_FN (hsa_memory_assign_agent)
1443 DLSYM_FN (hsa_memory_copy)
1444 DLSYM_FN (hsa_memory_free)
1445 DLSYM_FN (hsa_signal_destroy)
1446 DLSYM_FN (hsa_executable_get_symbol)
1447 DLSYM_FN (hsa_executable_symbol_get_info)
1448 DLSYM_FN (hsa_executable_iterate_symbols)
1449 DLSYM_FN (hsa_queue_add_write_index_release)
1450 DLSYM_FN (hsa_queue_load_read_index_acquire)
1451 DLSYM_FN (hsa_queue_load_read_index_relaxed)
1452 DLSYM_FN (hsa_queue_load_write_index_relaxed)
1453 DLSYM_FN (hsa_signal_wait_acquire)
1454 DLSYM_FN (hsa_signal_store_relaxed)
1455 DLSYM_FN (hsa_signal_store_release)
1456 DLSYM_FN (hsa_signal_load_acquire)
1457 DLSYM_FN (hsa_queue_destroy)
1458 DLSYM_FN (hsa_code_object_deserialize)
1459 DLSYM_OPT_FN (hsa_amd_memory_lock)
1460 DLSYM_OPT_FN (hsa_amd_memory_unlock)
1461 DLSYM_OPT_FN (hsa_amd_memory_async_copy_rect)
1462 return true;
1463 #undef DLSYM_OPT_FN
1464 #undef DLSYM_FN
1465 }
1466
1467 static gcn_isa isa_code (const char *isa);
1468
1469 /* Return true if the agent is a GPU and can accept of concurrent submissions
1470 from different threads. */
1471
1472 static bool
1473 suitable_hsa_agent_p (hsa_agent_t agent)
1474 {
1475 hsa_device_type_t device_type;
1476 hsa_status_t status
1477 = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_DEVICE,
1478 &device_type);
1479 if (status != HSA_STATUS_SUCCESS)
1480 return false;
1481
1482 switch (device_type)
1483 {
1484 case HSA_DEVICE_TYPE_GPU:
1485 {
1486 char name[64];
1487 hsa_status_t status
1488 = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_NAME, name);
1489 if (status != HSA_STATUS_SUCCESS
1490 || isa_code (name) == EF_AMDGPU_MACH_UNSUPPORTED)
1491 {
1492 GCN_DEBUG ("Ignoring unsupported agent '%s'\n",
1493 status == HSA_STATUS_SUCCESS ? name : "invalid");
1494 return false;
1495 }
1496 }
1497 break;
1498 case HSA_DEVICE_TYPE_CPU:
1499 if (!support_cpu_devices)
1500 return false;
1501 break;
1502 default:
1503 return false;
1504 }
1505
1506 uint32_t features = 0;
1507 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_FEATURE,
1508 &features);
1509 if (status != HSA_STATUS_SUCCESS
1510 || !(features & HSA_AGENT_FEATURE_KERNEL_DISPATCH))
1511 return false;
1512 hsa_queue_type_t queue_type;
1513 status = hsa_fns.hsa_agent_get_info_fn (agent, HSA_AGENT_INFO_QUEUE_TYPE,
1514 &queue_type);
1515 if (status != HSA_STATUS_SUCCESS
1516 || (queue_type != HSA_QUEUE_TYPE_MULTI))
1517 return false;
1518
1519 return true;
1520 }
1521
1522 /* Callback of hsa_iterate_agents; if AGENT is a GPU device, increment
1523 agent_count in hsa_context. */
1524
1525 static hsa_status_t
1526 count_gpu_agents (hsa_agent_t agent, void *data __attribute__ ((unused)))
1527 {
1528 if (suitable_hsa_agent_p (agent))
1529 hsa_context.agent_count++;
1530 return HSA_STATUS_SUCCESS;
1531 }
1532
1533 /* Callback of hsa_iterate_agents; if AGENT is a GPU device, assign the agent
1534 id to the describing structure in the hsa context. The index of the
1535 structure is pointed to by DATA, increment it afterwards. */
1536
1537 static hsa_status_t
1538 assign_agent_ids (hsa_agent_t agent, void *data)
1539 {
1540 if (suitable_hsa_agent_p (agent))
1541 {
1542 int *agent_index = (int *) data;
1543 hsa_context.agents[*agent_index].id = agent;
1544 ++*agent_index;
1545 }
1546 return HSA_STATUS_SUCCESS;
1547 }
1548
1549 /* Initialize hsa_context if it has not already been done.
1550 If !PROBE: returns TRUE on success.
1551 If PROBE: returns TRUE on success or if the plugin/device shall be silently
1552 ignored, and otherwise emits an error and returns FALSE. */
1553
1554 static bool
1555 init_hsa_context (bool probe)
1556 {
1557 hsa_status_t status;
1558 int agent_index = 0;
1559
1560 if (hsa_context.initialized)
1561 return true;
1562 init_environment_variables ();
1563 if (!init_hsa_runtime_functions ())
1564 {
1565 const char *msg = "Run-time could not be dynamically opened";
1566 if (suppress_host_fallback)
1567 GOMP_PLUGIN_fatal ("%s\n", msg);
1568 else
1569 GCN_WARNING ("%s\n", msg);
1570 return probe ? true : false;
1571 }
1572 status = hsa_fns.hsa_init_fn ();
1573 if (status != HSA_STATUS_SUCCESS)
1574 return hsa_error ("Run-time could not be initialized", status);
1575 GCN_DEBUG ("HSA run-time initialized for GCN\n");
1576
1577 if (debug)
1578 dump_hsa_system_info ();
1579
1580 status = hsa_fns.hsa_iterate_agents_fn (count_gpu_agents, NULL);
1581 if (status != HSA_STATUS_SUCCESS)
1582 return hsa_error ("GCN GPU devices could not be enumerated", status);
1583 GCN_DEBUG ("There are %i GCN GPU devices.\n", hsa_context.agent_count);
1584
1585 hsa_context.agents
1586 = GOMP_PLUGIN_malloc_cleared (hsa_context.agent_count
1587 * sizeof (struct agent_info));
1588 status = hsa_fns.hsa_iterate_agents_fn (assign_agent_ids, &agent_index);
1589 if (status != HSA_STATUS_SUCCESS)
1590 return hsa_error ("Scanning compute agents failed", status);
1591 if (agent_index != hsa_context.agent_count)
1592 {
1593 GOMP_PLUGIN_error ("Failed to assign IDs to all GCN agents");
1594 return false;
1595 }
1596
1597 if (debug)
1598 {
1599 status = hsa_fns.hsa_iterate_agents_fn (dump_hsa_agent_info, NULL);
1600 if (status != HSA_STATUS_SUCCESS)
1601 GOMP_PLUGIN_error ("Failed to list all HSA runtime agents");
1602 }
1603
1604 uint16_t minor, major;
1605 status = hsa_fns.hsa_system_get_info_fn (HSA_SYSTEM_INFO_VERSION_MINOR,
1606 &minor);
1607 if (status != HSA_STATUS_SUCCESS)
1608 GOMP_PLUGIN_error ("Failed to obtain HSA runtime minor version");
1609 status = hsa_fns.hsa_system_get_info_fn (HSA_SYSTEM_INFO_VERSION_MAJOR,
1610 &major);
1611 if (status != HSA_STATUS_SUCCESS)
1612 GOMP_PLUGIN_error ("Failed to obtain HSA runtime major version");
1613
1614 size_t len = sizeof hsa_context.driver_version_s;
1615 int printed = snprintf (hsa_context.driver_version_s, len,
1616 "HSA Runtime %hu.%hu", (unsigned short int)major,
1617 (unsigned short int)minor);
1618 if (printed >= len)
1619 GCN_WARNING ("HSA runtime version string was truncated."
1620 "Version %hu.%hu is too long.", (unsigned short int)major,
1621 (unsigned short int)minor);
1622
1623 hsa_context.initialized = true;
1624 return true;
1625 }
1626
1627 /* Verify that hsa_context has already been initialized and return the
1628 agent_info structure describing device number N. Return NULL on error. */
1629
1630 static struct agent_info *
1631 get_agent_info (int n)
1632 {
1633 if (!hsa_context.initialized)
1634 {
1635 GOMP_PLUGIN_error ("Attempt to use uninitialized GCN context.");
1636 return NULL;
1637 }
1638 if (n >= hsa_context.agent_count)
1639 {
1640 GOMP_PLUGIN_error ("Request to operate on non-existent GCN device %i", n);
1641 return NULL;
1642 }
1643 if (!hsa_context.agents[n].initialized)
1644 {
1645 GOMP_PLUGIN_error ("Attempt to use an uninitialized GCN agent.");
1646 return NULL;
1647 }
1648 return &hsa_context.agents[n];
1649 }
1650
1651 /* Callback of hsa_agent_iterate_regions, via get_*_memory_region functions.
1652
1653 Selects (breaks at) a suitable region of type KIND. */
1654
1655 static hsa_status_t
1656 get_memory_region (hsa_region_t region, hsa_region_t *retval,
1657 hsa_region_global_flag_t kind)
1658 {
1659 hsa_status_t status;
1660 hsa_region_segment_t segment;
1661
1662 status = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_SEGMENT,
1663 &segment);
1664 if (status != HSA_STATUS_SUCCESS)
1665 return status;
1666 if (segment != HSA_REGION_SEGMENT_GLOBAL)
1667 return HSA_STATUS_SUCCESS;
1668
1669 uint32_t flags;
1670 status = hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_GLOBAL_FLAGS,
1671 &flags);
1672 if (status != HSA_STATUS_SUCCESS)
1673 return status;
1674 if (flags & kind)
1675 {
1676 *retval = region;
1677 return HSA_STATUS_INFO_BREAK;
1678 }
1679 return HSA_STATUS_SUCCESS;
1680 }
1681
1682 /* Callback of hsa_agent_iterate_regions.
1683
1684 Selects a kernargs memory region. */
1685
1686 static hsa_status_t
1687 get_kernarg_memory_region (hsa_region_t region, void *data)
1688 {
1689 return get_memory_region (region, (hsa_region_t *)data,
1690 HSA_REGION_GLOBAL_FLAG_KERNARG);
1691 }
1692
1693 /* Callback of hsa_agent_iterate_regions.
1694
1695 Selects a coarse-grained memory region suitable for the heap and
1696 offload data. */
1697
1698 static hsa_status_t
1699 get_data_memory_region (hsa_region_t region, void *data)
1700 {
1701 return get_memory_region (region, (hsa_region_t *)data,
1702 HSA_REGION_GLOBAL_FLAG_COARSE_GRAINED);
1703 }
1704
1705 static int
1706 elf_gcn_isa_field (Elf64_Ehdr *image)
1707 {
1708 return image->e_flags & EF_AMDGPU_MACH_MASK;
1709 }
1710
1711 static int
1712 elf_gcn_isa_is_generic (Elf64_Ehdr *image)
1713 {
1714 return (image->e_ident[8] == ELFABIVERSION_AMDGPU_HSA_V6
1715 && GET_GENERIC_VERSION (image->e_flags));
1716 }
1717
1718 /* Returns the name that the HSA runtime uses for the ISA or NULL if we do not
1719 support the ISA. */
1720
1721 static const char*
1722 isa_name (int isa) {
1723 switch(isa)
1724 {
1725 #define GCN_DEVICE(name, NAME, ELF, ...) \
1726 case ELF: return #name;
1727 #include "../../gcc/config/gcn/gcn-devices.def"
1728 }
1729 return NULL;
1730 }
1731
1732 /* Returns the code which is used in the GCN object code to identify the ISA with
1733 the given name (as used by the HSA runtime). */
1734
1735 static gcn_isa
1736 isa_code(const char *isa) {
1737 #define GCN_DEVICE(name, NAME, ELF, ...) \
1738 if (!strcmp (isa, #name)) return ELF;
1739 #include "../../gcc/config/gcn/gcn-devices.def"
1740
1741 return EF_AMDGPU_MACH_UNSUPPORTED;
1742 }
1743
1744 /* CDNA2 devices have twice as many VGPRs compared to older devices. */
1745
1746 static int
1747 max_isa_vgprs (int isa)
1748 {
1749 switch (isa)
1750 {
1751 #define GCN_DEVICE(name, NAME, ELF, ISA, XNACK, SRAM, WAVE64, CU, \
1752 MAX_ISA_VGPRS, ...) \
1753 case ELF: return MAX_ISA_VGPRS;
1754 #include "../../gcc/config/gcn/gcn-devices.def"
1755 default:
1756 GOMP_PLUGIN_fatal ("unhandled ISA in max_isa_vgprs");
1757 }
1758 }
1759
1760 /* }}} */
1761 /* {{{ Run */
1762
1763 /* Create or reuse a team arena and stack space.
1764
1765 Team arenas are used by OpenMP to avoid calling malloc multiple times
1766 while setting up each team. This is purely a performance optimization.
1767
1768 The stack space is used by all kernels. We must allocate it in such a
1769 way that the reverse offload implmentation can access the data.
1770
1771 Allocating this memory costs performance, so this function will reuse an
1772 existing allocation if a large enough one is idle.
1773 The memory lock is released, but not deallocated, when the kernel exits. */
1774
1775 static void
1776 configure_ephemeral_memories (struct kernel_info *kernel,
1777 struct kernargs_abi *kernargs, int num_teams,
1778 int num_threads)
1779 {
1780 struct agent_info *agent = kernel->agent;
1781 struct ephemeral_memories_list **next_ptr = &agent->ephemeral_memories_list;
1782 struct ephemeral_memories_list *item;
1783
1784 int actual_arena_size = (kernel->kind == KIND_OPENMP
1785 ? team_arena_size : 0);
1786 int actual_arena_total_size = actual_arena_size * num_teams;
1787 size_t size = (actual_arena_total_size
1788 + num_teams * num_threads * stack_size);
1789
1790 for (item = *next_ptr; item; next_ptr = &item->next, item = item->next)
1791 {
1792 if (item->size < size)
1793 continue;
1794
1795 if (pthread_mutex_trylock (&item->in_use) == 0)
1796 break;
1797 }
1798
1799 if (!item)
1800 {
1801 GCN_DEBUG ("Creating a new %sstack for %d teams with %d threads"
1802 " (%zd bytes)\n", (actual_arena_size ? "arena and " : ""),
1803 num_teams, num_threads, size);
1804
1805 if (pthread_mutex_lock (&agent->ephemeral_memories_write_lock))
1806 {
1807 GOMP_PLUGIN_error ("Could not lock a GCN agent program mutex");
1808 return;
1809 }
1810 item = malloc (sizeof (*item));
1811 item->size = size;
1812 item->next = NULL;
1813 *next_ptr = item;
1814
1815 if (pthread_mutex_init (&item->in_use, NULL))
1816 {
1817 GOMP_PLUGIN_error ("Failed to initialize a GCN memory write mutex");
1818 return;
1819 }
1820 if (pthread_mutex_lock (&item->in_use))
1821 {
1822 GOMP_PLUGIN_error ("Could not lock a GCN agent program mutex");
1823 return;
1824 }
1825 if (pthread_mutex_unlock (&agent->ephemeral_memories_write_lock))
1826 {
1827 GOMP_PLUGIN_error ("Could not unlock a GCN agent program mutex");
1828 return;
1829 }
1830
1831 hsa_status_t status;
1832 status = hsa_fns.hsa_memory_allocate_fn (agent->data_region, size,
1833 &item->address);
1834 if (status != HSA_STATUS_SUCCESS)
1835 hsa_fatal ("Could not allocate memory for GCN kernel arena", status);
1836 status = hsa_fns.hsa_memory_assign_agent_fn (item->address, agent->id,
1837 HSA_ACCESS_PERMISSION_RW);
1838 if (status != HSA_STATUS_SUCCESS)
1839 hsa_fatal ("Could not assign arena & stack memory to device", status);
1840 }
1841
1842 kernargs->arena_ptr = (actual_arena_total_size
1843 ? (uint64_t)item->address
1844 : 0);
1845 kernargs->stack_ptr = (uint64_t)item->address + actual_arena_total_size;
1846 kernargs->arena_size_per_team = actual_arena_size;
1847 kernargs->stack_size_per_thread = stack_size;
1848 }
1849
1850 /* Mark an ephemeral memory space available for reuse. */
1851
1852 static void
1853 release_ephemeral_memories (struct agent_info* agent, void *address)
1854 {
1855 struct ephemeral_memories_list *item;
1856
1857 for (item = agent->ephemeral_memories_list; item; item = item->next)
1858 {
1859 if (item->address == address)
1860 {
1861 if (pthread_mutex_unlock (&item->in_use))
1862 GOMP_PLUGIN_error ("Could not unlock a GCN agent program mutex");
1863 return;
1864 }
1865 }
1866 GOMP_PLUGIN_error ("Could not find a GCN arena to release.");
1867 }
1868
1869 /* Clean up all the allocated team arenas. */
1870
1871 static bool
1872 destroy_ephemeral_memories (struct agent_info *agent)
1873 {
1874 struct ephemeral_memories_list *item, *next;
1875
1876 for (item = agent->ephemeral_memories_list; item; item = next)
1877 {
1878 next = item->next;
1879 hsa_fns.hsa_memory_free_fn (item->address);
1880 if (pthread_mutex_destroy (&item->in_use))
1881 {
1882 GOMP_PLUGIN_error ("Failed to destroy a GCN memory mutex");
1883 return false;
1884 }
1885 free (item);
1886 }
1887 agent->ephemeral_memories_list = NULL;
1888
1889 return true;
1890 }
1891
1892 /* Allocate memory on a specified device. */
1893
1894 static void *
1895 alloc_by_agent (struct agent_info *agent, size_t size)
1896 {
1897 GCN_DEBUG ("Allocating %zu bytes on device %d\n", size, agent->device_id);
1898
1899 void *ptr;
1900 hsa_status_t status = hsa_fns.hsa_memory_allocate_fn (agent->data_region,
1901 size, &ptr);
1902 if (status != HSA_STATUS_SUCCESS)
1903 {
1904 hsa_error ("Could not allocate device memory", status);
1905 return NULL;
1906 }
1907
1908 status = hsa_fns.hsa_memory_assign_agent_fn (ptr, agent->id,
1909 HSA_ACCESS_PERMISSION_RW);
1910 if (status != HSA_STATUS_SUCCESS)
1911 {
1912 hsa_error ("Could not assign data memory to device", status);
1913 return NULL;
1914 }
1915
1916 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
1917 bool profiling_dispatch_p
1918 = __builtin_expect (thr != NULL && thr->prof_info != NULL, false);
1919 if (profiling_dispatch_p)
1920 {
1921 acc_prof_info *prof_info = thr->prof_info;
1922 acc_event_info data_event_info;
1923 acc_api_info *api_info = thr->api_info;
1924
1925 prof_info->event_type = acc_ev_alloc;
1926
1927 data_event_info.data_event.event_type = prof_info->event_type;
1928 data_event_info.data_event.valid_bytes
1929 = _ACC_DATA_EVENT_INFO_VALID_BYTES;
1930 data_event_info.data_event.parent_construct
1931 = acc_construct_parallel;
1932 data_event_info.data_event.implicit = 1;
1933 data_event_info.data_event.tool_info = NULL;
1934 data_event_info.data_event.var_name = NULL;
1935 data_event_info.data_event.bytes = size;
1936 data_event_info.data_event.host_ptr = NULL;
1937 data_event_info.data_event.device_ptr = (void *) ptr;
1938
1939 api_info->device_api = acc_device_api_other;
1940
1941 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &data_event_info,
1942 api_info);
1943 }
1944
1945 return ptr;
1946 }
1947
1948 /* Create kernel dispatch data structure for given KERNEL, along with
1949 the necessary device signals and memory allocations. */
1950
1951 static struct kernel_dispatch *
1952 create_kernel_dispatch (struct kernel_info *kernel, int num_teams,
1953 int num_threads)
1954 {
1955 struct agent_info *agent = kernel->agent;
1956 struct kernel_dispatch *shadow
1957 = GOMP_PLUGIN_malloc_cleared (sizeof (struct kernel_dispatch));
1958
1959 shadow->agent = kernel->agent;
1960 shadow->object = kernel->object;
1961
1962 hsa_signal_t sync_signal;
1963 hsa_status_t status = hsa_fns.hsa_signal_create_fn (1, 0, NULL, &sync_signal);
1964 if (status != HSA_STATUS_SUCCESS)
1965 hsa_fatal ("Error creating the GCN sync signal", status);
1966
1967 shadow->signal = sync_signal.handle;
1968 shadow->private_segment_size = kernel->private_segment_size;
1969
1970 if (lowlat_size < 0)
1971 {
1972 /* Divide the LDS between the number of running teams.
1973 Allocate not less than is defined in the kernel metadata. */
1974 int teams_per_cu = num_teams / get_cu_count (agent);
1975 int LDS_per_team = (teams_per_cu ? 65536 / teams_per_cu : 65536);
1976 shadow->group_segment_size
1977 = (kernel->group_segment_size > LDS_per_team
1978 ? kernel->group_segment_size
1979 : LDS_per_team);;
1980 }
1981 else if (lowlat_size < GCN_LOWLAT_HEAP+8)
1982 /* Ensure that there's space for the OpenMP libgomp data. */
1983 shadow->group_segment_size = GCN_LOWLAT_HEAP+8;
1984 else
1985 shadow->group_segment_size = (lowlat_size > 65536
1986 ? 65536
1987 : lowlat_size);
1988
1989 /* We expect kernels to request a single pointer, explicitly, and the
1990 rest of struct kernargs, implicitly. If they request anything else
1991 then something is wrong. */
1992 if (kernel->kernarg_segment_size > 8)
1993 {
1994 GOMP_PLUGIN_fatal ("Unexpectedly large kernargs segment requested");
1995 return NULL;
1996 }
1997
1998 status = hsa_fns.hsa_memory_allocate_fn (agent->kernarg_region,
1999 sizeof (struct kernargs),
2000 &shadow->kernarg_address);
2001 if (status != HSA_STATUS_SUCCESS)
2002 hsa_fatal ("Could not allocate memory for GCN kernel arguments", status);
2003 struct kernargs *kernargs = shadow->kernarg_address;
2004
2005 /* Zero-initialize the output_data (minimum needed). */
2006 kernargs->abi.out_ptr = (int64_t)&kernargs->output_data;
2007 kernargs->output_data.next_output = 0;
2008 for (unsigned i = 0;
2009 i < (sizeof (kernargs->output_data.queue)
2010 / sizeof (kernargs->output_data.queue[0]));
2011 i++)
2012 kernargs->output_data.queue[i].written = 0;
2013 kernargs->output_data.consumed = 0;
2014
2015 /* Pass in the heap location. */
2016 kernargs->abi.heap_ptr = (int64_t)kernel->module->heap;
2017
2018 /* Create the ephemeral memory spaces. */
2019 configure_ephemeral_memories (kernel, &kernargs->abi, num_teams, num_threads);
2020
2021 /* Ensure we can recognize unset return values. */
2022 kernargs->output_data.return_value = 0xcafe0000;
2023
2024 return shadow;
2025 }
2026
2027 static void
2028 process_reverse_offload (uint64_t fn, uint64_t mapnum, uint64_t hostaddrs,
2029 uint64_t sizes, uint64_t kinds, uint64_t dev_num64)
2030 {
2031 int dev_num = dev_num64;
2032 GOMP_PLUGIN_target_rev (fn, mapnum, hostaddrs, sizes, kinds, dev_num,
2033 NULL);
2034 }
2035
2036 /* Output any data written to console output from the kernel. It is expected
2037 that this function is polled during kernel execution.
2038
2039 We print all entries from the last item printed to the next entry without
2040 a "written" flag. If the "final" flag is set then it'll continue right to
2041 the end.
2042
2043 The print buffer is circular, but the from and to locations don't wrap when
2044 the buffer does, so the output limit is UINT_MAX. The target blocks on
2045 output when the buffer is full. */
2046
2047 static void
2048 console_output (struct kernel_info *kernel, struct kernargs *kernargs,
2049 bool final)
2050 {
2051 unsigned int limit = (sizeof (kernargs->output_data.queue)
2052 / sizeof (kernargs->output_data.queue[0]));
2053
2054 unsigned int from = __atomic_load_n (&kernargs->output_data.consumed,
2055 __ATOMIC_ACQUIRE);
2056 unsigned int to = kernargs->output_data.next_output;
2057
2058 if (from > to)
2059 {
2060 /* Overflow. */
2061 if (final)
2062 printf ("GCN print buffer overflowed.\n");
2063 return;
2064 }
2065
2066 unsigned int i;
2067 for (i = from; i < to; i++)
2068 {
2069 struct printf_data *data = &kernargs->output_data.queue[i%limit];
2070
2071 if (!data->written && !final)
2072 break;
2073
2074 switch (data->type)
2075 {
2076 case 0: printf ("%.128s%ld\n", data->msg, data->ivalue); break;
2077 case 1: printf ("%.128s%f\n", data->msg, data->dvalue); break;
2078 case 2: printf ("%.128s%.128s\n", data->msg, data->text); break;
2079 case 3: printf ("%.128s%.128s", data->msg, data->text); break;
2080 case 4:
2081 process_reverse_offload (data->value_u64[0], data->value_u64[1],
2082 data->value_u64[2], data->value_u64[3],
2083 data->value_u64[4], data->value_u64[5]);
2084 break;
2085 default: printf ("GCN print buffer error!\n"); break;
2086 }
2087 data->written = 0;
2088 __atomic_store_n (&kernargs->output_data.consumed, i+1,
2089 __ATOMIC_RELEASE);
2090 }
2091 fflush (stdout);
2092 }
2093
2094 /* Release data structure created for a kernel dispatch in SHADOW argument,
2095 and clean up the signal and memory allocations. */
2096
2097 static void
2098 release_kernel_dispatch (struct kernel_dispatch *shadow)
2099 {
2100 GCN_DEBUG ("Released kernel dispatch: %p\n", shadow);
2101
2102 struct kernargs *kernargs = shadow->kernarg_address;
2103 void *addr = (void *)kernargs->abi.arena_ptr;
2104 if (!addr)
2105 addr = (void *)kernargs->abi.stack_ptr;
2106 release_ephemeral_memories (shadow->agent, addr);
2107
2108 hsa_fns.hsa_memory_free_fn (shadow->kernarg_address);
2109
2110 hsa_signal_t s;
2111 s.handle = shadow->signal;
2112 hsa_fns.hsa_signal_destroy_fn (s);
2113
2114 free (shadow);
2115 }
2116
2117 /* Extract the properties from a kernel binary. */
2118
2119 static void
2120 init_kernel_properties (struct kernel_info *kernel)
2121 {
2122 hsa_status_t status;
2123 struct agent_info *agent = kernel->agent;
2124 hsa_executable_symbol_t kernel_symbol;
2125 char *buf = alloca (strlen (kernel->name) + 4);
2126 sprintf (buf, "%s.kd", kernel->name);
2127 status = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
2128 buf, agent->id,
2129 0, &kernel_symbol);
2130 if (status != HSA_STATUS_SUCCESS)
2131 {
2132 hsa_warn ("Could not find symbol for kernel in the code object", status);
2133 fprintf (stderr, "not found name: '%s'\n", buf);
2134 dump_executable_symbols (agent->executable);
2135 goto failure;
2136 }
2137 GCN_DEBUG ("Located kernel %s\n", kernel->name);
2138 status = hsa_fns.hsa_executable_symbol_get_info_fn
2139 (kernel_symbol, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_OBJECT, &kernel->object);
2140 if (status != HSA_STATUS_SUCCESS)
2141 hsa_fatal ("Could not extract a kernel object from its symbol", status);
2142 status = hsa_fns.hsa_executable_symbol_get_info_fn
2143 (kernel_symbol, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_KERNARG_SEGMENT_SIZE,
2144 &kernel->kernarg_segment_size);
2145 if (status != HSA_STATUS_SUCCESS)
2146 hsa_fatal ("Could not get info about kernel argument size", status);
2147 status = hsa_fns.hsa_executable_symbol_get_info_fn
2148 (kernel_symbol, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_GROUP_SEGMENT_SIZE,
2149 &kernel->group_segment_size);
2150 if (status != HSA_STATUS_SUCCESS)
2151 hsa_fatal ("Could not get info about kernel group segment size", status);
2152 status = hsa_fns.hsa_executable_symbol_get_info_fn
2153 (kernel_symbol, HSA_EXECUTABLE_SYMBOL_INFO_KERNEL_PRIVATE_SEGMENT_SIZE,
2154 &kernel->private_segment_size);
2155 if (status != HSA_STATUS_SUCCESS)
2156 hsa_fatal ("Could not get info about kernel private segment size",
2157 status);
2158
2159 /* The kernel type is not known until something tries to launch it. */
2160 kernel->kind = KIND_UNKNOWN;
2161
2162 GCN_DEBUG ("Kernel structure for %s fully initialized with "
2163 "following segment sizes: \n", kernel->name);
2164 GCN_DEBUG (" group_segment_size: %u\n",
2165 (unsigned) kernel->group_segment_size);
2166 GCN_DEBUG (" private_segment_size: %u\n",
2167 (unsigned) kernel->private_segment_size);
2168 GCN_DEBUG (" kernarg_segment_size: %u\n",
2169 (unsigned) kernel->kernarg_segment_size);
2170 return;
2171
2172 failure:
2173 kernel->initialization_failed = true;
2174 }
2175
2176 /* Do all the work that is necessary before running KERNEL for the first time.
2177 The function assumes the program has been created, finalized and frozen by
2178 create_and_finalize_hsa_program. */
2179
2180 static void
2181 init_kernel (struct kernel_info *kernel)
2182 {
2183 if (pthread_mutex_lock (&kernel->init_mutex))
2184 GOMP_PLUGIN_fatal ("Could not lock a GCN kernel initialization mutex");
2185 if (kernel->initialized)
2186 {
2187 if (pthread_mutex_unlock (&kernel->init_mutex))
2188 GOMP_PLUGIN_fatal ("Could not unlock a GCN kernel initialization "
2189 "mutex");
2190
2191 return;
2192 }
2193
2194 init_kernel_properties (kernel);
2195
2196 if (!kernel->initialization_failed)
2197 {
2198 GCN_DEBUG ("\n");
2199
2200 kernel->initialized = true;
2201 }
2202 if (pthread_mutex_unlock (&kernel->init_mutex))
2203 GOMP_PLUGIN_fatal ("Could not unlock a GCN kernel initialization "
2204 "mutex");
2205 }
2206
2207 /* Run KERNEL on its agent, pass VARS to it as arguments and take
2208 launch attributes from KLA.
2209
2210 MODULE_LOCKED indicates that the caller already holds the lock and
2211 run_kernel need not lock it again.
2212 If AQ is NULL then agent->sync_queue will be used. */
2213
2214 static void
2215 run_kernel (struct kernel_info *kernel, void *vars,
2216 struct GOMP_kernel_launch_attributes *kla,
2217 struct goacc_asyncqueue *aq, bool module_locked)
2218 {
2219 struct agent_info *agent = kernel->agent;
2220 GCN_DEBUG ("SGPRs: %d, VGPRs: %d\n", kernel->description->sgpr_count,
2221 kernel->description->vpgr_count);
2222
2223 /* Reduce the number of threads/workers if there are insufficient
2224 VGPRs available to run the kernels together. */
2225 if (kla->ndim == 3 && kernel->description->vpgr_count > 0)
2226 {
2227 int max_vgprs = max_isa_vgprs (agent->device_isa);
2228 int granulated_vgprs = (kernel->description->vpgr_count + 3) & ~3;
2229 int max_threads = (max_vgprs / granulated_vgprs) * 4;
2230 if (kla->gdims[2] > max_threads)
2231 {
2232 GCN_WARNING ("Too many VGPRs required to support %d threads/workers"
2233 " per team/gang - reducing to %d threads/workers.\n",
2234 kla->gdims[2], max_threads);
2235 kla->gdims[2] = max_threads;
2236 }
2237 }
2238
2239 GCN_DEBUG ("GCN launch on queue: %d:%d\n", kernel->agent->device_id,
2240 (aq ? aq->id : 0));
2241 GCN_DEBUG ("GCN launch attribs: gdims:[");
2242 int i;
2243 for (i = 0; i < kla->ndim; ++i)
2244 {
2245 if (i)
2246 DEBUG_PRINT (", ");
2247 DEBUG_PRINT ("%u", kla->gdims[i]);
2248 }
2249 DEBUG_PRINT ("], normalized gdims:[");
2250 for (i = 0; i < kla->ndim; ++i)
2251 {
2252 if (i)
2253 DEBUG_PRINT (", ");
2254 DEBUG_PRINT ("%u", kla->gdims[i] / kla->wdims[i]);
2255 }
2256 DEBUG_PRINT ("], wdims:[");
2257 for (i = 0; i < kla->ndim; ++i)
2258 {
2259 if (i)
2260 DEBUG_PRINT (", ");
2261 DEBUG_PRINT ("%u", kla->wdims[i]);
2262 }
2263 DEBUG_PRINT ("]\n");
2264 DEBUG_FLUSH ();
2265
2266 if (!module_locked && pthread_rwlock_rdlock (&agent->module_rwlock))
2267 GOMP_PLUGIN_fatal ("Unable to read-lock a GCN agent rwlock");
2268
2269 if (!agent->initialized)
2270 GOMP_PLUGIN_fatal ("Agent must be initialized");
2271
2272 if (!kernel->initialized)
2273 GOMP_PLUGIN_fatal ("Called kernel must be initialized");
2274
2275 hsa_queue_t *command_q = (aq ? aq->hsa_queue : kernel->agent->sync_queue);
2276
2277 uint64_t index
2278 = hsa_fns.hsa_queue_add_write_index_release_fn (command_q, 1);
2279 GCN_DEBUG ("Got AQL index %llu\n", (long long int) index);
2280
2281 /* Wait until the queue is not full before writing the packet. */
2282 while (index - hsa_fns.hsa_queue_load_read_index_acquire_fn (command_q)
2283 >= command_q->size)
2284 ;
2285
2286 /* Do not allow the dimensions to be overridden when running
2287 constructors or destructors. */
2288 int override_x = kernel->kind == KIND_UNKNOWN ? 0 : override_x_dim;
2289 int override_z = kernel->kind == KIND_UNKNOWN ? 0 : override_z_dim;
2290
2291 hsa_kernel_dispatch_packet_t *packet;
2292 packet = ((hsa_kernel_dispatch_packet_t *) command_q->base_address)
2293 + index % command_q->size;
2294
2295 memset (((uint8_t *) packet) + 4, 0, sizeof (*packet) - 4);
2296 packet->grid_size_x = override_x ? : kla->gdims[0];
2297 packet->workgroup_size_x = get_group_size (kla->ndim,
2298 packet->grid_size_x,
2299 kla->wdims[0]);
2300
2301 if (kla->ndim >= 2)
2302 {
2303 packet->grid_size_y = kla->gdims[1];
2304 packet->workgroup_size_y = get_group_size (kla->ndim, kla->gdims[1],
2305 kla->wdims[1]);
2306 }
2307 else
2308 {
2309 packet->grid_size_y = 1;
2310 packet->workgroup_size_y = 1;
2311 }
2312
2313 if (kla->ndim == 3)
2314 {
2315 packet->grid_size_z = limit_worker_threads (override_z
2316 ? : kla->gdims[2]);
2317 packet->workgroup_size_z = get_group_size (kla->ndim,
2318 packet->grid_size_z,
2319 kla->wdims[2]);
2320 }
2321 else
2322 {
2323 packet->grid_size_z = 1;
2324 packet->workgroup_size_z = 1;
2325 }
2326
2327 GCN_DEBUG ("GCN launch actuals: grid:[%u, %u, %u],"
2328 " normalized grid:[%u, %u, %u], workgroup:[%u, %u, %u]\n",
2329 packet->grid_size_x, packet->grid_size_y, packet->grid_size_z,
2330 packet->grid_size_x / packet->workgroup_size_x,
2331 packet->grid_size_y / packet->workgroup_size_y,
2332 packet->grid_size_z / packet->workgroup_size_z,
2333 packet->workgroup_size_x, packet->workgroup_size_y,
2334 packet->workgroup_size_z);
2335
2336 struct kernel_dispatch *shadow
2337 = create_kernel_dispatch (kernel, packet->grid_size_x,
2338 packet->grid_size_z);
2339 shadow->queue = command_q;
2340
2341 if (debug)
2342 {
2343 fprintf (stderr, "\nKernel has following dependencies:\n");
2344 print_kernel_dispatch (shadow, 2);
2345 }
2346
2347 packet->private_segment_size = shadow->private_segment_size;
2348 packet->group_segment_size = shadow->group_segment_size;
2349 packet->kernel_object = shadow->object;
2350 packet->kernarg_address = shadow->kernarg_address;
2351 hsa_signal_t s;
2352 s.handle = shadow->signal;
2353 packet->completion_signal = s;
2354 hsa_fns.hsa_signal_store_relaxed_fn (s, 1);
2355 memcpy (shadow->kernarg_address, &vars, sizeof (vars));
2356
2357 GCN_DEBUG ("Copying kernel runtime pointer to kernarg_address\n");
2358
2359 uint16_t header;
2360 header = HSA_PACKET_TYPE_KERNEL_DISPATCH << HSA_PACKET_HEADER_TYPE;
2361 header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_ACQUIRE_FENCE_SCOPE;
2362 header |= HSA_FENCE_SCOPE_SYSTEM << HSA_PACKET_HEADER_RELEASE_FENCE_SCOPE;
2363
2364 GCN_DEBUG ("Going to dispatch kernel %s on device %d\n", kernel->name,
2365 agent->device_id);
2366
2367 packet_store_release ((uint32_t *) packet, header,
2368 (uint16_t) kla->ndim
2369 << HSA_KERNEL_DISPATCH_PACKET_SETUP_DIMENSIONS);
2370
2371 hsa_fns.hsa_signal_store_release_fn (command_q->doorbell_signal,
2372 index);
2373
2374 GCN_DEBUG ("Kernel dispatched, waiting for completion\n");
2375
2376 /* Root signal waits with 1ms timeout. */
2377 while (hsa_fns.hsa_signal_wait_acquire_fn (s, HSA_SIGNAL_CONDITION_LT, 1,
2378 1000 * 1000,
2379 HSA_WAIT_STATE_BLOCKED) != 0)
2380 {
2381 console_output (kernel, shadow->kernarg_address, false);
2382 }
2383 console_output (kernel, shadow->kernarg_address, true);
2384
2385 struct kernargs *kernargs = shadow->kernarg_address;
2386 unsigned int return_value = (unsigned int)kernargs->output_data.return_value;
2387
2388 release_kernel_dispatch (shadow);
2389
2390 if (!module_locked && pthread_rwlock_unlock (&agent->module_rwlock))
2391 GOMP_PLUGIN_fatal ("Unable to unlock a GCN agent rwlock");
2392
2393 unsigned int upper = (return_value & ~0xffff) >> 16;
2394 if (upper == 0xcafe)
2395 ; // exit not called, normal termination.
2396 else if (upper == 0xffff)
2397 ; // exit called.
2398 else
2399 {
2400 GOMP_PLUGIN_error ("Possible kernel exit value corruption, 2 most"
2401 " significant bytes aren't 0xffff or 0xcafe: 0x%x\n",
2402 return_value);
2403 abort ();
2404 }
2405
2406 if (upper == 0xffff)
2407 {
2408 unsigned int signal = (return_value >> 8) & 0xff;
2409
2410 if (signal == SIGABRT)
2411 {
2412 GCN_WARNING ("GCN Kernel aborted\n");
2413 abort ();
2414 }
2415 else if (signal != 0)
2416 {
2417 GCN_WARNING ("GCN Kernel received unknown signal\n");
2418 abort ();
2419 }
2420
2421 GCN_DEBUG ("GCN Kernel exited with value: %d\n", return_value & 0xff);
2422 exit (return_value & 0xff);
2423 }
2424 }
2425
2426 /* }}} */
2427 /* {{{ Load/Unload */
2428
2429 /* Initialize KERNEL from D and other parameters. Return true on success. */
2430
2431 static bool
2432 init_basic_kernel_info (struct kernel_info *kernel,
2433 struct hsa_kernel_description *d,
2434 struct agent_info *agent,
2435 struct module_info *module)
2436 {
2437 kernel->agent = agent;
2438 kernel->module = module;
2439 kernel->name = d->name;
2440 kernel->description = d;
2441 if (pthread_mutex_init (&kernel->init_mutex, NULL))
2442 {
2443 GOMP_PLUGIN_error ("Failed to initialize a GCN kernel mutex");
2444 return false;
2445 }
2446 return true;
2447 }
2448
2449 /* If status is SUCCESS, assume that the code runs if either the ISA of agent
2450 and code is the same - or it is generic code.
2451 Otherwise, execution failed with the provided status code; try to give
2452 some useful diagnostic. */
2453
2454 static bool
2455 isa_matches_agent (struct agent_info *agent, Elf64_Ehdr *image,
2456 hsa_status_t status)
2457 {
2458 /* Generic image - assume that it works and only return to here
2459 when it fails, i.e. fatal == true. */
2460 if (status == HSA_STATUS_SUCCESS && elf_gcn_isa_is_generic (image))
2461 return true;
2462
2463 int isa_field = elf_gcn_isa_field (image);
2464 if (status == HSA_STATUS_SUCCESS && isa_field == agent->device_isa)
2465 return true;
2466
2467 /* If we get here, either the binary is non-generic and has a mismatch of
2468 the ISA - or is generic but not handled by the ROCm (e.g. because ROCm
2469 is too old). */
2470
2471 char msg[340];
2472 char agent_isa_xs[8];
2473 char device_isa_xs[8];
2474 const char *agent_isa_s = isa_name (agent->device_isa);
2475 const char *device_isa_s = isa_name (isa_field);
2476 if (agent_isa_s == NULL)
2477 {
2478 snprintf (agent_isa_xs, sizeof agent_isa_xs,
2479 "0x%X", agent->device_isa);
2480 agent_isa_s = agent_isa_xs;
2481 }
2482 if (device_isa_s == NULL)
2483 {
2484 snprintf (device_isa_xs, sizeof device_isa_xs, "0x%X", isa_field);
2485 device_isa_s = device_isa_xs;
2486 }
2487
2488 /* Some error which should be unrelated to the ISA. */
2489 if (status != HSA_STATUS_SUCCESS
2490 && status != HSA_STATUS_ERROR_INVALID_CODE_OBJECT
2491 && status != HSA_STATUS_ERROR_INVALID_ISA_NAME
2492 && status != HSA_STATUS_ERROR_INCOMPATIBLE_ARGUMENTS)
2493 snprintf (msg, sizeof msg,
2494 "Could not load GCN code object with ISA %s on GPU with "
2495 "ISA %s (device %d).\n"
2496 "Consider using ROCR_VISIBLE_DEVICES to disable incompatible "
2497 "devices or run with LOADER_ENABLE_LOGGING=1 for more details.",
2498 device_isa_s, agent_isa_s, agent->device_id);
2499 else if (status == HSA_STATUS_ERROR_INVALID_ISA_NAME
2500 && elf_gcn_isa_is_generic (image))
2501 snprintf (msg, sizeof msg,
2502 "Unsupported generic ISA %s on GPU with ISA %s (device %d).\n"
2503 "%s%s%s"
2504 "Consider using ROCR_VISIBLE_DEVICES to disable incompatible "
2505 "devices, run with LOADER_ENABLE_LOGGING=1 for more details, "
2506 "or try updating to a ROCm that supports this generic ISA.",
2507 device_isa_s, agent_isa_s, agent->device_id,
2508 agent_isa_s[0] != '0'
2509 ? "Try to recompile with '-foffload-options=-march=" : "",
2510 agent_isa_s[0] != '0' ? agent_isa_s : "",
2511 agent_isa_s[0] != '0' ? ".\n" : "");
2512 else if (agent_isa_s[0] == '0')
2513 snprintf (msg, sizeof msg,
2514 "GCN code object ISA '%s' is incompatible with GPU ISA '%s' "
2515 "(device %d).\n"
2516 "Consider using ROCR_VISIBLE_DEVICES to disable incompatible "
2517 "devices or run with LOADER_ENABLE_LOGGING=1 for more details.",
2518 device_isa_s, agent_isa_s, agent->device_id);
2519 else
2520 snprintf (msg, sizeof msg,
2521 "GCN code object ISA '%s' is incompatible with GPU ISA '%s' "
2522 "(device %d).\n"
2523 "Try to recompile with '-foffload-options=-march=%s',\n"
2524 "or use ROCR_VISIBLE_DEVICES to disable incompatible "
2525 "devices.\n",
2526 device_isa_s, agent_isa_s, agent->device_id, agent_isa_s);
2527
2528 hsa_error (msg, status != HSA_STATUS_SUCCESS
2529 ? status : HSA_STATUS_ERROR_INVALID_CODE_OBJECT);
2530 return false;
2531 }
2532
2533 /* Create and finalize the program consisting of all loaded modules. */
2534
2535 static bool
2536 create_and_finalize_hsa_program (struct agent_info *agent)
2537 {
2538 hsa_status_t status;
2539 bool res = true;
2540 if (pthread_mutex_lock (&agent->prog_mutex))
2541 {
2542 GOMP_PLUGIN_error ("Could not lock a GCN agent program mutex");
2543 return false;
2544 }
2545 if (agent->prog_finalized)
2546 goto final;
2547
2548 status
2549 = hsa_fns.hsa_executable_create_fn (HSA_PROFILE_FULL,
2550 HSA_EXECUTABLE_STATE_UNFROZEN,
2551 "", &agent->executable);
2552 if (status != HSA_STATUS_SUCCESS)
2553 {
2554 hsa_error ("Could not create GCN executable", status);
2555 goto fail;
2556 }
2557
2558 /* Load any GCN modules. */
2559 struct module_info *module = agent->module;
2560 if (module)
2561 {
2562 Elf64_Ehdr *image = (Elf64_Ehdr *)module->image_desc->gcn_image->image;
2563
2564 /* Check the ISA early because older ROCm had unhelpful errors. */
2565 if (!isa_matches_agent (agent, image, HSA_STATUS_SUCCESS))
2566 goto fail;
2567
2568 hsa_code_object_t co = { 0 };
2569 status = hsa_fns.hsa_code_object_deserialize_fn
2570 (module->image_desc->gcn_image->image,
2571 module->image_desc->gcn_image->size,
2572 NULL, &co);
2573 if (status != HSA_STATUS_SUCCESS)
2574 {
2575 hsa_error ("Could not deserialize GCN code object", status);
2576 goto fail;
2577 }
2578
2579 status = hsa_fns.hsa_executable_load_code_object_fn
2580 (agent->executable, agent->id, co, "");
2581 if (status != HSA_STATUS_SUCCESS)
2582 {
2583 isa_matches_agent (agent, image, status);
2584 goto fail;
2585 }
2586
2587 if (!module->heap)
2588 {
2589 status = hsa_fns.hsa_memory_allocate_fn (agent->data_region,
2590 gcn_kernel_heap_size,
2591 (void**)&module->heap);
2592 if (status != HSA_STATUS_SUCCESS)
2593 {
2594 hsa_error ("Could not allocate memory for GCN heap", status);
2595 goto fail;
2596 }
2597
2598 status = hsa_fns.hsa_memory_assign_agent_fn
2599 (module->heap, agent->id, HSA_ACCESS_PERMISSION_RW);
2600 if (status != HSA_STATUS_SUCCESS)
2601 {
2602 hsa_error ("Could not assign GCN heap memory to device", status);
2603 goto fail;
2604 }
2605
2606 hsa_fns.hsa_memory_copy_fn (&module->heap->size,
2607 &gcn_kernel_heap_size,
2608 sizeof (gcn_kernel_heap_size));
2609 }
2610
2611 }
2612
2613 if (debug)
2614 dump_executable_symbols (agent->executable);
2615
2616 status = hsa_fns.hsa_executable_freeze_fn (agent->executable, "");
2617 if (status != HSA_STATUS_SUCCESS)
2618 {
2619 hsa_error ("Could not freeze the GCN executable", status);
2620 goto fail;
2621 }
2622
2623 final:
2624 agent->prog_finalized = true;
2625
2626 if (pthread_mutex_unlock (&agent->prog_mutex))
2627 {
2628 GOMP_PLUGIN_error ("Could not unlock a GCN agent program mutex");
2629 res = false;
2630 }
2631
2632 return res;
2633
2634 fail:
2635 res = false;
2636 goto final;
2637 }
2638
2639 /* Free the HSA program in agent and everything associated with it and set
2640 agent->prog_finalized and the initialized flags of all kernels to false.
2641 Return TRUE on success. */
2642
2643 static bool
2644 destroy_hsa_program (struct agent_info *agent)
2645 {
2646 if (!agent->prog_finalized)
2647 return true;
2648
2649 hsa_status_t status;
2650
2651 GCN_DEBUG ("Destroying the current GCN program.\n");
2652
2653 status = hsa_fns.hsa_executable_destroy_fn (agent->executable);
2654 if (status != HSA_STATUS_SUCCESS)
2655 return hsa_error ("Could not destroy GCN executable", status);
2656
2657 if (agent->module)
2658 {
2659 int i;
2660 for (i = 0; i < agent->module->kernel_count; i++)
2661 agent->module->kernels[i].initialized = false;
2662
2663 if (agent->module->heap)
2664 {
2665 hsa_fns.hsa_memory_free_fn (agent->module->heap);
2666 agent->module->heap = NULL;
2667 }
2668 }
2669 agent->prog_finalized = false;
2670 return true;
2671 }
2672
2673 /* Deinitialize all information associated with MODULE and kernels within
2674 it. Return TRUE on success. */
2675
2676 static bool
2677 destroy_module (struct module_info *module, bool locked)
2678 {
2679 /* Run destructors before destroying module. */
2680 struct GOMP_kernel_launch_attributes kla =
2681 { 3,
2682 /* Grid size. */
2683 { 1, 64, 1 },
2684 /* Work-group size. */
2685 { 1, 64, 1 }
2686 };
2687
2688 if (module->fini_array_func)
2689 {
2690 init_kernel (module->fini_array_func);
2691 run_kernel (module->fini_array_func, NULL, &kla, NULL, locked);
2692 }
2693 module->constructors_run_p = false;
2694
2695 int i;
2696 for (i = 0; i < module->kernel_count; i++)
2697 if (pthread_mutex_destroy (&module->kernels[i].init_mutex))
2698 {
2699 GOMP_PLUGIN_error ("Failed to destroy a GCN kernel initialization "
2700 "mutex");
2701 return false;
2702 }
2703
2704 return true;
2705 }
2706
2707 /* }}} */
2708 /* {{{ Async */
2709
2710 /* Callback of dispatch queues to report errors. */
2711
2712 static void
2713 execute_queue_entry (struct goacc_asyncqueue *aq, int index)
2714 {
2715 struct queue_entry *entry = &aq->queue[index];
2716
2717 switch (entry->type)
2718 {
2719 case KERNEL_LAUNCH:
2720 if (DEBUG_QUEUES)
2721 GCN_DEBUG ("Async thread %d:%d: Executing launch entry (%d)\n",
2722 aq->agent->device_id, aq->id, index);
2723 run_kernel (entry->u.launch.kernel,
2724 entry->u.launch.vars,
2725 &entry->u.launch.kla, aq, false);
2726 if (DEBUG_QUEUES)
2727 GCN_DEBUG ("Async thread %d:%d: Executing launch entry (%d) done\n",
2728 aq->agent->device_id, aq->id, index);
2729 break;
2730
2731 case CALLBACK:
2732 if (DEBUG_QUEUES)
2733 GCN_DEBUG ("Async thread %d:%d: Executing callback entry (%d)\n",
2734 aq->agent->device_id, aq->id, index);
2735 entry->u.callback.fn (entry->u.callback.data);
2736 if (DEBUG_QUEUES)
2737 GCN_DEBUG ("Async thread %d:%d: Executing callback entry (%d) done\n",
2738 aq->agent->device_id, aq->id, index);
2739 break;
2740
2741 case ASYNC_WAIT:
2742 {
2743 /* FIXME: is it safe to access a placeholder that may already have
2744 been executed? */
2745 struct placeholder *placeholderp = entry->u.asyncwait.placeholderp;
2746
2747 if (DEBUG_QUEUES)
2748 GCN_DEBUG ("Async thread %d:%d: Executing async wait entry (%d)\n",
2749 aq->agent->device_id, aq->id, index);
2750
2751 pthread_mutex_lock (&placeholderp->mutex);
2752
2753 while (!placeholderp->executed)
2754 pthread_cond_wait (&placeholderp->cond, &placeholderp->mutex);
2755
2756 pthread_mutex_unlock (&placeholderp->mutex);
2757
2758 if (pthread_cond_destroy (&placeholderp->cond))
2759 GOMP_PLUGIN_error ("Failed to destroy serialization cond");
2760
2761 if (pthread_mutex_destroy (&placeholderp->mutex))
2762 GOMP_PLUGIN_error ("Failed to destroy serialization mutex");
2763
2764 if (DEBUG_QUEUES)
2765 GCN_DEBUG ("Async thread %d:%d: Executing async wait "
2766 "entry (%d) done\n", aq->agent->device_id, aq->id, index);
2767 }
2768 break;
2769
2770 case ASYNC_PLACEHOLDER:
2771 pthread_mutex_lock (&entry->u.placeholder.mutex);
2772 entry->u.placeholder.executed = 1;
2773 pthread_cond_signal (&entry->u.placeholder.cond);
2774 pthread_mutex_unlock (&entry->u.placeholder.mutex);
2775 break;
2776
2777 default:
2778 GOMP_PLUGIN_fatal ("Unknown queue element");
2779 }
2780 }
2781
2782 /* This function is run as a thread to service an async queue in the
2783 background. It runs continuously until the stop flag is set. */
2784
2785 static void *
2786 drain_queue (void *thread_arg)
2787 {
2788 struct goacc_asyncqueue *aq = thread_arg;
2789
2790 if (DRAIN_QUEUE_SYNCHRONOUS_P)
2791 {
2792 aq->drain_queue_stop = 2;
2793 return NULL;
2794 }
2795
2796 pthread_mutex_lock (&aq->mutex);
2797
2798 while (true)
2799 {
2800 if (aq->drain_queue_stop)
2801 break;
2802
2803 if (aq->queue_n > 0)
2804 {
2805 pthread_mutex_unlock (&aq->mutex);
2806 execute_queue_entry (aq, aq->queue_first);
2807
2808 pthread_mutex_lock (&aq->mutex);
2809 aq->queue_first = ((aq->queue_first + 1)
2810 % ASYNC_QUEUE_SIZE);
2811 aq->queue_n--;
2812
2813 if (DEBUG_THREAD_SIGNAL)
2814 GCN_DEBUG ("Async thread %d:%d: broadcasting queue out update\n",
2815 aq->agent->device_id, aq->id);
2816 pthread_cond_broadcast (&aq->queue_cond_out);
2817 pthread_mutex_unlock (&aq->mutex);
2818
2819 if (DEBUG_QUEUES)
2820 GCN_DEBUG ("Async thread %d:%d: continue\n", aq->agent->device_id,
2821 aq->id);
2822 pthread_mutex_lock (&aq->mutex);
2823 }
2824 else
2825 {
2826 if (DEBUG_THREAD_SLEEP)
2827 GCN_DEBUG ("Async thread %d:%d: going to sleep\n",
2828 aq->agent->device_id, aq->id);
2829 pthread_cond_wait (&aq->queue_cond_in, &aq->mutex);
2830 if (DEBUG_THREAD_SLEEP)
2831 GCN_DEBUG ("Async thread %d:%d: woke up, rechecking\n",
2832 aq->agent->device_id, aq->id);
2833 }
2834 }
2835
2836 aq->drain_queue_stop = 2;
2837 if (DEBUG_THREAD_SIGNAL)
2838 GCN_DEBUG ("Async thread %d:%d: broadcasting last queue out update\n",
2839 aq->agent->device_id, aq->id);
2840 pthread_cond_broadcast (&aq->queue_cond_out);
2841 pthread_mutex_unlock (&aq->mutex);
2842
2843 GCN_DEBUG ("Async thread %d:%d: returning\n", aq->agent->device_id, aq->id);
2844 return NULL;
2845 }
2846
2847 /* This function is used only when DRAIN_QUEUE_SYNCHRONOUS_P is set, which
2848 is not usually the case. This is just a debug tool. */
2849
2850 static void
2851 drain_queue_synchronous (struct goacc_asyncqueue *aq)
2852 {
2853 pthread_mutex_lock (&aq->mutex);
2854
2855 while (aq->queue_n > 0)
2856 {
2857 execute_queue_entry (aq, aq->queue_first);
2858
2859 aq->queue_first = ((aq->queue_first + 1)
2860 % ASYNC_QUEUE_SIZE);
2861 aq->queue_n--;
2862 }
2863
2864 pthread_mutex_unlock (&aq->mutex);
2865 }
2866
2867 /* Block the current thread until an async queue is writable. The aq->mutex
2868 lock should be held on entry, and remains locked on exit. */
2869
2870 static void
2871 wait_for_queue_nonfull (struct goacc_asyncqueue *aq)
2872 {
2873 if (aq->queue_n == ASYNC_QUEUE_SIZE)
2874 {
2875 /* Queue is full. Wait for it to not be full. */
2876 while (aq->queue_n == ASYNC_QUEUE_SIZE)
2877 pthread_cond_wait (&aq->queue_cond_out, &aq->mutex);
2878 }
2879 }
2880
2881 /* Request an asynchronous kernel launch on the specified queue. This
2882 may block if the queue is full, but returns without waiting for the
2883 kernel to run. */
2884
2885 static void
2886 queue_push_launch (struct goacc_asyncqueue *aq, struct kernel_info *kernel,
2887 void *vars, struct GOMP_kernel_launch_attributes *kla)
2888 {
2889 assert (aq->agent == kernel->agent);
2890
2891 pthread_mutex_lock (&aq->mutex);
2892
2893 wait_for_queue_nonfull (aq);
2894
2895 int queue_last = ((aq->queue_first + aq->queue_n)
2896 % ASYNC_QUEUE_SIZE);
2897 if (DEBUG_QUEUES)
2898 GCN_DEBUG ("queue_push_launch %d:%d: at %i\n", aq->agent->device_id,
2899 aq->id, queue_last);
2900
2901 aq->queue[queue_last].type = KERNEL_LAUNCH;
2902 aq->queue[queue_last].u.launch.kernel = kernel;
2903 aq->queue[queue_last].u.launch.vars = vars;
2904 aq->queue[queue_last].u.launch.kla = *kla;
2905
2906 aq->queue_n++;
2907
2908 if (DEBUG_THREAD_SIGNAL)
2909 GCN_DEBUG ("signalling async thread %d:%d: cond_in\n",
2910 aq->agent->device_id, aq->id);
2911 pthread_cond_signal (&aq->queue_cond_in);
2912
2913 pthread_mutex_unlock (&aq->mutex);
2914 }
2915
2916 /* Request an asynchronous callback on the specified queue. The callback
2917 function will be called, with the given opaque data, from the appropriate
2918 async thread, when all previous items on that queue are complete. */
2919
2920 static void
2921 queue_push_callback (struct goacc_asyncqueue *aq, void (*fn)(void *),
2922 void *data)
2923 {
2924 pthread_mutex_lock (&aq->mutex);
2925
2926 wait_for_queue_nonfull (aq);
2927
2928 int queue_last = ((aq->queue_first + aq->queue_n)
2929 % ASYNC_QUEUE_SIZE);
2930 if (DEBUG_QUEUES)
2931 GCN_DEBUG ("queue_push_callback %d:%d: at %i\n", aq->agent->device_id,
2932 aq->id, queue_last);
2933
2934 aq->queue[queue_last].type = CALLBACK;
2935 aq->queue[queue_last].u.callback.fn = fn;
2936 aq->queue[queue_last].u.callback.data = data;
2937
2938 aq->queue_n++;
2939
2940 if (DEBUG_THREAD_SIGNAL)
2941 GCN_DEBUG ("signalling async thread %d:%d: cond_in\n",
2942 aq->agent->device_id, aq->id);
2943 pthread_cond_signal (&aq->queue_cond_in);
2944
2945 pthread_mutex_unlock (&aq->mutex);
2946 }
2947
2948 /* Request that a given async thread wait for another thread (unspecified) to
2949 reach the given placeholder. The wait will occur when all previous entries
2950 on the queue are complete. A placeholder is effectively a kind of signal
2951 which simply sets a flag when encountered in a queue. */
2952
2953 static void
2954 queue_push_asyncwait (struct goacc_asyncqueue *aq,
2955 struct placeholder *placeholderp)
2956 {
2957 pthread_mutex_lock (&aq->mutex);
2958
2959 wait_for_queue_nonfull (aq);
2960
2961 int queue_last = ((aq->queue_first + aq->queue_n) % ASYNC_QUEUE_SIZE);
2962 if (DEBUG_QUEUES)
2963 GCN_DEBUG ("queue_push_asyncwait %d:%d: at %i\n", aq->agent->device_id,
2964 aq->id, queue_last);
2965
2966 aq->queue[queue_last].type = ASYNC_WAIT;
2967 aq->queue[queue_last].u.asyncwait.placeholderp = placeholderp;
2968
2969 aq->queue_n++;
2970
2971 if (DEBUG_THREAD_SIGNAL)
2972 GCN_DEBUG ("signalling async thread %d:%d: cond_in\n",
2973 aq->agent->device_id, aq->id);
2974 pthread_cond_signal (&aq->queue_cond_in);
2975
2976 pthread_mutex_unlock (&aq->mutex);
2977 }
2978
2979 /* Add a placeholder into an async queue. When the async thread reaches the
2980 placeholder it will set the "executed" flag to true and continue.
2981 Another thread may be waiting on this thread reaching the placeholder. */
2982
2983 static struct placeholder *
2984 queue_push_placeholder (struct goacc_asyncqueue *aq)
2985 {
2986 struct placeholder *placeholderp;
2987
2988 pthread_mutex_lock (&aq->mutex);
2989
2990 wait_for_queue_nonfull (aq);
2991
2992 int queue_last = ((aq->queue_first + aq->queue_n) % ASYNC_QUEUE_SIZE);
2993 if (DEBUG_QUEUES)
2994 GCN_DEBUG ("queue_push_placeholder %d:%d: at %i\n", aq->agent->device_id,
2995 aq->id, queue_last);
2996
2997 aq->queue[queue_last].type = ASYNC_PLACEHOLDER;
2998 placeholderp = &aq->queue[queue_last].u.placeholder;
2999
3000 if (pthread_mutex_init (&placeholderp->mutex, NULL))
3001 {
3002 pthread_mutex_unlock (&aq->mutex);
3003 GOMP_PLUGIN_error ("Failed to initialize serialization mutex");
3004 }
3005
3006 if (pthread_cond_init (&placeholderp->cond, NULL))
3007 {
3008 pthread_mutex_unlock (&aq->mutex);
3009 GOMP_PLUGIN_error ("Failed to initialize serialization cond");
3010 }
3011
3012 placeholderp->executed = 0;
3013
3014 aq->queue_n++;
3015
3016 if (DEBUG_THREAD_SIGNAL)
3017 GCN_DEBUG ("signalling async thread %d:%d: cond_in\n",
3018 aq->agent->device_id, aq->id);
3019 pthread_cond_signal (&aq->queue_cond_in);
3020
3021 pthread_mutex_unlock (&aq->mutex);
3022
3023 return placeholderp;
3024 }
3025
3026 /* Signal an asynchronous thread to terminate, and wait for it to do so. */
3027
3028 static void
3029 finalize_async_thread (struct goacc_asyncqueue *aq)
3030 {
3031 pthread_mutex_lock (&aq->mutex);
3032 if (aq->drain_queue_stop == 2)
3033 {
3034 pthread_mutex_unlock (&aq->mutex);
3035 return;
3036 }
3037
3038 aq->drain_queue_stop = 1;
3039
3040 if (DEBUG_THREAD_SIGNAL)
3041 GCN_DEBUG ("Signalling async thread %d:%d: cond_in\n",
3042 aq->agent->device_id, aq->id);
3043 pthread_cond_signal (&aq->queue_cond_in);
3044
3045 while (aq->drain_queue_stop != 2)
3046 {
3047 if (DEBUG_THREAD_SLEEP)
3048 GCN_DEBUG ("Waiting for async thread %d:%d to finish, putting thread"
3049 " to sleep\n", aq->agent->device_id, aq->id);
3050 pthread_cond_wait (&aq->queue_cond_out, &aq->mutex);
3051 if (DEBUG_THREAD_SLEEP)
3052 GCN_DEBUG ("Waiting, woke up thread %d:%d. Rechecking\n",
3053 aq->agent->device_id, aq->id);
3054 }
3055
3056 GCN_DEBUG ("Done waiting for async thread %d:%d\n", aq->agent->device_id,
3057 aq->id);
3058 pthread_mutex_unlock (&aq->mutex);
3059
3060 int err = pthread_join (aq->thread_drain_queue, NULL);
3061 if (err != 0)
3062 GOMP_PLUGIN_fatal ("Join async thread %d:%d: failed: %s",
3063 aq->agent->device_id, aq->id, strerror (err));
3064 GCN_DEBUG ("Joined with async thread %d:%d\n", aq->agent->device_id, aq->id);
3065 }
3066
3067 /* Set up an async queue for OpenMP. There will be only one. The
3068 implementation simply uses an OpenACC async queue.
3069 FIXME: is this thread-safe if two threads call this function? */
3070
3071 static void
3072 maybe_init_omp_async (struct agent_info *agent)
3073 {
3074 if (!agent->omp_async_queue)
3075 agent->omp_async_queue
3076 = GOMP_OFFLOAD_openacc_async_construct (agent->device_id);
3077 }
3078
3079 /* A wrapper that works around an issue in the HSA runtime with host-to-device
3080 copies from read-only pages. */
3081
3082 static void
3083 hsa_memory_copy_wrapper (void *dst, const void *src, size_t len)
3084 {
3085 hsa_status_t status = hsa_fns.hsa_memory_copy_fn (dst, src, len);
3086
3087 if (status == HSA_STATUS_SUCCESS)
3088 return;
3089
3090 /* It appears that the copy fails if the source data is in a read-only page.
3091 We can't detect that easily, so try copying the data to a temporary buffer
3092 and doing the copy again if we got an error above. */
3093
3094 GCN_WARNING ("Read-only data transfer bug workaround triggered for "
3095 "[%p:+%d]\n", (void *) src, (int) len);
3096
3097 void *src_copy = malloc (len);
3098 memcpy (src_copy, src, len);
3099 status = hsa_fns.hsa_memory_copy_fn (dst, (const void *) src_copy, len);
3100 free (src_copy);
3101 if (status != HSA_STATUS_SUCCESS)
3102 GOMP_PLUGIN_error ("memory copy failed");
3103 }
3104
3105 /* Copy data to or from a device. This is intended for use as an async
3106 callback event. */
3107
3108 static void
3109 copy_data (void *data_)
3110 {
3111 struct copy_data *data = (struct copy_data *)data_;
3112 GCN_DEBUG ("Async thread %d:%d: Copying %zu bytes from (%p) to (%p)\n",
3113 data->aq->agent->device_id, data->aq->id, data->len, data->src,
3114 data->dst);
3115 hsa_memory_copy_wrapper (data->dst, data->src, data->len);
3116 free (data);
3117 }
3118
3119 /* Request an asynchronous data copy, to or from a device, on a given queue.
3120 The event will be registered as a callback. */
3121
3122 static void
3123 queue_push_copy (struct goacc_asyncqueue *aq, void *dst, const void *src,
3124 size_t len)
3125 {
3126 if (DEBUG_QUEUES)
3127 GCN_DEBUG ("queue_push_copy %d:%d: %zu bytes from (%p) to (%p)\n",
3128 aq->agent->device_id, aq->id, len, src, dst);
3129 struct copy_data *data
3130 = (struct copy_data *)GOMP_PLUGIN_malloc (sizeof (struct copy_data));
3131 data->dst = dst;
3132 data->src = src;
3133 data->len = len;
3134 data->aq = aq;
3135 queue_push_callback (aq, copy_data, data);
3136 }
3137
3138 /* Return true if the given queue is currently empty. */
3139
3140 static int
3141 queue_empty (struct goacc_asyncqueue *aq)
3142 {
3143 pthread_mutex_lock (&aq->mutex);
3144 int res = aq->queue_n == 0 ? 1 : 0;
3145 pthread_mutex_unlock (&aq->mutex);
3146
3147 return res;
3148 }
3149
3150 /* Wait for a given queue to become empty. This implements an OpenACC wait
3151 directive. */
3152
3153 static void
3154 wait_queue (struct goacc_asyncqueue *aq)
3155 {
3156 if (DRAIN_QUEUE_SYNCHRONOUS_P)
3157 {
3158 drain_queue_synchronous (aq);
3159 return;
3160 }
3161
3162 pthread_mutex_lock (&aq->mutex);
3163
3164 while (aq->queue_n > 0)
3165 {
3166 if (DEBUG_THREAD_SLEEP)
3167 GCN_DEBUG ("waiting for thread %d:%d, putting thread to sleep\n",
3168 aq->agent->device_id, aq->id);
3169 pthread_cond_wait (&aq->queue_cond_out, &aq->mutex);
3170 if (DEBUG_THREAD_SLEEP)
3171 GCN_DEBUG ("thread %d:%d woke up. Rechecking\n", aq->agent->device_id,
3172 aq->id);
3173 }
3174
3175 pthread_mutex_unlock (&aq->mutex);
3176 GCN_DEBUG ("waiting for thread %d:%d, done\n", aq->agent->device_id, aq->id);
3177 }
3178
3179 /* }}} */
3180 /* {{{ OpenACC support */
3181
3182 /* Execute an OpenACC kernel, synchronously or asynchronously. */
3183
3184 static void
3185 gcn_exec (struct kernel_info *kernel,
3186 void **devaddrs, unsigned *dims, void *targ_mem_desc, bool async,
3187 struct goacc_asyncqueue *aq)
3188 {
3189 if (!GOMP_OFFLOAD_can_run (kernel))
3190 GOMP_PLUGIN_fatal ("OpenACC host fallback unimplemented.");
3191
3192 /* If we get here then this must be an OpenACC kernel. */
3193 kernel->kind = KIND_OPENACC;
3194
3195 struct hsa_kernel_description *hsa_kernel_desc = NULL;
3196 for (unsigned i = 0; i < kernel->module->image_desc->kernel_count; i++)
3197 {
3198 struct hsa_kernel_description *d
3199 = &kernel->module->image_desc->kernel_infos[i];
3200 if (d->name == kernel->name)
3201 {
3202 hsa_kernel_desc = d;
3203 break;
3204 }
3205 }
3206
3207 /* We may have statically-determined dimensions in
3208 hsa_kernel_desc->oacc_dims[] or dimensions passed to this offload kernel
3209 invocation at runtime in dims[]. We allow static dimensions to take
3210 priority over dynamic dimensions when present (non-zero). */
3211 if (hsa_kernel_desc->oacc_dims[0] > 0)
3212 dims[0] = hsa_kernel_desc->oacc_dims[0];
3213 if (hsa_kernel_desc->oacc_dims[1] > 0)
3214 dims[1] = hsa_kernel_desc->oacc_dims[1];
3215 if (hsa_kernel_desc->oacc_dims[2] > 0)
3216 dims[2] = hsa_kernel_desc->oacc_dims[2];
3217
3218 /* Ideally, when a dimension isn't explicitly specified, we should
3219 tune it to run 40 (or 32?) threads per CU with no threads getting queued.
3220 In practice, we tune for peak performance on BabelStream, which
3221 for OpenACC is currently 32 threads per CU. */
3222 if (dims[0] == 0 && dims[1] == 0)
3223 {
3224 /* If any of the OpenACC dimensions remain 0 then we get to pick a
3225 number. There isn't really a correct answer for this without a clue
3226 about the problem size, so let's do a reasonable number of workers
3227 and gangs. */
3228
3229 dims[0] = get_cu_count (kernel->agent) * 4; /* Gangs. */
3230 dims[1] = 8; /* Workers. */
3231 }
3232 else if (dims[0] == 0 && dims[1] > 0)
3233 {
3234 /* Auto-scale the number of gangs with the requested number of workers. */
3235 dims[0] = get_cu_count (kernel->agent) * (32 / dims[1]);
3236 }
3237 else if (dims[0] > 0 && dims[1] == 0)
3238 {
3239 /* Auto-scale the number of workers with the requested number of gangs. */
3240 dims[1] = get_cu_count (kernel->agent) * 32 / dims[0];
3241 if (dims[1] == 0)
3242 dims[1] = 1;
3243 if (dims[1] > 16)
3244 dims[1] = 16;
3245 }
3246
3247 /* The incoming dimensions are expressed in terms of gangs, workers, and
3248 vectors. The HSA dimensions are expressed in terms of "work-items",
3249 which means multiples of vector lanes.
3250
3251 The "grid size" specifies the size of the problem space, and the
3252 "work-group size" specifies how much of that we want a single compute
3253 unit to chew on at once.
3254
3255 The three dimensions do not really correspond to hardware, but the
3256 important thing is that the HSA runtime will launch as many
3257 work-groups as it takes to process the entire grid, and each
3258 work-group will contain as many wave-fronts as it takes to process
3259 the work-items in that group.
3260
3261 Essentially, as long as we set the Y dimension to 64 (the number of
3262 vector lanes in hardware), and the Z group size to the maximum (16),
3263 then we will get the gangs (X) and workers (Z) launched as we expect.
3264
3265 The reason for the apparent reversal of vector and worker dimension
3266 order is to do with the way the run-time distributes work-items across
3267 v1 and v2. */
3268 struct GOMP_kernel_launch_attributes kla =
3269 {3,
3270 /* Grid size. */
3271 {dims[0], 64, dims[1]},
3272 /* Work-group size. */
3273 {1, 64, 16}
3274 };
3275
3276 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
3277 acc_prof_info *prof_info = thr->prof_info;
3278 acc_event_info enqueue_launch_event_info;
3279 acc_api_info *api_info = thr->api_info;
3280 bool profiling_dispatch_p = __builtin_expect (prof_info != NULL, false);
3281 if (profiling_dispatch_p)
3282 {
3283 prof_info->event_type = acc_ev_enqueue_launch_start;
3284
3285 enqueue_launch_event_info.launch_event.event_type
3286 = prof_info->event_type;
3287 enqueue_launch_event_info.launch_event.valid_bytes
3288 = _ACC_LAUNCH_EVENT_INFO_VALID_BYTES;
3289 enqueue_launch_event_info.launch_event.parent_construct
3290 = acc_construct_parallel;
3291 enqueue_launch_event_info.launch_event.implicit = 1;
3292 enqueue_launch_event_info.launch_event.tool_info = NULL;
3293 enqueue_launch_event_info.launch_event.kernel_name
3294 = (char *) kernel->name;
3295 enqueue_launch_event_info.launch_event.num_gangs = kla.gdims[0];
3296 enqueue_launch_event_info.launch_event.num_workers = kla.gdims[2];
3297 enqueue_launch_event_info.launch_event.vector_length = kla.gdims[1];
3298
3299 api_info->device_api = acc_device_api_other;
3300
3301 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info,
3302 &enqueue_launch_event_info, api_info);
3303 }
3304
3305 if (!async)
3306 run_kernel (kernel, devaddrs, &kla, NULL, false);
3307 else
3308 queue_push_launch (aq, kernel, devaddrs, &kla);
3309
3310 if (profiling_dispatch_p)
3311 {
3312 prof_info->event_type = acc_ev_enqueue_launch_end;
3313 enqueue_launch_event_info.launch_event.event_type = prof_info->event_type;
3314 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info,
3315 &enqueue_launch_event_info,
3316 api_info);
3317 }
3318 }
3319
3320 /* }}} */
3321 /* {{{ Generic Plugin API */
3322
3323 /* Return the name of the accelerator, which is "gcn". */
3324
3325 const char *
3326 GOMP_OFFLOAD_get_name (void)
3327 {
3328 return "gcn";
3329 }
3330
3331 /* Return the UID; if not available return NULL.
3332 Returns freshly allocated memoy. */
3333
3334 const char *
3335 GOMP_OFFLOAD_get_uid (int ord)
3336 {
3337 char *str;
3338 hsa_status_t status;
3339 struct agent_info *agent = get_agent_info (ord);
3340
3341 /* HSA documentation states: maximally 21 characters including NUL. */
3342 str = GOMP_PLUGIN_malloc (21 * sizeof (char));
3343 status = hsa_fns.hsa_agent_get_info_fn (agent->id, HSA_AMD_AGENT_INFO_UUID,
3344 str);
3345 if (status != HSA_STATUS_SUCCESS)
3346 {
3347 free (str);
3348 return NULL;
3349 }
3350 return str;
3351 }
3352
3353 /* Return the specific capabilities the HSA accelerator have. */
3354
3355 unsigned int
3356 GOMP_OFFLOAD_get_caps (void)
3357 {
3358 /* FIXME: Enable shared memory for APU, but not discrete GPU. */
3359 return /*GOMP_OFFLOAD_CAP_SHARED_MEM |*/ GOMP_OFFLOAD_CAP_OPENMP_400
3360 | GOMP_OFFLOAD_CAP_OPENACC_200;
3361 }
3362
3363 /* Identify as GCN accelerator. */
3364
3365 int
3366 GOMP_OFFLOAD_get_type (void)
3367 {
3368 return OFFLOAD_TARGET_TYPE_GCN;
3369 }
3370
3371 /* Return the libgomp version number we're compatible with. There is
3372 no requirement for cross-version compatibility. */
3373
3374 unsigned
3375 GOMP_OFFLOAD_version (void)
3376 {
3377 return GOMP_VERSION;
3378 }
3379
3380 /* Return the number of GCN devices on the system. */
3381
3382 int
3383 GOMP_OFFLOAD_get_num_devices (unsigned int omp_requires_mask)
3384 {
3385 if (!init_hsa_context (true))
3386 exit (EXIT_FAILURE);
3387 /* Return -1 if no omp_requires_mask cannot be fulfilled but
3388 devices were present. */
3389 if (hsa_context.agent_count > 0
3390 && ((omp_requires_mask
3391 & ~(GOMP_REQUIRES_UNIFIED_ADDRESS
3392 | GOMP_REQUIRES_UNIFIED_SHARED_MEMORY
3393 | GOMP_REQUIRES_SELF_MAPS
3394 | GOMP_REQUIRES_REVERSE_OFFLOAD)) != 0))
3395 return -1;
3396 /* Check whether host page access is supported; this is per system level
3397 (all GPUs supported by HSA). While intrinsically true for APUs, it
3398 requires XNACK support for discrete GPUs. */
3399 if (hsa_context.agent_count > 0
3400 && (omp_requires_mask
3401 & (GOMP_REQUIRES_UNIFIED_SHARED_MEMORY | GOMP_REQUIRES_SELF_MAPS)))
3402 {
3403 bool b;
3404 hsa_system_info_t type = HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT;
3405 hsa_status_t status = hsa_fns.hsa_system_get_info_fn (type, &b);
3406 if (status != HSA_STATUS_SUCCESS)
3407 GOMP_PLUGIN_error ("HSA_AMD_SYSTEM_INFO_SVM_ACCESSIBLE_BY_DEFAULT "
3408 "failed");
3409 if (!b)
3410 return -1;
3411 }
3412
3413 return hsa_context.agent_count;
3414 }
3415
3416 /* Initialize device (agent) number N so that it can be used for computation.
3417 Return TRUE on success. */
3418
3419 bool
3420 GOMP_OFFLOAD_init_device (int n)
3421 {
3422 if (!init_hsa_context (false))
3423 return false;
3424 if (n >= hsa_context.agent_count)
3425 {
3426 GOMP_PLUGIN_error ("Request to initialize non-existent GCN device %i", n);
3427 return false;
3428 }
3429 struct agent_info *agent = &hsa_context.agents[n];
3430
3431 if (agent->initialized)
3432 return true;
3433
3434 agent->device_id = n;
3435
3436 if (pthread_rwlock_init (&agent->module_rwlock, NULL))
3437 {
3438 GOMP_PLUGIN_error ("Failed to initialize a GCN agent rwlock");
3439 return false;
3440 }
3441 if (pthread_mutex_init (&agent->prog_mutex, NULL))
3442 {
3443 GOMP_PLUGIN_error ("Failed to initialize a GCN agent program mutex");
3444 return false;
3445 }
3446 if (pthread_mutex_init (&agent->async_queues_mutex, NULL))
3447 {
3448 GOMP_PLUGIN_error ("Failed to initialize a GCN agent queue mutex");
3449 return false;
3450 }
3451 if (pthread_mutex_init (&agent->ephemeral_memories_write_lock, NULL))
3452 {
3453 GOMP_PLUGIN_error ("Failed to initialize a GCN team arena write mutex");
3454 return false;
3455 }
3456 agent->async_queues = NULL;
3457 agent->omp_async_queue = NULL;
3458 agent->ephemeral_memories_list = NULL;
3459
3460 uint32_t queue_size;
3461 hsa_status_t status;
3462 status = hsa_fns.hsa_agent_get_info_fn (agent->id,
3463 HSA_AGENT_INFO_QUEUE_MAX_SIZE,
3464 &queue_size);
3465 if (status != HSA_STATUS_SUCCESS)
3466 return hsa_error ("Error requesting maximum queue size of the GCN agent",
3467 status);
3468
3469 status = hsa_fns.hsa_agent_get_info_fn (agent->id, HSA_AGENT_INFO_NAME,
3470 &agent->name);
3471 if (status != HSA_STATUS_SUCCESS)
3472 return hsa_error ("Error querying the name of the agent", status);
3473
3474 agent->device_isa = isa_code (agent->name);
3475 if (agent->device_isa == EF_AMDGPU_MACH_UNSUPPORTED)
3476 {
3477 char msg[33 + 64 + 1];
3478 snprintf (msg, sizeof msg,
3479 "Unknown GCN agent architecture '%s'", agent->name);
3480 return hsa_error (msg, HSA_STATUS_ERROR);
3481 }
3482
3483 status = hsa_fns.hsa_agent_get_info_fn (agent->id, HSA_AGENT_INFO_VENDOR_NAME,
3484 &agent->vendor_name);
3485 if (status != HSA_STATUS_SUCCESS)
3486 return hsa_error ("Error querying the vendor name of the agent", status);
3487
3488 status = hsa_fns.hsa_queue_create_fn (agent->id, queue_size,
3489 HSA_QUEUE_TYPE_MULTI,
3490 hsa_queue_callback, NULL, UINT32_MAX,
3491 UINT32_MAX, &agent->sync_queue);
3492 if (status != HSA_STATUS_SUCCESS)
3493 return hsa_error ("Error creating command queue", status);
3494
3495 agent->kernarg_region.handle = (uint64_t) -1;
3496 status = hsa_fns.hsa_agent_iterate_regions_fn (agent->id,
3497 get_kernarg_memory_region,
3498 &agent->kernarg_region);
3499 if (status != HSA_STATUS_SUCCESS
3500 && status != HSA_STATUS_INFO_BREAK)
3501 hsa_error ("Scanning memory regions failed", status);
3502 if (agent->kernarg_region.handle == (uint64_t) -1)
3503 {
3504 GOMP_PLUGIN_error ("Could not find suitable memory region for kernel "
3505 "arguments");
3506 return false;
3507 }
3508 GCN_DEBUG ("Selected kernel arguments memory region:\n");
3509 dump_hsa_region (agent->kernarg_region, NULL);
3510
3511 agent->data_region.handle = (uint64_t) -1;
3512 status = hsa_fns.hsa_agent_iterate_regions_fn (agent->id,
3513 get_data_memory_region,
3514 &agent->data_region);
3515 if (status != HSA_STATUS_SUCCESS
3516 && status != HSA_STATUS_INFO_BREAK)
3517 hsa_error ("Scanning memory regions failed", status);
3518 if (agent->data_region.handle == (uint64_t) -1)
3519 {
3520 GOMP_PLUGIN_error ("Could not find suitable memory region for device "
3521 "data");
3522 return false;
3523 }
3524 GCN_DEBUG ("Selected device data memory region:\n");
3525 dump_hsa_region (agent->data_region, NULL);
3526
3527 GCN_DEBUG ("GCN agent %d initialized\n", n);
3528
3529 agent->initialized = true;
3530 return true;
3531 }
3532
3533 /* Load GCN object-code module described by struct gcn_image_desc in
3534 TARGET_DATA and return references to kernel descriptors in TARGET_TABLE.
3535 If there are any constructors then run them. If not NULL, REV_FN_TABLE will
3536 contain the on-device addresses of the functions for reverse offload. To be
3537 freed by the caller. */
3538
3539 int
3540 GOMP_OFFLOAD_load_image (int ord, unsigned version, const void *target_data,
3541 struct addr_pair **target_table,
3542 uint64_t **rev_fn_table,
3543 uint64_t *host_ind_fn_table)
3544 {
3545 if (GOMP_VERSION_DEV (version) != GOMP_VERSION_GCN)
3546 {
3547 GOMP_PLUGIN_error ("Offload data incompatible with GCN plugin"
3548 " (expected %u, received %u)",
3549 GOMP_VERSION_GCN, GOMP_VERSION_DEV (version));
3550 return -1;
3551 }
3552
3553 struct gcn_image_desc *image_desc = (struct gcn_image_desc *) target_data;
3554 struct agent_info *agent;
3555 struct addr_pair *pair;
3556 struct module_info *module;
3557 struct kernel_info *kernel;
3558 int kernel_count = image_desc->kernel_count;
3559 unsigned ind_func_count = GOMP_VERSION_SUPPORTS_INDIRECT_FUNCS (version)
3560 ? image_desc->ind_func_count : 0;
3561 unsigned var_count = image_desc->global_variable_count;
3562 /* Currently, "others" is a struct of ICVS. */
3563 int other_count = 1;
3564
3565 agent = get_agent_info (ord);
3566 if (!agent)
3567 return -1;
3568
3569 if (pthread_rwlock_wrlock (&agent->module_rwlock))
3570 {
3571 GOMP_PLUGIN_error ("Unable to write-lock a GCN agent rwlock");
3572 return -1;
3573 }
3574 if (agent->prog_finalized
3575 && !destroy_hsa_program (agent))
3576 return -1;
3577
3578 GCN_DEBUG ("Encountered %d kernels in an image\n", kernel_count);
3579 GCN_DEBUG ("Encountered %d indirect functions in an image\n", ind_func_count);
3580 GCN_DEBUG ("Encountered %u global variables in an image\n", var_count);
3581 GCN_DEBUG ("Expect %d other variables in an image\n", other_count);
3582 pair = GOMP_PLUGIN_malloc ((kernel_count + var_count + other_count - 2)
3583 * sizeof (struct addr_pair));
3584 *target_table = pair;
3585 module = (struct module_info *)
3586 GOMP_PLUGIN_malloc_cleared (sizeof (struct module_info)
3587 + kernel_count * sizeof (struct kernel_info));
3588 module->image_desc = image_desc;
3589 module->kernel_count = kernel_count;
3590 module->heap = NULL;
3591 module->constructors_run_p = false;
3592
3593 kernel = &module->kernels[0];
3594
3595 /* Allocate memory for kernel dependencies. */
3596 for (unsigned i = 0; i < kernel_count; i++)
3597 {
3598 struct hsa_kernel_description *d = &image_desc->kernel_infos[i];
3599 if (!init_basic_kernel_info (kernel, d, agent, module))
3600 return -1;
3601 if (strcmp (d->name, "_init_array") == 0)
3602 module->init_array_func = kernel;
3603 else if (strcmp (d->name, "_fini_array") == 0)
3604 module->fini_array_func = kernel;
3605 else
3606 {
3607 pair->start = (uintptr_t) kernel;
3608 pair->end = (uintptr_t) (kernel + 1);
3609 pair++;
3610 }
3611 kernel++;
3612 }
3613
3614 agent->module = module;
3615 if (pthread_rwlock_unlock (&agent->module_rwlock))
3616 {
3617 GOMP_PLUGIN_error ("Unable to unlock a GCN agent rwlock");
3618 return -1;
3619 }
3620
3621 if (!create_and_finalize_hsa_program (agent))
3622 return -1;
3623
3624 if (var_count > 0)
3625 {
3626 hsa_status_t status;
3627 hsa_executable_symbol_t var_symbol;
3628 status = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
3629 ".offload_var_table",
3630 agent->id,
3631 0, &var_symbol);
3632
3633 if (status != HSA_STATUS_SUCCESS)
3634 hsa_fatal ("Could not find symbol for variable in the code object",
3635 status);
3636
3637 uint64_t var_table_addr;
3638 status = hsa_fns.hsa_executable_symbol_get_info_fn
3639 (var_symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
3640 &var_table_addr);
3641 if (status != HSA_STATUS_SUCCESS)
3642 hsa_fatal ("Could not extract a variable from its symbol", status);
3643
3644 struct {
3645 uint64_t addr;
3646 uint64_t size;
3647 } var_table[var_count];
3648 GOMP_OFFLOAD_dev2host (agent->device_id, var_table,
3649 (void*)var_table_addr, sizeof (var_table));
3650
3651 for (unsigned i = 0; i < var_count; i++)
3652 {
3653 pair->start = var_table[i].addr;
3654 pair->end = var_table[i].addr + var_table[i].size;
3655 GCN_DEBUG ("Found variable at %p with size %lu\n",
3656 (void *)var_table[i].addr, var_table[i].size);
3657 pair++;
3658 }
3659 }
3660
3661 if (ind_func_count > 0)
3662 {
3663 hsa_status_t status;
3664
3665 /* Read indirect function table from image. */
3666 hsa_executable_symbol_t ind_funcs_symbol;
3667 status = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
3668 ".offload_ind_func_table",
3669 agent->id,
3670 0, &ind_funcs_symbol);
3671
3672 if (status != HSA_STATUS_SUCCESS)
3673 hsa_fatal ("Could not find .offload_ind_func_table symbol in the "
3674 "code object", status);
3675
3676 uint64_t ind_funcs_table_addr;
3677 status = hsa_fns.hsa_executable_symbol_get_info_fn
3678 (ind_funcs_symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
3679 &ind_funcs_table_addr);
3680 if (status != HSA_STATUS_SUCCESS)
3681 hsa_fatal ("Could not extract a variable from its symbol", status);
3682
3683 uint64_t ind_funcs_table[ind_func_count];
3684 GOMP_OFFLOAD_dev2host (agent->device_id, ind_funcs_table,
3685 (void*) ind_funcs_table_addr,
3686 sizeof (ind_funcs_table));
3687
3688 /* Build host->target address map for indirect functions. */
3689 uint64_t ind_fn_map[ind_func_count * 2 + 1];
3690 for (unsigned i = 0; i < ind_func_count; i++)
3691 {
3692 ind_fn_map[i * 2] = host_ind_fn_table[i];
3693 ind_fn_map[i * 2 + 1] = ind_funcs_table[i];
3694 GCN_DEBUG ("Indirect function %d: %lx->%lx\n",
3695 i, host_ind_fn_table[i], ind_funcs_table[i]);
3696 }
3697 ind_fn_map[ind_func_count * 2] = 0;
3698
3699 /* Write the map onto the target. */
3700 void *map_target_addr
3701 = GOMP_OFFLOAD_alloc (agent->device_id, sizeof (ind_fn_map));
3702 GCN_DEBUG ("Allocated indirect map at %p\n", map_target_addr);
3703
3704 GOMP_OFFLOAD_host2dev (agent->device_id, map_target_addr,
3705 (void*) ind_fn_map,
3706 sizeof (ind_fn_map));
3707
3708 /* Write address of the map onto the target. */
3709 hsa_executable_symbol_t symbol;
3710
3711 status
3712 = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
3713 XSTRING (GOMP_INDIRECT_ADDR_MAP),
3714 agent->id, 0, &symbol);
3715 if (status != HSA_STATUS_SUCCESS)
3716 hsa_fatal ("Could not find GOMP_INDIRECT_ADDR_MAP in code object",
3717 status);
3718
3719 uint64_t varptr;
3720 uint32_t varsize;
3721
3722 status = hsa_fns.hsa_executable_symbol_get_info_fn
3723 (symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
3724 &varptr);
3725 if (status != HSA_STATUS_SUCCESS)
3726 hsa_fatal ("Could not extract a variable from its symbol", status);
3727 status = hsa_fns.hsa_executable_symbol_get_info_fn
3728 (symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE,
3729 &varsize);
3730 if (status != HSA_STATUS_SUCCESS)
3731 hsa_fatal ("Could not extract a variable size from its symbol",
3732 status);
3733
3734 GCN_DEBUG ("Found GOMP_INDIRECT_ADDR_MAP at %lx with size %d\n",
3735 varptr, varsize);
3736
3737 GOMP_OFFLOAD_host2dev (agent->device_id, (void *) varptr,
3738 &map_target_addr,
3739 sizeof (map_target_addr));
3740 }
3741
3742 GCN_DEBUG ("Looking for variable %s\n", XSTRING (GOMP_ADDITIONAL_ICVS));
3743
3744 hsa_status_t status;
3745 hsa_executable_symbol_t var_symbol;
3746 status = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
3747 XSTRING (GOMP_ADDITIONAL_ICVS),
3748 agent->id, 0, &var_symbol);
3749 if (status == HSA_STATUS_SUCCESS)
3750 {
3751 uint64_t varptr;
3752 uint32_t varsize;
3753
3754 status = hsa_fns.hsa_executable_symbol_get_info_fn
3755 (var_symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
3756 &varptr);
3757 if (status != HSA_STATUS_SUCCESS)
3758 hsa_fatal ("Could not extract a variable from its symbol", status);
3759 status = hsa_fns.hsa_executable_symbol_get_info_fn
3760 (var_symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_SIZE,
3761 &varsize);
3762 if (status != HSA_STATUS_SUCCESS)
3763 hsa_fatal ("Could not extract a variable size from its symbol",
3764 status);
3765
3766 pair->start = varptr;
3767 pair->end = varptr + varsize;
3768 }
3769 else
3770 {
3771 /* The variable was not in this image. */
3772 GCN_DEBUG ("Variable not found in image: %s\n",
3773 XSTRING (GOMP_ADDITIONAL_ICVS));
3774 pair->start = pair->end = 0;
3775 }
3776
3777 /* Ensure that constructors are run first. */
3778 struct GOMP_kernel_launch_attributes kla =
3779 { 3,
3780 /* Grid size. */
3781 { 1, 64, 1 },
3782 /* Work-group size. */
3783 { 1, 64, 1 }
3784 };
3785
3786 if (module->init_array_func)
3787 {
3788 init_kernel (module->init_array_func);
3789 run_kernel (module->init_array_func, NULL, &kla, NULL, false);
3790 }
3791 module->constructors_run_p = true;
3792
3793 /* Don't report kernels that libgomp need not know about. */
3794 if (module->init_array_func)
3795 kernel_count--;
3796 if (module->fini_array_func)
3797 kernel_count--;
3798
3799 if (rev_fn_table != NULL && kernel_count == 0)
3800 *rev_fn_table = NULL;
3801 else if (rev_fn_table != NULL)
3802 {
3803 hsa_status_t status;
3804 hsa_executable_symbol_t var_symbol;
3805 status = hsa_fns.hsa_executable_get_symbol_fn (agent->executable, NULL,
3806 ".offload_func_table",
3807 agent->id, 0, &var_symbol);
3808 if (status != HSA_STATUS_SUCCESS)
3809 hsa_fatal ("Could not find symbol for variable in the code object",
3810 status);
3811 uint64_t fn_table_addr;
3812 status = hsa_fns.hsa_executable_symbol_get_info_fn
3813 (var_symbol, HSA_EXECUTABLE_SYMBOL_INFO_VARIABLE_ADDRESS,
3814 &fn_table_addr);
3815 if (status != HSA_STATUS_SUCCESS)
3816 hsa_fatal ("Could not extract a variable from its symbol", status);
3817 *rev_fn_table = GOMP_PLUGIN_malloc (kernel_count * sizeof (uint64_t));
3818 GOMP_OFFLOAD_dev2host (agent->device_id, *rev_fn_table,
3819 (void*) fn_table_addr,
3820 kernel_count * sizeof (uint64_t));
3821 }
3822
3823 return kernel_count + var_count + other_count;
3824 }
3825
3826 /* Unload GCN object-code module described by struct gcn_image_desc in
3827 TARGET_DATA from agent number N. Return TRUE on success. */
3828
3829 bool
3830 GOMP_OFFLOAD_unload_image (int n, unsigned version, const void *target_data)
3831 {
3832 if (GOMP_VERSION_DEV (version) != GOMP_VERSION_GCN)
3833 {
3834 GOMP_PLUGIN_error ("Offload data incompatible with GCN plugin"
3835 " (expected %u, received %u)",
3836 GOMP_VERSION_GCN, GOMP_VERSION_DEV (version));
3837 return false;
3838 }
3839
3840 struct agent_info *agent;
3841 agent = get_agent_info (n);
3842 if (!agent)
3843 return false;
3844
3845 if (pthread_rwlock_wrlock (&agent->module_rwlock))
3846 {
3847 GOMP_PLUGIN_error ("Unable to write-lock a GCN agent rwlock");
3848 return false;
3849 }
3850
3851 if (!agent->module || agent->module->image_desc != target_data)
3852 {
3853 GOMP_PLUGIN_error ("Attempt to unload an image that has never been "
3854 "loaded before");
3855 return false;
3856 }
3857
3858 if (!destroy_module (agent->module, true))
3859 return false;
3860 free (agent->module);
3861 agent->module = NULL;
3862 if (!destroy_hsa_program (agent))
3863 return false;
3864 if (pthread_rwlock_unlock (&agent->module_rwlock))
3865 {
3866 GOMP_PLUGIN_error ("Unable to unlock a GCN agent rwlock");
3867 return false;
3868 }
3869 return true;
3870 }
3871
3872 /* Deinitialize all information and status associated with agent number N. We
3873 do not attempt any synchronization, assuming the user and libgomp will not
3874 attempt deinitialization of a device that is in any way being used at the
3875 same time. Return TRUE on success. */
3876
3877 bool
3878 GOMP_OFFLOAD_fini_device (int n)
3879 {
3880 struct agent_info *agent = get_agent_info (n);
3881 if (!agent)
3882 return false;
3883
3884 if (!agent->initialized)
3885 return true;
3886
3887 if (agent->omp_async_queue)
3888 {
3889 GOMP_OFFLOAD_openacc_async_destruct (agent->omp_async_queue);
3890 agent->omp_async_queue = NULL;
3891 }
3892
3893 if (agent->module)
3894 {
3895 if (!destroy_module (agent->module, false))
3896 return false;
3897 free (agent->module);
3898 agent->module = NULL;
3899 }
3900
3901 if (!destroy_ephemeral_memories (agent))
3902 return false;
3903
3904 if (!destroy_hsa_program (agent))
3905 return false;
3906
3907 hsa_status_t status = hsa_fns.hsa_queue_destroy_fn (agent->sync_queue);
3908 if (status != HSA_STATUS_SUCCESS)
3909 return hsa_error ("Error destroying command queue", status);
3910
3911 if (pthread_mutex_destroy (&agent->prog_mutex))
3912 {
3913 GOMP_PLUGIN_error ("Failed to destroy a GCN agent program mutex");
3914 return false;
3915 }
3916 if (pthread_rwlock_destroy (&agent->module_rwlock))
3917 {
3918 GOMP_PLUGIN_error ("Failed to destroy a GCN agent rwlock");
3919 return false;
3920 }
3921
3922 if (pthread_mutex_destroy (&agent->async_queues_mutex))
3923 {
3924 GOMP_PLUGIN_error ("Failed to destroy a GCN agent queue mutex");
3925 return false;
3926 }
3927 if (pthread_mutex_destroy (&agent->ephemeral_memories_write_lock))
3928 {
3929 GOMP_PLUGIN_error ("Failed to destroy a GCN memory mutex");
3930 return false;
3931 }
3932 agent->initialized = false;
3933 return true;
3934 }
3935
3936 /* Return true if the HSA runtime can run function FN_PTR. */
3937
3938 bool
3939 GOMP_OFFLOAD_can_run (void *fn_ptr)
3940 {
3941 struct kernel_info *kernel = (struct kernel_info *) fn_ptr;
3942
3943 init_kernel (kernel);
3944 if (kernel->initialization_failed)
3945 GOMP_PLUGIN_fatal ("kernel initialization failed");
3946
3947 return true;
3948 }
3949
3950 /* Allocate memory on device N. */
3951
3952 void *
3953 GOMP_OFFLOAD_alloc (int n, size_t size)
3954 {
3955 struct agent_info *agent = get_agent_info (n);
3956 return alloc_by_agent (agent, size);
3957 }
3958
3959 /* Free memory from device N. */
3960
3961 bool
3962 GOMP_OFFLOAD_free (int device, void *ptr)
3963 {
3964 GCN_DEBUG ("Freeing memory on device %d\n", device);
3965
3966 hsa_status_t status = hsa_fns.hsa_memory_free_fn (ptr);
3967 if (status != HSA_STATUS_SUCCESS)
3968 {
3969 hsa_error ("Could not free device memory", status);
3970 return false;
3971 }
3972
3973 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
3974 bool profiling_dispatch_p
3975 = __builtin_expect (thr != NULL && thr->prof_info != NULL, false);
3976 if (profiling_dispatch_p)
3977 {
3978 acc_prof_info *prof_info = thr->prof_info;
3979 acc_event_info data_event_info;
3980 acc_api_info *api_info = thr->api_info;
3981
3982 prof_info->event_type = acc_ev_free;
3983
3984 data_event_info.data_event.event_type = prof_info->event_type;
3985 data_event_info.data_event.valid_bytes
3986 = _ACC_DATA_EVENT_INFO_VALID_BYTES;
3987 data_event_info.data_event.parent_construct
3988 = acc_construct_parallel;
3989 data_event_info.data_event.implicit = 1;
3990 data_event_info.data_event.tool_info = NULL;
3991 data_event_info.data_event.var_name = NULL;
3992 data_event_info.data_event.bytes = 0;
3993 data_event_info.data_event.host_ptr = NULL;
3994 data_event_info.data_event.device_ptr = (void *) ptr;
3995
3996 api_info->device_api = acc_device_api_other;
3997
3998 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &data_event_info,
3999 api_info);
4000 }
4001
4002 return true;
4003 }
4004
4005 /* Copy data from DEVICE to host. */
4006
4007 bool
4008 GOMP_OFFLOAD_dev2host (int device, void *dst, const void *src, size_t n)
4009 {
4010 GCN_DEBUG ("Copying %zu bytes from device %d (%p) to host (%p)\n", n, device,
4011 src, dst);
4012 hsa_status_t status = hsa_fns.hsa_memory_copy_fn (dst, src, n);
4013 if (status != HSA_STATUS_SUCCESS)
4014 GOMP_PLUGIN_error ("memory copy failed");
4015 return true;
4016 }
4017
4018 /* Copy data from host to DEVICE. */
4019
4020 bool
4021 GOMP_OFFLOAD_host2dev (int device, void *dst, const void *src, size_t n)
4022 {
4023 GCN_DEBUG ("Copying %zu bytes from host (%p) to device %d (%p)\n", n, src,
4024 device, dst);
4025 hsa_memory_copy_wrapper (dst, src, n);
4026 return true;
4027 }
4028
4029 /* Copy data within DEVICE. Do the copy asynchronously, if appropriate. */
4030
4031 bool
4032 GOMP_OFFLOAD_dev2dev (int device, void *dst, const void *src, size_t n)
4033 {
4034 struct gcn_thread *thread_data = gcn_thread ();
4035
4036 if (thread_data && !async_synchronous_p (thread_data->async))
4037 {
4038 struct agent_info *agent = get_agent_info (device);
4039 maybe_init_omp_async (agent);
4040 if (!agent->omp_async_queue)
4041 return false;
4042 queue_push_copy (agent->omp_async_queue, dst, src, n);
4043 return true;
4044 }
4045
4046 GCN_DEBUG ("Copying %zu bytes from device %d (%p) to device %d (%p)\n", n,
4047 device, src, device, dst);
4048 hsa_status_t status = hsa_fns.hsa_memory_copy_fn (dst, src, n);
4049 if (status != HSA_STATUS_SUCCESS)
4050 GOMP_PLUGIN_error ("memory copy failed");
4051 return true;
4052 }
4053
4054 /* Here <quantity>_size refers to <quantity> multiplied by size -- i.e.
4055 measured in bytes. So we have:
4056
4057 dim1_size: number of bytes to copy on innermost dimension ("row")
4058 dim0_len: number of rows to copy
4059 dst: base pointer for destination of copy
4060 dst_offset1_size: innermost row offset (for dest), in bytes
4061 dst_offset0_len: offset, number of rows (for dest)
4062 dst_dim1_size: whole-array dest row length, in bytes (pitch)
4063 src: base pointer for source of copy
4064 src_offset1_size: innermost row offset (for source), in bytes
4065 src_offset0_len: offset, number of rows (for source)
4066 src_dim1_size: whole-array source row length, in bytes (pitch)
4067 */
4068
4069 int
4070 GOMP_OFFLOAD_memcpy2d (int dst_ord, int src_ord, size_t dim1_size,
4071 size_t dim0_len, void *dst, size_t dst_offset1_size,
4072 size_t dst_offset0_len, size_t dst_dim1_size,
4073 const void *src, size_t src_offset1_size,
4074 size_t src_offset0_len, size_t src_dim1_size)
4075 {
4076 if (!hsa_fns.hsa_amd_memory_lock_fn
4077 || !hsa_fns.hsa_amd_memory_unlock_fn
4078 || !hsa_fns.hsa_amd_memory_async_copy_rect_fn)
4079 return -1;
4080
4081 /* GCN hardware requires 4-byte alignment for base addresses & pitches. Bail
4082 out quietly if we have anything oddly-aligned rather than letting the
4083 driver raise an error. */
4084 if ((((uintptr_t) dst) & 3) != 0 || (((uintptr_t) src) & 3) != 0)
4085 return -1;
4086
4087 if ((dst_dim1_size & 3) != 0 || (src_dim1_size & 3) != 0)
4088 return -1;
4089
4090 /* Only handle host to device or device to host transfers here. */
4091 if ((dst_ord == -1 && src_ord == -1)
4092 || (dst_ord != -1 && src_ord != -1))
4093 return -1;
4094
4095 hsa_amd_copy_direction_t dir
4096 = (src_ord == -1) ? hsaHostToDevice : hsaDeviceToHost;
4097 hsa_agent_t copy_agent;
4098
4099 /* We need to pin (lock) host memory before we start the transfer. Try to
4100 lock the minimum size necessary, i.e. using partial first/last rows of the
4101 whole array. Something like this:
4102
4103 rows -->
4104 ..............
4105 c | ..#######+++++ <- first row apart from {src,dst}_offset1_size
4106 o | ++#######+++++ <- whole row
4107 l | ++#######+++++ <- "
4108 s v ++#######..... <- last row apart from trailing remainder
4109 ..............
4110
4111 We could split very large transfers into several rectangular copies, but
4112 that is unimplemented for now. */
4113
4114 size_t bounded_size_host, first_elem_offset_host;
4115 void *host_ptr;
4116 if (dir == hsaHostToDevice)
4117 {
4118 bounded_size_host = src_dim1_size * (dim0_len - 1) + dim1_size;
4119 first_elem_offset_host = src_offset0_len * src_dim1_size
4120 + src_offset1_size;
4121 host_ptr = (void *) src;
4122 struct agent_info *agent = get_agent_info (dst_ord);
4123 copy_agent = agent->id;
4124 }
4125 else
4126 {
4127 bounded_size_host = dst_dim1_size * (dim0_len - 1) + dim1_size;
4128 first_elem_offset_host = dst_offset0_len * dst_dim1_size
4129 + dst_offset1_size;
4130 host_ptr = dst;
4131 struct agent_info *agent = get_agent_info (src_ord);
4132 copy_agent = agent->id;
4133 }
4134
4135 void *agent_ptr;
4136
4137 hsa_status_t status
4138 = hsa_fns.hsa_amd_memory_lock_fn (host_ptr + first_elem_offset_host,
4139 bounded_size_host, NULL, 0, &agent_ptr);
4140 /* We can't lock the host memory: don't give up though, we might still be
4141 able to use the slow path in our caller. So, don't make this an
4142 error. */
4143 if (status != HSA_STATUS_SUCCESS)
4144 return -1;
4145
4146 hsa_pitched_ptr_t dstpp, srcpp;
4147 hsa_dim3_t dst_offsets, src_offsets, ranges;
4148
4149 int retval = 1;
4150
4151 hsa_signal_t completion_signal;
4152 status = hsa_fns.hsa_signal_create_fn (1, 0, NULL, &completion_signal);
4153 if (status != HSA_STATUS_SUCCESS)
4154 {
4155 retval = -1;
4156 goto unlock;
4157 }
4158
4159 if (dir == hsaHostToDevice)
4160 {
4161 srcpp.base = agent_ptr - first_elem_offset_host;
4162 dstpp.base = dst;
4163 }
4164 else
4165 {
4166 srcpp.base = (void *) src;
4167 dstpp.base = agent_ptr - first_elem_offset_host;
4168 }
4169
4170 srcpp.pitch = src_dim1_size;
4171 srcpp.slice = 0;
4172
4173 src_offsets.x = src_offset1_size;
4174 src_offsets.y = src_offset0_len;
4175 src_offsets.z = 0;
4176
4177 dstpp.pitch = dst_dim1_size;
4178 dstpp.slice = 0;
4179
4180 dst_offsets.x = dst_offset1_size;
4181 dst_offsets.y = dst_offset0_len;
4182 dst_offsets.z = 0;
4183
4184 ranges.x = dim1_size;
4185 ranges.y = dim0_len;
4186 ranges.z = 1;
4187
4188 status
4189 = hsa_fns.hsa_amd_memory_async_copy_rect_fn (&dstpp, &dst_offsets, &srcpp,
4190 &src_offsets, &ranges,
4191 copy_agent, dir, 0, NULL,
4192 completion_signal);
4193 /* If the rectangular copy fails, we might still be able to use the slow
4194 path. We need to unlock the host memory though, so don't return
4195 immediately. */
4196 if (status != HSA_STATUS_SUCCESS)
4197 retval = -1;
4198 else
4199 hsa_fns.hsa_signal_wait_acquire_fn (completion_signal,
4200 HSA_SIGNAL_CONDITION_LT, 1, UINT64_MAX,
4201 HSA_WAIT_STATE_ACTIVE);
4202
4203 hsa_fns.hsa_signal_destroy_fn (completion_signal);
4204
4205 unlock:
4206 status = hsa_fns.hsa_amd_memory_unlock_fn (host_ptr + first_elem_offset_host);
4207 if (status != HSA_STATUS_SUCCESS)
4208 hsa_fatal ("Could not unlock host memory", status);
4209
4210 return retval;
4211 }
4212
4213 /* As above, <quantity>_size refers to <quantity> multiplied by size -- i.e.
4214 measured in bytes. So we have:
4215
4216 dim2_size: number of bytes to copy on innermost dimension ("row")
4217 dim1_len: number of rows per slice to copy
4218 dim0_len: number of slices to copy
4219 dst: base pointer for destination of copy
4220 dst_offset2_size: innermost row offset (for dest), in bytes
4221 dst_offset1_len: offset, number of rows (for dest)
4222 dst_offset0_len: offset, number of slices (for dest)
4223 dst_dim2_size: whole-array dest row length, in bytes (pitch)
4224 dst_dim1_len: whole-array number of rows in slice (for dest)
4225 src: base pointer for source of copy
4226 src_offset2_size: innermost row offset (for source), in bytes
4227 src_offset1_len: offset, number of rows (for source)
4228 src_offset0_len: offset, number of slices (for source)
4229 src_dim2_size: whole-array source row length, in bytes (pitch)
4230 src_dim1_len: whole-array number of rows in slice (for source)
4231 */
4232
4233 int
4234 GOMP_OFFLOAD_memcpy3d (int dst_ord, int src_ord, size_t dim2_size,
4235 size_t dim1_len, size_t dim0_len, void *dst,
4236 size_t dst_offset2_size, size_t dst_offset1_len,
4237 size_t dst_offset0_len, size_t dst_dim2_size,
4238 size_t dst_dim1_len, const void *src,
4239 size_t src_offset2_size, size_t src_offset1_len,
4240 size_t src_offset0_len, size_t src_dim2_size,
4241 size_t src_dim1_len)
4242 {
4243 if (!hsa_fns.hsa_amd_memory_lock_fn
4244 || !hsa_fns.hsa_amd_memory_unlock_fn
4245 || !hsa_fns.hsa_amd_memory_async_copy_rect_fn)
4246 return -1;
4247
4248 /* GCN hardware requires 4-byte alignment for base addresses & pitches. Bail
4249 out quietly if we have anything oddly-aligned rather than letting the
4250 driver raise an error. */
4251 if ((((uintptr_t) dst) & 3) != 0 || (((uintptr_t) src) & 3) != 0)
4252 return -1;
4253
4254 if ((dst_dim2_size & 3) != 0 || (src_dim2_size & 3) != 0)
4255 return -1;
4256
4257 /* Only handle host to device or device to host transfers here. */
4258 if ((dst_ord == -1 && src_ord == -1)
4259 || (dst_ord != -1 && src_ord != -1))
4260 return -1;
4261
4262 hsa_amd_copy_direction_t dir
4263 = (src_ord == -1) ? hsaHostToDevice : hsaDeviceToHost;
4264 hsa_agent_t copy_agent;
4265
4266 /* We need to pin (lock) host memory before we start the transfer. Try to
4267 lock the minimum size necessary, i.e. using partial first/last slices of
4268 the whole 3D array. Something like this:
4269
4270 slice 0: slice 1: slice 2:
4271 __________ __________ __________
4272 ^ /+++++++++/ : /+++++++++/ : / /
4273 column /+++##++++/| | /+++##++++/| | /+++## / # = subarray
4274 / / ##++++/ | |/+++##++++/ | |/+++##++++/ + = area to pin
4275 /_________/ : /_________/ : /_________/
4276 row --->
4277
4278 We could split very large transfers into several rectangular copies, but
4279 that is unimplemented for now. */
4280
4281 size_t bounded_size_host, first_elem_offset_host;
4282 void *host_ptr;
4283 if (dir == hsaHostToDevice)
4284 {
4285 size_t slice_bytes = src_dim2_size * src_dim1_len;
4286 bounded_size_host = slice_bytes * (dim0_len - 1)
4287 + src_dim2_size * (dim1_len - 1)
4288 + dim2_size;
4289 first_elem_offset_host = src_offset0_len * slice_bytes
4290 + src_offset1_len * src_dim2_size
4291 + src_offset2_size;
4292 host_ptr = (void *) src;
4293 struct agent_info *agent = get_agent_info (dst_ord);
4294 copy_agent = agent->id;
4295 }
4296 else
4297 {
4298 size_t slice_bytes = dst_dim2_size * dst_dim1_len;
4299 bounded_size_host = slice_bytes * (dim0_len - 1)
4300 + dst_dim2_size * (dim1_len - 1)
4301 + dim2_size;
4302 first_elem_offset_host = dst_offset0_len * slice_bytes
4303 + dst_offset1_len * dst_dim2_size
4304 + dst_offset2_size;
4305 host_ptr = dst;
4306 struct agent_info *agent = get_agent_info (src_ord);
4307 copy_agent = agent->id;
4308 }
4309
4310 void *agent_ptr;
4311
4312 hsa_status_t status
4313 = hsa_fns.hsa_amd_memory_lock_fn (host_ptr + first_elem_offset_host,
4314 bounded_size_host, NULL, 0, &agent_ptr);
4315 /* We can't lock the host memory: don't give up though, we might still be
4316 able to use the slow path in our caller (maybe even with iterated memcpy2d
4317 calls). So, don't make this an error. */
4318 if (status != HSA_STATUS_SUCCESS)
4319 return -1;
4320
4321 hsa_pitched_ptr_t dstpp, srcpp;
4322 hsa_dim3_t dst_offsets, src_offsets, ranges;
4323
4324 int retval = 1;
4325
4326 hsa_signal_t completion_signal;
4327 status = hsa_fns.hsa_signal_create_fn (1, 0, NULL, &completion_signal);
4328 if (status != HSA_STATUS_SUCCESS)
4329 {
4330 retval = -1;
4331 goto unlock;
4332 }
4333
4334 if (dir == hsaHostToDevice)
4335 {
4336 srcpp.base = agent_ptr - first_elem_offset_host;
4337 dstpp.base = dst;
4338 }
4339 else
4340 {
4341 srcpp.base = (void *) src;
4342 dstpp.base = agent_ptr - first_elem_offset_host;
4343 }
4344
4345 /* Pitch is measured in bytes. */
4346 srcpp.pitch = src_dim2_size;
4347 /* Slice is also measured in bytes (i.e. total per-slice). */
4348 srcpp.slice = src_dim2_size * src_dim1_len;
4349
4350 src_offsets.x = src_offset2_size;
4351 src_offsets.y = src_offset1_len;
4352 src_offsets.z = src_offset0_len;
4353
4354 /* As above. */
4355 dstpp.pitch = dst_dim2_size;
4356 dstpp.slice = dst_dim2_size * dst_dim1_len;
4357
4358 dst_offsets.x = dst_offset2_size;
4359 dst_offsets.y = dst_offset1_len;
4360 dst_offsets.z = dst_offset0_len;
4361
4362 ranges.x = dim2_size;
4363 ranges.y = dim1_len;
4364 ranges.z = dim0_len;
4365
4366 status
4367 = hsa_fns.hsa_amd_memory_async_copy_rect_fn (&dstpp, &dst_offsets, &srcpp,
4368 &src_offsets, &ranges,
4369 copy_agent, dir, 0, NULL,
4370 completion_signal);
4371 /* If the rectangular copy fails, we might still be able to use the slow
4372 path. We need to unlock the host memory though, so don't return
4373 immediately. */
4374 if (status != HSA_STATUS_SUCCESS)
4375 retval = -1;
4376 else
4377 {
4378 hsa_signal_value_t sv
4379 = hsa_fns.hsa_signal_wait_acquire_fn (completion_signal,
4380 HSA_SIGNAL_CONDITION_LT, 1,
4381 UINT64_MAX,
4382 HSA_WAIT_STATE_ACTIVE);
4383 if (sv < 0)
4384 {
4385 GCN_WARNING ("async copy rect failure");
4386 retval = -1;
4387 }
4388 }
4389
4390 hsa_fns.hsa_signal_destroy_fn (completion_signal);
4391
4392 unlock:
4393 status = hsa_fns.hsa_amd_memory_unlock_fn (host_ptr + first_elem_offset_host);
4394 if (status != HSA_STATUS_SUCCESS)
4395 hsa_fatal ("Could not unlock host memory", status);
4396
4397 return retval;
4398 }
4399
4400
4401 static bool
4402 init_hip_runtime_functions (void)
4403 {
4404 bool inited = false;
4405 if (inited)
4406 return hip_fns.hipStreamCreate_fn != NULL;
4407 inited = true;
4408
4409 void *handle = dlopen (hip_runtime_lib, RTLD_LAZY);
4410 if (handle == NULL)
4411 return false;
4412
4413 #define DLSYM_OPT_FN(function) \
4414 hip_fns.function##_fn = dlsym (handle, #function)
4415
4416 DLSYM_OPT_FN (hipStreamCreate);
4417 DLSYM_OPT_FN (hipStreamDestroy);
4418 DLSYM_OPT_FN (hipStreamSynchronize);
4419 DLSYM_OPT_FN (hipCtxGetCurrent);
4420 DLSYM_OPT_FN (hipGetDevice);
4421 DLSYM_OPT_FN (hipSetDevice);
4422 #undef DLSYM_OPT_FN
4423
4424 if (!hip_fns.hipStreamCreate_fn
4425 || !hip_fns.hipStreamDestroy_fn
4426 || !hip_fns.hipStreamSynchronize_fn
4427 || !hip_fns.hipCtxGetCurrent_fn
4428 || !hip_fns.hipGetDevice_fn
4429 || !hip_fns.hipSetDevice_fn)
4430 {
4431 hip_fns.hipStreamCreate_fn = NULL;
4432 return false;
4433 }
4434
4435 return true;
4436 }
4437
4438
4439 void
4440 GOMP_OFFLOAD_interop (struct interop_obj_t *obj, int ord,
4441 enum gomp_interop_flag action, bool targetsync,
4442 const char *prefer_type)
4443 {
4444 if ((action == gomp_interop_flag_destroy || action == gomp_interop_flag_use)
4445 && !obj->stream)
4446 return;
4447 if ((action == gomp_interop_flag_destroy || action == gomp_interop_flag_use)
4448 && obj->fr == omp_ifr_hsa)
4449 {
4450 /* Wait until the queue is is empty. */
4451 bool is_empty;
4452 uint64_t read_index, write_index;
4453 hsa_queue_t *queue = (hsa_queue_t *) obj->stream;
4454 do
4455 {
4456 read_index = hsa_fns.hsa_queue_load_read_index_relaxed_fn (queue);
4457 write_index = hsa_fns.hsa_queue_load_write_index_relaxed_fn (queue);
4458 is_empty = (read_index == write_index);
4459 }
4460 while (!is_empty);
4461
4462 if (action == gomp_interop_flag_destroy)
4463 {
4464 hsa_status_t status = hsa_fns.hsa_queue_destroy_fn (queue);
4465 if (status != HSA_STATUS_SUCCESS)
4466 hsa_fatal ("Error destroying interop hsa_queue_t", status);
4467 }
4468 return;
4469 }
4470 if (action == gomp_interop_flag_destroy)
4471 {
4472 hipError_t err = hip_fns.hipStreamDestroy_fn ((hipStream_t) obj->stream);
4473 if (err != 0)
4474 GOMP_PLUGIN_fatal ("Error destroying interop hipStream_t: %d", err);
4475 return;
4476 }
4477 if (action == gomp_interop_flag_use)
4478 {
4479 hipError_t err
4480 = hip_fns.hipStreamSynchronize_fn ((hipStream_t) obj->stream);
4481 if (err != 0)
4482 GOMP_PLUGIN_fatal ("Error synchronizing interop hipStream_t: %d", err);
4483 return;
4484 }
4485
4486 bool fr_set = false;
4487
4488 /* Check for the preferred type; cf. parser in C/C++/Fortran or
4489 dump_omp_init_prefer_type for the format.
4490 Accept the first '{...}' block that specifies a 'fr' that we support.
4491 Currently, no 'attr(...)' are supported. */
4492 if (prefer_type)
4493 while (prefer_type[0] == (char) GOMP_INTEROP_IFR_SEPARATOR)
4494 {
4495 /* '{' item block starts. */
4496 prefer_type++;
4497 /* 'fr(...)' block */
4498 while (prefer_type[0] != (char) GOMP_INTEROP_IFR_SEPARATOR)
4499 {
4500 omp_interop_fr_t fr = (omp_interop_fr_t) prefer_type[0];
4501 if (fr == omp_ifr_hip)
4502 {
4503 obj->fr = omp_ifr_hip;
4504 fr_set = true;
4505 }
4506 if (fr == omp_ifr_hsa)
4507 {
4508 obj->fr = omp_ifr_hsa;
4509 fr_set = true;
4510 }
4511 prefer_type++;
4512 }
4513 prefer_type++;
4514 /* 'attr(...)' block */
4515 while (prefer_type[0] != '\0')
4516 {
4517 /* const char *attr = prefer_type; */
4518 prefer_type += strlen (prefer_type) + 1;
4519 }
4520 prefer_type++;
4521 /* end of '}'. */
4522 if (fr_set)
4523 break;
4524 }
4525
4526 /* Prefer HIP, use HSA as fallback. The warning is only printed if GCN_DEBUG
4527 is set and does not distinguishes between on prefer_type or hip prefer_type
4528 nor whether a later/lower preference also specifies 'hsa'.
4529 The assumption is that the user code handles HSA gracefully, but likely
4530 just by falling back to the host version. On the other hand, have_hip is
4531 likely true if HSA is available. */
4532 if (!fr_set || obj->fr == omp_ifr_hip)
4533 {
4534 bool have_hip = init_hip_runtime_functions ();
4535 if (have_hip)
4536 obj->fr = omp_ifr_hip;
4537 else
4538 {
4539 GCN_WARNING ("interop object requested, using HSA instead of HIP "
4540 "as %s could not be loaded", hip_runtime_lib);
4541 obj->fr = omp_ifr_hsa;
4542 }
4543 }
4544
4545 _Static_assert (sizeof (uint64_t) == sizeof (hsa_agent_t),
4546 "sizeof (uint64_t) == sizeof (hsa_agent_t)");
4547 struct agent_info *agent = get_agent_info (ord);
4548 obj->device_data = agent;
4549
4550 if (targetsync && obj->fr == omp_ifr_hsa)
4551 {
4552 hsa_status_t status;
4553 /* Queue size must be (for GPUs) a power of 2 >= 40, i.e. at least 64 and
4554 maximally HSA_AGENT_INFO_QUEUE_MAX_SIZE. Arbitrary choice: */
4555 uint32_t queue_size = ASYNC_QUEUE_SIZE;
4556 status = hsa_fns.hsa_queue_create_fn (agent->id, queue_size,
4557 HSA_QUEUE_TYPE_MULTI,
4558 NULL, NULL, UINT32_MAX, UINT32_MAX,
4559 (hsa_queue_t **) &obj->stream);
4560 if (status != HSA_STATUS_SUCCESS)
4561 hsa_fatal ("Error creating interop hsa_queue_t", status);
4562 }
4563 else if (targetsync)
4564 {
4565 hipError_t err;
4566 int dev_curr;
4567 err = hip_fns.hipGetDevice_fn (&dev_curr);
4568 if (!err && ord != dev_curr)
4569 err = hip_fns.hipSetDevice_fn (ord);
4570 if (!err)
4571 err = hip_fns.hipStreamCreate_fn ((hipStream_t *) &obj->stream);
4572 if (!err && ord != dev_curr)
4573 err = hip_fns.hipSetDevice_fn (dev_curr);
4574 if (err != 0)
4575 GOMP_PLUGIN_fatal ("Error creating interop hipStream_t: %d", err);
4576 }
4577 }
4578
4579 intptr_t
4580 GOMP_OFFLOAD_get_interop_int (struct interop_obj_t *obj,
4581 omp_interop_property_t property_id,
4582 omp_interop_rc_t *ret_code)
4583 {
4584 if (obj->fr != omp_ifr_hip && obj->fr != omp_ifr_hsa)
4585 {
4586 if (ret_code)
4587 *ret_code = omp_irc_no_value; /* Hmm. */
4588 return 0;
4589 }
4590 switch (property_id)
4591 {
4592 case omp_ipr_fr_id:
4593 if (ret_code)
4594 *ret_code = omp_irc_success;
4595 return obj->fr;
4596 case omp_ipr_fr_name:
4597 if (ret_code)
4598 *ret_code = omp_irc_type_str;
4599 return 0;
4600 case omp_ipr_vendor:
4601 if (ret_code)
4602 *ret_code = omp_irc_success;
4603 return 1; /* amd */
4604 case omp_ipr_vendor_name:
4605 if (ret_code)
4606 *ret_code = omp_irc_type_str;
4607 return 0;
4608 case omp_ipr_device_num:
4609 if (ret_code)
4610 *ret_code = omp_irc_success;
4611 return obj->device_num;
4612 case omp_ipr_platform:
4613 if (ret_code)
4614 *ret_code = omp_irc_no_value;
4615 return 0;
4616 case omp_ipr_device:
4617 if (obj->fr == omp_ifr_hsa)
4618 {
4619 if (ret_code)
4620 *ret_code = omp_irc_type_ptr;
4621 return 0;
4622 }
4623 if (ret_code)
4624 *ret_code = omp_irc_success;
4625 return ((struct agent_info *) obj->device_data)->device_id;
4626 case omp_ipr_device_context:
4627 if (ret_code && obj->fr == omp_ifr_hsa)
4628 *ret_code = omp_irc_no_value;
4629 else if (ret_code)
4630 *ret_code = omp_irc_type_ptr;
4631 return 0;
4632 case omp_ipr_targetsync:
4633 if (ret_code && !obj->stream)
4634 *ret_code = omp_irc_no_value;
4635 else if (ret_code)
4636 *ret_code = omp_irc_type_ptr;
4637 return 0;
4638 default:
4639 break;
4640 }
4641 __builtin_unreachable ();
4642 return 0;
4643 }
4644
4645 void *
4646 GOMP_OFFLOAD_get_interop_ptr (struct interop_obj_t *obj,
4647 omp_interop_property_t property_id,
4648 omp_interop_rc_t *ret_code)
4649 {
4650 if (obj->fr != omp_ifr_hip && obj->fr != omp_ifr_hsa)
4651 {
4652 if (ret_code)
4653 *ret_code = omp_irc_no_value; /* Hmm. */
4654 return 0;
4655 }
4656 switch (property_id)
4657 {
4658 case omp_ipr_fr_id:
4659 if (ret_code)
4660 *ret_code = omp_irc_type_int;
4661 return NULL;
4662 case omp_ipr_fr_name:
4663 if (ret_code)
4664 *ret_code = omp_irc_type_str;
4665 return NULL;
4666 case omp_ipr_vendor:
4667 if (ret_code)
4668 *ret_code = omp_irc_type_str;
4669 return NULL;
4670 case omp_ipr_vendor_name:
4671 if (ret_code)
4672 *ret_code = omp_irc_type_str;
4673 return NULL;
4674 case omp_ipr_device_num:
4675 if (ret_code)
4676 *ret_code = omp_irc_type_int;
4677 return NULL;
4678 case omp_ipr_platform:
4679 if (ret_code)
4680 *ret_code = omp_irc_no_value;
4681 return NULL;
4682 case omp_ipr_device:
4683 if (obj->fr == omp_ifr_hsa)
4684 {
4685 if (ret_code)
4686 *ret_code = omp_irc_success;
4687 /* hsa_agent_t is an struct containing a single uint64_t. */
4688 return &((struct agent_info *) obj->device_data)->id;
4689 }
4690 else
4691 {
4692 if (ret_code)
4693 *ret_code = omp_irc_type_int;
4694 return NULL;
4695 }
4696 case omp_ipr_device_context:
4697 if (obj->fr == omp_ifr_hsa)
4698 {
4699 if (ret_code)
4700 *ret_code = omp_irc_no_value;
4701 return NULL;
4702 }
4703 else
4704 {
4705 hipCtx_t ctx;
4706 int dev_curr;
4707 int dev = ((struct agent_info *) obj->device_data)->device_id;
4708 hipError_t err;
4709 err = hip_fns.hipGetDevice_fn (&dev_curr);
4710 if (!err && dev != dev_curr)
4711 err = hip_fns.hipSetDevice_fn (dev);
4712 if (!err)
4713 err = hip_fns.hipCtxGetCurrent_fn (&ctx);
4714 if (!err && dev != dev_curr)
4715 err = hip_fns.hipSetDevice_fn (dev_curr);
4716 if (err)
4717 GOMP_PLUGIN_fatal ("Error obtaining hipCtx_t for device %d: %d",
4718 obj->device_num, err);
4719 if (ret_code)
4720 *ret_code = omp_irc_success;
4721 return ctx;
4722 }
4723 case omp_ipr_targetsync:
4724 if (!obj->stream)
4725 {
4726 if (ret_code)
4727 *ret_code = omp_irc_no_value;
4728 return NULL;
4729 }
4730 if (ret_code)
4731 *ret_code = omp_irc_success;
4732 return obj->stream;
4733 default:
4734 break;
4735 }
4736 __builtin_unreachable ();
4737 return NULL;
4738 }
4739
4740 const char *
4741 GOMP_OFFLOAD_get_interop_str (struct interop_obj_t *obj,
4742 omp_interop_property_t property_id,
4743 omp_interop_rc_t *ret_code)
4744 {
4745 if (obj->fr != omp_ifr_hip && obj->fr != omp_ifr_hsa)
4746 {
4747 if (ret_code)
4748 *ret_code = omp_irc_no_value; /* Hmm. */
4749 return 0;
4750 }
4751 switch (property_id)
4752 {
4753 case omp_ipr_fr_id:
4754 if (ret_code)
4755 *ret_code = omp_irc_type_int;
4756 return NULL;
4757 case omp_ipr_fr_name:
4758 if (ret_code)
4759 *ret_code = omp_irc_success;
4760 if (obj->fr == omp_ifr_hip)
4761 return "hip";
4762 if (obj->fr == omp_ifr_hsa)
4763 return "hsa";
4764 case omp_ipr_vendor:
4765 if (ret_code)
4766 *ret_code = omp_irc_type_int;
4767 return NULL;
4768 case omp_ipr_vendor_name:
4769 if (ret_code)
4770 *ret_code = omp_irc_success;
4771 return "amd";
4772 case omp_ipr_device_num:
4773 if (ret_code)
4774 *ret_code = omp_irc_type_int;
4775 return NULL;
4776 case omp_ipr_platform:
4777 if (ret_code)
4778 *ret_code = omp_irc_no_value;
4779 return NULL;
4780 case omp_ipr_device:
4781 if (ret_code && obj->fr == omp_ifr_hsa)
4782 *ret_code = omp_irc_type_ptr;
4783 else if (ret_code)
4784 *ret_code = omp_irc_type_int;
4785 return NULL;
4786 case omp_ipr_device_context:
4787 if (ret_code && obj->fr == omp_ifr_hsa)
4788 *ret_code = omp_irc_no_value;
4789 else if (ret_code)
4790 *ret_code = omp_irc_type_ptr;
4791 return NULL;
4792 case omp_ipr_targetsync:
4793 if (ret_code && !obj->stream)
4794 *ret_code = omp_irc_no_value;
4795 else if (ret_code)
4796 *ret_code = omp_irc_type_ptr;
4797 return NULL;
4798 default:
4799 break;
4800 }
4801 __builtin_unreachable ();
4802 return 0;
4803 }
4804
4805 const char *
4806 GOMP_OFFLOAD_get_interop_type_desc (struct interop_obj_t *obj,
4807 omp_interop_property_t property_id)
4808 {
4809 _Static_assert (omp_ipr_targetsync == omp_ipr_first,
4810 "omp_ipr_targetsync == omp_ipr_first");
4811 _Static_assert (omp_ipr_platform - omp_ipr_first + 1 == 4,
4812 "omp_ipr_platform - omp_ipr_first + 1 == 4");
4813 static const char *desc_hip[] = {"N/A", /* platform */
4814 "hipDevice_t", /* device */
4815 "hipCtx_t", /* device_context */
4816 "hipStream_t"}; /* targetsync */
4817 static const char *desc_hsa[] = {"N/A", /* platform */
4818 "hsa_agent_t *", /* device */
4819 "N/A", /* device_context */
4820 "hsa_queue_t *"}; /* targetsync */
4821 if (obj->fr == omp_ifr_hip)
4822 return desc_hip[omp_ipr_platform - property_id];
4823 else
4824 return desc_hsa[omp_ipr_platform - property_id];
4825 return NULL;
4826 }
4827
4828 /* }}} */
4829 /* {{{ OpenMP Plugin API */
4830
4831 /* Run a synchronous OpenMP kernel on DEVICE and pass it an array of pointers
4832 in VARS as a parameter. The kernel is identified by FN_PTR which must point
4833 to a kernel_info structure, and must have previously been loaded to the
4834 specified device. */
4835
4836 void
4837 GOMP_OFFLOAD_run (int device, void *fn_ptr, void *vars, void **args)
4838 {
4839 struct agent_info *agent = get_agent_info (device);
4840 struct kernel_info *kernel = (struct kernel_info *) fn_ptr;
4841 struct GOMP_kernel_launch_attributes def;
4842 struct GOMP_kernel_launch_attributes *kla;
4843 assert (agent == kernel->agent);
4844
4845 /* If we get here then the kernel must be OpenMP. */
4846 kernel->kind = KIND_OPENMP;
4847
4848 if (!parse_target_attributes (args, &def, &kla, agent))
4849 {
4850 GCN_WARNING ("Will not run GCN kernel because the grid size is zero\n");
4851 return;
4852 }
4853 run_kernel (kernel, vars, kla, NULL, false);
4854 }
4855
4856 /* Run an asynchronous OpenMP kernel on DEVICE. This is similar to
4857 GOMP_OFFLOAD_run except that the launch is queued and there is a call to
4858 GOMP_PLUGIN_target_task_completion when it has finished. */
4859
4860 void
4861 GOMP_OFFLOAD_async_run (int device, void *tgt_fn, void *tgt_vars,
4862 void **args, void *async_data)
4863 {
4864 GCN_DEBUG ("GOMP_OFFLOAD_async_run invoked\n");
4865 struct agent_info *agent = get_agent_info (device);
4866 struct kernel_info *kernel = (struct kernel_info *) tgt_fn;
4867 struct GOMP_kernel_launch_attributes def;
4868 struct GOMP_kernel_launch_attributes *kla;
4869 assert (agent == kernel->agent);
4870
4871 /* If we get here then the kernel must be OpenMP. */
4872 kernel->kind = KIND_OPENMP;
4873
4874 if (!parse_target_attributes (args, &def, &kla, agent))
4875 {
4876 GCN_WARNING ("Will not run GCN kernel because the grid size is zero\n");
4877 return;
4878 }
4879
4880 maybe_init_omp_async (agent);
4881 if (!agent->omp_async_queue)
4882 GOMP_PLUGIN_fatal ("Asynchronous queue initialization failed");
4883 queue_push_launch (agent->omp_async_queue, kernel, tgt_vars, kla);
4884 queue_push_callback (agent->omp_async_queue,
4885 GOMP_PLUGIN_target_task_completion, async_data);
4886 }
4887
4888 /* }}} */
4889 /* {{{ OpenACC Plugin API */
4890
4891 /* Run a synchronous OpenACC kernel. The device number is inferred from the
4892 already-loaded KERNEL. */
4893
4894 void
4895 GOMP_OFFLOAD_openacc_exec (void (*fn_ptr) (void *),
4896 size_t mapnum __attribute__((unused)),
4897 void **hostaddrs __attribute__((unused)),
4898 void **devaddrs, unsigned *dims,
4899 void *targ_mem_desc)
4900 {
4901 struct kernel_info *kernel = (struct kernel_info *) fn_ptr;
4902
4903 gcn_exec (kernel, devaddrs, dims, targ_mem_desc, false, NULL);
4904 }
4905
4906 /* Run an asynchronous OpenACC kernel on the specified queue. */
4907
4908 void
4909 GOMP_OFFLOAD_openacc_async_exec (void (*fn_ptr) (void *),
4910 size_t mapnum __attribute__((unused)),
4911 void **hostaddrs __attribute__((unused)),
4912 void **devaddrs,
4913 unsigned *dims, void *targ_mem_desc,
4914 struct goacc_asyncqueue *aq)
4915 {
4916 struct kernel_info *kernel = (struct kernel_info *) fn_ptr;
4917
4918 gcn_exec (kernel, devaddrs, dims, targ_mem_desc, true, aq);
4919 }
4920
4921 /* Create a new asynchronous thread and queue for running future kernels. */
4922
4923 struct goacc_asyncqueue *
4924 GOMP_OFFLOAD_openacc_async_construct (int device)
4925 {
4926 struct agent_info *agent = get_agent_info (device);
4927
4928 pthread_mutex_lock (&agent->async_queues_mutex);
4929
4930 struct goacc_asyncqueue *aq = GOMP_PLUGIN_malloc (sizeof (*aq));
4931 aq->agent = get_agent_info (device);
4932 aq->prev = NULL;
4933 aq->next = agent->async_queues;
4934 if (aq->next)
4935 {
4936 aq->next->prev = aq;
4937 aq->id = aq->next->id + 1;
4938 }
4939 else
4940 aq->id = 1;
4941 agent->async_queues = aq;
4942
4943 aq->queue_first = 0;
4944 aq->queue_n = 0;
4945 aq->drain_queue_stop = 0;
4946
4947 if (pthread_mutex_init (&aq->mutex, NULL))
4948 {
4949 GOMP_PLUGIN_error ("Failed to initialize a GCN agent queue mutex");
4950 return NULL;
4951 }
4952 if (pthread_cond_init (&aq->queue_cond_in, NULL))
4953 {
4954 GOMP_PLUGIN_error ("Failed to initialize a GCN agent queue cond");
4955 return NULL;
4956 }
4957 if (pthread_cond_init (&aq->queue_cond_out, NULL))
4958 {
4959 GOMP_PLUGIN_error ("Failed to initialize a GCN agent queue cond");
4960 return NULL;
4961 }
4962
4963 hsa_status_t status = hsa_fns.hsa_queue_create_fn (agent->id,
4964 ASYNC_QUEUE_SIZE,
4965 HSA_QUEUE_TYPE_MULTI,
4966 hsa_queue_callback, NULL,
4967 UINT32_MAX, UINT32_MAX,
4968 &aq->hsa_queue);
4969 if (status != HSA_STATUS_SUCCESS)
4970 hsa_fatal ("Error creating command queue", status);
4971
4972 int err = pthread_create (&aq->thread_drain_queue, NULL, &drain_queue, aq);
4973 if (err != 0)
4974 GOMP_PLUGIN_fatal ("GCN asynchronous thread creation failed: %s",
4975 strerror (err));
4976 GCN_DEBUG ("Async thread %d:%d: created\n", aq->agent->device_id,
4977 aq->id);
4978
4979 pthread_mutex_unlock (&agent->async_queues_mutex);
4980
4981 return aq;
4982 }
4983
4984 /* Destroy an existing asynchronous thread and queue. Waits for any
4985 currently-running task to complete, but cancels any queued tasks. */
4986
4987 bool
4988 GOMP_OFFLOAD_openacc_async_destruct (struct goacc_asyncqueue *aq)
4989 {
4990 struct agent_info *agent = aq->agent;
4991
4992 finalize_async_thread (aq);
4993
4994 pthread_mutex_lock (&agent->async_queues_mutex);
4995
4996 int err;
4997 if ((err = pthread_mutex_destroy (&aq->mutex)))
4998 {
4999 GOMP_PLUGIN_error ("Failed to destroy a GCN async queue mutex: %d", err);
5000 goto fail;
5001 }
5002 if (pthread_cond_destroy (&aq->queue_cond_in))
5003 {
5004 GOMP_PLUGIN_error ("Failed to destroy a GCN async queue cond");
5005 goto fail;
5006 }
5007 if (pthread_cond_destroy (&aq->queue_cond_out))
5008 {
5009 GOMP_PLUGIN_error ("Failed to destroy a GCN async queue cond");
5010 goto fail;
5011 }
5012 hsa_status_t status = hsa_fns.hsa_queue_destroy_fn (aq->hsa_queue);
5013 if (status != HSA_STATUS_SUCCESS)
5014 {
5015 hsa_error ("Error destroying command queue", status);
5016 goto fail;
5017 }
5018
5019 if (aq->prev)
5020 aq->prev->next = aq->next;
5021 if (aq->next)
5022 aq->next->prev = aq->prev;
5023 if (agent->async_queues == aq)
5024 agent->async_queues = aq->next;
5025
5026 GCN_DEBUG ("Async thread %d:%d: destroyed\n", agent->device_id, aq->id);
5027
5028 free (aq);
5029 pthread_mutex_unlock (&agent->async_queues_mutex);
5030 return true;
5031
5032 fail:
5033 pthread_mutex_unlock (&agent->async_queues_mutex);
5034 return false;
5035 }
5036
5037 /* Return true if the specified async queue is currently empty. */
5038
5039 int
5040 GOMP_OFFLOAD_openacc_async_test (struct goacc_asyncqueue *aq)
5041 {
5042 return queue_empty (aq);
5043 }
5044
5045 /* Block until the specified queue has executed all its tasks and the
5046 queue is empty. */
5047
5048 bool
5049 GOMP_OFFLOAD_openacc_async_synchronize (struct goacc_asyncqueue *aq)
5050 {
5051 wait_queue (aq);
5052 return true;
5053 }
5054
5055 /* Add a serialization point across two async queues. Any new tasks added to
5056 AQ2, after this call, will not run until all tasks on AQ1, at the time
5057 of this call, have completed. */
5058
5059 bool
5060 GOMP_OFFLOAD_openacc_async_serialize (struct goacc_asyncqueue *aq1,
5061 struct goacc_asyncqueue *aq2)
5062 {
5063 /* For serialize, stream aq2 waits for aq1 to complete work that has been
5064 scheduled to run on it up to this point. */
5065 if (aq1 != aq2)
5066 {
5067 struct placeholder *placeholderp = queue_push_placeholder (aq1);
5068 queue_push_asyncwait (aq2, placeholderp);
5069 }
5070 return true;
5071 }
5072
5073 /* Add an opaque callback to the given async queue. */
5074
5075 void
5076 GOMP_OFFLOAD_openacc_async_queue_callback (struct goacc_asyncqueue *aq,
5077 void (*fn) (void *), void *data)
5078 {
5079 queue_push_callback (aq, fn, data);
5080 }
5081
5082 /* Queue up an asynchronous data copy from host to DEVICE. */
5083
5084 bool
5085 GOMP_OFFLOAD_openacc_async_host2dev (int device, void *dst, const void *src,
5086 size_t n, struct goacc_asyncqueue *aq)
5087 {
5088 struct agent_info *agent = get_agent_info (device);
5089 assert (agent == aq->agent);
5090 queue_push_copy (aq, dst, src, n);
5091 return true;
5092 }
5093
5094 /* Queue up an asynchronous data copy from DEVICE to host. */
5095
5096 bool
5097 GOMP_OFFLOAD_openacc_async_dev2host (int device, void *dst, const void *src,
5098 size_t n, struct goacc_asyncqueue *aq)
5099 {
5100 struct agent_info *agent = get_agent_info (device);
5101 assert (agent == aq->agent);
5102 queue_push_copy (aq, dst, src, n);
5103 return true;
5104 }
5105
5106 union goacc_property_value
5107 GOMP_OFFLOAD_openacc_get_property (int device, enum goacc_property prop)
5108 {
5109 struct agent_info *agent = get_agent_info (device);
5110
5111 union goacc_property_value propval = { .val = 0 };
5112
5113 switch (prop)
5114 {
5115 case GOACC_PROPERTY_FREE_MEMORY:
5116 /* Not supported. */
5117 break;
5118 case GOACC_PROPERTY_MEMORY:
5119 {
5120 size_t size;
5121 hsa_region_t region = agent->data_region;
5122 hsa_status_t status =
5123 hsa_fns.hsa_region_get_info_fn (region, HSA_REGION_INFO_SIZE, &size);
5124 if (status == HSA_STATUS_SUCCESS)
5125 propval.val = size;
5126 break;
5127 }
5128 case GOACC_PROPERTY_NAME:
5129 propval.ptr = agent->name;
5130 break;
5131 case GOACC_PROPERTY_VENDOR:
5132 propval.ptr = agent->vendor_name;
5133 break;
5134 case GOACC_PROPERTY_DRIVER:
5135 propval.ptr = hsa_context.driver_version_s;
5136 break;
5137 }
5138
5139 return propval;
5140 }
5141
5142 /* Set up plugin-specific thread-local-data (host-side). */
5143
5144 void *
5145 GOMP_OFFLOAD_openacc_create_thread_data (int ord __attribute__((unused)))
5146 {
5147 struct gcn_thread *thread_data
5148 = GOMP_PLUGIN_malloc (sizeof (struct gcn_thread));
5149
5150 thread_data->async = GOMP_ASYNC_SYNC;
5151
5152 return (void *) thread_data;
5153 }
5154
5155 /* Clean up plugin-specific thread-local-data. */
5156
5157 void
5158 GOMP_OFFLOAD_openacc_destroy_thread_data (void *data)
5159 {
5160 free (data);
5161 }
5162
5163 /* }}} */