Debian Codegraph @

libgomp/plugin/plugin-nvptx.c

raw
1 /* Plugin for NVPTX 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 /* Nvidia PTX-specific parts of OpenACC support. The cuda driver
30 library appears to hold some implicit state, but the documentation
31 is not clear as to what that state might be. Or how one might
32 propagate it from one thread to another. */
33
34 #define _GNU_SOURCE
35 #include "openacc.h"
36 #include "config.h"
37 #include "symcat.h"
38 #define _LIBGOMP_PLUGIN_INCLUDE 1
39 #include "libgomp-plugin.h"
40 #undef _LIBGOMP_PLUGIN_INCLUDE
41 #include "oacc-plugin.h"
42 #include "gomp-constants.h"
43 #include "oacc-int.h"
44
45 /* For struct rev_offload + GOMP_REV_OFFLOAD_VAR. */
46 #include "config/nvptx/libgomp-nvptx.h"
47
48 #include <pthread.h>
49 #ifndef PLUGIN_NVPTX_INCLUDE_SYSTEM_CUDA_H
50 # include "cuda/cuda.h"
51 #else
52 # include <cuda.h>
53 #endif
54 #include <stdbool.h>
55 #include <limits.h>
56 #include <string.h>
57 #include <stdio.h>
58 #include <unistd.h>
59 #include <assert.h>
60 #include <errno.h>
61 #include <stdlib.h>
62
63 /* An arbitrary fixed limit (128MB) for the size of the OpenMP soft stacks
64 block to cache between kernel invocations. For soft-stacks blocks bigger
65 than this, we will free the block before attempting another GPU memory
66 allocation (i.e. in GOMP_OFFLOAD_alloc). Otherwise, if an allocation fails,
67 we will free the cached soft-stacks block anyway then retry the
68 allocation. If that fails too, we lose. */
69
70 #define SOFTSTACK_CACHE_LIMIT 134217728
71
72 #if CUDA_VERSION < 6000
73 extern CUresult cuGetErrorString (CUresult, const char **);
74 #define CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR 82
75 #endif
76
77 #if CUDA_VERSION >= 6050
78 #undef cuLinkCreate
79 #undef cuLinkAddData
80 CUresult cuLinkAddData (CUlinkState, CUjitInputType, void *, size_t,
81 const char *, unsigned, CUjit_option *, void **);
82 CUresult cuLinkCreate (unsigned, CUjit_option *, void **, CUlinkState *);
83 #else
84 typedef size_t (*CUoccupancyB2DSize)(int);
85 CUresult cuLinkAddData_v2 (CUlinkState, CUjitInputType, void *, size_t,
86 const char *, unsigned, CUjit_option *, void **);
87 CUresult cuLinkCreate_v2 (unsigned, CUjit_option *, void **, CUlinkState *);
88 CUresult cuOccupancyMaxPotentialBlockSize(int *, int *, CUfunction,
89 CUoccupancyB2DSize, size_t, int);
90 #endif
91
92 #define DO_PRAGMA(x) _Pragma (#x)
93
94 #ifndef PLUGIN_NVPTX_LINK_LIBCUDA
95 # include <dlfcn.h>
96
97 struct cuda_lib_s {
98
99 # define CUDA_ONE_CALL(call) \
100 __typeof (call) *call;
101 # define CUDA_ONE_CALL_MAYBE_NULL(call) \
102 CUDA_ONE_CALL (call)
103 #include "cuda-lib.def"
104 # undef CUDA_ONE_CALL
105 # undef CUDA_ONE_CALL_MAYBE_NULL
106
107 } cuda_lib;
108
109 /* -1 if init_cuda_lib has not been called yet, false
110 if it has been and failed, true if it has been and succeeded. */
111 static signed char cuda_lib_inited = -1;
112
113 /* Dynamically load the CUDA runtime library and initialize function
114 pointers, return false if unsuccessful, true if successful. */
115 static bool
116 init_cuda_lib (void)
117 {
118 if (cuda_lib_inited != -1)
119 return cuda_lib_inited;
120 const char *cuda_runtime_lib = "libcuda.so.1";
121 void *h = dlopen (cuda_runtime_lib, RTLD_LAZY);
122 cuda_lib_inited = false;
123 if (h == NULL)
124 return false;
125
126 # define CUDA_ONE_CALL(call) CUDA_ONE_CALL_1 (call, false)
127 # define CUDA_ONE_CALL_MAYBE_NULL(call) CUDA_ONE_CALL_1 (call, true)
128 # define CUDA_ONE_CALL_1(call, allow_null) \
129 cuda_lib.call = dlsym (h, #call); \
130 if (!allow_null && cuda_lib.call == NULL) \
131 GOMP_PLUGIN_fatal ("'%s' is missing '%s'", cuda_runtime_lib, #call);
132 #include "cuda-lib.def"
133 # undef CUDA_ONE_CALL
134 # undef CUDA_ONE_CALL_1
135 # undef CUDA_ONE_CALL_MAYBE_NULL
136
137 cuda_lib_inited = true;
138 return true;
139 }
140 # define CUDA_CALL_PREFIX cuda_lib.
141 #else
142
143 # define CUDA_ONE_CALL(call)
144 # define CUDA_ONE_CALL_MAYBE_NULL(call) DO_PRAGMA (weak call)
145 #include "cuda-lib.def"
146 #undef CUDA_ONE_CALL_MAYBE_NULL
147 #undef CUDA_ONE_CALL
148
149 # define CUDA_CALL_PREFIX
150 # define init_cuda_lib() true
151 #endif
152
153 #include "secure_getenv.h"
154
155 static void notify_var (const char *, const char *);
156
157 #undef MIN
158 #undef MAX
159 #define MIN(X,Y) ((X) < (Y) ? (X) : (Y))
160 #define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
161
162 /* Convenience macros for the frequently used CUDA library call and
163 error handling sequence as well as CUDA library calls that
164 do the error checking themselves or don't do it at all. */
165
166 #define CUDA_CALL_ERET(ERET, FN, ...) \
167 do { \
168 unsigned __r \
169 = CUDA_CALL_PREFIX FN (__VA_ARGS__); \
170 if (__r != CUDA_SUCCESS) \
171 { \
172 GOMP_PLUGIN_error (#FN " error: %s", \
173 cuda_error (__r)); \
174 return ERET; \
175 } \
176 } while (0)
177
178 #define CUDA_CALL(FN, ...) \
179 CUDA_CALL_ERET (false, FN, __VA_ARGS__)
180
181 #define CUDA_CALL_ASSERT(FN, ...) \
182 do { \
183 unsigned __r \
184 = CUDA_CALL_PREFIX FN (__VA_ARGS__); \
185 if (__r != CUDA_SUCCESS) \
186 { \
187 GOMP_PLUGIN_fatal (#FN " error: %s", \
188 cuda_error (__r)); \
189 } \
190 } while (0)
191
192 #define CUDA_CALL_NOCHECK(FN, ...) \
193 CUDA_CALL_PREFIX FN (__VA_ARGS__)
194
195 #define CUDA_CALL_EXISTS(FN) \
196 CUDA_CALL_PREFIX FN
197
198 static const char *
199 cuda_error (CUresult r)
200 {
201 const char *fallback = "unknown cuda error";
202 const char *desc;
203
204 if (!CUDA_CALL_EXISTS (cuGetErrorString))
205 return fallback;
206
207 r = CUDA_CALL_NOCHECK (cuGetErrorString, r, &desc);
208 if (r == CUDA_SUCCESS)
209 return desc;
210
211 return fallback;
212 }
213
214 /* Version of the CUDA Toolkit in the same MAJOR.MINOR format that is used by
215 Nvidia, such as in the 'deviceQuery' program (Nvidia's CUDA samples). */
216 static char cuda_driver_version_s[30];
217
218 static unsigned int instantiated_devices = 0;
219 static pthread_mutex_t ptx_dev_lock = PTHREAD_MUTEX_INITIALIZER;
220
221 /* NVPTX/CUDA specific definition of asynchronous queues. */
222 struct goacc_asyncqueue
223 {
224 CUstream cuda_stream;
225 };
226
227 struct nvptx_callback
228 {
229 void (*fn) (void *);
230 void *ptr;
231 struct goacc_asyncqueue *aq;
232 struct nvptx_callback *next;
233 };
234
235 /* Thread-specific data for PTX. */
236
237 struct nvptx_thread
238 {
239 /* We currently have this embedded inside the plugin because libgomp manages
240 devices through integer target_ids. This might be better if using an
241 opaque target-specific pointer directly from gomp_device_descr. */
242 struct ptx_device *ptx_dev;
243 };
244
245 /* Target data function launch information. */
246
247 struct targ_fn_launch
248 {
249 const char *fn;
250 unsigned short dim[GOMP_DIM_MAX];
251 };
252
253 /* Target PTX object information. */
254
255 struct targ_ptx_obj
256 {
257 const char *code;
258 size_t size;
259 };
260
261 /* Target data image information. */
262
263 typedef struct nvptx_tdata
264 {
265 const struct targ_ptx_obj *ptx_objs;
266 unsigned ptx_num;
267
268 const char *const *var_names;
269 unsigned var_num;
270
271 const struct targ_fn_launch *fn_descs;
272 unsigned fn_num;
273
274 unsigned ind_fn_num;
275 } nvptx_tdata_t;
276
277 /* Descriptor of a loaded function. */
278
279 struct targ_fn_descriptor
280 {
281 CUfunction fn;
282 const struct targ_fn_launch *launch;
283 int regs_per_thread;
284 int max_threads_per_block;
285 };
286
287 /* A loaded PTX image. */
288 struct ptx_image_data
289 {
290 const void *target_data;
291 CUmodule module;
292
293 struct targ_fn_descriptor *fns; /* Array of functions. */
294
295 struct ptx_image_data *next;
296 };
297
298 struct ptx_free_block
299 {
300 void *ptr;
301 struct ptx_free_block *next;
302 };
303
304 struct ptx_device
305 {
306 CUcontext ctx;
307 bool ctx_shared;
308 CUdevice dev;
309
310 int ord;
311 bool overlap;
312 bool map;
313 bool concur;
314 bool mkern;
315 int mode;
316 int clock_khz;
317 int num_sms;
318 int regs_per_block;
319 int regs_per_sm;
320 int warp_size;
321 int max_threads_per_block;
322 int max_threads_per_multiprocessor;
323 int default_dims[GOMP_DIM_MAX];
324
325 /* Length as used by the CUDA Runtime API ('struct cudaDeviceProp'). */
326 char name[256];
327
328 struct ptx_image_data *images; /* Images loaded on device. */
329 pthread_mutex_t image_lock; /* Lock for above list. */
330
331 struct ptx_free_block *free_blocks;
332 pthread_mutex_t free_blocks_lock;
333
334 /* OpenMP stacks, cached between kernel invocations. */
335 struct
336 {
337 CUdeviceptr ptr;
338 size_t size;
339 pthread_mutex_t lock;
340 } omp_stacks;
341
342 struct rev_offload *rev_data;
343 struct ptx_device *next;
344 };
345
346 static struct ptx_device **ptx_devices;
347
348 /* "Native" GPU thread stack size. */
349 static unsigned native_gpu_thread_stack_size = 0;
350
351 /* OpenMP kernels reserve a small amount of ".shared" space for use by
352 omp_alloc. The size is configured using GOMP_NVPTX_LOWLAT_POOL, but the
353 default is set here. */
354 static unsigned lowlat_pool_size = 8 * 1024;
355
356 static bool nvptx_do_global_cdtors (CUmodule, struct ptx_device *,
357 const char *);
358 static size_t nvptx_stacks_size ();
359 static void *nvptx_stacks_acquire (struct ptx_device *, size_t, int);
360
361 static inline struct nvptx_thread *
362 nvptx_thread (void)
363 {
364 return (struct nvptx_thread *) GOMP_PLUGIN_acc_thread ();
365 }
366
367 /* Initialize the device. Return TRUE on success, else FALSE. PTX_DEV_LOCK
368 should be locked on entry and remains locked on exit. */
369
370 static bool
371 nvptx_init (void)
372 {
373 int ndevs;
374
375 if (instantiated_devices != 0)
376 return true;
377
378 if (!init_cuda_lib ())
379 return false;
380
381 CUDA_CALL (cuInit, 0);
382
383 int cuda_driver_version;
384 CUDA_CALL_ERET (NULL, cuDriverGetVersion, &cuda_driver_version);
385 snprintf (cuda_driver_version_s, sizeof cuda_driver_version_s,
386 "CUDA Driver %u.%u",
387 cuda_driver_version / 1000, cuda_driver_version % 1000 / 10);
388
389 CUDA_CALL (cuDeviceGetCount, &ndevs);
390 ptx_devices = GOMP_PLUGIN_malloc_cleared (sizeof (struct ptx_device *)
391 * ndevs);
392
393 return true;
394 }
395
396 /* Select the N'th PTX device for the current host thread. The device must
397 have been previously opened before calling this function. */
398
399 static bool
400 nvptx_attach_host_thread_to_device (int n)
401 {
402 CUdevice dev;
403 CUresult r;
404 struct ptx_device *ptx_dev;
405 CUcontext thd_ctx;
406
407 r = CUDA_CALL_NOCHECK (cuCtxGetDevice, &dev);
408 if (r == CUDA_ERROR_NOT_PERMITTED)
409 {
410 /* Assume we're in a CUDA callback, just return true. */
411 return true;
412 }
413 if (r != CUDA_SUCCESS && r != CUDA_ERROR_INVALID_CONTEXT)
414 {
415 GOMP_PLUGIN_error ("cuCtxGetDevice error: %s", cuda_error (r));
416 return false;
417 }
418
419 if (r != CUDA_ERROR_INVALID_CONTEXT && dev == n)
420 return true;
421 else
422 {
423 CUcontext old_ctx;
424
425 ptx_dev = ptx_devices[n];
426 if (!ptx_dev)
427 {
428 GOMP_PLUGIN_error ("device %d not found", n);
429 return false;
430 }
431
432 CUDA_CALL (cuCtxGetCurrent, &thd_ctx);
433
434 /* We don't necessarily have a current context (e.g. if it has been
435 destroyed. Pop it if we do though. */
436 if (thd_ctx != NULL)
437 CUDA_CALL (cuCtxPopCurrent, &old_ctx);
438
439 CUDA_CALL (cuCtxPushCurrent, ptx_dev->ctx);
440 }
441 return true;
442 }
443
444 static struct ptx_device *
445 nvptx_open_device (int n)
446 {
447 struct ptx_device *ptx_dev;
448 CUdevice dev, ctx_dev;
449 CUresult r;
450 int pi;
451
452 CUDA_CALL_ERET (NULL, cuDeviceGet, &dev, n);
453
454 ptx_dev = GOMP_PLUGIN_malloc (sizeof (struct ptx_device));
455
456 ptx_dev->ord = n;
457 ptx_dev->dev = dev;
458 ptx_dev->ctx_shared = false;
459
460 r = CUDA_CALL_NOCHECK (cuCtxGetDevice, &ctx_dev);
461 if (r != CUDA_SUCCESS && r != CUDA_ERROR_INVALID_CONTEXT)
462 {
463 GOMP_PLUGIN_error ("cuCtxGetDevice error: %s", cuda_error (r));
464 return NULL;
465 }
466
467 if (r != CUDA_ERROR_INVALID_CONTEXT && ctx_dev != dev)
468 {
469 /* The current host thread has an active context for a different device.
470 Detach it. */
471 CUcontext old_ctx;
472 CUDA_CALL_ERET (NULL, cuCtxPopCurrent, &old_ctx);
473 }
474
475 CUDA_CALL_ERET (NULL, cuCtxGetCurrent, &ptx_dev->ctx);
476
477 if (!ptx_dev->ctx)
478 CUDA_CALL_ERET (NULL, cuCtxCreate, &ptx_dev->ctx, CU_CTX_SCHED_AUTO, dev);
479 else
480 ptx_dev->ctx_shared = true;
481
482 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
483 &pi, CU_DEVICE_ATTRIBUTE_GPU_OVERLAP, dev);
484 ptx_dev->overlap = pi;
485
486 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
487 &pi, CU_DEVICE_ATTRIBUTE_CAN_MAP_HOST_MEMORY, dev);
488 ptx_dev->map = pi;
489
490 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
491 &pi, CU_DEVICE_ATTRIBUTE_CONCURRENT_KERNELS, dev);
492 ptx_dev->concur = pi;
493
494 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
495 &pi, CU_DEVICE_ATTRIBUTE_COMPUTE_MODE, dev);
496 ptx_dev->mode = pi;
497
498 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
499 &pi, CU_DEVICE_ATTRIBUTE_INTEGRATED, dev);
500 ptx_dev->mkern = pi;
501
502 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
503 &pi, CU_DEVICE_ATTRIBUTE_CLOCK_RATE, dev);
504 ptx_dev->clock_khz = pi;
505
506 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
507 &pi, CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT, dev);
508 ptx_dev->num_sms = pi;
509
510 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
511 &pi, CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_BLOCK, dev);
512 ptx_dev->regs_per_block = pi;
513
514 /* CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR is defined only
515 in CUDA 6.0 and newer. */
516 r = CUDA_CALL_NOCHECK (cuDeviceGetAttribute, &pi,
517 CU_DEVICE_ATTRIBUTE_MAX_REGISTERS_PER_MULTIPROCESSOR,
518 dev);
519 /* Fallback: use limit of registers per block, which is usually equal. */
520 if (r == CUDA_ERROR_INVALID_VALUE)
521 pi = ptx_dev->regs_per_block;
522 else if (r != CUDA_SUCCESS)
523 {
524 GOMP_PLUGIN_error ("cuDeviceGetAttribute error: %s", cuda_error (r));
525 return NULL;
526 }
527 ptx_dev->regs_per_sm = pi;
528
529 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute,
530 &pi, CU_DEVICE_ATTRIBUTE_WARP_SIZE, dev);
531 if (pi != 32)
532 {
533 GOMP_PLUGIN_error ("Only warp size 32 is supported");
534 return NULL;
535 }
536 ptx_dev->warp_size = pi;
537
538 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute, &pi,
539 CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK, dev);
540 ptx_dev->max_threads_per_block = pi;
541
542 CUDA_CALL_ERET (NULL, cuDeviceGetAttribute, &pi,
543 CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_MULTIPROCESSOR, dev);
544 ptx_dev->max_threads_per_multiprocessor = pi;
545
546 /* Required below for reverse offload as implemented, but with compute
547 capability >= 2.0 and 64bit device processes, this should be universally be
548 the case; hence, an assert. */
549 r = CUDA_CALL_NOCHECK (cuDeviceGetAttribute, &pi,
550 CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING, dev);
551 assert (r == CUDA_SUCCESS && pi);
552
553 for (int i = 0; i != GOMP_DIM_MAX; i++)
554 ptx_dev->default_dims[i] = 0;
555
556 CUDA_CALL_ERET (NULL, cuDeviceGetName, ptx_dev->name, sizeof ptx_dev->name,
557 dev);
558
559 ptx_dev->images = NULL;
560 pthread_mutex_init (&ptx_dev->image_lock, NULL);
561
562 ptx_dev->free_blocks = NULL;
563 pthread_mutex_init (&ptx_dev->free_blocks_lock, NULL);
564
565 /* "Native" GPU thread stack size. */
566 {
567 /* This is intentionally undocumented, until we work out a proper, common
568 scheme (as much as makes sense) between all offload plugins as well
569 as between nvptx offloading use of "native" stacks for OpenACC vs.
570 OpenMP "soft stacks" vs. OpenMP '-msoft-stack-reserve-local=[...]'.
571
572 GCN offloading has a 'GCN_STACK_SIZE' environment variable (without
573 'GOMP_' prefix): documented; presumably used for all things OpenACC and
574 OpenMP? Based on GCN command-line option '-mstack-size=[...]' (marked
575 "obsolete"), that one may be set via a GCN 'mkoffload'-synthesized
576 'constructor' function. */
577 const char *var_name = "GOMP_NVPTX_NATIVE_GPU_THREAD_STACK_SIZE";
578 const char *env_var = secure_getenv (var_name);
579 notify_var (var_name, env_var);
580
581 if (env_var != NULL)
582 {
583 char *endptr;
584 unsigned long val = strtoul (env_var, &endptr, 10);
585 if (endptr == NULL || *endptr != '\0'
586 || errno == ERANGE || errno == EINVAL
587 || val > UINT_MAX)
588 GOMP_PLUGIN_error ("Error parsing %s", var_name);
589 else
590 native_gpu_thread_stack_size = val;
591 }
592 }
593 if (native_gpu_thread_stack_size == 0)
594 ; /* Zero means use default. */
595 else
596 {
597 GOMP_PLUGIN_debug (0, "Setting \"native\" GPU thread stack size"
598 " ('CU_LIMIT_STACK_SIZE') to %u bytes\n",
599 native_gpu_thread_stack_size);
600 CUDA_CALL_ERET (NULL,
601 cuCtxSetLimit,
602 CU_LIMIT_STACK_SIZE,
603 (size_t) native_gpu_thread_stack_size);
604 }
605
606 /* OpenMP "soft stacks". */
607 ptx_dev->omp_stacks.ptr = 0;
608 ptx_dev->omp_stacks.size = 0;
609 pthread_mutex_init (&ptx_dev->omp_stacks.lock, NULL);
610
611 ptx_dev->rev_data = NULL;
612
613 return ptx_dev;
614 }
615
616 static bool
617 nvptx_close_device (struct ptx_device *ptx_dev)
618 {
619 if (!ptx_dev)
620 return true;
621
622 bool ret = true;
623
624 for (struct ptx_image_data *image = ptx_dev->images;
625 image != NULL;
626 image = image->next)
627 {
628 if (!nvptx_do_global_cdtors (image->module, ptx_dev,
629 "__do_global_dtors__entry"
630 /* or "__do_global_dtors__entry__mgomp" */))
631 ret = false;
632 }
633
634 for (struct ptx_free_block *b = ptx_dev->free_blocks; b;)
635 {
636 struct ptx_free_block *b_next = b->next;
637 CUDA_CALL (cuMemFree, (CUdeviceptr) b->ptr);
638 free (b);
639 b = b_next;
640 }
641
642 pthread_mutex_destroy (&ptx_dev->free_blocks_lock);
643 pthread_mutex_destroy (&ptx_dev->image_lock);
644
645 pthread_mutex_destroy (&ptx_dev->omp_stacks.lock);
646
647 if (ptx_dev->omp_stacks.ptr)
648 CUDA_CALL (cuMemFree, ptx_dev->omp_stacks.ptr);
649
650 if (!ptx_dev->ctx_shared)
651 CUDA_CALL (cuCtxDestroy, ptx_dev->ctx);
652
653 free (ptx_dev);
654
655 return ret;
656 }
657
658 static int
659 nvptx_get_num_devices (void)
660 {
661 int n;
662
663 /* This function will be called before the plugin has been initialized in
664 order to enumerate available devices, but CUDA API routines can't be used
665 until cuInit has been called. Just call it now (but don't yet do any
666 further initialization). */
667 if (instantiated_devices == 0)
668 {
669 if (!init_cuda_lib ())
670 return 0;
671 CUresult r = CUDA_CALL_NOCHECK (cuInit, 0);
672 /* This is not an error: e.g. we may have CUDA libraries installed but
673 no devices available. */
674 if (r == CUDA_ERROR_NO_DEVICE)
675 {
676 GOMP_PLUGIN_debug (0, "Disabling nvptx offloading; cuInit: %s\n",
677 cuda_error (r));
678 return 0;
679 }
680 else if (r != CUDA_SUCCESS)
681 GOMP_PLUGIN_fatal ("cuInit error: %s", cuda_error (r));
682 }
683
684 CUDA_CALL_ASSERT (cuDeviceGetCount, &n);
685 return n;
686 }
687
688 static void
689 notify_var (const char *var_name, const char *env_var)
690 {
691 if (env_var == NULL)
692 GOMP_PLUGIN_debug (0, "%s: <Not defined>\n", var_name);
693 else
694 GOMP_PLUGIN_debug (0, "%s: '%s'\n", var_name, env_var);
695 }
696
697 static void
698 process_GOMP_NVPTX_JIT (intptr_t *gomp_nvptx_o)
699 {
700 const char *var_name = "GOMP_NVPTX_JIT";
701 const char *env_var = secure_getenv (var_name);
702 notify_var (var_name, env_var);
703
704 if (env_var == NULL)
705 return;
706
707 const char *c = env_var;
708 while (*c != '\0')
709 {
710 while (*c == ' ')
711 c++;
712
713 if (c[0] == '-' && c[1] == 'O'
714 && '0' <= c[2] && c[2] <= '4'
715 && (c[3] == '\0' || c[3] == ' '))
716 {
717 *gomp_nvptx_o = c[2] - '0';
718 c += 3;
719 continue;
720 }
721
722 GOMP_PLUGIN_error ("Error parsing %s", var_name);
723 break;
724 }
725 }
726
727 static bool
728 link_ptx (CUmodule *module, const struct targ_ptx_obj *ptx_objs,
729 unsigned num_objs)
730 {
731 CUjit_option opts[7];
732 void *optvals[7];
733 float elapsed = 0.0;
734 char elog[1024];
735 char ilog[16384];
736 CUlinkState linkstate;
737 CUresult r;
738 void *linkout;
739 size_t linkoutsize __attribute__ ((unused));
740
741 opts[0] = CU_JIT_WALL_TIME;
742 optvals[0] = &elapsed;
743
744 opts[1] = CU_JIT_INFO_LOG_BUFFER;
745 optvals[1] = &ilog[0];
746
747 opts[2] = CU_JIT_INFO_LOG_BUFFER_SIZE_BYTES;
748 optvals[2] = (void *) sizeof ilog;
749
750 opts[3] = CU_JIT_ERROR_LOG_BUFFER;
751 optvals[3] = &elog[0];
752
753 opts[4] = CU_JIT_ERROR_LOG_BUFFER_SIZE_BYTES;
754 optvals[4] = (void *) sizeof elog;
755
756 opts[5] = CU_JIT_LOG_VERBOSE;
757 optvals[5] = (void *) 1;
758
759 static intptr_t gomp_nvptx_o = -1;
760
761 static bool init_done = false;
762 if (!init_done)
763 {
764 process_GOMP_NVPTX_JIT (&gomp_nvptx_o);
765 init_done = true;
766 }
767
768 int nopts = 6;
769 if (gomp_nvptx_o != -1)
770 {
771 opts[nopts] = CU_JIT_OPTIMIZATION_LEVEL;
772 optvals[nopts] = (void *) gomp_nvptx_o;
773 nopts++;
774 }
775
776 if (CUDA_CALL_EXISTS (cuLinkCreate_v2))
777 CUDA_CALL (cuLinkCreate_v2, nopts, opts, optvals, &linkstate);
778 else
779 CUDA_CALL (cuLinkCreate, nopts, opts, optvals, &linkstate);
780
781 for (; num_objs--; ptx_objs++)
782 {
783 /* cuLinkAddData's 'data' argument erroneously omits the const
784 qualifier. */
785 GOMP_PLUGIN_debug (0, "Loading:\n---\n%s\n---\n", ptx_objs->code);
786 if (CUDA_CALL_EXISTS (cuLinkAddData_v2))
787 r = CUDA_CALL_NOCHECK (cuLinkAddData_v2, linkstate, CU_JIT_INPUT_PTX,
788 (char *) ptx_objs->code, ptx_objs->size,
789 0, 0, 0, 0);
790 else
791 r = CUDA_CALL_NOCHECK (cuLinkAddData, linkstate, CU_JIT_INPUT_PTX,
792 (char *) ptx_objs->code, ptx_objs->size,
793 0, 0, 0, 0);
794 if (r != CUDA_SUCCESS)
795 {
796 GOMP_PLUGIN_error ("Link error log %s\n", &elog[0]);
797 GOMP_PLUGIN_error ("cuLinkAddData (ptx_code) error: %s",
798 cuda_error (r));
799 return false;
800 }
801 }
802
803 GOMP_PLUGIN_debug (0, "Linking\n");
804 r = CUDA_CALL_NOCHECK (cuLinkComplete, linkstate, &linkout, &linkoutsize);
805
806 GOMP_PLUGIN_debug (0, "Link complete: %fms\n", elapsed);
807 GOMP_PLUGIN_debug (0, "Link log %s\n", &ilog[0]);
808
809 if (r != CUDA_SUCCESS)
810 {
811 GOMP_PLUGIN_error ("Link error log %s\n", &elog[0]);
812 GOMP_PLUGIN_error ("cuLinkComplete error: %s", cuda_error (r));
813 return false;
814 }
815
816 CUDA_CALL (cuModuleLoadData, module, linkout);
817 CUDA_CALL (cuLinkDestroy, linkstate);
818 return true;
819 }
820
821 static void
822 nvptx_exec (void (*fn), unsigned *dims, void *targ_mem_desc,
823 CUdeviceptr dp, CUstream stream)
824 {
825 struct targ_fn_descriptor *targ_fn = (struct targ_fn_descriptor *) fn;
826 CUfunction function;
827 int i;
828 void *kargs[1];
829 struct nvptx_thread *nvthd = nvptx_thread ();
830 int warp_size = nvthd->ptx_dev->warp_size;
831
832 function = targ_fn->fn;
833
834 /* Initialize the launch dimensions. Typically this is constant,
835 provided by the device compiler, but we must permit runtime
836 values. */
837 int seen_zero = 0;
838 for (i = 0; i != GOMP_DIM_MAX; i++)
839 {
840 if (targ_fn->launch->dim[i])
841 dims[i] = targ_fn->launch->dim[i];
842 if (!dims[i])
843 seen_zero = 1;
844 }
845
846 if (seen_zero)
847 {
848 pthread_mutex_lock (&ptx_dev_lock);
849
850 static int gomp_openacc_dims[GOMP_DIM_MAX];
851 if (!gomp_openacc_dims[0])
852 {
853 /* See if the user provided GOMP_OPENACC_DIM environment
854 variable to specify runtime defaults. */
855 for (int i = 0; i < GOMP_DIM_MAX; ++i)
856 gomp_openacc_dims[i] = GOMP_PLUGIN_acc_default_dim (i);
857 }
858
859 if (!nvthd->ptx_dev->default_dims[0])
860 {
861 int default_dims[GOMP_DIM_MAX];
862 for (int i = 0; i < GOMP_DIM_MAX; ++i)
863 default_dims[i] = gomp_openacc_dims[i];
864
865 int gang, worker, vector;
866 {
867 int block_size = nvthd->ptx_dev->max_threads_per_block;
868 int cpu_size = nvthd->ptx_dev->max_threads_per_multiprocessor;
869 int dev_size = nvthd->ptx_dev->num_sms;
870 GOMP_PLUGIN_debug (0, " warp_size=%d, block_size=%d,"
871 " dev_size=%d, cpu_size=%d\n",
872 warp_size, block_size, dev_size, cpu_size);
873
874 gang = (cpu_size / block_size) * dev_size;
875 worker = block_size / warp_size;
876 vector = warp_size;
877 }
878
879 /* There is no upper bound on the gang size. The best size
880 matches the hardware configuration. Logical gangs are
881 scheduled onto physical hardware. To maximize usage, we
882 should guess a large number. */
883 if (default_dims[GOMP_DIM_GANG] < 1)
884 default_dims[GOMP_DIM_GANG] = gang ? gang : 1024;
885 /* The worker size must not exceed the hardware. */
886 if (default_dims[GOMP_DIM_WORKER] < 1
887 || (default_dims[GOMP_DIM_WORKER] > worker && gang))
888 default_dims[GOMP_DIM_WORKER] = worker;
889 /* The vector size must exactly match the hardware. */
890 if (default_dims[GOMP_DIM_VECTOR] < 1
891 || (default_dims[GOMP_DIM_VECTOR] != vector && gang))
892 default_dims[GOMP_DIM_VECTOR] = vector;
893
894 GOMP_PLUGIN_debug (0, " default dimensions [%d,%d,%d]\n",
895 default_dims[GOMP_DIM_GANG],
896 default_dims[GOMP_DIM_WORKER],
897 default_dims[GOMP_DIM_VECTOR]);
898
899 for (i = 0; i != GOMP_DIM_MAX; i++)
900 nvthd->ptx_dev->default_dims[i] = default_dims[i];
901 }
902 pthread_mutex_unlock (&ptx_dev_lock);
903
904 {
905 bool default_dim_p[GOMP_DIM_MAX];
906 for (i = 0; i != GOMP_DIM_MAX; i++)
907 default_dim_p[i] = !dims[i];
908
909 if (!CUDA_CALL_EXISTS (cuOccupancyMaxPotentialBlockSize))
910 {
911 for (i = 0; i != GOMP_DIM_MAX; i++)
912 if (default_dim_p[i])
913 dims[i] = nvthd->ptx_dev->default_dims[i];
914
915 if (default_dim_p[GOMP_DIM_VECTOR])
916 dims[GOMP_DIM_VECTOR]
917 = MIN (dims[GOMP_DIM_VECTOR],
918 (targ_fn->max_threads_per_block / warp_size
919 * warp_size));
920
921 if (default_dim_p[GOMP_DIM_WORKER])
922 dims[GOMP_DIM_WORKER]
923 = MIN (dims[GOMP_DIM_WORKER],
924 targ_fn->max_threads_per_block / dims[GOMP_DIM_VECTOR]);
925 }
926 else
927 {
928 /* Handle the case that the compiler allows the runtime to choose
929 the vector-length conservatively, by ignoring
930 gomp_openacc_dims[GOMP_DIM_VECTOR]. TODO: actually handle
931 it. */
932 int vectors = 0;
933 /* TODO: limit gomp_openacc_dims[GOMP_DIM_WORKER] such that that
934 gomp_openacc_dims[GOMP_DIM_WORKER] * actual_vectors does not
935 exceed targ_fn->max_threads_per_block. */
936 int workers = gomp_openacc_dims[GOMP_DIM_WORKER];
937 int gangs = gomp_openacc_dims[GOMP_DIM_GANG];
938 int grids, blocks;
939
940 CUDA_CALL_ASSERT (cuOccupancyMaxPotentialBlockSize, &grids,
941 &blocks, function, NULL, 0,
942 dims[GOMP_DIM_WORKER] * dims[GOMP_DIM_VECTOR]);
943 GOMP_PLUGIN_debug (0, "cuOccupancyMaxPotentialBlockSize: "
944 "grid = %d, block = %d\n", grids, blocks);
945
946 /* Keep the num_gangs proportional to the block size. In
947 the case were a block size is limited by shared-memory
948 or the register file capacity, the runtime will not
949 excessively over assign gangs to the multiprocessor
950 units if their state is going to be swapped out even
951 more than necessary. The constant factor 2 is there to
952 prevent threads from idling when there is insufficient
953 work for them. */
954 if (gangs == 0)
955 gangs = 2 * grids * (blocks / warp_size);
956
957 if (vectors == 0)
958 vectors = warp_size;
959
960 if (workers == 0)
961 {
962 int actual_vectors = (default_dim_p[GOMP_DIM_VECTOR]
963 ? vectors
964 : dims[GOMP_DIM_VECTOR]);
965 workers = blocks / actual_vectors;
966 workers = MAX (workers, 1);
967 /* If we need a per-worker barrier ... . */
968 if (actual_vectors > 32)
969 /* Don't use more barriers than available. */
970 workers = MIN (workers, 15);
971 }
972
973 for (i = 0; i != GOMP_DIM_MAX; i++)
974 if (default_dim_p[i])
975 switch (i)
976 {
977 case GOMP_DIM_GANG: dims[i] = gangs; break;
978 case GOMP_DIM_WORKER: dims[i] = workers; break;
979 case GOMP_DIM_VECTOR: dims[i] = vectors; break;
980 default: GOMP_PLUGIN_fatal ("invalid dim");
981 }
982 }
983 }
984 }
985
986 /* Check if the accelerator has sufficient hardware resources to
987 launch the offloaded kernel. */
988 if (dims[GOMP_DIM_WORKER] * dims[GOMP_DIM_VECTOR]
989 > targ_fn->max_threads_per_block)
990 {
991 const char *msg
992 = ("The Nvidia accelerator has insufficient resources to launch '%s'"
993 " with num_workers = %d and vector_length = %d"
994 "; "
995 "recompile the program with 'num_workers = x and vector_length = y'"
996 " on that offloaded region or '-fopenacc-dim=:x:y' where"
997 " x * y <= %d"
998 ".\n");
999 GOMP_PLUGIN_fatal (msg, targ_fn->launch->fn, dims[GOMP_DIM_WORKER],
1000 dims[GOMP_DIM_VECTOR], targ_fn->max_threads_per_block);
1001 }
1002
1003 /* Check if the accelerator has sufficient barrier resources to
1004 launch the offloaded kernel. */
1005 if (dims[GOMP_DIM_WORKER] > 15 && dims[GOMP_DIM_VECTOR] > 32)
1006 {
1007 const char *msg
1008 = ("The Nvidia accelerator has insufficient barrier resources to launch"
1009 " '%s' with num_workers = %d and vector_length = %d"
1010 "; "
1011 "recompile the program with 'num_workers = x' on that offloaded"
1012 " region or '-fopenacc-dim=:x:' where x <= 15"
1013 "; "
1014 "or, recompile the program with 'vector_length = 32' on that"
1015 " offloaded region or '-fopenacc-dim=::32'"
1016 ".\n");
1017 GOMP_PLUGIN_fatal (msg, targ_fn->launch->fn, dims[GOMP_DIM_WORKER],
1018 dims[GOMP_DIM_VECTOR]);
1019 }
1020
1021 GOMP_PLUGIN_debug (0, " %s: kernel %s: launch"
1022 " gangs=%u, workers=%u, vectors=%u\n",
1023 __FUNCTION__, targ_fn->launch->fn, dims[GOMP_DIM_GANG],
1024 dims[GOMP_DIM_WORKER], dims[GOMP_DIM_VECTOR]);
1025
1026 // OpenACC CUDA
1027 //
1028 // num_gangs nctaid.x
1029 // num_workers ntid.y
1030 // vector length ntid.x
1031
1032 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
1033 acc_prof_info *prof_info = thr->prof_info;
1034 acc_event_info enqueue_launch_event_info;
1035 acc_api_info *api_info = thr->api_info;
1036 bool profiling_p = __builtin_expect (prof_info != NULL, false);
1037 if (profiling_p)
1038 {
1039 prof_info->event_type = acc_ev_enqueue_launch_start;
1040
1041 enqueue_launch_event_info.launch_event.event_type
1042 = prof_info->event_type;
1043 enqueue_launch_event_info.launch_event.valid_bytes
1044 = _ACC_LAUNCH_EVENT_INFO_VALID_BYTES;
1045 enqueue_launch_event_info.launch_event.parent_construct
1046 = acc_construct_parallel;
1047 enqueue_launch_event_info.launch_event.implicit = 1;
1048 enqueue_launch_event_info.launch_event.tool_info = NULL;
1049 enqueue_launch_event_info.launch_event.kernel_name = targ_fn->launch->fn;
1050 enqueue_launch_event_info.launch_event.num_gangs
1051 = dims[GOMP_DIM_GANG];
1052 enqueue_launch_event_info.launch_event.num_workers
1053 = dims[GOMP_DIM_WORKER];
1054 enqueue_launch_event_info.launch_event.vector_length
1055 = dims[GOMP_DIM_VECTOR];
1056
1057 api_info->device_api = acc_device_api_cuda;
1058
1059 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &enqueue_launch_event_info,
1060 api_info);
1061 }
1062
1063 kargs[0] = &dp;
1064 CUDA_CALL_ASSERT (cuLaunchKernel, function,
1065 dims[GOMP_DIM_GANG], 1, 1,
1066 dims[GOMP_DIM_VECTOR], dims[GOMP_DIM_WORKER], 1,
1067 0, stream, kargs, 0);
1068
1069 if (profiling_p)
1070 {
1071 prof_info->event_type = acc_ev_enqueue_launch_end;
1072 enqueue_launch_event_info.launch_event.event_type
1073 = prof_info->event_type;
1074 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &enqueue_launch_event_info,
1075 api_info);
1076 }
1077
1078 GOMP_PLUGIN_debug (0, " %s: kernel %s: finished\n", __FUNCTION__,
1079 targ_fn->launch->fn);
1080 }
1081
1082 void * openacc_get_current_cuda_context (void);
1083
1084 static void
1085 goacc_profiling_acc_ev_alloc (struct goacc_thread *thr, void *dp, size_t s)
1086 {
1087 acc_prof_info *prof_info = thr->prof_info;
1088 acc_event_info data_event_info;
1089 acc_api_info *api_info = thr->api_info;
1090
1091 prof_info->event_type = acc_ev_alloc;
1092
1093 data_event_info.data_event.event_type = prof_info->event_type;
1094 data_event_info.data_event.valid_bytes = _ACC_DATA_EVENT_INFO_VALID_BYTES;
1095 data_event_info.data_event.parent_construct = acc_construct_parallel;
1096 data_event_info.data_event.implicit = 1;
1097 data_event_info.data_event.tool_info = NULL;
1098 data_event_info.data_event.var_name = NULL;
1099 data_event_info.data_event.bytes = s;
1100 data_event_info.data_event.host_ptr = NULL;
1101 data_event_info.data_event.device_ptr = dp;
1102
1103 api_info->device_api = acc_device_api_cuda;
1104
1105 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &data_event_info, api_info);
1106 }
1107
1108 /* Free the cached soft-stacks block if it is above the SOFTSTACK_CACHE_LIMIT
1109 size threshold, or if FORCE is true. */
1110
1111 static void
1112 nvptx_stacks_free (struct ptx_device *ptx_dev, bool force)
1113 {
1114 pthread_mutex_lock (&ptx_dev->omp_stacks.lock);
1115 if (ptx_dev->omp_stacks.ptr
1116 && (force || ptx_dev->omp_stacks.size > SOFTSTACK_CACHE_LIMIT))
1117 {
1118 CUresult r = CUDA_CALL_NOCHECK (cuMemFree, ptx_dev->omp_stacks.ptr);
1119 if (r != CUDA_SUCCESS)
1120 GOMP_PLUGIN_fatal ("cuMemFree error: %s", cuda_error (r));
1121 ptx_dev->omp_stacks.ptr = 0;
1122 ptx_dev->omp_stacks.size = 0;
1123 }
1124 pthread_mutex_unlock (&ptx_dev->omp_stacks.lock);
1125 }
1126
1127 static void *
1128 nvptx_alloc (size_t s, bool suppress_errors)
1129 {
1130 CUdeviceptr d;
1131
1132 CUresult r = CUDA_CALL_NOCHECK (cuMemAlloc, &d, s);
1133 if (suppress_errors && r == CUDA_ERROR_OUT_OF_MEMORY)
1134 return NULL;
1135 else if (r != CUDA_SUCCESS)
1136 {
1137 GOMP_PLUGIN_error ("nvptx_alloc error: %s", cuda_error (r));
1138 return NULL;
1139 }
1140
1141 /* NOTE: We only do profiling stuff if the memory allocation succeeds. */
1142 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
1143 bool profiling_p
1144 = __builtin_expect (thr != NULL && thr->prof_info != NULL, false);
1145 if (profiling_p)
1146 goacc_profiling_acc_ev_alloc (thr, (void *) d, s);
1147
1148 return (void *) d;
1149 }
1150
1151 static void
1152 goacc_profiling_acc_ev_free (struct goacc_thread *thr, void *p)
1153 {
1154 acc_prof_info *prof_info = thr->prof_info;
1155 acc_event_info data_event_info;
1156 acc_api_info *api_info = thr->api_info;
1157
1158 prof_info->event_type = acc_ev_free;
1159
1160 data_event_info.data_event.event_type = prof_info->event_type;
1161 data_event_info.data_event.valid_bytes = _ACC_DATA_EVENT_INFO_VALID_BYTES;
1162 data_event_info.data_event.parent_construct = acc_construct_parallel;
1163 data_event_info.data_event.implicit = 1;
1164 data_event_info.data_event.tool_info = NULL;
1165 data_event_info.data_event.var_name = NULL;
1166 data_event_info.data_event.bytes = -1;
1167 data_event_info.data_event.host_ptr = NULL;
1168 data_event_info.data_event.device_ptr = p;
1169
1170 api_info->device_api = acc_device_api_cuda;
1171
1172 GOMP_PLUGIN_goacc_profiling_dispatch (prof_info, &data_event_info, api_info);
1173 }
1174
1175 static bool
1176 nvptx_free (void *p, struct ptx_device *ptx_dev)
1177 {
1178 CUdeviceptr pb;
1179 size_t ps;
1180
1181 CUresult r = CUDA_CALL_NOCHECK (cuMemGetAddressRange, &pb, &ps,
1182 (CUdeviceptr) p);
1183 if (r == CUDA_ERROR_NOT_PERMITTED)
1184 {
1185 /* We assume that this error indicates we are in a CUDA callback context,
1186 where all CUDA calls are not allowed (see cuStreamAddCallback
1187 documentation for description). Arrange to free this piece of device
1188 memory later. */
1189 struct ptx_free_block *n
1190 = GOMP_PLUGIN_malloc (sizeof (struct ptx_free_block));
1191 n->ptr = p;
1192 pthread_mutex_lock (&ptx_dev->free_blocks_lock);
1193 n->next = ptx_dev->free_blocks;
1194 ptx_dev->free_blocks = n;
1195 pthread_mutex_unlock (&ptx_dev->free_blocks_lock);
1196 return true;
1197 }
1198 else if (r != CUDA_SUCCESS)
1199 {
1200 GOMP_PLUGIN_error ("cuMemGetAddressRange error: %s", cuda_error (r));
1201 return false;
1202 }
1203 if ((CUdeviceptr) p != pb)
1204 {
1205 GOMP_PLUGIN_error ("invalid device address");
1206 return false;
1207 }
1208
1209 CUDA_CALL (cuMemFree, (CUdeviceptr) p);
1210 struct goacc_thread *thr = GOMP_PLUGIN_goacc_thread ();
1211 bool profiling_p
1212 = __builtin_expect (thr != NULL && thr->prof_info != NULL, false);
1213 if (profiling_p)
1214 goacc_profiling_acc_ev_free (thr, p);
1215
1216 return true;
1217 }
1218
1219 static void *
1220 nvptx_get_current_cuda_device (void)
1221 {
1222 struct nvptx_thread *nvthd = nvptx_thread ();
1223
1224 if (!nvthd || !nvthd->ptx_dev)
1225 return NULL;
1226
1227 return &nvthd->ptx_dev->dev;
1228 }
1229
1230 static void *
1231 nvptx_get_current_cuda_context (void)
1232 {
1233 struct nvptx_thread *nvthd = nvptx_thread ();
1234
1235 if (!nvthd || !nvthd->ptx_dev)
1236 return NULL;
1237
1238 return nvthd->ptx_dev->ctx;
1239 }
1240
1241 /* Plugin entry points. */
1242
1243 const char *
1244 GOMP_OFFLOAD_get_name (void)
1245 {
1246 return "nvptx";
1247 }
1248
1249 /* Return the UID; if not available return NULL.
1250 Returns freshly allocated memoy. */
1251
1252 const char *
1253 GOMP_OFFLOAD_get_uid (int ord)
1254 {
1255 CUresult r;
1256 CUuuid s;
1257 struct ptx_device *dev = ptx_devices[ord];
1258
1259 if (CUDA_CALL_EXISTS (cuDeviceGetUuid_v2))
1260 r = CUDA_CALL_NOCHECK (cuDeviceGetUuid_v2, &s, dev->dev);
1261 else if (CUDA_CALL_EXISTS (cuDeviceGetUuid))
1262 r = CUDA_CALL_NOCHECK (cuDeviceGetUuid, &s, dev->dev);
1263 else
1264 return NULL;
1265 if (r != CUDA_SUCCESS)
1266 NULL;
1267
1268 size_t len = strlen ("GPU-12345678-9abc-defg-hijk-lmniopqrstuv");
1269 char *str = (char *) GOMP_PLUGIN_malloc (len + 1);
1270 sprintf (str,
1271 "GPU-%02x" "%02x" "%02x" "%02x"
1272 "-%02x" "%02x"
1273 "-%02x" "%02x"
1274 "-%02x" "%02x" "%02x" "%02x" "%02x" "%02x" "%02x" "%02x",
1275 (unsigned char) s.bytes[0], (unsigned char) s.bytes[1],
1276 (unsigned char) s.bytes[2], (unsigned char) s.bytes[3],
1277 (unsigned char) s.bytes[4], (unsigned char) s.bytes[5],
1278 (unsigned char) s.bytes[6], (unsigned char) s.bytes[7],
1279 (unsigned char) s.bytes[8], (unsigned char) s.bytes[9],
1280 (unsigned char) s.bytes[10], (unsigned char) s.bytes[11],
1281 (unsigned char) s.bytes[12], (unsigned char) s.bytes[13],
1282 (unsigned char) s.bytes[14], (unsigned char) s.bytes[15]);
1283 return str;
1284 }
1285
1286 unsigned int
1287 GOMP_OFFLOAD_get_caps (void)
1288 {
1289 return GOMP_OFFLOAD_CAP_OPENACC_200 | GOMP_OFFLOAD_CAP_OPENMP_400;
1290 }
1291
1292 int
1293 GOMP_OFFLOAD_get_type (void)
1294 {
1295 return OFFLOAD_TARGET_TYPE_NVIDIA_PTX;
1296 }
1297
1298 int
1299 GOMP_OFFLOAD_get_num_devices (unsigned int omp_requires_mask)
1300 {
1301 int num_devices = nvptx_get_num_devices ();
1302 /* Return -1 if no omp_requires_mask cannot be fulfilled but
1303 devices were present. Unified-shared address: see comment in
1304 nvptx_open_device for CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING. */
1305 if (num_devices > 0
1306 && ((omp_requires_mask
1307 & ~(GOMP_REQUIRES_UNIFIED_ADDRESS
1308 | GOMP_REQUIRES_SELF_MAPS
1309 | GOMP_REQUIRES_UNIFIED_SHARED_MEMORY
1310 | GOMP_REQUIRES_REVERSE_OFFLOAD)) != 0))
1311 return -1;
1312 /* Check whether host page access (direct or via migration) is supported;
1313 if so, enable USM. Currently, capabilities is per device type, hence,
1314 check all devices. */
1315 if (num_devices > 0
1316 && (omp_requires_mask
1317 & (GOMP_REQUIRES_UNIFIED_SHARED_MEMORY | GOMP_REQUIRES_SELF_MAPS)))
1318 for (int dev = 0; dev < num_devices; dev++)
1319 {
1320 int pi;
1321 CUresult r;
1322 r = CUDA_CALL_NOCHECK (cuDeviceGetAttribute, &pi,
1323 CU_DEVICE_ATTRIBUTE_PAGEABLE_MEMORY_ACCESS, dev);
1324 if (r != CUDA_SUCCESS || pi == 0)
1325 return -1;
1326 }
1327 return num_devices;
1328 }
1329
1330 bool
1331 GOMP_OFFLOAD_init_device (int n)
1332 {
1333 struct ptx_device *dev;
1334
1335 pthread_mutex_lock (&ptx_dev_lock);
1336
1337 if (!nvptx_init () || ptx_devices[n] != NULL)
1338 {
1339 pthread_mutex_unlock (&ptx_dev_lock);
1340 return false;
1341 }
1342
1343 dev = nvptx_open_device (n);
1344 if (dev)
1345 {
1346 ptx_devices[n] = dev;
1347 instantiated_devices++;
1348 }
1349
1350 const char *var_name = "GOMP_NVPTX_LOWLAT_POOL";
1351 const char *env_var = secure_getenv (var_name);
1352 notify_var (var_name, env_var);
1353
1354 if (env_var != NULL)
1355 {
1356 char *endptr;
1357 unsigned long val = strtoul (env_var, &endptr, 10);
1358 if (endptr == NULL || *endptr != '\0'
1359 || errno == ERANGE || errno == EINVAL
1360 || val > UINT_MAX)
1361 GOMP_PLUGIN_error ("Error parsing %s", var_name);
1362 else
1363 lowlat_pool_size = val;
1364 }
1365
1366 pthread_mutex_unlock (&ptx_dev_lock);
1367
1368 return dev != NULL;
1369 }
1370
1371 bool
1372 GOMP_OFFLOAD_fini_device (int n)
1373 {
1374 pthread_mutex_lock (&ptx_dev_lock);
1375
1376 if (ptx_devices[n] != NULL)
1377 {
1378 if (!nvptx_attach_host_thread_to_device (n)
1379 || !nvptx_close_device (ptx_devices[n]))
1380 {
1381 pthread_mutex_unlock (&ptx_dev_lock);
1382 return false;
1383 }
1384 ptx_devices[n] = NULL;
1385 instantiated_devices--;
1386 }
1387
1388 if (instantiated_devices == 0)
1389 {
1390 free (ptx_devices);
1391 ptx_devices = NULL;
1392 }
1393
1394 pthread_mutex_unlock (&ptx_dev_lock);
1395 return true;
1396 }
1397
1398 /* Return the libgomp version number we're compatible with. There is
1399 no requirement for cross-version compatibility. */
1400
1401 unsigned
1402 GOMP_OFFLOAD_version (void)
1403 {
1404 return GOMP_VERSION;
1405 }
1406
1407 /* Initialize __nvptx_clocktick, if present in MODULE. */
1408
1409 static void
1410 nvptx_set_clocktick (CUmodule module, struct ptx_device *dev)
1411 {
1412 CUdeviceptr dptr;
1413 CUresult r = CUDA_CALL_NOCHECK (cuModuleGetGlobal, &dptr, NULL,
1414 module, "__nvptx_clocktick");
1415 if (r == CUDA_ERROR_NOT_FOUND)
1416 return;
1417 if (r != CUDA_SUCCESS)
1418 GOMP_PLUGIN_fatal ("cuModuleGetGlobal error: %s", cuda_error (r));
1419 double __nvptx_clocktick = 1e-3 / dev->clock_khz;
1420 r = CUDA_CALL_NOCHECK (cuMemcpyHtoD, dptr, &__nvptx_clocktick,
1421 sizeof (__nvptx_clocktick));
1422 if (r != CUDA_SUCCESS)
1423 GOMP_PLUGIN_fatal ("cuMemcpyHtoD error: %s", cuda_error (r));
1424 }
1425
1426 /* Invoke MODULE's global constructors/destructors. */
1427
1428 static bool
1429 nvptx_do_global_cdtors (CUmodule module, struct ptx_device *ptx_dev,
1430 const char *funcname)
1431 {
1432 bool ret = true;
1433 char *funcname_mgomp = NULL;
1434 CUresult r;
1435 CUfunction funcptr;
1436 r = CUDA_CALL_NOCHECK (cuModuleGetFunction,
1437 &funcptr, module, funcname);
1438 GOMP_PLUGIN_debug (0, "cuModuleGetFunction (%s): %s\n",
1439 funcname, cuda_error (r));
1440 if (r == CUDA_ERROR_NOT_FOUND)
1441 {
1442 /* Try '[funcname]__mgomp'. */
1443
1444 size_t funcname_len = strlen (funcname);
1445 const char *mgomp_suffix = "__mgomp";
1446 size_t mgomp_suffix_len = strlen (mgomp_suffix);
1447 funcname_mgomp
1448 = GOMP_PLUGIN_malloc (funcname_len + mgomp_suffix_len + 1);
1449 memcpy (funcname_mgomp, funcname, funcname_len);
1450 memcpy (funcname_mgomp + funcname_len,
1451 mgomp_suffix, mgomp_suffix_len + 1);
1452 funcname = funcname_mgomp;
1453
1454 r = CUDA_CALL_NOCHECK (cuModuleGetFunction,
1455 &funcptr, module, funcname);
1456 GOMP_PLUGIN_debug (0, "cuModuleGetFunction (%s): %s\n",
1457 funcname, cuda_error (r));
1458 }
1459 if (r == CUDA_ERROR_NOT_FOUND)
1460 ;
1461 else if (r != CUDA_SUCCESS)
1462 {
1463 GOMP_PLUGIN_error ("cuModuleGetFunction (%s) error: %s",
1464 funcname, cuda_error (r));
1465 ret = false;
1466 }
1467 else
1468 {
1469 /* If necessary, set up soft stack. */
1470 void *nvptx_stacks_0;
1471 void *kargs[1];
1472 if (funcname_mgomp)
1473 {
1474 size_t stack_size = nvptx_stacks_size ();
1475 pthread_mutex_lock (&ptx_dev->omp_stacks.lock);
1476 nvptx_stacks_0 = nvptx_stacks_acquire (ptx_dev, stack_size, 1);
1477 nvptx_stacks_0 += stack_size;
1478 kargs[0] = &nvptx_stacks_0;
1479 }
1480 r = CUDA_CALL_NOCHECK (cuLaunchKernel,
1481 funcptr,
1482 1, 1, 1, 1, 1, 1,
1483 /* sharedMemBytes */ 0,
1484 /* hStream */ NULL,
1485 /* kernelParams */ funcname_mgomp ? kargs : NULL,
1486 /* extra */ NULL);
1487 if (r != CUDA_SUCCESS)
1488 {
1489 GOMP_PLUGIN_error ("cuLaunchKernel (%s) error: %s",
1490 funcname, cuda_error (r));
1491 ret = false;
1492 }
1493
1494 r = CUDA_CALL_NOCHECK (cuStreamSynchronize,
1495 NULL);
1496 if (r != CUDA_SUCCESS)
1497 {
1498 GOMP_PLUGIN_error ("cuStreamSynchronize (%s) error: %s",
1499 funcname, cuda_error (r));
1500 ret = false;
1501 }
1502
1503 if (funcname_mgomp)
1504 pthread_mutex_unlock (&ptx_dev->omp_stacks.lock);
1505 }
1506
1507 if (funcname_mgomp)
1508 free (funcname_mgomp);
1509
1510 return ret;
1511 }
1512
1513 /* Load the (partial) program described by TARGET_DATA to device
1514 number ORD. Allocate and return TARGET_TABLE. If not NULL, REV_FN_TABLE
1515 will contain the on-device addresses of the functions for reverse offload.
1516 To be freed by the caller. */
1517
1518 int
1519 GOMP_OFFLOAD_load_image (int ord, unsigned version, const void *target_data,
1520 struct addr_pair **target_table,
1521 uint64_t **rev_fn_table,
1522 uint64_t *host_ind_fn_table)
1523 {
1524 CUmodule module;
1525 const char *const *var_names;
1526 const struct targ_fn_launch *fn_descs;
1527 unsigned int fn_entries, var_entries, ind_fn_entries, other_entries, i, j;
1528 struct targ_fn_descriptor *targ_fns;
1529 struct addr_pair *targ_tbl;
1530 const nvptx_tdata_t *img_header = (const nvptx_tdata_t *) target_data;
1531 struct ptx_image_data *new_image;
1532 struct ptx_device *dev;
1533
1534 if (GOMP_VERSION_DEV (version) > GOMP_VERSION_NVIDIA_PTX)
1535 {
1536 GOMP_PLUGIN_error ("Offload data incompatible with PTX plugin"
1537 " (expected %u, received %u)",
1538 GOMP_VERSION_NVIDIA_PTX, GOMP_VERSION_DEV (version));
1539 return -1;
1540 }
1541
1542 if (!nvptx_attach_host_thread_to_device (ord)
1543 || !link_ptx (&module, img_header->ptx_objs, img_header->ptx_num))
1544 return -1;
1545
1546 dev = ptx_devices[ord];
1547
1548 /* The mkoffload utility emits a struct of pointers/integers at the
1549 start of each offload image. The array of kernel names and the
1550 functions addresses form a one-to-one correspondence. */
1551
1552 var_entries = img_header->var_num;
1553 var_names = img_header->var_names;
1554 fn_entries = img_header->fn_num;
1555 fn_descs = img_header->fn_descs;
1556 ind_fn_entries = GOMP_VERSION_SUPPORTS_INDIRECT_FUNCS (version)
1557 ? img_header->ind_fn_num : 0;
1558
1559 /* Currently, other_entries contains only the struct of ICVs. */
1560 other_entries = 1;
1561
1562 targ_tbl = GOMP_PLUGIN_malloc (sizeof (struct addr_pair)
1563 * (fn_entries + var_entries + other_entries));
1564 targ_fns = GOMP_PLUGIN_malloc (sizeof (struct targ_fn_descriptor)
1565 * fn_entries);
1566
1567 *target_table = targ_tbl;
1568
1569 new_image = GOMP_PLUGIN_malloc (sizeof (struct ptx_image_data));
1570 new_image->target_data = target_data;
1571 new_image->module = module;
1572 new_image->fns = targ_fns;
1573
1574 pthread_mutex_lock (&dev->image_lock);
1575 new_image->next = dev->images;
1576 dev->images = new_image;
1577 pthread_mutex_unlock (&dev->image_lock);
1578
1579 for (i = 0; i < fn_entries; i++, targ_fns++, targ_tbl++)
1580 {
1581 CUfunction function;
1582 int nregs, mthrs;
1583
1584 CUDA_CALL_ERET (-1, cuModuleGetFunction, &function, module,
1585 fn_descs[i].fn);
1586 CUDA_CALL_ERET (-1, cuFuncGetAttribute, &nregs,
1587 CU_FUNC_ATTRIBUTE_NUM_REGS, function);
1588 CUDA_CALL_ERET (-1, cuFuncGetAttribute, &mthrs,
1589 CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK, function);
1590
1591 targ_fns->fn = function;
1592 targ_fns->launch = &fn_descs[i];
1593 targ_fns->regs_per_thread = nregs;
1594 targ_fns->max_threads_per_block = mthrs;
1595
1596 targ_tbl->start = (uintptr_t) targ_fns;
1597 targ_tbl->end = targ_tbl->start + 1;
1598 }
1599
1600 for (j = 0; j < var_entries; j++, targ_tbl++)
1601 {
1602 CUdeviceptr var;
1603 size_t bytes;
1604
1605 CUDA_CALL_ERET (-1, cuModuleGetGlobal,
1606 &var, &bytes, module, var_names[j]);
1607
1608 targ_tbl->start = (uintptr_t) var;
1609 targ_tbl->end = targ_tbl->start + bytes;
1610 }
1611
1612 if (ind_fn_entries > 0)
1613 {
1614 CUdeviceptr var;
1615 size_t bytes;
1616
1617 /* Read indirect function table from image. */
1618 CUresult r = CUDA_CALL_NOCHECK (cuModuleGetGlobal, &var, &bytes, module,
1619 "$offload_ind_func_table");
1620 if (r != CUDA_SUCCESS)
1621 GOMP_PLUGIN_fatal ("cuModuleGetGlobal error: %s", cuda_error (r));
1622 assert (bytes == sizeof (uint64_t) * ind_fn_entries);
1623
1624 uint64_t ind_fn_table[ind_fn_entries];
1625 r = CUDA_CALL_NOCHECK (cuMemcpyDtoH, ind_fn_table, var, bytes);
1626 if (r != CUDA_SUCCESS)
1627 GOMP_PLUGIN_fatal ("cuMemcpyDtoH error: %s", cuda_error (r));
1628
1629 /* Build host->target address map for indirect functions. */
1630 uint64_t ind_fn_map[ind_fn_entries * 2 + 1];
1631 for (unsigned k = 0; k < ind_fn_entries; k++)
1632 {
1633 ind_fn_map[k * 2] = host_ind_fn_table[k];
1634 ind_fn_map[k * 2 + 1] = ind_fn_table[k];
1635 GOMP_PLUGIN_debug (0, "Indirect function %d: %lx->%lx\n",
1636 k, host_ind_fn_table[k], ind_fn_table[k]);
1637 }
1638 ind_fn_map[ind_fn_entries * 2] = 0;
1639
1640 /* Write the map onto the target. */
1641 void *map_target_addr
1642 = GOMP_OFFLOAD_alloc (ord, sizeof (ind_fn_map));
1643 GOMP_PLUGIN_debug (0, "Allocated indirect map at %p\n", map_target_addr);
1644
1645 GOMP_OFFLOAD_host2dev (ord, map_target_addr,
1646 (void*) ind_fn_map,
1647 sizeof (ind_fn_map));
1648
1649 /* Write address of the map onto the target. */
1650 CUdeviceptr varptr;
1651 size_t varsize;
1652 r = CUDA_CALL_NOCHECK (cuModuleGetGlobal, &varptr, &varsize,
1653 module, XSTRING (GOMP_INDIRECT_ADDR_MAP));
1654 if (r != CUDA_SUCCESS)
1655 GOMP_PLUGIN_fatal ("Indirect map variable not found in image: %s",
1656 cuda_error (r));
1657
1658 GOMP_PLUGIN_debug (0,
1659 "Indirect map variable found at %llx with size %ld\n",
1660 varptr, varsize);
1661
1662 GOMP_OFFLOAD_host2dev (ord, (void *) varptr, &map_target_addr,
1663 sizeof (map_target_addr));
1664 }
1665
1666 CUdeviceptr varptr;
1667 size_t varsize;
1668 CUresult r = CUDA_CALL_NOCHECK (cuModuleGetGlobal, &varptr, &varsize,
1669 module, XSTRING (GOMP_ADDITIONAL_ICVS));
1670
1671 if (r == CUDA_SUCCESS)
1672 {
1673 targ_tbl->start = (uintptr_t) varptr;
1674 targ_tbl->end = (uintptr_t) (varptr + varsize);
1675 }
1676 else
1677 /* The variable was not in this image. */
1678 targ_tbl->start = targ_tbl->end = 0;
1679
1680 if (rev_fn_table && fn_entries == 0)
1681 *rev_fn_table = NULL;
1682 else if (rev_fn_table)
1683 {
1684 CUdeviceptr var;
1685 size_t bytes;
1686 unsigned int i;
1687 r = CUDA_CALL_NOCHECK (cuModuleGetGlobal, &var, &bytes, module,
1688 "$offload_func_table");
1689 if (r != CUDA_SUCCESS)
1690 GOMP_PLUGIN_fatal ("cuModuleGetGlobal error: %s", cuda_error (r));
1691 assert (bytes == sizeof (uint64_t) * fn_entries);
1692 *rev_fn_table = GOMP_PLUGIN_malloc (sizeof (uint64_t) * fn_entries);
1693 r = CUDA_CALL_NOCHECK (cuMemcpyDtoH, *rev_fn_table, var, bytes);
1694 if (r != CUDA_SUCCESS)
1695 GOMP_PLUGIN_fatal ("cuMemcpyDtoH error: %s", cuda_error (r));
1696 /* Free if only NULL entries. */
1697 for (i = 0; i < fn_entries; ++i)
1698 if ((*rev_fn_table)[i] != 0)
1699 break;
1700 if (i == fn_entries)
1701 {
1702 free (*rev_fn_table);
1703 *rev_fn_table = NULL;
1704 }
1705 }
1706
1707 if (rev_fn_table && *rev_fn_table && dev->rev_data == NULL)
1708 {
1709 /* Get the on-device GOMP_REV_OFFLOAD_VAR variable. It should be
1710 available but it might be not. One reason could be: if the user code
1711 has 'omp target device(ancestor:1)' in pure hostcode, GOMP_target_ext
1712 is not called on the device and, hence, it and GOMP_REV_OFFLOAD_VAR
1713 are not linked in. */
1714 CUdeviceptr device_rev_offload_var;
1715 size_t device_rev_offload_size;
1716 CUresult r = CUDA_CALL_NOCHECK (cuModuleGetGlobal,
1717 &device_rev_offload_var,
1718 &device_rev_offload_size, module,
1719 XSTRING (GOMP_REV_OFFLOAD_VAR));
1720 if (r != CUDA_SUCCESS)
1721 {
1722 free (*rev_fn_table);
1723 *rev_fn_table = NULL;
1724 }
1725 else
1726 {
1727 /* cuMemHostAlloc memory is accessible on the device, if
1728 unified-shared address is supported; this is assumed - see comment
1729 in nvptx_open_device for CU_DEVICE_ATTRIBUTE_UNIFIED_ADDRESSING. */
1730 CUDA_CALL_ASSERT (cuMemHostAlloc, (void **) &dev->rev_data,
1731 sizeof (*dev->rev_data), CU_MEMHOSTALLOC_DEVICEMAP);
1732 CUdeviceptr dp = (CUdeviceptr) dev->rev_data;
1733 r = CUDA_CALL_NOCHECK (cuMemcpyHtoD, device_rev_offload_var, &dp,
1734 sizeof (dp));
1735 if (r != CUDA_SUCCESS)
1736 GOMP_PLUGIN_fatal ("cuMemcpyHtoD error: %s", cuda_error (r));
1737 }
1738 }
1739
1740 nvptx_set_clocktick (module, dev);
1741
1742 if (!nvptx_do_global_cdtors (module, dev,
1743 "__do_global_ctors__entry"
1744 /* or "__do_global_ctors__entry__mgomp" */))
1745 return -1;
1746
1747 return fn_entries + var_entries + other_entries;
1748 }
1749
1750 /* Unload the program described by TARGET_DATA. DEV_DATA is the
1751 function descriptors allocated by G_O_load_image. */
1752
1753 bool
1754 GOMP_OFFLOAD_unload_image (int ord, unsigned version, const void *target_data)
1755 {
1756 struct ptx_image_data *image, **prev_p;
1757 struct ptx_device *dev = ptx_devices[ord];
1758
1759 if (GOMP_VERSION_DEV (version) > GOMP_VERSION_NVIDIA_PTX)
1760 {
1761 GOMP_PLUGIN_error ("Offload data incompatible with PTX plugin"
1762 " (expected %u, received %u)",
1763 GOMP_VERSION_NVIDIA_PTX, GOMP_VERSION_DEV (version));
1764 return false;
1765 }
1766
1767 bool ret = true;
1768 pthread_mutex_lock (&dev->image_lock);
1769 for (prev_p = &dev->images; (image = *prev_p) != 0; prev_p = &image->next)
1770 if (image->target_data == target_data)
1771 {
1772 if (!nvptx_do_global_cdtors (image->module, dev,
1773 "__do_global_dtors__entry"
1774 /* or "__do_global_dtors__entry__mgomp" */))
1775 ret = false;
1776
1777 *prev_p = image->next;
1778 if (CUDA_CALL_NOCHECK (cuModuleUnload, image->module) != CUDA_SUCCESS)
1779 ret = false;
1780 free (image->fns);
1781 free (image);
1782 break;
1783 }
1784 pthread_mutex_unlock (&dev->image_lock);
1785 return ret;
1786 }
1787
1788 void *
1789 GOMP_OFFLOAD_alloc (int ord, size_t size)
1790 {
1791 if (!nvptx_attach_host_thread_to_device (ord))
1792 return NULL;
1793
1794 struct ptx_device *ptx_dev = ptx_devices[ord];
1795 struct ptx_free_block *blocks, *tmp;
1796
1797 pthread_mutex_lock (&ptx_dev->free_blocks_lock);
1798 blocks = ptx_dev->free_blocks;
1799 ptx_dev->free_blocks = NULL;
1800 pthread_mutex_unlock (&ptx_dev->free_blocks_lock);
1801
1802 nvptx_stacks_free (ptx_dev, false);
1803
1804 while (blocks)
1805 {
1806 tmp = blocks->next;
1807 nvptx_free (blocks->ptr, ptx_dev);
1808 free (blocks);
1809 blocks = tmp;
1810 }
1811
1812 void *d = nvptx_alloc (size, true);
1813 if (d)
1814 return d;
1815 else
1816 {
1817 /* Memory allocation failed. Try freeing the stacks block, and
1818 retrying. */
1819 nvptx_stacks_free (ptx_dev, true);
1820 return nvptx_alloc (size, false);
1821 }
1822 }
1823
1824 bool
1825 GOMP_OFFLOAD_free (int ord, void *ptr)
1826 {
1827 return (nvptx_attach_host_thread_to_device (ord)
1828 && nvptx_free (ptr, ptx_devices[ord]));
1829 }
1830
1831 void
1832 GOMP_OFFLOAD_openacc_exec (void (*fn) (void *),
1833 size_t mapnum __attribute__((unused)),
1834 void **hostaddrs __attribute__((unused)),
1835 void **devaddrs,
1836 unsigned *dims, void *targ_mem_desc)
1837 {
1838 GOMP_PLUGIN_debug (0, "nvptx %s\n", __FUNCTION__);
1839
1840 CUdeviceptr dp = (CUdeviceptr) devaddrs;
1841 nvptx_exec (fn, dims, targ_mem_desc, dp, NULL);
1842
1843 CUresult r = CUDA_CALL_NOCHECK (cuStreamSynchronize, NULL);
1844 const char *maybe_abort_msg = "(perhaps abort was called)";
1845 if (r == CUDA_ERROR_LAUNCH_FAILED)
1846 GOMP_PLUGIN_fatal ("cuStreamSynchronize error: %s %s\n", cuda_error (r),
1847 maybe_abort_msg);
1848 else if (r != CUDA_SUCCESS)
1849 GOMP_PLUGIN_fatal ("cuStreamSynchronize error: %s", cuda_error (r));
1850 }
1851
1852 void
1853 GOMP_OFFLOAD_openacc_async_exec (void (*fn) (void *),
1854 size_t mapnum __attribute__((unused)),
1855 void **hostaddrs __attribute__((unused)),
1856 void **devaddrs,
1857 unsigned *dims, void *targ_mem_desc,
1858 struct goacc_asyncqueue *aq)
1859 {
1860 GOMP_PLUGIN_debug (0, "nvptx %s\n", __FUNCTION__);
1861
1862 CUdeviceptr dp = (CUdeviceptr) devaddrs;
1863 nvptx_exec (fn, dims, targ_mem_desc, dp, aq->cuda_stream);
1864 }
1865
1866 void *
1867 GOMP_OFFLOAD_openacc_create_thread_data (int ord)
1868 {
1869 struct ptx_device *ptx_dev;
1870 struct nvptx_thread *nvthd
1871 = GOMP_PLUGIN_malloc (sizeof (struct nvptx_thread));
1872 CUcontext thd_ctx;
1873
1874 ptx_dev = ptx_devices[ord];
1875
1876 assert (ptx_dev);
1877
1878 CUDA_CALL_ASSERT (cuCtxGetCurrent, &thd_ctx);
1879
1880 assert (ptx_dev->ctx);
1881
1882 if (!thd_ctx)
1883 CUDA_CALL_ASSERT (cuCtxPushCurrent, ptx_dev->ctx);
1884
1885 nvthd->ptx_dev = ptx_dev;
1886
1887 return (void *) nvthd;
1888 }
1889
1890 void
1891 GOMP_OFFLOAD_openacc_destroy_thread_data (void *data)
1892 {
1893 free (data);
1894 }
1895
1896 void *
1897 GOMP_OFFLOAD_openacc_cuda_get_current_device (void)
1898 {
1899 return nvptx_get_current_cuda_device ();
1900 }
1901
1902 void *
1903 GOMP_OFFLOAD_openacc_cuda_get_current_context (void)
1904 {
1905 return nvptx_get_current_cuda_context ();
1906 }
1907
1908 /* This returns a CUstream. */
1909 void *
1910 GOMP_OFFLOAD_openacc_cuda_get_stream (struct goacc_asyncqueue *aq)
1911 {
1912 return (void *) aq->cuda_stream;
1913 }
1914
1915 /* This takes a CUstream. */
1916 int
1917 GOMP_OFFLOAD_openacc_cuda_set_stream (struct goacc_asyncqueue *aq, void *stream)
1918 {
1919 if (aq->cuda_stream)
1920 {
1921 CUDA_CALL_ASSERT (cuStreamSynchronize, aq->cuda_stream);
1922 CUDA_CALL_ASSERT (cuStreamDestroy, aq->cuda_stream);
1923 }
1924
1925 aq->cuda_stream = (CUstream) stream;
1926 return 1;
1927 }
1928
1929 static struct goacc_asyncqueue *
1930 nvptx_goacc_asyncqueue_construct (unsigned int flags)
1931 {
1932 CUstream stream = NULL;
1933 CUDA_CALL_ERET (NULL, cuStreamCreate, &stream, flags);
1934
1935 struct goacc_asyncqueue *aq
1936 = GOMP_PLUGIN_malloc (sizeof (struct goacc_asyncqueue));
1937 aq->cuda_stream = stream;
1938 return aq;
1939 }
1940
1941 struct goacc_asyncqueue *
1942 GOMP_OFFLOAD_openacc_async_construct (int device __attribute__((unused)))
1943 {
1944 return nvptx_goacc_asyncqueue_construct (CU_STREAM_DEFAULT);
1945 }
1946
1947 static bool
1948 nvptx_goacc_asyncqueue_destruct (struct goacc_asyncqueue *aq)
1949 {
1950 CUDA_CALL_ERET (false, cuStreamDestroy, aq->cuda_stream);
1951 free (aq);
1952 return true;
1953 }
1954
1955 bool
1956 GOMP_OFFLOAD_openacc_async_destruct (struct goacc_asyncqueue *aq)
1957 {
1958 return nvptx_goacc_asyncqueue_destruct (aq);
1959 }
1960
1961 int
1962 GOMP_OFFLOAD_openacc_async_test (struct goacc_asyncqueue *aq)
1963 {
1964 CUresult r = CUDA_CALL_NOCHECK (cuStreamQuery, aq->cuda_stream);
1965 if (r == CUDA_SUCCESS)
1966 return 1;
1967 if (r == CUDA_ERROR_NOT_READY)
1968 return 0;
1969
1970 GOMP_PLUGIN_error ("cuStreamQuery error: %s", cuda_error (r));
1971 return -1;
1972 }
1973
1974 static bool
1975 nvptx_goacc_asyncqueue_synchronize (struct goacc_asyncqueue *aq)
1976 {
1977 CUDA_CALL_ERET (false, cuStreamSynchronize, aq->cuda_stream);
1978 return true;
1979 }
1980
1981 bool
1982 GOMP_OFFLOAD_openacc_async_synchronize (struct goacc_asyncqueue *aq)
1983 {
1984 return nvptx_goacc_asyncqueue_synchronize (aq);
1985 }
1986
1987 bool
1988 GOMP_OFFLOAD_openacc_async_serialize (struct goacc_asyncqueue *aq1,
1989 struct goacc_asyncqueue *aq2)
1990 {
1991 CUevent e;
1992 CUDA_CALL_ERET (false, cuEventCreate, &e, CU_EVENT_DISABLE_TIMING);
1993 CUDA_CALL_ERET (false, cuEventRecord, e, aq1->cuda_stream);
1994 CUDA_CALL_ERET (false, cuStreamWaitEvent, aq2->cuda_stream, e, 0);
1995 return true;
1996 }
1997
1998 static void
1999 cuda_callback_wrapper (CUstream stream, CUresult res, void *ptr)
2000 {
2001 if (res != CUDA_SUCCESS)
2002 GOMP_PLUGIN_fatal ("%s error: %s", __FUNCTION__, cuda_error (res));
2003 struct nvptx_callback *cb = (struct nvptx_callback *) ptr;
2004 cb->fn (cb->ptr);
2005 free (ptr);
2006 }
2007
2008 void
2009 GOMP_OFFLOAD_openacc_async_queue_callback (struct goacc_asyncqueue *aq,
2010 void (*callback_fn)(void *),
2011 void *userptr)
2012 {
2013 struct nvptx_callback *b = GOMP_PLUGIN_malloc (sizeof (*b));
2014 b->fn = callback_fn;
2015 b->ptr = userptr;
2016 b->aq = aq;
2017 CUDA_CALL_ASSERT (cuStreamAddCallback, aq->cuda_stream,
2018 cuda_callback_wrapper, (void *) b, 0);
2019 }
2020
2021 static bool
2022 cuda_memcpy_sanity_check (const void *h, const void *d, size_t s)
2023 {
2024 CUdeviceptr pb;
2025 size_t ps;
2026 if (!s)
2027 return true;
2028 if (!d)
2029 {
2030 GOMP_PLUGIN_error ("invalid device address");
2031 return false;
2032 }
2033 CUDA_CALL (cuMemGetAddressRange, &pb, &ps, (CUdeviceptr) d);
2034 if (!pb)
2035 {
2036 GOMP_PLUGIN_error ("invalid device address");
2037 return false;
2038 }
2039 if (!h)
2040 {
2041 GOMP_PLUGIN_error ("invalid host address");
2042 return false;
2043 }
2044 if (d == h)
2045 {
2046 GOMP_PLUGIN_error ("invalid host or device address");
2047 return false;
2048 }
2049 if ((void *)(d + s) > (void *)(pb + ps))
2050 {
2051 GOMP_PLUGIN_error ("invalid size");
2052 return false;
2053 }
2054 return true;
2055 }
2056
2057 bool
2058 GOMP_OFFLOAD_host2dev (int ord, void *dst, const void *src, size_t n)
2059 {
2060 if (!nvptx_attach_host_thread_to_device (ord)
2061 || !cuda_memcpy_sanity_check (src, dst, n))
2062 return false;
2063 CUDA_CALL (cuMemcpyHtoD, (CUdeviceptr) dst, src, n);
2064 return true;
2065 }
2066
2067 bool
2068 GOMP_OFFLOAD_dev2host (int ord, void *dst, const void *src, size_t n)
2069 {
2070 if (!nvptx_attach_host_thread_to_device (ord)
2071 || !cuda_memcpy_sanity_check (dst, src, n))
2072 return false;
2073 CUDA_CALL (cuMemcpyDtoH, dst, (CUdeviceptr) src, n);
2074 return true;
2075 }
2076
2077 bool
2078 GOMP_OFFLOAD_dev2dev (int ord, void *dst, const void *src, size_t n)
2079 {
2080 CUDA_CALL (cuMemcpyDtoDAsync, (CUdeviceptr) dst, (CUdeviceptr) src, n, NULL);
2081 return true;
2082 }
2083
2084 int
2085 GOMP_OFFLOAD_memcpy2d (int dst_ord, int src_ord, size_t dim1_size,
2086 size_t dim0_len, void *dst, size_t dst_offset1_size,
2087 size_t dst_offset0_len, size_t dst_dim1_size,
2088 const void *src, size_t src_offset1_size,
2089 size_t src_offset0_len, size_t src_dim1_size)
2090 {
2091 if (!nvptx_attach_host_thread_to_device (src_ord != -1 ? src_ord : dst_ord))
2092 return false;
2093
2094 /* TODO: Consider using CU_MEMORYTYPE_UNIFIED if supported. */
2095
2096 CUDA_MEMCPY2D data;
2097
2098 memset (&data, 0, sizeof (data));
2099 data.WidthInBytes = dim1_size;
2100 data.Height = dim0_len;
2101
2102 if (dst_ord == -1)
2103 {
2104 data.dstMemoryType = CU_MEMORYTYPE_HOST;
2105 data.dstHost = dst;
2106 }
2107 else
2108 {
2109 data.dstMemoryType = CU_MEMORYTYPE_DEVICE;
2110 data.dstDevice = (CUdeviceptr) dst;
2111 }
2112 data.dstPitch = dst_dim1_size;
2113 data.dstXInBytes = dst_offset1_size;
2114 data.dstY = dst_offset0_len;
2115
2116 if (src_ord == -1)
2117 {
2118 data.srcMemoryType = CU_MEMORYTYPE_HOST;
2119 data.srcHost = src;
2120 }
2121 else
2122 {
2123 data.srcMemoryType = CU_MEMORYTYPE_DEVICE;
2124 data.srcDevice = (CUdeviceptr) src;
2125 }
2126 data.srcPitch = src_dim1_size;
2127 data.srcXInBytes = src_offset1_size;
2128 data.srcY = src_offset0_len;
2129
2130 if (data.srcXInBytes != 0 || data.srcY != 0)
2131 {
2132 /* Adjust origin to the actual array data, else the CUDA 2D memory
2133 copy API calls below may fail to validate source/dest pointers
2134 correctly (especially for Fortran where the "virtual origin" of an
2135 array is often outside the stored data). */
2136 if (src_ord == -1)
2137 data.srcHost = (const void *) ((const char *) data.srcHost
2138 + data.srcY * data.srcPitch
2139 + data.srcXInBytes);
2140 else
2141 data.srcDevice += data.srcY * data.srcPitch + data.srcXInBytes;
2142 data.srcXInBytes = 0;
2143 data.srcY = 0;
2144 }
2145
2146 if (data.dstXInBytes != 0 || data.dstY != 0)
2147 {
2148 /* As above. */
2149 if (dst_ord == -1)
2150 data.dstHost = (void *) ((char *) data.dstHost
2151 + data.dstY * data.dstPitch
2152 + data.dstXInBytes);
2153 else
2154 data.dstDevice += data.dstY * data.dstPitch + data.dstXInBytes;
2155 data.dstXInBytes = 0;
2156 data.dstY = 0;
2157 }
2158
2159 CUresult res = CUDA_CALL_NOCHECK (cuMemcpy2D, &data);
2160 if (res == CUDA_ERROR_INVALID_VALUE)
2161 /* If pitch > CU_DEVICE_ATTRIBUTE_MAX_PITCH or for device-to-device
2162 for (some) memory not allocated by cuMemAllocPitch, cuMemcpy2D fails
2163 with an error; try the slower cuMemcpy2DUnaligned now. */
2164 CUDA_CALL (cuMemcpy2DUnaligned, &data);
2165 else if (res != CUDA_SUCCESS)
2166 {
2167 GOMP_PLUGIN_error ("cuMemcpy2D error: %s", cuda_error (res));
2168 return false;
2169 }
2170 return true;
2171 }
2172
2173 int
2174 GOMP_OFFLOAD_memcpy3d (int dst_ord, int src_ord, size_t dim2_size,
2175 size_t dim1_len, size_t dim0_len, void *dst,
2176 size_t dst_offset2_size, size_t dst_offset1_len,
2177 size_t dst_offset0_len, size_t dst_dim2_size,
2178 size_t dst_dim1_len, const void *src,
2179 size_t src_offset2_size, size_t src_offset1_len,
2180 size_t src_offset0_len, size_t src_dim2_size,
2181 size_t src_dim1_len)
2182 {
2183 if (!nvptx_attach_host_thread_to_device (src_ord != -1 ? src_ord : dst_ord))
2184 return false;
2185
2186 /* TODO: Consider using CU_MEMORYTYPE_UNIFIED if supported. */
2187
2188 CUDA_MEMCPY3D data;
2189
2190 memset (&data, 0, sizeof (data));
2191 data.WidthInBytes = dim2_size;
2192 data.Height = dim1_len;
2193 data.Depth = dim0_len;
2194
2195 if (dst_ord == -1)
2196 {
2197 data.dstMemoryType = CU_MEMORYTYPE_HOST;
2198 data.dstHost = dst;
2199 }
2200 else
2201 {
2202 data.dstMemoryType = CU_MEMORYTYPE_DEVICE;
2203 data.dstDevice = (CUdeviceptr) dst;
2204 }
2205 data.dstPitch = dst_dim2_size;
2206 data.dstHeight = dst_dim1_len;
2207 data.dstXInBytes = dst_offset2_size;
2208 data.dstY = dst_offset1_len;
2209 data.dstZ = dst_offset0_len;
2210
2211 if (src_ord == -1)
2212 {
2213 data.srcMemoryType = CU_MEMORYTYPE_HOST;
2214 data.srcHost = src;
2215 }
2216 else
2217 {
2218 data.srcMemoryType = CU_MEMORYTYPE_DEVICE;
2219 data.srcDevice = (CUdeviceptr) src;
2220 }
2221 data.srcPitch = src_dim2_size;
2222 data.srcHeight = src_dim1_len;
2223 data.srcXInBytes = src_offset2_size;
2224 data.srcY = src_offset1_len;
2225 data.srcZ = src_offset0_len;
2226
2227 if (data.srcXInBytes != 0 || data.srcY != 0 || data.srcZ != 0)
2228 {
2229 /* Adjust origin to the actual array data, else the CUDA 3D memory
2230 copy API call below may fail to validate source/dest pointers
2231 correctly (especially for Fortran where the "virtual origin" of an
2232 array is often outside the stored data). */
2233 if (src_ord == -1)
2234 data.srcHost
2235 = (const void *) ((const char *) data.srcHost
2236 + (data.srcZ * data.srcHeight + data.srcY)
2237 * data.srcPitch
2238 + data.srcXInBytes);
2239 else
2240 data.srcDevice
2241 += (data.srcZ * data.srcHeight + data.srcY) * data.srcPitch
2242 + data.srcXInBytes;
2243 data.srcXInBytes = 0;
2244 data.srcY = 0;
2245 data.srcZ = 0;
2246 }
2247
2248 if (data.dstXInBytes != 0 || data.dstY != 0 || data.dstZ != 0)
2249 {
2250 /* As above. */
2251 if (dst_ord == -1)
2252 data.dstHost = (void *) ((char *) data.dstHost
2253 + (data.dstZ * data.dstHeight + data.dstY)
2254 * data.dstPitch
2255 + data.dstXInBytes);
2256 else
2257 data.dstDevice
2258 += (data.dstZ * data.dstHeight + data.dstY) * data.dstPitch
2259 + data.dstXInBytes;
2260 data.dstXInBytes = 0;
2261 data.dstY = 0;
2262 data.dstZ = 0;
2263 }
2264
2265 CUDA_CALL (cuMemcpy3D, &data);
2266 return true;
2267 }
2268
2269 bool
2270 GOMP_OFFLOAD_openacc_async_host2dev (int ord, void *dst, const void *src,
2271 size_t n, struct goacc_asyncqueue *aq)
2272 {
2273 if (!nvptx_attach_host_thread_to_device (ord)
2274 || !cuda_memcpy_sanity_check (src, dst, n))
2275 return false;
2276 CUDA_CALL (cuMemcpyHtoDAsync, (CUdeviceptr) dst, src, n, aq->cuda_stream);
2277 return true;
2278 }
2279
2280 bool
2281 GOMP_OFFLOAD_openacc_async_dev2host (int ord, void *dst, const void *src,
2282 size_t n, struct goacc_asyncqueue *aq)
2283 {
2284 if (!nvptx_attach_host_thread_to_device (ord)
2285 || !cuda_memcpy_sanity_check (dst, src, n))
2286 return false;
2287 CUDA_CALL (cuMemcpyDtoHAsync, dst, (CUdeviceptr) src, n, aq->cuda_stream);
2288 return true;
2289 }
2290
2291 union goacc_property_value
2292 GOMP_OFFLOAD_openacc_get_property (int n, enum goacc_property prop)
2293 {
2294 union goacc_property_value propval = { .val = 0 };
2295
2296 pthread_mutex_lock (&ptx_dev_lock);
2297
2298 if (n >= nvptx_get_num_devices () || n < 0 || ptx_devices[n] == NULL)
2299 {
2300 pthread_mutex_unlock (&ptx_dev_lock);
2301 return propval;
2302 }
2303
2304 struct ptx_device *ptx_dev = ptx_devices[n];
2305 switch (prop)
2306 {
2307 case GOACC_PROPERTY_MEMORY:
2308 {
2309 size_t total_mem;
2310
2311 CUDA_CALL_ERET (propval, cuDeviceTotalMem, &total_mem, ptx_dev->dev);
2312 propval.val = total_mem;
2313 }
2314 break;
2315 case GOACC_PROPERTY_FREE_MEMORY:
2316 {
2317 size_t total_mem;
2318 size_t free_mem;
2319 CUdevice ctxdev;
2320
2321 CUDA_CALL_ERET (propval, cuCtxGetDevice, &ctxdev);
2322 if (ptx_dev->dev == ctxdev)
2323 CUDA_CALL_ERET (propval, cuMemGetInfo, &free_mem, &total_mem);
2324 else if (ptx_dev->ctx)
2325 {
2326 CUcontext old_ctx;
2327
2328 CUDA_CALL_ERET (propval, cuCtxPushCurrent, ptx_dev->ctx);
2329 CUDA_CALL_ERET (propval, cuMemGetInfo, &free_mem, &total_mem);
2330 CUDA_CALL_ASSERT (cuCtxPopCurrent, &old_ctx);
2331 }
2332 else
2333 {
2334 CUcontext new_ctx;
2335
2336 CUDA_CALL_ERET (propval, cuCtxCreate, &new_ctx, CU_CTX_SCHED_AUTO,
2337 ptx_dev->dev);
2338 CUDA_CALL_ERET (propval, cuMemGetInfo, &free_mem, &total_mem);
2339 CUDA_CALL_ASSERT (cuCtxDestroy, new_ctx);
2340 }
2341 propval.val = free_mem;
2342 }
2343 break;
2344 case GOACC_PROPERTY_NAME:
2345 propval.ptr = ptx_dev->name;
2346 break;
2347 case GOACC_PROPERTY_VENDOR:
2348 propval.ptr = "Nvidia";
2349 break;
2350 case GOACC_PROPERTY_DRIVER:
2351 propval.ptr = cuda_driver_version_s;
2352 break;
2353 default:
2354 break;
2355 }
2356
2357 pthread_mutex_unlock (&ptx_dev_lock);
2358 return propval;
2359 }
2360
2361 /* Adjust launch dimensions: pick good values for number of blocks and warps
2362 and ensure that number of warps does not exceed CUDA limits as well as GCC's
2363 own limits. */
2364
2365 static void
2366 nvptx_adjust_launch_bounds (struct targ_fn_descriptor *fn,
2367 struct ptx_device *ptx_dev,
2368 int *teams_p, int *threads_p)
2369 {
2370 int max_warps_block = fn->max_threads_per_block / 32;
2371 /* Maximum 32 warps per block is an implementation limit in NVPTX backend
2372 and libgcc, which matches documented limit of all GPUs as of 2015. */
2373 if (max_warps_block > 32)
2374 max_warps_block = 32;
2375 if (*threads_p <= 0)
2376 *threads_p = 8;
2377 if (*threads_p > max_warps_block)
2378 *threads_p = max_warps_block;
2379
2380 int regs_per_block = fn->regs_per_thread * 32 * *threads_p;
2381 /* This is an estimate of how many blocks the device can host simultaneously.
2382 Actual limit, which may be lower, can be queried with "occupancy control"
2383 driver interface (since CUDA 6.0). */
2384 int max_blocks = ptx_dev->regs_per_sm / regs_per_block * ptx_dev->num_sms;
2385 if (*teams_p <= 0 || *teams_p > max_blocks)
2386 *teams_p = max_blocks;
2387 }
2388
2389 /* Return the size of per-warp stacks (see gcc -msoft-stack) to use for OpenMP
2390 target regions. */
2391
2392 static size_t
2393 nvptx_stacks_size ()
2394 {
2395 return 128 * 1024;
2396 }
2397
2398 /* Return contiguous storage for NUM stacks, each SIZE bytes. The lock for
2399 the storage should be held on entry, and remains held on exit. */
2400
2401 static void *
2402 nvptx_stacks_acquire (struct ptx_device *ptx_dev, size_t size, int num)
2403 {
2404 if (ptx_dev->omp_stacks.ptr && ptx_dev->omp_stacks.size >= size * num)
2405 return (void *) ptx_dev->omp_stacks.ptr;
2406
2407 /* Free the old, too-small stacks. */
2408 if (ptx_dev->omp_stacks.ptr)
2409 {
2410 CUresult r = CUDA_CALL_NOCHECK (cuCtxSynchronize, );
2411 if (r != CUDA_SUCCESS)
2412 GOMP_PLUGIN_fatal ("cuCtxSynchronize error: %s\n", cuda_error (r));
2413 r = CUDA_CALL_NOCHECK (cuMemFree, ptx_dev->omp_stacks.ptr);
2414 if (r != CUDA_SUCCESS)
2415 GOMP_PLUGIN_fatal ("cuMemFree error: %s", cuda_error (r));
2416 }
2417
2418 /* Make new and bigger stacks, and remember where we put them and how big
2419 they are. */
2420 CUresult r = CUDA_CALL_NOCHECK (cuMemAlloc, &ptx_dev->omp_stacks.ptr,
2421 size * num);
2422 if (r != CUDA_SUCCESS)
2423 GOMP_PLUGIN_fatal ("cuMemAlloc error: %s", cuda_error (r));
2424
2425 ptx_dev->omp_stacks.size = size * num;
2426
2427 return (void *) ptx_dev->omp_stacks.ptr;
2428 }
2429
2430 void
2431 GOMP_OFFLOAD_interop (struct interop_obj_t *obj, int ord,
2432 enum gomp_interop_flag action, bool targetsync,
2433 const char *prefer_type)
2434 {
2435 obj->fr = omp_ifr_cuda;
2436
2437 if (action == gomp_interop_flag_destroy)
2438 {
2439 if (obj->stream)
2440 CUDA_CALL_ASSERT (cuStreamDestroy, obj->stream);
2441 return;
2442 }
2443 if (action == gomp_interop_flag_use)
2444 {
2445 if (obj->stream)
2446 CUDA_CALL_ASSERT (cuStreamSynchronize, obj->stream);
2447 return;
2448 }
2449
2450 /* Check for the preferred type; cf. parser in C/C++/Fortran or
2451 dump_omp_init_prefer_type for the format.
2452 Accept the first '{...}' block that specifies a 'fr' that we support.
2453 Currently, no 'attr(...)' are supported. */
2454 if (prefer_type)
2455 while (prefer_type[0] == (char) GOMP_INTEROP_IFR_SEPARATOR)
2456 {
2457 bool found = false;
2458 /* '{' item block starts. */
2459 prefer_type++;
2460 /* 'fr(...)' block */
2461 while (prefer_type[0] != (char) GOMP_INTEROP_IFR_SEPARATOR)
2462 {
2463 omp_interop_fr_t fr = (omp_interop_fr_t) prefer_type[0];
2464 if (fr == omp_ifr_cuda
2465 || fr == omp_ifr_cuda_driver
2466 || fr == omp_ifr_hip)
2467 {
2468 obj->fr = fr;
2469 found = true;
2470 }
2471 prefer_type++;
2472 }
2473 prefer_type++;
2474 /* 'attr(...)' block */
2475 while (prefer_type[0] != '\0')
2476 {
2477 /* const char *attr = prefer_type; */
2478 prefer_type += strlen (prefer_type) + 1;
2479 }
2480 prefer_type++;
2481 /* end of '}'. */
2482 if (found)
2483 break;
2484 }
2485
2486 struct ptx_device *ptx_dev = obj->device_data = ptx_devices[ord];
2487
2488 if (targetsync)
2489 {
2490 CUstream stream = NULL;
2491 CUdevice cur_ctx_dev;
2492 CUresult res = CUDA_CALL_NOCHECK (cuCtxGetDevice, &cur_ctx_dev);
2493 if (res != CUDA_SUCCESS && res != CUDA_ERROR_INVALID_CONTEXT)
2494 GOMP_PLUGIN_fatal ("cuCtxGetDevice error: %s", cuda_error (res));
2495 if (res != CUDA_ERROR_INVALID_CONTEXT && ptx_dev->dev == cur_ctx_dev)
2496 CUDA_CALL_ASSERT (cuStreamCreate, &stream, CU_STREAM_DEFAULT);
2497 else
2498 {
2499 CUcontext old_ctx;
2500 assert (ptx_dev->ctx);
2501 CUDA_CALL_ASSERT (cuCtxPushCurrent, ptx_dev->ctx);
2502 CUDA_CALL_ASSERT (cuStreamCreate, &stream, CU_STREAM_DEFAULT);
2503 if (res != CUDA_ERROR_INVALID_CONTEXT)
2504 CUDA_CALL_ASSERT (cuCtxPopCurrent, &old_ctx);
2505 }
2506 obj->stream = stream;
2507 }
2508 }
2509
2510
2511 intptr_t
2512 GOMP_OFFLOAD_get_interop_int (struct interop_obj_t *obj,
2513 omp_interop_property_t property_id,
2514 omp_interop_rc_t *ret_code)
2515 {
2516 if (obj->fr != omp_ifr_cuda
2517 && obj->fr != omp_ifr_cuda_driver
2518 && obj->fr != omp_ifr_hip)
2519 {
2520 if (ret_code)
2521 *ret_code = omp_irc_no_value; /* Hmm. */
2522 return 0;
2523 }
2524 switch (property_id)
2525 {
2526 case omp_ipr_fr_id:
2527 if (ret_code)
2528 *ret_code = omp_irc_success;
2529 return obj->fr;
2530 case omp_ipr_fr_name:
2531 if (ret_code)
2532 *ret_code = omp_irc_type_str;
2533 return 0;
2534 case omp_ipr_vendor:
2535 if (ret_code)
2536 *ret_code = omp_irc_success;
2537 return 11; /* nvidia */
2538 case omp_ipr_vendor_name:
2539 if (ret_code)
2540 *ret_code = omp_irc_type_str;
2541 return 0;
2542 case omp_ipr_device_num:
2543 if (ret_code)
2544 *ret_code = omp_irc_success;
2545 return obj->device_num;
2546 case omp_ipr_platform:
2547 if (ret_code)
2548 *ret_code = omp_irc_no_value;
2549 return 0;
2550 case omp_ipr_device:
2551 if (ret_code)
2552 *ret_code = omp_irc_success;
2553 return ((struct ptx_device *) obj->device_data)->dev;
2554 case omp_ipr_device_context:
2555 if (ret_code && obj->fr == omp_ifr_cuda)
2556 *ret_code = omp_irc_no_value;
2557 else if (ret_code)
2558 *ret_code = omp_irc_type_ptr;
2559 return 0;
2560 case omp_ipr_targetsync:
2561 if (!obj->stream)
2562 {
2563 if (ret_code)
2564 *ret_code = omp_irc_no_value;
2565 return 0;
2566 }
2567 /* ptr fits into (u)intptr_t */
2568 if (ret_code)
2569 *ret_code = omp_irc_success;
2570 return (uintptr_t) obj->stream;
2571 default:
2572 break;
2573 }
2574 __builtin_unreachable ();
2575 return 0;
2576 }
2577
2578 void *
2579 GOMP_OFFLOAD_get_interop_ptr (struct interop_obj_t *obj,
2580 omp_interop_property_t property_id,
2581 omp_interop_rc_t *ret_code)
2582 {
2583 if (obj->fr != omp_ifr_cuda
2584 && obj->fr != omp_ifr_cuda_driver
2585 && obj->fr != omp_ifr_hip)
2586 {
2587 if (ret_code)
2588 *ret_code = omp_irc_no_value; /* Hmm. */
2589 return 0;
2590 }
2591 switch (property_id)
2592 {
2593 case omp_ipr_fr_id:
2594 if (ret_code)
2595 *ret_code = omp_irc_type_int;
2596 return NULL;
2597 case omp_ipr_fr_name:
2598 if (ret_code)
2599 *ret_code = omp_irc_type_str;
2600 return NULL;
2601 case omp_ipr_vendor:
2602 if (ret_code)
2603 *ret_code = omp_irc_type_int;
2604 return NULL;
2605 case omp_ipr_vendor_name:
2606 if (ret_code)
2607 *ret_code = omp_irc_type_str;
2608 return NULL;
2609 case omp_ipr_device_num:
2610 if (ret_code)
2611 *ret_code = omp_irc_type_int;
2612 return NULL;
2613 case omp_ipr_platform:
2614 if (ret_code)
2615 *ret_code = omp_irc_no_value;
2616 return NULL;
2617 case omp_ipr_device:
2618 if (ret_code)
2619 *ret_code = omp_irc_type_int;
2620 return NULL;
2621 case omp_ipr_device_context:
2622 if (obj->fr == omp_ifr_cuda)
2623 {
2624 if (ret_code)
2625 *ret_code = omp_irc_no_value;
2626 return NULL;
2627 }
2628 if (ret_code)
2629 *ret_code = omp_irc_success;
2630 return ((struct ptx_device *) obj->device_data)->ctx;
2631 case omp_ipr_targetsync:
2632 if (!obj->stream)
2633 {
2634 if (ret_code)
2635 *ret_code = omp_irc_no_value;
2636 return NULL;
2637 }
2638 if (ret_code)
2639 *ret_code = omp_irc_success;
2640 return obj->stream;
2641 default:
2642 break;
2643 }
2644 __builtin_unreachable ();
2645 return NULL;
2646 }
2647
2648 const char *
2649 GOMP_OFFLOAD_get_interop_str (struct interop_obj_t *obj,
2650 omp_interop_property_t property_id,
2651 omp_interop_rc_t *ret_code)
2652 {
2653 if (obj->fr != omp_ifr_cuda
2654 && obj->fr != omp_ifr_cuda_driver
2655 && obj->fr != omp_ifr_hip)
2656 {
2657 if (ret_code)
2658 *ret_code = omp_irc_no_value; /* Hmm. */
2659 return 0;
2660 }
2661 switch (property_id)
2662 {
2663 case omp_ipr_fr_id:
2664 if (ret_code)
2665 *ret_code = omp_irc_type_int;
2666 return NULL;
2667 case omp_ipr_fr_name:
2668 if (ret_code)
2669 *ret_code = omp_irc_success;
2670 if (obj->fr == omp_ifr_cuda)
2671 return "cuda";
2672 if (obj->fr == omp_ifr_cuda_driver)
2673 return "cuda_driver";
2674 if (obj->fr == omp_ifr_hip)
2675 return "hip";
2676 break;
2677 case omp_ipr_vendor:
2678 if (ret_code)
2679 *ret_code = omp_irc_type_int;
2680 return NULL;
2681 case omp_ipr_vendor_name:
2682 if (ret_code)
2683 *ret_code = omp_irc_success;
2684 return "nvidia";
2685 case omp_ipr_device_num:
2686 if (ret_code)
2687 *ret_code = omp_irc_type_int;
2688 return NULL;
2689 case omp_ipr_platform:
2690 if (ret_code)
2691 *ret_code = omp_irc_no_value;
2692 return NULL;
2693 case omp_ipr_device:
2694 if (ret_code)
2695 *ret_code = omp_irc_type_ptr;
2696 return NULL;
2697 case omp_ipr_device_context:
2698 if (ret_code && obj->fr == omp_ifr_cuda)
2699 *ret_code = omp_irc_no_value;
2700 else if (ret_code)
2701 *ret_code = omp_irc_type_ptr;
2702 return NULL;
2703 case omp_ipr_targetsync:
2704 if (ret_code && !obj->stream)
2705 *ret_code = omp_irc_no_value;
2706 else if (ret_code)
2707 *ret_code = omp_irc_type_ptr;
2708 return NULL;
2709 default:
2710 break;
2711 }
2712 __builtin_unreachable ();
2713 return NULL;
2714 }
2715
2716 const char *
2717 GOMP_OFFLOAD_get_interop_type_desc (struct interop_obj_t *obj,
2718 omp_interop_property_t property_id)
2719 {
2720 _Static_assert (omp_ipr_targetsync == omp_ipr_first,
2721 "omp_ipr_targetsync == omp_ipr_first");
2722 _Static_assert (omp_ipr_platform - omp_ipr_first + 1 == 4,
2723 "omp_ipr_platform - omp_ipr_first + 1 == 4");
2724 static const char *desc_cuda[] = {"N/A", /* platform */
2725 "int", /* device */
2726 "N/A", /* device_context */
2727 "cudaStream_t"}; /* targetsync */
2728 static const char *desc_cuda_driver[] = {"N/A", /* platform */
2729 "CUdevice", /* device */
2730 "CUcontext", /* device_context */
2731 "CUstream"}; /* targetsync */
2732 static const char *desc_hip[] = {"N/A", /* platform */
2733 "hipDevice_t", /* device */
2734 "hipCtx_t", /* device_context */
2735 "hipStream_t"}; /* targetsync */
2736 if (obj->fr == omp_ifr_cuda)
2737 return desc_cuda[omp_ipr_platform - property_id];
2738 if (obj->fr == omp_ifr_cuda_driver)
2739 return desc_cuda_driver[omp_ipr_platform - property_id];
2740 else
2741 return desc_hip[omp_ipr_platform - property_id];
2742 return NULL;
2743 }
2744
2745 void
2746 GOMP_OFFLOAD_run (int ord, void *tgt_fn, void *tgt_vars, void **args)
2747 {
2748 struct targ_fn_descriptor *tgt_fn_desc
2749 = (struct targ_fn_descriptor *) tgt_fn;
2750 CUfunction function = tgt_fn_desc->fn;
2751 const struct targ_fn_launch *launch = tgt_fn_desc->launch;
2752 const char *fn_name = launch->fn;
2753 CUresult r;
2754 struct ptx_device *ptx_dev = ptx_devices[ord];
2755 const char *maybe_abort_msg = "(perhaps abort was called)";
2756 int teams = 0, threads = 0;
2757
2758 if (!args)
2759 GOMP_PLUGIN_fatal ("No target arguments provided");
2760 while (*args)
2761 {
2762 intptr_t id = (intptr_t) *args++, val;
2763 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
2764 val = (intptr_t) *args++;
2765 else
2766 val = id >> GOMP_TARGET_ARG_VALUE_SHIFT;
2767 if ((id & GOMP_TARGET_ARG_DEVICE_MASK) != GOMP_TARGET_ARG_DEVICE_ALL)
2768 continue;
2769 val = val > INT_MAX ? INT_MAX : val;
2770 id &= GOMP_TARGET_ARG_ID_MASK;
2771 if (id == GOMP_TARGET_ARG_NUM_TEAMS)
2772 teams = val;
2773 else if (id == GOMP_TARGET_ARG_THREAD_LIMIT)
2774 threads = val;
2775 }
2776 nvptx_adjust_launch_bounds (tgt_fn, ptx_dev, &teams, &threads);
2777
2778 bool reverse_offload = ptx_dev->rev_data != NULL;
2779 struct goacc_asyncqueue *reverse_offload_aq = NULL;
2780 if (reverse_offload)
2781 {
2782 reverse_offload_aq
2783 = nvptx_goacc_asyncqueue_construct (CU_STREAM_NON_BLOCKING);
2784 if (!reverse_offload_aq)
2785 exit (EXIT_FAILURE);
2786 }
2787
2788 size_t stack_size = nvptx_stacks_size ();
2789
2790 pthread_mutex_lock (&ptx_dev->omp_stacks.lock);
2791 void *stacks = nvptx_stacks_acquire (ptx_dev, stack_size, teams * threads);
2792 void *fn_args[] = {tgt_vars, stacks, (void *) stack_size};
2793 size_t fn_args_size = sizeof fn_args;
2794 void *config[] = {
2795 CU_LAUNCH_PARAM_BUFFER_POINTER, fn_args,
2796 CU_LAUNCH_PARAM_BUFFER_SIZE, &fn_args_size,
2797 CU_LAUNCH_PARAM_END
2798 };
2799 GOMP_PLUGIN_debug (0, " %s: kernel %s: launch"
2800 " [(teams: %u), 1, 1] [(lanes: 32), (threads: %u), 1]\n",
2801 __FUNCTION__, fn_name, teams, threads);
2802 r = CUDA_CALL_NOCHECK (cuLaunchKernel, function, teams, 1, 1,
2803 32, threads, 1, lowlat_pool_size, NULL, NULL, config);
2804 if (r != CUDA_SUCCESS)
2805 GOMP_PLUGIN_fatal ("cuLaunchKernel error: %s", cuda_error (r));
2806 if (reverse_offload)
2807 while (true)
2808 {
2809 r = CUDA_CALL_NOCHECK (cuStreamQuery, NULL);
2810 if (r == CUDA_SUCCESS)
2811 break;
2812 if (r == CUDA_ERROR_LAUNCH_FAILED)
2813 GOMP_PLUGIN_fatal ("cuStreamQuery error: %s %s\n", cuda_error (r),
2814 maybe_abort_msg);
2815 else if (r != CUDA_ERROR_NOT_READY)
2816 GOMP_PLUGIN_fatal ("cuStreamQuery error: %s", cuda_error (r));
2817
2818 if (__atomic_load_n (&ptx_dev->rev_data->fn, __ATOMIC_ACQUIRE) != 0)
2819 {
2820 struct rev_offload *rev_data = ptx_dev->rev_data;
2821 GOMP_PLUGIN_target_rev (rev_data->fn, rev_data->mapnum,
2822 rev_data->addrs, rev_data->sizes,
2823 rev_data->kinds, rev_data->dev_num,
2824 reverse_offload_aq);
2825 if (!nvptx_goacc_asyncqueue_synchronize (reverse_offload_aq))
2826 exit (EXIT_FAILURE);
2827 __atomic_store_n (&rev_data->fn, 0, __ATOMIC_RELEASE);
2828 }
2829 usleep (1);
2830 }
2831 else
2832 r = CUDA_CALL_NOCHECK (cuCtxSynchronize, );
2833 if (r == CUDA_ERROR_LAUNCH_FAILED)
2834 GOMP_PLUGIN_fatal ("cuCtxSynchronize error: %s %s\n", cuda_error (r),
2835 maybe_abort_msg);
2836 else if (r != CUDA_SUCCESS)
2837 GOMP_PLUGIN_fatal ("cuCtxSynchronize error: %s", cuda_error (r));
2838
2839 pthread_mutex_unlock (&ptx_dev->omp_stacks.lock);
2840
2841 if (reverse_offload)
2842 {
2843 if (!nvptx_goacc_asyncqueue_destruct (reverse_offload_aq))
2844 exit (EXIT_FAILURE);
2845 }
2846 }
2847
2848 /* TODO: Implement GOMP_OFFLOAD_async_run. */