Debian Codegraph @

libgomp/target.c

raw
1 /* Copyright (C) 2013-2025 Free Software Foundation, Inc.
2 Contributed by Jakub Jelinek <[email protected]>.
3
4 This file is part of the GNU Offloading and Multi Processing Library
5 (libgomp).
6
7 Libgomp is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 Libgomp is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
14 FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 more details.
16
17 Under Section 7 of GPL version 3, you are granted additional
18 permissions described in the GCC Runtime Library Exception, version
19 3.1, as published by the Free Software Foundation.
20
21 You should have received a copy of the GNU General Public License and
22 a copy of the GCC Runtime Library Exception along with this program;
23 see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
24 <http://www.gnu.org/licenses/>. */
25
26 /* This file contains the support of offloading. */
27
28 #include "libgomp.h"
29 #include "oacc-plugin.h"
30 #include "oacc-int.h"
31 #include "gomp-constants.h"
32 #include <limits.h>
33 #include <stdbool.h>
34 #include <stdlib.h>
35 #ifdef HAVE_INTTYPES_H
36 # include <inttypes.h> /* For PRIu64. */
37 #endif
38 #include <string.h>
39 #include <stdio.h> /* For snprintf. */
40 #include <assert.h>
41 #include <errno.h>
42
43 #ifdef PLUGIN_SUPPORT
44 #include <dlfcn.h>
45 #include "plugin-suffix.h"
46 #endif
47
48 /* Define another splay tree instantiation - for reverse offload. */
49 #define splay_tree_prefix reverse
50 #define splay_tree_static
51 #define splay_tree_c
52 #include "splay-tree.h"
53
54 /* Used by omp_get_device_from_uid / omp_get_uid_from_device for the host. */
55 static char *str_omp_initial_device = "OMP_INITIAL_DEVICE";
56 #define STR_OMP_DEV_PREFIX "OMP_DEV_"
57
58 typedef uintptr_t *hash_entry_type;
59 static inline void * htab_alloc (size_t size) { return gomp_malloc (size); }
60 static inline void htab_free (void *ptr) { free (ptr); }
61 #include "hashtab.h"
62
63 ialias_redirect (GOMP_task)
64
65 static inline hashval_t
66 htab_hash (hash_entry_type element)
67 {
68 return hash_pointer ((void *) element);
69 }
70
71 static inline bool
72 htab_eq (hash_entry_type x, hash_entry_type y)
73 {
74 return x == y;
75 }
76
77 #define FIELD_TGT_EMPTY (~(size_t) 0)
78
79 static void gomp_target_init (void);
80
81 /* The whole initialization code for offloading plugins is only run one. */
82 static pthread_once_t gomp_is_initialized = PTHREAD_ONCE_INIT;
83
84 /* Mutex for offload image registration. */
85 static gomp_mutex_t register_lock;
86
87 /* This structure describes an offload image.
88 It contains type of the target device, pointer to host table descriptor, and
89 pointer to target data. */
90 struct offload_image_descr {
91 unsigned version;
92 enum offload_target_type type;
93 const void *host_table;
94 const void *target_data;
95 };
96
97 /* Array of descriptors of offload images. */
98 static struct offload_image_descr *offload_images;
99
100 /* Total number of offload images. */
101 static int num_offload_images;
102
103 /* Array of descriptors for all available devices. */
104 static struct gomp_device_descr *devices;
105
106 /* Total number of available devices. */
107 static int num_devices;
108
109 /* Number of GOMP_OFFLOAD_CAP_OPENMP_400 devices. */
110 static int num_devices_openmp;
111
112 /* OpenMP requires mask. */
113 static int omp_requires_mask;
114
115 /* Similar to gomp_realloc, but release register_lock before gomp_fatal. */
116
117 static void *
118 gomp_realloc_unlock (void *old, size_t size)
119 {
120 void *ret = realloc (old, size);
121 if (ret == NULL)
122 {
123 gomp_mutex_unlock (&register_lock);
124 gomp_fatal ("Out of memory allocating %lu bytes", (unsigned long) size);
125 }
126 return ret;
127 }
128
129 attribute_hidden void
130 gomp_init_targets_once (void)
131 {
132 (void) pthread_once (&gomp_is_initialized, gomp_target_init);
133 }
134
135 attribute_hidden int
136 gomp_get_num_devices (void)
137 {
138 gomp_init_targets_once ();
139 return num_devices_openmp;
140 }
141
142 static struct gomp_device_descr *
143 resolve_device (int device_id, bool remapped)
144 {
145 /* Get number of devices and thus ensure that 'gomp_init_targets_once' was
146 called, which must be done before using default_device_var. */
147 int num_devices = gomp_get_num_devices ();
148
149 if ((remapped && device_id == GOMP_DEVICE_ICV)
150 || device_id == GOMP_DEVICE_DEFAULT_OMP_61)
151 {
152 struct gomp_task_icv *icv = gomp_icv (false);
153 device_id = icv->default_device_var;
154 remapped = false;
155 }
156
157 if (device_id < 0)
158 {
159 if (device_id == (remapped ? GOMP_DEVICE_HOST_FALLBACK
160 : omp_initial_device))
161 return NULL;
162 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY
163 && num_devices == 0)
164 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, "
165 "but only the host device is available");
166 else if (device_id == omp_invalid_device)
167 gomp_fatal ("omp_invalid_device encountered");
168 else if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY)
169 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, "
170 "but device not found");
171
172 return NULL;
173 }
174 else if (device_id >= num_devices)
175 {
176 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY
177 && device_id != num_devices)
178 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, "
179 "but device not found");
180
181 return NULL;
182 }
183
184 gomp_mutex_lock (&devices[device_id].lock);
185 if (devices[device_id].state == GOMP_DEVICE_UNINITIALIZED)
186 gomp_init_device (&devices[device_id]);
187 else if (devices[device_id].state == GOMP_DEVICE_FINALIZED)
188 {
189 gomp_mutex_unlock (&devices[device_id].lock);
190
191 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY)
192 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, "
193 "but device is finalized");
194
195 return NULL;
196 }
197 gomp_mutex_unlock (&devices[device_id].lock);
198
199 return &devices[device_id];
200 }
201
202
203 static inline splay_tree_key
204 gomp_map_lookup (splay_tree mem_map, splay_tree_key key)
205 {
206 if (key->host_start != key->host_end)
207 return splay_tree_lookup (mem_map, key);
208
209 key->host_end++;
210 splay_tree_key n = splay_tree_lookup (mem_map, key);
211 key->host_end--;
212 if (n)
213 return n;
214 key->host_start--;
215 n = splay_tree_lookup (mem_map, key);
216 key->host_start++;
217 if (n)
218 return n;
219 return splay_tree_lookup (mem_map, key);
220 }
221
222 static inline reverse_splay_tree_key
223 gomp_map_lookup_rev (reverse_splay_tree mem_map_rev, reverse_splay_tree_key key)
224 {
225 return reverse_splay_tree_lookup (mem_map_rev, key);
226 }
227
228 static inline splay_tree_key
229 gomp_map_0len_lookup (splay_tree mem_map, splay_tree_key key)
230 {
231 if (key->host_start != key->host_end)
232 return splay_tree_lookup (mem_map, key);
233
234 key->host_end++;
235 splay_tree_key n = splay_tree_lookup (mem_map, key);
236 key->host_end--;
237 return n;
238 }
239
240 static inline void
241 gomp_device_copy (struct gomp_device_descr *devicep,
242 bool (*copy_func) (int, void *, const void *, size_t),
243 const char *dst, void *dstaddr,
244 const char *src, const void *srcaddr,
245 size_t size)
246 {
247 if (!copy_func (devicep->target_id, dstaddr, srcaddr, size))
248 {
249 gomp_mutex_unlock (&devicep->lock);
250 gomp_fatal ("Copying of %s object [%p..%p) to %s object [%p..%p) failed",
251 src, srcaddr, srcaddr + size, dst, dstaddr, dstaddr + size);
252 }
253 }
254
255 static inline void
256 goacc_device_copy_async (struct gomp_device_descr *devicep,
257 bool (*copy_func) (int, void *, const void *, size_t,
258 struct goacc_asyncqueue *),
259 const char *dst, void *dstaddr,
260 const char *src, const void *srcaddr,
261 const void *srcaddr_orig,
262 size_t size, struct goacc_asyncqueue *aq)
263 {
264 if (!copy_func (devicep->target_id, dstaddr, srcaddr, size, aq))
265 {
266 gomp_mutex_unlock (&devicep->lock);
267 if (srcaddr_orig && srcaddr_orig != srcaddr)
268 gomp_fatal ("Copying of %s object [%p..%p)"
269 " via buffer %s object [%p..%p)"
270 " to %s object [%p..%p) failed",
271 src, srcaddr_orig, srcaddr_orig + size,
272 src, srcaddr, srcaddr + size,
273 dst, dstaddr, dstaddr + size);
274 else
275 gomp_fatal ("Copying of %s object [%p..%p)"
276 " to %s object [%p..%p) failed",
277 src, srcaddr, srcaddr + size,
278 dst, dstaddr, dstaddr + size);
279 }
280 }
281
282 /* Infrastructure for coalescing adjacent or nearly adjacent (in device addresses)
283 host to device memory transfers. */
284
285 struct gomp_coalesce_chunk
286 {
287 /* The starting and ending point of a coalesced chunk of memory. */
288 size_t start, end;
289 };
290
291 struct gomp_coalesce_buf
292 {
293 /* Buffer into which gomp_copy_host2dev will memcpy data and from which
294 it will be copied to the device. */
295 void *buf;
296 struct target_mem_desc *tgt;
297 /* Array with offsets, chunks[i].start is the starting offset and
298 chunks[i].end ending offset relative to tgt->tgt_start device address
299 of chunks which are to be copied to buf and later copied to device. */
300 struct gomp_coalesce_chunk *chunks;
301 /* Number of chunks in chunks array, or -1 if coalesce buffering should not
302 be performed. */
303 long chunk_cnt;
304 /* During construction of chunks array, how many memory regions are within
305 the last chunk. If there is just one memory region for a chunk, we copy
306 it directly to device rather than going through buf. */
307 long use_cnt;
308 };
309
310 /* Maximum size of memory region considered for coalescing. Larger copies
311 are performed directly. */
312 #define MAX_COALESCE_BUF_SIZE (32 * 1024)
313
314 /* Maximum size of a gap in between regions to consider them being copied
315 within the same chunk. All the device offsets considered are within
316 newly allocated device memory, so it isn't fatal if we copy some padding
317 in between from host to device. The gaps come either from alignment
318 padding or from memory regions which are not supposed to be copied from
319 host to device (e.g. map(alloc:), map(from:) etc.). */
320 #define MAX_COALESCE_BUF_GAP (4 * 1024)
321
322 /* Add region with device tgt_start relative offset and length to CBUF.
323
324 This must not be used for asynchronous copies, because the host data might
325 not be computed yet (by an earlier asynchronous compute region, for
326 example). The exception is for EPHEMERAL data, that we know is available
327 already "by construction". */
328
329 static inline void
330 gomp_coalesce_buf_add (struct gomp_coalesce_buf *cbuf, size_t start, size_t len)
331 {
332 if (len > MAX_COALESCE_BUF_SIZE || len == 0)
333 return;
334 if (cbuf->chunk_cnt)
335 {
336 if (cbuf->chunk_cnt < 0)
337 return;
338 if (start < cbuf->chunks[cbuf->chunk_cnt - 1].end)
339 {
340 cbuf->chunk_cnt = -1;
341 return;
342 }
343 if (start < cbuf->chunks[cbuf->chunk_cnt - 1].end + MAX_COALESCE_BUF_GAP)
344 {
345 cbuf->chunks[cbuf->chunk_cnt - 1].end = start + len;
346 cbuf->use_cnt++;
347 return;
348 }
349 /* If the last chunk is only used by one mapping, discard it,
350 as it will be one host to device copy anyway and
351 memcpying it around will only waste cycles. */
352 if (cbuf->use_cnt == 1)
353 cbuf->chunk_cnt--;
354 }
355 cbuf->chunks[cbuf->chunk_cnt].start = start;
356 cbuf->chunks[cbuf->chunk_cnt].end = start + len;
357 cbuf->chunk_cnt++;
358 cbuf->use_cnt = 1;
359 }
360
361 /* Return true for mapping kinds which need to copy data from the
362 host to device for regions that weren't previously mapped. */
363
364 static inline bool
365 gomp_to_device_kind_p (int kind)
366 {
367 switch (kind)
368 {
369 case GOMP_MAP_ALLOC:
370 case GOMP_MAP_FROM:
371 case GOMP_MAP_FORCE_ALLOC:
372 case GOMP_MAP_FORCE_FROM:
373 case GOMP_MAP_ALWAYS_FROM:
374 case GOMP_MAP_ALWAYS_PRESENT_FROM:
375 case GOMP_MAP_FORCE_PRESENT:
376 return false;
377 default:
378 return true;
379 }
380 }
381
382 /* Copy host memory to an offload device. In asynchronous mode (if AQ is
383 non-NULL), when the source data is stack or may otherwise be deallocated
384 before the asynchronous copy takes place, EPHEMERAL must be passed as
385 TRUE. */
386
387 attribute_hidden void
388 gomp_copy_host2dev (struct gomp_device_descr *devicep,
389 struct goacc_asyncqueue *aq,
390 void *d, const void *h, size_t sz,
391 bool ephemeral, struct gomp_coalesce_buf *cbuf)
392 {
393 if (cbuf)
394 {
395 uintptr_t doff = (uintptr_t) d - cbuf->tgt->tgt_start;
396 if (doff < cbuf->chunks[cbuf->chunk_cnt - 1].end)
397 {
398 long first = 0;
399 long last = cbuf->chunk_cnt - 1;
400 while (first <= last)
401 {
402 long middle = (first + last) >> 1;
403 if (cbuf->chunks[middle].end <= doff)
404 first = middle + 1;
405 else if (cbuf->chunks[middle].start <= doff)
406 {
407 if (doff + sz > cbuf->chunks[middle].end)
408 {
409 gomp_mutex_unlock (&devicep->lock);
410 gomp_fatal ("internal libgomp cbuf error");
411 }
412
413 /* In an asynchronous context, verify that CBUF isn't used
414 with non-EPHEMERAL data; see 'gomp_coalesce_buf_add'. */
415 if (__builtin_expect (aq != NULL, 0))
416 assert (ephemeral);
417
418 memcpy ((char *) cbuf->buf + (doff - cbuf->chunks[0].start),
419 h, sz);
420 return;
421 }
422 else
423 last = middle - 1;
424 }
425 }
426 }
427
428 if (__builtin_expect (aq != NULL, 0))
429 {
430 void *h_buf = (void *) h;
431 if (ephemeral)
432 {
433 /* We're queueing up an asynchronous copy from data that may
434 disappear before the transfer takes place (i.e. because it is a
435 stack local in a function that is no longer executing). As we've
436 not been able to use CBUF, make a copy of the data into a
437 temporary buffer. */
438 h_buf = gomp_malloc (sz);
439 memcpy (h_buf, h, sz);
440 }
441 goacc_device_copy_async (devicep, devicep->openacc.async.host2dev_func,
442 "dev", d, "host", h_buf, h, sz, aq);
443 if (ephemeral)
444 /* Free once the transfer has completed. */
445 devicep->openacc.async.queue_callback_func (aq, free, h_buf);
446 }
447 else
448 gomp_device_copy (devicep, devicep->host2dev_func,
449 "dev", d, "host", h, sz);
450 }
451
452 attribute_hidden void
453 gomp_copy_dev2host (struct gomp_device_descr *devicep,
454 struct goacc_asyncqueue *aq,
455 void *h, const void *d, size_t sz)
456 {
457 if (__builtin_expect (aq != NULL, 0))
458 goacc_device_copy_async (devicep, devicep->openacc.async.dev2host_func,
459 "host", h, "dev", d, NULL, sz, aq);
460 else
461 gomp_device_copy (devicep, devicep->dev2host_func, "host", h, "dev", d, sz);
462 }
463
464 static void
465 gomp_free_device_memory (struct gomp_device_descr *devicep, void *devptr)
466 {
467 if (!devicep->free_func (devicep->target_id, devptr))
468 {
469 gomp_mutex_unlock (&devicep->lock);
470 gomp_fatal ("error in freeing device memory block at %p", devptr);
471 }
472 }
473
474 /* Increment reference count of a splay_tree_key region K by 1.
475 If REFCOUNT_SET != NULL, use it to track already seen refcounts, and only
476 increment the value if refcount is not yet contained in the set (used for
477 OpenMP 5.0, which specifies that a region's refcount is adjusted at most
478 once for each construct). */
479
480 static inline void
481 gomp_increment_refcount (splay_tree_key k, htab_t *refcount_set)
482 {
483 if (k == NULL
484 || k->refcount == REFCOUNT_INFINITY
485 || k->refcount == REFCOUNT_ACC_MAP_DATA)
486 return;
487
488 uintptr_t *refcount_ptr = &k->refcount;
489
490 if (REFCOUNT_STRUCTELEM_FIRST_P (k->refcount))
491 refcount_ptr = &k->structelem_refcount;
492 else if (REFCOUNT_STRUCTELEM_P (k->refcount))
493 refcount_ptr = k->structelem_refcount_ptr;
494
495 if (refcount_set)
496 {
497 if (htab_find (*refcount_set, refcount_ptr))
498 return;
499 uintptr_t **slot = htab_find_slot (refcount_set, refcount_ptr, INSERT);
500 *slot = refcount_ptr;
501 }
502
503 *refcount_ptr += 1;
504 return;
505 }
506
507 /* Decrement reference count of a splay_tree_key region K by 1, or if DELETE_P
508 is true, set reference count to zero. If REFCOUNT_SET != NULL, use it to
509 track already seen refcounts, and only adjust the value if refcount is not
510 yet contained in the set (like gomp_increment_refcount).
511
512 Return out-values: set *DO_COPY to true if we set the refcount to zero, or
513 it is already zero and we know we decremented it earlier. This signals that
514 associated maps should be copied back to host.
515
516 *DO_REMOVE is set to true when we this is the first handling of this refcount
517 and we are setting it to zero. This signals a removal of this key from the
518 splay-tree map.
519
520 Copy and removal are separated due to cases like handling of structure
521 elements, e.g. each map of a structure element representing a possible copy
522 out of a structure field has to be handled individually, but we only signal
523 removal for one (the first encountered) sibing map. */
524
525 static inline void
526 gomp_decrement_refcount (splay_tree_key k, htab_t *refcount_set, bool delete_p,
527 bool *do_copy, bool *do_remove)
528 {
529 if (k == NULL
530 || k->refcount == REFCOUNT_INFINITY
531 || k->refcount == REFCOUNT_ACC_MAP_DATA)
532 {
533 *do_copy = *do_remove = false;
534 return;
535 }
536
537 uintptr_t *refcount_ptr = &k->refcount;
538
539 if (REFCOUNT_STRUCTELEM_FIRST_P (k->refcount))
540 refcount_ptr = &k->structelem_refcount;
541 else if (REFCOUNT_STRUCTELEM_P (k->refcount))
542 refcount_ptr = k->structelem_refcount_ptr;
543
544 bool new_encountered_refcount;
545 bool set_to_zero = false;
546 bool is_zero = false;
547
548 uintptr_t orig_refcount = *refcount_ptr;
549
550 if (refcount_set)
551 {
552 if (htab_find (*refcount_set, refcount_ptr))
553 {
554 new_encountered_refcount = false;
555 goto end;
556 }
557
558 uintptr_t **slot = htab_find_slot (refcount_set, refcount_ptr, INSERT);
559 *slot = refcount_ptr;
560 new_encountered_refcount = true;
561 }
562 else
563 /* If no refcount_set being used, assume all keys are being decremented
564 for the first time. */
565 new_encountered_refcount = true;
566
567 if (delete_p)
568 *refcount_ptr = 0;
569 else if (*refcount_ptr > 0)
570 *refcount_ptr -= 1;
571
572 end:
573 if (*refcount_ptr == 0)
574 {
575 if (orig_refcount > 0)
576 set_to_zero = true;
577
578 is_zero = true;
579 }
580
581 *do_copy = (set_to_zero || (!new_encountered_refcount && is_zero));
582 *do_remove = (new_encountered_refcount && set_to_zero);
583 }
584
585 /* Handle the case where gomp_map_lookup, splay_tree_lookup or
586 gomp_map_0len_lookup found oldn for newn.
587 Helper function of gomp_map_vars. */
588
589 static inline void
590 gomp_map_vars_existing (struct gomp_device_descr *devicep,
591 struct goacc_asyncqueue *aq, splay_tree_key oldn,
592 splay_tree_key newn, struct target_var_desc *tgt_var,
593 unsigned char kind, bool always_to_flag, bool implicit,
594 struct gomp_coalesce_buf *cbuf,
595 htab_t *refcount_set)
596 {
597 assert (kind != GOMP_MAP_ATTACH
598 || kind != GOMP_MAP_ATTACH_ZERO_LENGTH_ARRAY_SECTION);
599
600 tgt_var->key = oldn;
601 tgt_var->copy_from = GOMP_MAP_COPY_FROM_P (kind);
602 tgt_var->always_copy_from = GOMP_MAP_ALWAYS_FROM_P (kind);
603 tgt_var->is_attach = false;
604 tgt_var->offset = newn->host_start - oldn->host_start;
605
606 /* For implicit maps, old contained in new is valid. */
607 bool implicit_subset = (implicit
608 && newn->host_start <= oldn->host_start
609 && oldn->host_end <= newn->host_end);
610 if (implicit_subset)
611 tgt_var->length = oldn->host_end - oldn->host_start;
612 else
613 tgt_var->length = newn->host_end - newn->host_start;
614
615 if (GOMP_MAP_FORCE_P (kind)
616 /* For implicit maps, old contained in new is valid. */
617 || !(implicit_subset
618 /* Otherwise, new contained inside old is considered valid. */
619 || (oldn->host_start <= newn->host_start
620 && newn->host_end <= oldn->host_end)))
621 {
622 gomp_mutex_unlock (&devicep->lock);
623 gomp_fatal ("Trying to map into device [%p..%p) object when "
624 "[%p..%p) is already mapped",
625 (void *) newn->host_start, (void *) newn->host_end,
626 (void *) oldn->host_start, (void *) oldn->host_end);
627 }
628
629 if (GOMP_MAP_ALWAYS_TO_P (kind) || always_to_flag)
630 {
631 /* Implicit + always should not happen. If this does occur, below
632 address/length adjustment is a TODO. */
633 assert (!implicit_subset);
634
635 if (oldn->aux && oldn->aux->attach_count)
636 {
637 /* We have to be careful not to overwrite still attached pointers
638 during the copyback to host. */
639 uintptr_t addr = newn->host_start;
640 while (addr < newn->host_end)
641 {
642 size_t i = (addr - oldn->host_start) / sizeof (void *);
643 if (oldn->aux->attach_count[i] == 0)
644 gomp_copy_host2dev (devicep, aq,
645 (void *) (oldn->tgt->tgt_start
646 + oldn->tgt_offset
647 + addr - oldn->host_start),
648 (void *) addr,
649 sizeof (void *), false, cbuf);
650 addr += sizeof (void *);
651 }
652 }
653 else
654 gomp_copy_host2dev (devicep, aq,
655 (void *) (oldn->tgt->tgt_start + oldn->tgt_offset
656 + newn->host_start - oldn->host_start),
657 (void *) newn->host_start,
658 newn->host_end - newn->host_start, false, cbuf);
659 }
660
661 gomp_increment_refcount (oldn, refcount_set);
662 }
663
664 static int
665 get_kind (bool short_mapkind, void *kinds, int idx)
666 {
667 if (!short_mapkind)
668 return ((unsigned char *) kinds)[idx];
669
670 int val = ((unsigned short *) kinds)[idx];
671 if (GOMP_MAP_IMPLICIT_P (val))
672 val &= ~GOMP_MAP_IMPLICIT;
673 return val;
674 }
675
676
677 static bool
678 get_implicit (bool short_mapkind, void *kinds, int idx)
679 {
680 if (!short_mapkind)
681 return false;
682
683 int val = ((unsigned short *) kinds)[idx];
684 return GOMP_MAP_IMPLICIT_P (val);
685 }
686
687 static void
688 gomp_map_pointer (struct target_mem_desc *tgt, struct goacc_asyncqueue *aq,
689 uintptr_t host_ptr, uintptr_t target_offset, uintptr_t bias,
690 struct gomp_coalesce_buf *cbuf,
691 bool allow_zero_length_array_sections)
692 {
693 struct gomp_device_descr *devicep = tgt->device_descr;
694 struct splay_tree_s *mem_map = &devicep->mem_map;
695 struct splay_tree_key_s cur_node;
696
697 cur_node.host_start = host_ptr;
698 if (cur_node.host_start == (uintptr_t) NULL)
699 {
700 cur_node.tgt_offset = (uintptr_t) NULL;
701 gomp_copy_host2dev (devicep, aq,
702 (void *) (tgt->tgt_start + target_offset),
703 (void *) &cur_node.tgt_offset, sizeof (void *),
704 true, cbuf);
705 return;
706 }
707 /* Add bias to the pointer value. */
708 cur_node.host_start += bias;
709 cur_node.host_end = cur_node.host_start;
710 splay_tree_key n = gomp_map_lookup (mem_map, &cur_node);
711 if (n == NULL)
712 {
713 if (allow_zero_length_array_sections)
714 cur_node.tgt_offset = cur_node.host_start;
715 else
716 {
717 gomp_mutex_unlock (&devicep->lock);
718 gomp_fatal ("Pointer target of array section wasn't mapped");
719 }
720 }
721 else
722 {
723 cur_node.host_start -= n->host_start;
724 cur_node.tgt_offset
725 = n->tgt->tgt_start + n->tgt_offset + cur_node.host_start;
726 /* At this point tgt_offset is target address of the
727 array section. Now subtract bias to get what we want
728 to initialize the pointer with. */
729 cur_node.tgt_offset -= bias;
730 }
731 gomp_copy_host2dev (devicep, aq, (void *) (tgt->tgt_start + target_offset),
732 (void *) &cur_node.tgt_offset, sizeof (void *),
733 true, cbuf);
734 }
735
736 static void
737 gomp_map_fields_existing (struct target_mem_desc *tgt,
738 struct goacc_asyncqueue *aq, splay_tree_key n,
739 size_t first, size_t i, void **hostaddrs,
740 size_t *sizes, void *kinds,
741 struct gomp_coalesce_buf *cbuf, htab_t *refcount_set)
742 {
743 struct gomp_device_descr *devicep = tgt->device_descr;
744 struct splay_tree_s *mem_map = &devicep->mem_map;
745 struct splay_tree_key_s cur_node;
746 int kind;
747 bool implicit;
748 const bool short_mapkind = true;
749 const int typemask = short_mapkind ? 0xff : 0x7;
750
751 cur_node.host_start = (uintptr_t) hostaddrs[i];
752 cur_node.host_end = cur_node.host_start + sizes[i];
753 splay_tree_key n2 = gomp_map_0len_lookup (mem_map, &cur_node);
754 kind = get_kind (short_mapkind, kinds, i);
755 implicit = get_implicit (short_mapkind, kinds, i);
756 if (n2
757 && n2->tgt == n->tgt
758 && n2->host_start - n->host_start == n2->tgt_offset - n->tgt_offset)
759 {
760 gomp_map_vars_existing (devicep, aq, n2, &cur_node, &tgt->list[i],
761 kind & typemask, false, implicit, cbuf,
762 refcount_set);
763 return;
764 }
765 if (sizes[i] == 0)
766 {
767 if (cur_node.host_start > (uintptr_t) hostaddrs[first - 1])
768 {
769 cur_node.host_start--;
770 n2 = splay_tree_lookup (mem_map, &cur_node);
771 cur_node.host_start++;
772 if (n2
773 && n2->tgt == n->tgt
774 && n2->host_start - n->host_start
775 == n2->tgt_offset - n->tgt_offset)
776 {
777 gomp_map_vars_existing (devicep, aq, n2, &cur_node, &tgt->list[i],
778 kind & typemask, false, implicit, cbuf,
779 refcount_set);
780 return;
781 }
782 }
783 cur_node.host_end++;
784 n2 = splay_tree_lookup (mem_map, &cur_node);
785 cur_node.host_end--;
786 if (n2
787 && n2->tgt == n->tgt
788 && n2->host_start - n->host_start == n2->tgt_offset - n->tgt_offset)
789 {
790 gomp_map_vars_existing (devicep, aq, n2, &cur_node, &tgt->list[i],
791 kind & typemask, false, implicit, cbuf,
792 refcount_set);
793 return;
794 }
795 }
796 gomp_mutex_unlock (&devicep->lock);
797 gomp_fatal ("Trying to map into device [%p..%p) structure element when "
798 "other mapped elements from the same structure weren't mapped "
799 "together with it", (void *) cur_node.host_start,
800 (void *) cur_node.host_end);
801 }
802
803 /* Update the devptr by setting it to the device address of the host pointee
804 'attach_to'; devptr is obtained from the splay_tree_key n.
805 When the pointer is already attached or the host pointee is either
806 NULL or in memory map, this function returns true.
807 Otherwise, the device pointer is set to point to the host pointee and:
808 - If allow_zero_length_array_sections is set, true is returned.
809 - Else, if fail_if_not_found is set, a fatal error is issued.
810 - Otherwise, false is returned. */
811
812 attribute_hidden bool
813 gomp_attach_pointer (struct gomp_device_descr *devicep,
814 struct goacc_asyncqueue *aq, splay_tree mem_map,
815 splay_tree_key n, uintptr_t attach_to, size_t bias,
816 struct gomp_coalesce_buf *cbufp,
817 bool allow_zero_length_array_sections,
818 bool fail_if_not_found)
819 {
820 struct splay_tree_key_s s;
821 size_t size, idx;
822
823 if (n == NULL)
824 {
825 gomp_mutex_unlock (&devicep->lock);
826 gomp_fatal ("enclosing struct not mapped for attach");
827 }
828
829 size = (n->host_end - n->host_start + sizeof (void *) - 1) / sizeof (void *);
830 /* We might have a pointer in a packed struct: however we cannot have more
831 than one such pointer in each pointer-sized portion of the struct, so
832 this is safe. */
833 idx = (attach_to - n->host_start) / sizeof (void *);
834
835 if (!n->aux)
836 n->aux = gomp_malloc_cleared (sizeof (struct splay_tree_aux));
837
838 if (!n->aux->attach_count)
839 n->aux->attach_count
840 = gomp_malloc_cleared (sizeof (*n->aux->attach_count) * size);
841
842 if (n->aux->attach_count[idx] < UINTPTR_MAX)
843 n->aux->attach_count[idx]++;
844 else
845 {
846 gomp_mutex_unlock (&devicep->lock);
847 gomp_fatal ("attach count overflow");
848 }
849
850 if (n->aux->attach_count[idx] == 1)
851 {
852 uintptr_t devptr = n->tgt->tgt_start + n->tgt_offset + attach_to
853 - n->host_start;
854 uintptr_t target = (uintptr_t) *(void **) attach_to;
855 splay_tree_key tn;
856 uintptr_t data;
857
858 if ((void *) target == NULL)
859 {
860 /* As a special case, allow attaching NULL host pointers. This
861 allows e.g. unassociated Fortran pointers to be mapped
862 properly. */
863 data = 0;
864
865 gomp_debug (1,
866 "%s: attaching NULL host pointer, target %p "
867 "(struct base %p)\n", __FUNCTION__, (void *) devptr,
868 (void *) (n->tgt->tgt_start + n->tgt_offset));
869
870 gomp_copy_host2dev (devicep, aq, (void *) devptr, (void *) &data,
871 sizeof (void *), true, cbufp);
872
873 return true;
874 }
875
876 s.host_start = target + bias;
877 s.host_end = s.host_start + 1;
878 tn = splay_tree_lookup (mem_map, &s);
879
880 if (!tn)
881 {
882 /* We copy the host pointer when the target region is not mapped;
883 for allow_zero_length_array_sections, that's permitted.
884 Otherwise, it depends on the context. Return false in that
885 case, unless fail_if_not_found. */
886 if (!allow_zero_length_array_sections && fail_if_not_found)
887 {
888 gomp_mutex_unlock (&devicep->lock);
889 gomp_fatal ("pointer target not mapped for attach");
890 }
891 data = target;
892 }
893 else
894 data = tn->tgt->tgt_start + tn->tgt_offset + target - tn->host_start;
895
896 gomp_debug (1,
897 "%s: attaching host %p, target %p (struct base %p) to %p\n",
898 __FUNCTION__, (void *) attach_to, (void *) devptr,
899 (void *) (n->tgt->tgt_start + n->tgt_offset), (void *) data);
900
901 gomp_copy_host2dev (devicep, aq, (void *) devptr, (void *) &data,
902 sizeof (void *), true, cbufp);
903 if (!tn && !allow_zero_length_array_sections)
904 return false;
905 }
906 else
907 gomp_debug (1, "%s: attach count for %p -> %u\n", __FUNCTION__,
908 (void *) attach_to, (int) n->aux->attach_count[idx]);
909 return true;
910 }
911
912 attribute_hidden void
913 gomp_detach_pointer (struct gomp_device_descr *devicep,
914 struct goacc_asyncqueue *aq, splay_tree_key n,
915 uintptr_t detach_from, bool finalize,
916 struct gomp_coalesce_buf *cbufp)
917 {
918 size_t idx;
919
920 if (n == NULL)
921 {
922 gomp_mutex_unlock (&devicep->lock);
923 gomp_fatal ("enclosing struct not mapped for detach");
924 }
925
926 idx = (detach_from - n->host_start) / sizeof (void *);
927
928 if (!n->aux || !n->aux->attach_count)
929 {
930 gomp_mutex_unlock (&devicep->lock);
931 gomp_fatal ("no attachment counters for struct");
932 }
933
934 if (finalize)
935 n->aux->attach_count[idx] = 1;
936
937 if (n->aux->attach_count[idx] == 0)
938 {
939 gomp_mutex_unlock (&devicep->lock);
940 gomp_fatal ("attach count underflow");
941 }
942 else
943 n->aux->attach_count[idx]--;
944
945 if (n->aux->attach_count[idx] == 0)
946 {
947 uintptr_t devptr = n->tgt->tgt_start + n->tgt_offset + detach_from
948 - n->host_start;
949 uintptr_t target = (uintptr_t) *(void **) detach_from;
950
951 gomp_debug (1,
952 "%s: detaching host %p, target %p (struct base %p) to %p\n",
953 __FUNCTION__, (void *) detach_from, (void *) devptr,
954 (void *) (n->tgt->tgt_start + n->tgt_offset),
955 (void *) target);
956
957 gomp_copy_host2dev (devicep, aq, (void *) devptr, (void *) &target,
958 sizeof (void *), true, cbufp);
959 }
960 else
961 gomp_debug (1, "%s: attach count for %p -> %u\n", __FUNCTION__,
962 (void *) detach_from, (int) n->aux->attach_count[idx]);
963 }
964
965 attribute_hidden uintptr_t
966 gomp_map_val (struct target_mem_desc *tgt, void **hostaddrs, size_t i)
967 {
968 if (tgt->list[i].key != NULL)
969 return tgt->list[i].key->tgt->tgt_start
970 + tgt->list[i].key->tgt_offset
971 + tgt->list[i].offset;
972
973 switch (tgt->list[i].offset)
974 {
975 case OFFSET_INLINED:
976 return (uintptr_t) hostaddrs[i];
977
978 case OFFSET_POINTER:
979 return 0;
980
981 case OFFSET_STRUCT:
982 return tgt->list[i + 1].key->tgt->tgt_start
983 + tgt->list[i + 1].key->tgt_offset
984 + tgt->list[i + 1].offset
985 + (uintptr_t) hostaddrs[i]
986 - (uintptr_t) hostaddrs[i + 1];
987
988 default:
989 return tgt->tgt_start + tgt->list[i].offset;
990 }
991 }
992
993 static inline __attribute__((always_inline)) struct target_mem_desc *
994 gomp_map_vars_internal (struct gomp_device_descr *devicep,
995 struct goacc_asyncqueue *aq, size_t mapnum,
996 void **hostaddrs, void **devaddrs, size_t *sizes,
997 void *kinds, bool short_mapkind,
998 htab_t *refcount_set,
999 enum gomp_map_vars_kind pragma_kind)
1000 {
1001 size_t i, tgt_align, tgt_size, not_found_cnt = 0;
1002 bool has_firstprivate = false;
1003 bool has_always_ptrset = false;
1004 bool openmp_p = (pragma_kind & GOMP_MAP_VARS_OPENACC) == 0;
1005 const int rshift = short_mapkind ? 8 : 3;
1006 const int typemask = short_mapkind ? 0xff : 0x7;
1007 struct splay_tree_s *mem_map = &devicep->mem_map;
1008 struct splay_tree_key_s cur_node;
1009 struct target_mem_desc *tgt
1010 = gomp_malloc (sizeof (*tgt) + sizeof (tgt->list[0]) * mapnum);
1011 tgt->list_count = mapnum;
1012 tgt->refcount = (pragma_kind & GOMP_MAP_VARS_ENTER_DATA) ? 0 : 1;
1013 tgt->device_descr = devicep;
1014 tgt->prev = NULL;
1015 struct gomp_coalesce_buf cbuf, *cbufp = NULL;
1016
1017 if (mapnum == 0)
1018 {
1019 tgt->tgt_start = 0;
1020 tgt->tgt_end = 0;
1021 return tgt;
1022 }
1023
1024 tgt_align = sizeof (void *);
1025 tgt_size = 0;
1026 cbuf.chunks = NULL;
1027 cbuf.chunk_cnt = -1;
1028 cbuf.use_cnt = 0;
1029 cbuf.buf = NULL;
1030 if (mapnum > 1 || (pragma_kind & GOMP_MAP_VARS_TARGET))
1031 {
1032 size_t chunks_size = (mapnum + 1) * sizeof (struct gomp_coalesce_chunk);
1033 cbuf.chunks = (struct gomp_coalesce_chunk *) gomp_alloca (chunks_size);
1034 cbuf.chunk_cnt = 0;
1035 }
1036 if (pragma_kind & GOMP_MAP_VARS_TARGET)
1037 {
1038 size_t align = 4 * sizeof (void *);
1039 tgt_align = align;
1040 tgt_size = mapnum * sizeof (void *);
1041 cbuf.chunk_cnt = 1;
1042 cbuf.use_cnt = 1 + (mapnum > 1);
1043 cbuf.chunks[0].start = 0;
1044 cbuf.chunks[0].end = tgt_size;
1045 }
1046
1047 gomp_mutex_lock (&devicep->lock);
1048 if (devicep->state == GOMP_DEVICE_FINALIZED)
1049 {
1050 gomp_mutex_unlock (&devicep->lock);
1051 free (tgt);
1052 return NULL;
1053 }
1054
1055 for (i = 0; i < mapnum; i++)
1056 {
1057 int kind = get_kind (short_mapkind, kinds, i);
1058 bool implicit = get_implicit (short_mapkind, kinds, i);
1059 if (hostaddrs[i] == NULL
1060 || (kind & typemask) == GOMP_MAP_FIRSTPRIVATE_INT)
1061 {
1062 tgt->list[i].key = NULL;
1063 tgt->list[i].offset = OFFSET_INLINED;
1064 continue;
1065 }
1066 else if ((kind & typemask) == GOMP_MAP_USE_DEVICE_PTR
1067 || (kind & typemask) == GOMP_MAP_USE_DEVICE_PTR_IF_PRESENT)
1068 {
1069 tgt->list[i].key = NULL;
1070 if (!not_found_cnt)
1071 {
1072 /* In OpenMP < 5.0 and OpenACC the mapping has to be done
1073 on a separate construct prior to using use_device_{addr,ptr}.
1074 In OpenMP 5.0, map directives need to be ordered by the
1075 middle-end before the use_device_* clauses. If
1076 !not_found_cnt, all mappings requested (if any) are already
1077 mapped, so use_device_{addr,ptr} can be resolved right away.
1078 Otherwise, if not_found_cnt, gomp_map_lookup might fail
1079 now but would succeed after performing the mappings in the
1080 following loop. We can't defer this always to the second
1081 loop, because it is not even invoked when !not_found_cnt
1082 after the first loop. */
1083 cur_node.host_start = (uintptr_t) hostaddrs[i];
1084 cur_node.host_end = cur_node.host_start;
1085 splay_tree_key n = gomp_map_lookup (mem_map, &cur_node);
1086 if (n != NULL)
1087 {
1088 cur_node.host_start -= n->host_start;
1089 hostaddrs[i]
1090 = (void *) (n->tgt->tgt_start + n->tgt_offset
1091 + cur_node.host_start);
1092 }
1093 else if ((kind & typemask) == GOMP_MAP_USE_DEVICE_PTR)
1094 {
1095 gomp_mutex_unlock (&devicep->lock);
1096 gomp_fatal ("use_device_ptr pointer wasn't mapped");
1097 }
1098 else if ((kind & typemask) == GOMP_MAP_USE_DEVICE_PTR_IF_PRESENT)
1099 /* If not present, continue using the host address. */
1100 ;
1101 else
1102 __builtin_unreachable ();
1103 tgt->list[i].offset = OFFSET_INLINED;
1104 }
1105 else
1106 tgt->list[i].offset = 0;
1107 continue;
1108 }
1109 else if ((kind & typemask) == GOMP_MAP_STRUCT
1110 || (kind & typemask) == GOMP_MAP_STRUCT_UNORD)
1111 {
1112 size_t first = i + 1;
1113 size_t last = i + sizes[i];
1114 cur_node.host_start = (uintptr_t) hostaddrs[i];
1115 cur_node.host_end = (uintptr_t) hostaddrs[last]
1116 + sizes[last];
1117 tgt->list[i].key = NULL;
1118 tgt->list[i].offset = OFFSET_STRUCT;
1119 splay_tree_key n = splay_tree_lookup (mem_map, &cur_node);
1120 if (n == NULL)
1121 {
1122 size_t align = (size_t) 1 << (kind >> rshift);
1123 if (tgt_align < align)
1124 tgt_align = align;
1125 tgt_size -= (uintptr_t) hostaddrs[first] - cur_node.host_start;
1126 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1127 tgt_size += cur_node.host_end - cur_node.host_start;
1128 not_found_cnt += last - i;
1129 for (i = first; i <= last; i++)
1130 {
1131 tgt->list[i].key = NULL;
1132 if (!aq
1133 && gomp_to_device_kind_p (get_kind (short_mapkind, kinds, i)
1134 & typemask)
1135 && sizes[i] != 0)
1136 gomp_coalesce_buf_add (&cbuf,
1137 tgt_size - cur_node.host_end
1138 + (uintptr_t) hostaddrs[i],
1139 sizes[i]);
1140 }
1141 i--;
1142 continue;
1143 }
1144 for (i = first; i <= last; i++)
1145 gomp_map_fields_existing (tgt, aq, n, first, i, hostaddrs,
1146 sizes, kinds, NULL, refcount_set);
1147 i--;
1148 continue;
1149 }
1150 else if ((kind & typemask) == GOMP_MAP_ALWAYS_POINTER)
1151 {
1152 tgt->list[i].key = NULL;
1153 tgt->list[i].offset = OFFSET_POINTER;
1154 has_firstprivate = true;
1155 continue;
1156 }
1157 else if ((kind & typemask) == GOMP_MAP_ATTACH
1158 || ((kind & typemask)
1159 == GOMP_MAP_ATTACH_ZERO_LENGTH_ARRAY_SECTION))
1160 {
1161 tgt->list[i].key = NULL;
1162 has_firstprivate = true;
1163 continue;
1164 }
1165 cur_node.host_start = (uintptr_t) hostaddrs[i];
1166 if (!GOMP_MAP_POINTER_P (kind & typemask))
1167 cur_node.host_end = cur_node.host_start + sizes[i];
1168 else
1169 cur_node.host_end = cur_node.host_start + sizeof (void *);
1170 if ((kind & typemask) == GOMP_MAP_FIRSTPRIVATE)
1171 {
1172 tgt->list[i].key = NULL;
1173
1174 size_t align = (size_t) 1 << (kind >> rshift);
1175 if (tgt_align < align)
1176 tgt_align = align;
1177 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1178 if (!aq)
1179 gomp_coalesce_buf_add (&cbuf, tgt_size,
1180 cur_node.host_end - cur_node.host_start);
1181 tgt_size += cur_node.host_end - cur_node.host_start;
1182 has_firstprivate = true;
1183 continue;
1184 }
1185 splay_tree_key n;
1186 if ((kind & typemask) == GOMP_MAP_ZERO_LEN_ARRAY_SECTION)
1187 {
1188 n = gomp_map_0len_lookup (mem_map, &cur_node);
1189 if (!n)
1190 {
1191 tgt->list[i].key = NULL;
1192 tgt->list[i].offset = OFFSET_INLINED;
1193 continue;
1194 }
1195 }
1196 else
1197 n = splay_tree_lookup (mem_map, &cur_node);
1198 if (n && n->refcount != REFCOUNT_LINK)
1199 {
1200 int always_to_cnt = 0;
1201 if ((kind & typemask) == GOMP_MAP_TO_PSET)
1202 {
1203 bool has_nullptr = false;
1204 size_t j;
1205 for (j = 0; j < n->tgt->list_count; j++)
1206 if (n->tgt->list[j].key == n)
1207 {
1208 has_nullptr = n->tgt->list[j].has_null_ptr_assoc;
1209 break;
1210 }
1211 if (n->tgt->list_count == 0)
1212 {
1213 /* 'declare target'; assume has_nullptr; it could also be
1214 statically assigned pointer, but that it should be to
1215 the equivalent variable on the host. */
1216 assert (n->refcount == REFCOUNT_INFINITY);
1217 has_nullptr = true;
1218 }
1219 else
1220 assert (j < n->tgt->list_count);
1221 /* Re-map the data if there is an 'always' modifier or if it a
1222 null pointer was there and non a nonnull has been found; that
1223 permits transparent re-mapping for Fortran array descriptors
1224 which were previously mapped unallocated. */
1225 for (j = i + 1; j < mapnum; j++)
1226 {
1227 int ptr_kind = get_kind (short_mapkind, kinds, j) & typemask;
1228 if (!GOMP_MAP_ALWAYS_POINTER_P (ptr_kind)
1229 && (!has_nullptr
1230 || !GOMP_MAP_POINTER_P (ptr_kind)
1231 || *(void **) hostaddrs[j] == NULL))
1232 break;
1233 else if ((uintptr_t) hostaddrs[j] < cur_node.host_start
1234 || ((uintptr_t) hostaddrs[j] + sizeof (void *)
1235 > cur_node.host_end))
1236 break;
1237 else
1238 {
1239 has_always_ptrset = true;
1240 ++always_to_cnt;
1241 }
1242 }
1243 }
1244 gomp_map_vars_existing (devicep, aq, n, &cur_node, &tgt->list[i],
1245 kind & typemask, always_to_cnt > 0, implicit,
1246 NULL, refcount_set);
1247 i += always_to_cnt;
1248 }
1249 else
1250 {
1251 tgt->list[i].key = NULL;
1252
1253 if ((kind & typemask) == GOMP_MAP_IF_PRESENT)
1254 {
1255 /* Not present, hence, skip entry - including its MAP_POINTER,
1256 when existing. */
1257 tgt->list[i].offset = OFFSET_INLINED;
1258 if (i + 1 < mapnum
1259 && ((typemask & get_kind (short_mapkind, kinds, i + 1))
1260 == GOMP_MAP_POINTER))
1261 {
1262 ++i;
1263 tgt->list[i].key = NULL;
1264 tgt->list[i].offset = 0;
1265 }
1266 continue;
1267 }
1268 size_t align = (size_t) 1 << (kind >> rshift);
1269 not_found_cnt++;
1270 if (tgt_align < align)
1271 tgt_align = align;
1272 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1273 if (!aq
1274 && gomp_to_device_kind_p (kind & typemask))
1275 gomp_coalesce_buf_add (&cbuf, tgt_size,
1276 cur_node.host_end - cur_node.host_start);
1277 tgt_size += cur_node.host_end - cur_node.host_start;
1278 if ((kind & typemask) == GOMP_MAP_TO_PSET)
1279 {
1280 size_t j;
1281 int kind;
1282 for (j = i + 1; j < mapnum; j++)
1283 if (!GOMP_MAP_POINTER_P ((kind = (get_kind (short_mapkind,
1284 kinds, j)) & typemask))
1285 && !GOMP_MAP_ALWAYS_POINTER_P (kind))
1286 break;
1287 else if ((uintptr_t) hostaddrs[j] < cur_node.host_start
1288 || ((uintptr_t) hostaddrs[j] + sizeof (void *)
1289 > cur_node.host_end))
1290 break;
1291 else
1292 {
1293 tgt->list[j].key = NULL;
1294 i++;
1295 }
1296 }
1297 }
1298 }
1299
1300 if (devaddrs)
1301 {
1302 if (mapnum != 1)
1303 {
1304 gomp_mutex_unlock (&devicep->lock);
1305 gomp_fatal ("unexpected aggregation");
1306 }
1307 tgt->to_free = devaddrs[0];
1308 tgt->tgt_start = (uintptr_t) tgt->to_free;
1309 tgt->tgt_end = tgt->tgt_start + sizes[0];
1310 }
1311 else if (not_found_cnt || (pragma_kind & GOMP_MAP_VARS_TARGET))
1312 {
1313 /* Allocate tgt_align aligned tgt_size block of memory. */
1314 /* FIXME: Perhaps change interface to allocate properly aligned
1315 memory. */
1316 tgt->to_free = devicep->alloc_func (devicep->target_id,
1317 tgt_size + tgt_align - 1);
1318 if (!tgt->to_free)
1319 {
1320 gomp_mutex_unlock (&devicep->lock);
1321 gomp_fatal ("device memory allocation fail");
1322 }
1323
1324 tgt->tgt_start = (uintptr_t) tgt->to_free;
1325 tgt->tgt_start = (tgt->tgt_start + tgt_align - 1) & ~(tgt_align - 1);
1326 tgt->tgt_end = tgt->tgt_start + tgt_size;
1327
1328 if (cbuf.use_cnt == 1)
1329 cbuf.chunk_cnt--;
1330 if (cbuf.chunk_cnt > 0)
1331 {
1332 cbuf.buf
1333 = malloc (cbuf.chunks[cbuf.chunk_cnt - 1].end - cbuf.chunks[0].start);
1334 if (cbuf.buf)
1335 {
1336 cbuf.tgt = tgt;
1337 cbufp = &cbuf;
1338 }
1339 }
1340 }
1341 else
1342 {
1343 tgt->to_free = NULL;
1344 tgt->tgt_start = 0;
1345 tgt->tgt_end = 0;
1346 }
1347
1348 tgt_size = 0;
1349 if (pragma_kind & GOMP_MAP_VARS_TARGET)
1350 tgt_size = mapnum * sizeof (void *);
1351
1352 tgt->array = NULL;
1353 if (not_found_cnt || has_firstprivate || has_always_ptrset)
1354 {
1355 if (not_found_cnt)
1356 tgt->array = gomp_malloc (not_found_cnt * sizeof (*tgt->array));
1357 splay_tree_node array = tgt->array;
1358 size_t j, field_tgt_offset = 0, field_tgt_clear = FIELD_TGT_EMPTY;
1359 uintptr_t field_tgt_base = 0;
1360 splay_tree_key field_tgt_structelem_first = NULL;
1361
1362 for (i = 0; i < mapnum; i++)
1363 if (has_always_ptrset
1364 && tgt->list[i].key
1365 && (get_kind (short_mapkind, kinds, i) & typemask)
1366 == GOMP_MAP_TO_PSET)
1367 {
1368 splay_tree_key k = tgt->list[i].key;
1369 bool has_nullptr = false;
1370 size_t j;
1371 for (j = 0; j < k->tgt->list_count; j++)
1372 if (k->tgt->list[j].key == k)
1373 {
1374 has_nullptr = k->tgt->list[j].has_null_ptr_assoc;
1375 break;
1376 }
1377 if (k->tgt->list_count == 0)
1378 has_nullptr = true;
1379 else
1380 assert (j < k->tgt->list_count);
1381
1382 tgt->list[i].has_null_ptr_assoc = false;
1383 for (j = i + 1; j < mapnum; j++)
1384 {
1385 int ptr_kind = get_kind (short_mapkind, kinds, j) & typemask;
1386 if (!GOMP_MAP_ALWAYS_POINTER_P (ptr_kind)
1387 && (!has_nullptr
1388 || !GOMP_MAP_POINTER_P (ptr_kind)
1389 || *(void **) hostaddrs[j] == NULL))
1390 break;
1391 else if ((uintptr_t) hostaddrs[j] < k->host_start
1392 || ((uintptr_t) hostaddrs[j] + sizeof (void *)
1393 > k->host_end))
1394 break;
1395 else
1396 {
1397 if (*(void **) hostaddrs[j] == NULL)
1398 tgt->list[i].has_null_ptr_assoc = true;
1399 tgt->list[j].key = k;
1400 tgt->list[j].copy_from = false;
1401 tgt->list[j].always_copy_from = false;
1402 tgt->list[j].is_attach = false;
1403 gomp_increment_refcount (k, refcount_set);
1404 gomp_map_pointer (k->tgt, aq,
1405 (uintptr_t) *(void **) hostaddrs[j],
1406 k->tgt_offset + ((uintptr_t) hostaddrs[j]
1407 - k->host_start),
1408 sizes[j], cbufp, false);
1409 }
1410 }
1411 i = j - 1;
1412 }
1413 else if (tgt->list[i].key == NULL)
1414 {
1415 int kind = get_kind (short_mapkind, kinds, i);
1416 bool implicit = get_implicit (short_mapkind, kinds, i);
1417 if (hostaddrs[i] == NULL)
1418 continue;
1419 switch (kind & typemask)
1420 {
1421 size_t align, len, first, last;
1422 splay_tree_key n;
1423 case GOMP_MAP_FIRSTPRIVATE:
1424 align = (size_t) 1 << (kind >> rshift);
1425 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1426 tgt->list[i].offset = tgt_size;
1427 len = sizes[i];
1428 gomp_copy_host2dev (devicep, aq,
1429 (void *) (tgt->tgt_start + tgt_size),
1430 (void *) hostaddrs[i], len, false, cbufp);
1431 /* Save device address in hostaddr to permit latter availablity
1432 when doing a deep-firstprivate with pointer attach. */
1433 hostaddrs[i] = (void *) (tgt->tgt_start + tgt_size);
1434 tgt_size += len;
1435
1436 /* If followed by GOMP_MAP_ATTACH, pointer assign this
1437 firstprivate to hostaddrs[i+1], which is assumed to contain a
1438 device address. */
1439 if (i + 1 < mapnum
1440 && (GOMP_MAP_ATTACH
1441 == (typemask & get_kind (short_mapkind, kinds, i+1))))
1442 {
1443 uintptr_t target = (uintptr_t) hostaddrs[i];
1444 void *devptr = *(void**) hostaddrs[i+1] + sizes[i+1];
1445 /* Per
1446 <https://inbox.sourceware.org/gcc-patches/[email protected]>
1447 "OpenMP: Handle descriptors in target's firstprivate [PR104949]"
1448 this probably needs revision for 'aq' usage. */
1449 assert (!aq);
1450 gomp_copy_host2dev (devicep, aq, devptr, &target,
1451 sizeof (void *), false, cbufp);
1452 ++i;
1453 }
1454 continue;
1455 case GOMP_MAP_FIRSTPRIVATE_INT:
1456 case GOMP_MAP_ZERO_LEN_ARRAY_SECTION:
1457 continue;
1458 case GOMP_MAP_USE_DEVICE_PTR_IF_PRESENT:
1459 /* The OpenACC 'host_data' construct only allows 'use_device'
1460 "mapping" clauses, so in the first loop, 'not_found_cnt'
1461 must always have been zero, so all OpenACC 'use_device'
1462 clauses have already been handled. (We can only easily test
1463 'use_device' with 'if_present' clause here.) */
1464 assert (tgt->list[i].offset == OFFSET_INLINED);
1465 /* Nevertheless, FALLTHRU to the normal handling, to keep the
1466 code conceptually simple, similar to the first loop. */
1467 case GOMP_MAP_USE_DEVICE_PTR:
1468 if (tgt->list[i].offset == 0)
1469 {
1470 cur_node.host_start = (uintptr_t) hostaddrs[i];
1471 cur_node.host_end = cur_node.host_start;
1472 n = gomp_map_lookup (mem_map, &cur_node);
1473 if (n != NULL)
1474 {
1475 cur_node.host_start -= n->host_start;
1476 hostaddrs[i]
1477 = (void *) (n->tgt->tgt_start + n->tgt_offset
1478 + cur_node.host_start);
1479 }
1480 else if ((kind & typemask) == GOMP_MAP_USE_DEVICE_PTR)
1481 {
1482 gomp_mutex_unlock (&devicep->lock);
1483 gomp_fatal ("use_device_ptr pointer wasn't mapped");
1484 }
1485 else if ((kind & typemask)
1486 == GOMP_MAP_USE_DEVICE_PTR_IF_PRESENT)
1487 /* If not present, continue using the host address. */
1488 ;
1489 else
1490 __builtin_unreachable ();
1491 tgt->list[i].offset = OFFSET_INLINED;
1492 }
1493 continue;
1494 case GOMP_MAP_STRUCT_UNORD:
1495 if (sizes[i] > 1)
1496 {
1497 void *first = hostaddrs[i + 1];
1498 for (size_t j = i + 1; j < i + sizes[i]; j++)
1499 if (hostaddrs[j + 1] != first)
1500 {
1501 gomp_mutex_unlock (&devicep->lock);
1502 gomp_fatal ("Mapped array elements must be the "
1503 "same (%p vs %p)", first,
1504 hostaddrs[j + 1]);
1505 }
1506 }
1507 /* Fallthrough. */
1508 case GOMP_MAP_STRUCT:
1509 first = i + 1;
1510 last = i + sizes[i];
1511 cur_node.host_start = (uintptr_t) hostaddrs[i];
1512 cur_node.host_end = (uintptr_t) hostaddrs[last]
1513 + sizes[last];
1514 if (tgt->list[first].key != NULL)
1515 continue;
1516 if (sizes[last] == 0)
1517 cur_node.host_end++;
1518 n = splay_tree_lookup (mem_map, &cur_node);
1519 if (sizes[last] == 0)
1520 cur_node.host_end--;
1521 if (n == NULL && cur_node.host_start == cur_node.host_end)
1522 {
1523 gomp_mutex_unlock (&devicep->lock);
1524 gomp_fatal ("Struct pointer member not mapped (%p)",
1525 (void*) hostaddrs[first]);
1526 }
1527 if (n == NULL)
1528 {
1529 size_t align = (size_t) 1 << (kind >> rshift);
1530 tgt_size -= (uintptr_t) hostaddrs[first]
1531 - (uintptr_t) hostaddrs[i];
1532 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1533 tgt_size += (uintptr_t) hostaddrs[first]
1534 - (uintptr_t) hostaddrs[i];
1535 field_tgt_base = (uintptr_t) hostaddrs[first];
1536 field_tgt_offset = tgt_size;
1537 field_tgt_clear = last;
1538 field_tgt_structelem_first = NULL;
1539 tgt_size += cur_node.host_end
1540 - (uintptr_t) hostaddrs[first];
1541 continue;
1542 }
1543 for (i = first; i <= last; i++)
1544 gomp_map_fields_existing (tgt, aq, n, first, i, hostaddrs,
1545 sizes, kinds, cbufp, refcount_set);
1546 i--;
1547 continue;
1548 case GOMP_MAP_ALWAYS_POINTER:
1549 cur_node.host_start = (uintptr_t) hostaddrs[i];
1550 cur_node.host_end = cur_node.host_start + sizeof (void *);
1551 n = splay_tree_lookup (mem_map, &cur_node);
1552 if (n == NULL
1553 || n->host_start > cur_node.host_start
1554 || n->host_end < cur_node.host_end)
1555 {
1556 gomp_mutex_unlock (&devicep->lock);
1557 gomp_fatal ("always pointer not mapped");
1558 }
1559 if (i > 0
1560 && ((get_kind (short_mapkind, kinds, i - 1) & typemask)
1561 != GOMP_MAP_ALWAYS_POINTER))
1562 cur_node.tgt_offset = gomp_map_val (tgt, hostaddrs, i - 1);
1563 if (cur_node.tgt_offset)
1564 cur_node.tgt_offset -= sizes[i];
1565 gomp_copy_host2dev (devicep, aq,
1566 (void *) (n->tgt->tgt_start
1567 + n->tgt_offset
1568 + cur_node.host_start
1569 - n->host_start),
1570 (void *) &cur_node.tgt_offset,
1571 sizeof (void *), true, cbufp);
1572 cur_node.tgt_offset = n->tgt->tgt_start + n->tgt_offset
1573 + cur_node.host_start - n->host_start;
1574 continue;
1575 case GOMP_MAP_IF_PRESENT:
1576 /* Not present - otherwise handled above. Skip over its
1577 MAP_POINTER as well. */
1578 if (i + 1 < mapnum
1579 && ((typemask & get_kind (short_mapkind, kinds, i + 1))
1580 == GOMP_MAP_POINTER))
1581 ++i;
1582 continue;
1583 case GOMP_MAP_ATTACH:
1584 case GOMP_MAP_ATTACH_ZERO_LENGTH_ARRAY_SECTION:
1585 {
1586 cur_node.host_start = (uintptr_t) hostaddrs[i];
1587 cur_node.host_end = cur_node.host_start + sizeof (void *);
1588 splay_tree_key n = splay_tree_lookup (mem_map, &cur_node);
1589 if (n != NULL)
1590 {
1591 tgt->list[i].key = n;
1592 tgt->list[i].offset = cur_node.host_start - n->host_start;
1593 tgt->list[i].length = n->host_end - n->host_start;
1594 tgt->list[i].copy_from = false;
1595 tgt->list[i].always_copy_from = false;
1596 tgt->list[i].is_attach = true;
1597 /* OpenACC 'attach'/'detach' doesn't affect
1598 structured/dynamic reference counts ('n->refcount',
1599 'n->dynamic_refcount'). */
1600
1601 bool zlas
1602 = ((kind & typemask)
1603 == GOMP_MAP_ATTACH_ZERO_LENGTH_ARRAY_SECTION);
1604 /* For 'target enter data', the map clauses are split;
1605 however, for more complex code with struct and
1606 pointer members, the mapping and the attach can end up
1607 in different sets; or the wrong mapping with the
1608 attach. As there is no way to know whether a size
1609 zero like 'var->ptr[i][:0]' happend in the same
1610 directive or not, the not-attached check is now
1611 fully silenced for 'enter data'. */
1612 if (openmp_p && (pragma_kind & GOMP_MAP_VARS_ENTER_DATA))
1613 zlas = true;
1614 if (!gomp_attach_pointer (devicep, aq, mem_map, n,
1615 (uintptr_t) hostaddrs[i], sizes[i],
1616 cbufp, zlas, !openmp_p))
1617 {
1618 /* Pointee not found; that's an error except for
1619 map(var[:n]) with n == 0; the compiler adds a
1620 runtime condition such that for those the kind is
1621 always GOMP_MAP_ZERO_LEN_ARRAY_SECTION. */
1622 for (j = i; j > 0; j--)
1623 if (*(void**) hostaddrs[i] == hostaddrs[j-1] - sizes[i]
1624 && sizes[j-1] == 0
1625 && (GOMP_MAP_ZERO_LEN_ARRAY_SECTION
1626 == (get_kind (short_mapkind, kinds, j-1)
1627 & typemask)))
1628 break;
1629 if (j == 0)
1630 {
1631 gomp_mutex_unlock (&devicep->lock);
1632 gomp_fatal ("pointer target not mapped for attach");
1633 }
1634 }
1635 }
1636 else if ((pragma_kind & GOMP_MAP_VARS_OPENACC) != 0)
1637 {
1638 gomp_mutex_unlock (&devicep->lock);
1639 gomp_fatal ("outer struct not mapped for attach");
1640 }
1641 continue;
1642 }
1643 default:
1644 break;
1645 }
1646 splay_tree_key k = &array->key;
1647 k->host_start = (uintptr_t) hostaddrs[i];
1648 if (!GOMP_MAP_POINTER_P (kind & typemask))
1649 k->host_end = k->host_start + sizes[i];
1650 else
1651 k->host_end = k->host_start + sizeof (void *);
1652 splay_tree_key n = splay_tree_lookup (mem_map, k);
1653 if (n && n->refcount != REFCOUNT_LINK)
1654 {
1655 if (field_tgt_clear != FIELD_TGT_EMPTY)
1656 {
1657 /* For this condition to be true, there must be a
1658 duplicate struct element mapping. This can happen with
1659 GOMP_MAP_STRUCT_UNORD mappings, for example. */
1660 tgt->list[i].key = n;
1661 if (openmp_p)
1662 {
1663 assert ((n->refcount & REFCOUNT_STRUCTELEM) != 0);
1664 assert (field_tgt_structelem_first != NULL);
1665
1666 if (i == field_tgt_clear)
1667 {
1668 n->refcount |= REFCOUNT_STRUCTELEM_FLAG_LAST;
1669 field_tgt_structelem_first = NULL;
1670 }
1671 }
1672 if (i == field_tgt_clear)
1673 field_tgt_clear = FIELD_TGT_EMPTY;
1674 gomp_increment_refcount (n, refcount_set);
1675 tgt->list[i].copy_from
1676 = GOMP_MAP_COPY_FROM_P (kind & typemask);
1677 tgt->list[i].always_copy_from
1678 = GOMP_MAP_ALWAYS_FROM_P (kind & typemask);
1679 tgt->list[i].is_attach = false;
1680 tgt->list[i].offset = 0;
1681 tgt->list[i].length = k->host_end - k->host_start;
1682 }
1683 else
1684 gomp_map_vars_existing (devicep, aq, n, k, &tgt->list[i],
1685 kind & typemask, false, implicit,
1686 cbufp, refcount_set);
1687 }
1688 else
1689 {
1690 k->aux = NULL;
1691 if (n && n->refcount == REFCOUNT_LINK)
1692 {
1693 /* Replace target address of the pointer with target address
1694 of mapped object in the splay tree. */
1695 splay_tree_remove (mem_map, n);
1696 k->aux
1697 = gomp_malloc_cleared (sizeof (struct splay_tree_aux));
1698 k->aux->link_key = n;
1699 }
1700 size_t align = (size_t) 1 << (kind >> rshift);
1701 tgt->list[i].key = k;
1702 k->tgt = tgt;
1703 k->refcount = 0;
1704 k->dynamic_refcount = 0;
1705 if (field_tgt_clear != FIELD_TGT_EMPTY)
1706 {
1707 k->tgt_offset = k->host_start - field_tgt_base
1708 + field_tgt_offset;
1709 if (openmp_p)
1710 {
1711 k->refcount = REFCOUNT_STRUCTELEM;
1712 if (field_tgt_structelem_first == NULL)
1713 {
1714 /* Set to first structure element of sequence. */
1715 k->refcount |= REFCOUNT_STRUCTELEM_FLAG_FIRST;
1716 field_tgt_structelem_first = k;
1717 }
1718 else
1719 /* Point to refcount of leading element, but do not
1720 increment again. */
1721 k->structelem_refcount_ptr
1722 = &field_tgt_structelem_first->structelem_refcount;
1723
1724 if (i == field_tgt_clear)
1725 {
1726 k->refcount |= REFCOUNT_STRUCTELEM_FLAG_LAST;
1727 field_tgt_structelem_first = NULL;
1728 }
1729 }
1730 if (i == field_tgt_clear)
1731 field_tgt_clear = FIELD_TGT_EMPTY;
1732 }
1733 else
1734 {
1735 tgt_size = (tgt_size + align - 1) & ~(align - 1);
1736 k->tgt_offset = tgt_size;
1737 tgt_size += k->host_end - k->host_start;
1738 }
1739 /* First increment, from 0 to 1. gomp_increment_refcount
1740 encapsulates the different increment cases, so use this
1741 instead of directly setting 1 during initialization. */
1742 gomp_increment_refcount (k, refcount_set);
1743
1744 tgt->list[i].copy_from = GOMP_MAP_COPY_FROM_P (kind & typemask);
1745 tgt->list[i].always_copy_from
1746 = GOMP_MAP_ALWAYS_FROM_P (kind & typemask);
1747 tgt->list[i].is_attach = false;
1748 tgt->list[i].offset = 0;
1749 tgt->list[i].length = k->host_end - k->host_start;
1750 tgt->refcount++;
1751 array->left = NULL;
1752 array->right = NULL;
1753 splay_tree_insert (mem_map, array);
1754 switch (kind & typemask)
1755 {
1756 case GOMP_MAP_ALLOC:
1757 case GOMP_MAP_FROM:
1758 case GOMP_MAP_FORCE_ALLOC:
1759 case GOMP_MAP_FORCE_FROM:
1760 case GOMP_MAP_ALWAYS_FROM:
1761 break;
1762 case GOMP_MAP_TO:
1763 case GOMP_MAP_TOFROM:
1764 case GOMP_MAP_FORCE_TO:
1765 case GOMP_MAP_FORCE_TOFROM:
1766 case GOMP_MAP_ALWAYS_TO:
1767 case GOMP_MAP_ALWAYS_TOFROM:
1768 gomp_copy_host2dev (devicep, aq,
1769 (void *) (tgt->tgt_start
1770 + k->tgt_offset),
1771 (void *) k->host_start,
1772 k->host_end - k->host_start,
1773 false, cbufp);
1774 break;
1775 case GOMP_MAP_POINTER:
1776 case GOMP_MAP_POINTER_TO_ZERO_LENGTH_ARRAY_SECTION:
1777 gomp_map_pointer
1778 (tgt, aq, (uintptr_t) *(void **) k->host_start,
1779 k->tgt_offset, sizes[i], cbufp,
1780 ((kind & typemask)
1781 == GOMP_MAP_POINTER_TO_ZERO_LENGTH_ARRAY_SECTION));
1782 break;
1783 case GOMP_MAP_TO_PSET:
1784 gomp_copy_host2dev (devicep, aq,
1785 (void *) (tgt->tgt_start
1786 + k->tgt_offset),
1787 (void *) k->host_start,
1788 k->host_end - k->host_start,
1789 false, cbufp);
1790 tgt->list[i].has_null_ptr_assoc = false;
1791
1792 for (j = i + 1; j < mapnum; j++)
1793 {
1794 int ptr_kind = (get_kind (short_mapkind, kinds, j)
1795 & typemask);
1796 if (!GOMP_MAP_POINTER_P (ptr_kind)
1797 && !GOMP_MAP_ALWAYS_POINTER_P (ptr_kind))
1798 break;
1799 else if ((uintptr_t) hostaddrs[j] < k->host_start
1800 || ((uintptr_t) hostaddrs[j] + sizeof (void *)
1801 > k->host_end))
1802 break;
1803 else
1804 {
1805 tgt->list[j].key = k;
1806 tgt->list[j].copy_from = false;
1807 tgt->list[j].always_copy_from = false;
1808 tgt->list[j].is_attach = false;
1809 tgt->list[i].has_null_ptr_assoc |= !(*(void **) hostaddrs[j]);
1810 /* For OpenMP, the use of refcount_sets causes
1811 errors if we set k->refcount = 1 above but also
1812 increment it again here, for decrementing will
1813 not properly match, since we decrement only once
1814 for each key's refcount. Therefore avoid this
1815 increment for OpenMP constructs. */
1816 if (!openmp_p)
1817 gomp_increment_refcount (k, refcount_set);
1818 gomp_map_pointer (tgt, aq,
1819 (uintptr_t) *(void **) hostaddrs[j],
1820 k->tgt_offset
1821 + ((uintptr_t) hostaddrs[j]
1822 - k->host_start),
1823 sizes[j], cbufp, false);
1824 }
1825 }
1826 i = j - 1;
1827 break;
1828 case GOMP_MAP_FORCE_PRESENT:
1829 case GOMP_MAP_ALWAYS_PRESENT_TO:
1830 case GOMP_MAP_ALWAYS_PRESENT_FROM:
1831 case GOMP_MAP_ALWAYS_PRESENT_TOFROM:
1832 {
1833 /* We already looked up the memory region above and it
1834 was missing. */
1835 size_t size = k->host_end - k->host_start;
1836 gomp_mutex_unlock (&devicep->lock);
1837 #ifdef HAVE_INTTYPES_H
1838 gomp_fatal ("present clause: not present on the device "
1839 "(addr: %p, size: %"PRIu64" (0x%"PRIx64"), "
1840 "dev: %d)", (void *) k->host_start,
1841 (uint64_t) size, (uint64_t) size,
1842 devicep->target_id);
1843 #else
1844 gomp_fatal ("present clause: not present on the device "
1845 "(addr: %p, size: %lu (0x%lx), dev: %d)",
1846 (void *) k->host_start,
1847 (unsigned long) size, (unsigned long) size,
1848 devicep->target_id);
1849 #endif
1850 }
1851 break;
1852 case GOMP_MAP_FORCE_DEVICEPTR:
1853 assert (k->host_end - k->host_start == sizeof (void *));
1854 gomp_copy_host2dev (devicep, aq,
1855 (void *) (tgt->tgt_start
1856 + k->tgt_offset),
1857 (void *) k->host_start,
1858 sizeof (void *), false, cbufp);
1859 break;
1860 default:
1861 gomp_mutex_unlock (&devicep->lock);
1862 gomp_fatal ("%s: unhandled kind 0x%.2x", __FUNCTION__,
1863 kind);
1864 }
1865
1866 if (k->aux && k->aux->link_key)
1867 {
1868 /* Set link pointer on target to the device address of the
1869 mapped object. Also deal with offsets due to
1870 array-section mapping. */
1871 void *tgt_addr = (void *) (tgt->tgt_start + k->tgt_offset
1872 - (k->host_start
1873 - k->aux->link_key->host_start));
1874 /* We intentionally do not use coalescing here, as it's not
1875 data allocated by the current call to this function. */
1876 gomp_copy_host2dev (devicep, aq, (void *) n->tgt_offset,
1877 &tgt_addr, sizeof (void *), true, NULL);
1878 }
1879 array++;
1880 }
1881 }
1882 }
1883
1884 if (pragma_kind & GOMP_MAP_VARS_TARGET)
1885 {
1886 for (i = 0; i < mapnum; i++)
1887 {
1888 cur_node.tgt_offset = gomp_map_val (tgt, hostaddrs, i);
1889 gomp_copy_host2dev (devicep, aq,
1890 (void *) (tgt->tgt_start + i * sizeof (void *)),
1891 (void *) &cur_node.tgt_offset, sizeof (void *),
1892 true, cbufp);
1893 }
1894 }
1895
1896 if (cbufp)
1897 {
1898 long c = 0;
1899 for (c = 0; c < cbuf.chunk_cnt; ++c)
1900 gomp_copy_host2dev (devicep, aq,
1901 (void *) (tgt->tgt_start + cbuf.chunks[c].start),
1902 (char *) cbuf.buf + (cbuf.chunks[c].start
1903 - cbuf.chunks[0].start),
1904 cbuf.chunks[c].end - cbuf.chunks[c].start,
1905 false, NULL);
1906 if (aq)
1907 /* Free once the transfer has completed. */
1908 devicep->openacc.async.queue_callback_func (aq, free, cbuf.buf);
1909 else
1910 free (cbuf.buf);
1911 cbuf.buf = NULL;
1912 cbufp = NULL;
1913 }
1914
1915 /* If the variable from "omp target enter data" map-list was already mapped,
1916 tgt is not needed. Otherwise tgt will be freed by gomp_unmap_vars or
1917 gomp_exit_data. */
1918 if ((pragma_kind & GOMP_MAP_VARS_ENTER_DATA) && tgt->refcount == 0)
1919 {
1920 free (tgt);
1921 tgt = NULL;
1922 }
1923
1924 gomp_mutex_unlock (&devicep->lock);
1925 return tgt;
1926 }
1927
1928 static struct target_mem_desc *
1929 gomp_map_vars (struct gomp_device_descr *devicep, size_t mapnum,
1930 void **hostaddrs, void **devaddrs, size_t *sizes, void *kinds,
1931 bool short_mapkind, htab_t *refcount_set,
1932 enum gomp_map_vars_kind pragma_kind)
1933 {
1934 /* This management of a local refcount_set is for convenience of callers
1935 who do not share a refcount_set over multiple map/unmap uses. */
1936 htab_t local_refcount_set = NULL;
1937 if (refcount_set == NULL)
1938 {
1939 local_refcount_set = htab_create (mapnum);
1940 refcount_set = &local_refcount_set;
1941 }
1942
1943 struct target_mem_desc *tgt;
1944 tgt = gomp_map_vars_internal (devicep, NULL, mapnum, hostaddrs, devaddrs,
1945 sizes, kinds, short_mapkind, refcount_set,
1946 pragma_kind);
1947 if (local_refcount_set)
1948 htab_free (local_refcount_set);
1949
1950 return tgt;
1951 }
1952
1953 attribute_hidden struct target_mem_desc *
1954 goacc_map_vars (struct gomp_device_descr *devicep,
1955 struct goacc_asyncqueue *aq, size_t mapnum,
1956 void **hostaddrs, void **devaddrs, size_t *sizes,
1957 void *kinds, bool short_mapkind,
1958 enum gomp_map_vars_kind pragma_kind)
1959 {
1960 return gomp_map_vars_internal (devicep, aq, mapnum, hostaddrs, devaddrs,
1961 sizes, kinds, short_mapkind, NULL,
1962 GOMP_MAP_VARS_OPENACC | pragma_kind);
1963 }
1964
1965 static void
1966 gomp_unmap_tgt (struct target_mem_desc *tgt)
1967 {
1968 /* Deallocate on target the tgt->tgt_start .. tgt->tgt_end region. */
1969 if (tgt->tgt_end)
1970 gomp_free_device_memory (tgt->device_descr, tgt->to_free);
1971
1972 free (tgt->array);
1973 free (tgt);
1974 }
1975
1976 static bool
1977 gomp_unref_tgt (void *ptr)
1978 {
1979 bool is_tgt_unmapped = false;
1980
1981 struct target_mem_desc *tgt = (struct target_mem_desc *) ptr;
1982
1983 if (tgt->refcount > 1)
1984 tgt->refcount--;
1985 else
1986 {
1987 gomp_unmap_tgt (tgt);
1988 is_tgt_unmapped = true;
1989 }
1990
1991 return is_tgt_unmapped;
1992 }
1993
1994 static void
1995 gomp_unref_tgt_void (void *ptr)
1996 {
1997 (void) gomp_unref_tgt (ptr);
1998 }
1999
2000 static void
2001 gomp_remove_splay_tree_key (splay_tree sp, splay_tree_key k)
2002 {
2003 splay_tree_remove (sp, k);
2004 if (k->aux)
2005 {
2006 if (k->aux->link_key)
2007 splay_tree_insert (sp, (splay_tree_node) k->aux->link_key);
2008 if (k->aux->attach_count)
2009 free (k->aux->attach_count);
2010 free (k->aux);
2011 k->aux = NULL;
2012 }
2013 }
2014
2015 static inline __attribute__((always_inline)) bool
2016 gomp_remove_var_internal (struct gomp_device_descr *devicep, splay_tree_key k,
2017 struct goacc_asyncqueue *aq)
2018 {
2019 bool is_tgt_unmapped = false;
2020
2021 if (REFCOUNT_STRUCTELEM_P (k->refcount))
2022 {
2023 if (REFCOUNT_STRUCTELEM_FIRST_P (k->refcount) == false)
2024 /* Infer the splay_tree_key of the first structelem key using the
2025 pointer to the first structleme_refcount. */
2026 k = (splay_tree_key) ((char *) k->structelem_refcount_ptr
2027 - offsetof (struct splay_tree_key_s,
2028 structelem_refcount));
2029 assert (REFCOUNT_STRUCTELEM_FIRST_P (k->refcount));
2030
2031 /* The array created by gomp_map_vars is an array of splay_tree_nodes,
2032 with the splay_tree_keys embedded inside. */
2033 splay_tree_node node =
2034 (splay_tree_node) ((char *) k
2035 - offsetof (struct splay_tree_node_s, key));
2036 while (true)
2037 {
2038 /* Starting from the _FIRST key, and continue for all following
2039 sibling keys. */
2040 gomp_remove_splay_tree_key (&devicep->mem_map, k);
2041 if (REFCOUNT_STRUCTELEM_LAST_P (k->refcount))
2042 break;
2043 else
2044 k = &(++node)->key;
2045 }
2046 }
2047 else
2048 gomp_remove_splay_tree_key (&devicep->mem_map, k);
2049
2050 if (aq)
2051 devicep->openacc.async.queue_callback_func (aq, gomp_unref_tgt_void,
2052 (void *) k->tgt);
2053 else
2054 is_tgt_unmapped = gomp_unref_tgt ((void *) k->tgt);
2055 return is_tgt_unmapped;
2056 }
2057
2058 attribute_hidden bool
2059 gomp_remove_var (struct gomp_device_descr *devicep, splay_tree_key k)
2060 {
2061 return gomp_remove_var_internal (devicep, k, NULL);
2062 }
2063
2064 /* Remove a variable asynchronously. This actually removes the variable
2065 mapping immediately, but retains the linked target_mem_desc until the
2066 asynchronous operation has completed (as it may still refer to target
2067 memory). The device lock must be held before entry, and remains locked on
2068 exit. */
2069
2070 attribute_hidden void
2071 gomp_remove_var_async (struct gomp_device_descr *devicep, splay_tree_key k,
2072 struct goacc_asyncqueue *aq)
2073 {
2074 (void) gomp_remove_var_internal (devicep, k, aq);
2075 }
2076
2077 /* Unmap variables described by TGT. If DO_COPYFROM is true, copy relevant
2078 variables back from device to host: if it is false, it is assumed that this
2079 has been done already. */
2080
2081 static inline __attribute__((always_inline)) void
2082 gomp_unmap_vars_internal (struct target_mem_desc *tgt, bool do_copyfrom,
2083 htab_t *refcount_set, struct goacc_asyncqueue *aq)
2084 {
2085 struct gomp_device_descr *devicep = tgt->device_descr;
2086
2087 if (tgt->list_count == 0)
2088 {
2089 free (tgt);
2090 return;
2091 }
2092
2093 gomp_mutex_lock (&devicep->lock);
2094 if (devicep->state == GOMP_DEVICE_FINALIZED)
2095 {
2096 gomp_mutex_unlock (&devicep->lock);
2097 free (tgt->array);
2098 free (tgt);
2099 return;
2100 }
2101
2102 size_t i;
2103
2104 /* We must perform detachments before any copies back to the host. */
2105 for (i = 0; i < tgt->list_count; i++)
2106 {
2107 splay_tree_key k = tgt->list[i].key;
2108
2109 if (k != NULL && tgt->list[i].is_attach)
2110 gomp_detach_pointer (devicep, aq, k, tgt->list[i].key->host_start
2111 + tgt->list[i].offset,
2112 false, NULL);
2113 }
2114
2115 for (i = 0; i < tgt->list_count; i++)
2116 {
2117 splay_tree_key k = tgt->list[i].key;
2118 if (k == NULL)
2119 continue;
2120
2121 /* OpenACC 'attach'/'detach' doesn't affect structured/dynamic reference
2122 counts ('n->refcount', 'n->dynamic_refcount'). */
2123 if (tgt->list[i].is_attach)
2124 continue;
2125
2126 bool do_copy, do_remove;
2127 gomp_decrement_refcount (k, refcount_set, false, &do_copy, &do_remove);
2128
2129 if ((do_copy && do_copyfrom && tgt->list[i].copy_from)
2130 || tgt->list[i].always_copy_from)
2131 gomp_copy_dev2host (devicep, aq,
2132 (void *) (k->host_start + tgt->list[i].offset),
2133 (void *) (k->tgt->tgt_start + k->tgt_offset
2134 + tgt->list[i].offset),
2135 tgt->list[i].length);
2136 if (do_remove)
2137 {
2138 struct target_mem_desc *k_tgt __attribute__((unused)) = k->tgt;
2139 bool is_tgt_unmapped __attribute__((unused))
2140 = gomp_remove_var (devicep, k);
2141 /* It would be bad if TGT got unmapped while we're still iterating
2142 over its LIST_COUNT, and also expect to use it in the following
2143 code. */
2144 assert (!is_tgt_unmapped
2145 || k_tgt != tgt);
2146 }
2147 }
2148
2149 if (aq)
2150 devicep->openacc.async.queue_callback_func (aq, gomp_unref_tgt_void,
2151 (void *) tgt);
2152 else
2153 gomp_unref_tgt ((void *) tgt);
2154
2155 gomp_mutex_unlock (&devicep->lock);
2156 }
2157
2158 static void
2159 gomp_unmap_vars (struct target_mem_desc *tgt, bool do_copyfrom,
2160 htab_t *refcount_set)
2161 {
2162 /* This management of a local refcount_set is for convenience of callers
2163 who do not share a refcount_set over multiple map/unmap uses. */
2164 htab_t local_refcount_set = NULL;
2165 if (refcount_set == NULL)
2166 {
2167 local_refcount_set = htab_create (tgt->list_count);
2168 refcount_set = &local_refcount_set;
2169 }
2170
2171 gomp_unmap_vars_internal (tgt, do_copyfrom, refcount_set, NULL);
2172
2173 if (local_refcount_set)
2174 htab_free (local_refcount_set);
2175 }
2176
2177 attribute_hidden void
2178 goacc_unmap_vars (struct target_mem_desc *tgt, bool do_copyfrom,
2179 struct goacc_asyncqueue *aq)
2180 {
2181 gomp_unmap_vars_internal (tgt, do_copyfrom, NULL, aq);
2182 }
2183
2184 static void
2185 gomp_update (struct gomp_device_descr *devicep, size_t mapnum, void **hostaddrs,
2186 size_t *sizes, void *kinds, bool short_mapkind)
2187 {
2188 size_t i;
2189 struct splay_tree_key_s cur_node;
2190 const int typemask = short_mapkind ? 0xff : 0x7;
2191
2192 if (!devicep)
2193 return;
2194
2195 if (mapnum == 0)
2196 return;
2197
2198 gomp_mutex_lock (&devicep->lock);
2199 if (devicep->state == GOMP_DEVICE_FINALIZED)
2200 {
2201 gomp_mutex_unlock (&devicep->lock);
2202 return;
2203 }
2204
2205 for (i = 0; i < mapnum; i++)
2206 if (sizes[i])
2207 {
2208 cur_node.host_start = (uintptr_t) hostaddrs[i];
2209 cur_node.host_end = cur_node.host_start + sizes[i];
2210 splay_tree_key n = splay_tree_lookup (&devicep->mem_map, &cur_node);
2211 if (n)
2212 {
2213 int kind = get_kind (short_mapkind, kinds, i);
2214 if (n->host_start > cur_node.host_start
2215 || n->host_end < cur_node.host_end)
2216 {
2217 gomp_mutex_unlock (&devicep->lock);
2218 gomp_fatal ("Trying to update [%p..%p) object when "
2219 "only [%p..%p) is mapped",
2220 (void *) cur_node.host_start,
2221 (void *) cur_node.host_end,
2222 (void *) n->host_start,
2223 (void *) n->host_end);
2224 }
2225
2226 if (n->aux && n->aux->attach_count)
2227 {
2228 uintptr_t addr = cur_node.host_start;
2229 while (addr < cur_node.host_end)
2230 {
2231 /* We have to be careful not to overwrite still attached
2232 pointers during host<->device updates. */
2233 size_t i = (addr - cur_node.host_start) / sizeof (void *);
2234 if (n->aux->attach_count[i] == 0)
2235 {
2236 void *devaddr = (void *) (n->tgt->tgt_start
2237 + n->tgt_offset
2238 + addr - n->host_start);
2239 if (GOMP_MAP_COPY_TO_P (kind & typemask))
2240 gomp_copy_host2dev (devicep, NULL,
2241 devaddr, (void *) addr,
2242 sizeof (void *), false, NULL);
2243 if (GOMP_MAP_COPY_FROM_P (kind & typemask))
2244 gomp_copy_dev2host (devicep, NULL,
2245 (void *) addr, devaddr,
2246 sizeof (void *));
2247 }
2248 addr += sizeof (void *);
2249 }
2250 }
2251 else
2252 {
2253 void *hostaddr = (void *) cur_node.host_start;
2254 void *devaddr = (void *) (n->tgt->tgt_start + n->tgt_offset
2255 + cur_node.host_start
2256 - n->host_start);
2257 size_t size = cur_node.host_end - cur_node.host_start;
2258
2259 if (GOMP_MAP_COPY_TO_P (kind & typemask))
2260 gomp_copy_host2dev (devicep, NULL, devaddr, hostaddr, size,
2261 false, NULL);
2262 if (GOMP_MAP_COPY_FROM_P (kind & typemask))
2263 gomp_copy_dev2host (devicep, NULL, hostaddr, devaddr, size);
2264 }
2265 }
2266 else
2267 {
2268 int kind = get_kind (short_mapkind, kinds, i);
2269
2270 if (GOMP_MAP_PRESENT_P (kind))
2271 {
2272 /* We already looked up the memory region above and it
2273 was missing. */
2274 gomp_mutex_unlock (&devicep->lock);
2275 #ifdef HAVE_INTTYPES_H
2276 gomp_fatal ("present clause: not present on the device "
2277 "(addr: %p, size: %"PRIu64" (0x%"PRIx64"), "
2278 "dev: %d)", (void *) hostaddrs[i],
2279 (uint64_t) sizes[i], (uint64_t) sizes[i],
2280 devicep->target_id);
2281 #else
2282 gomp_fatal ("present clause: not present on the device "
2283 "(addr: %p, size: %lu (0x%lx), dev: %d)",
2284 (void *) hostaddrs[i], (unsigned long) sizes[i],
2285 (unsigned long) sizes[i], devicep->target_id);
2286 #endif
2287 }
2288 }
2289 }
2290 gomp_mutex_unlock (&devicep->lock);
2291 }
2292
2293 static struct gomp_offload_icv_list *
2294 gomp_get_offload_icv_item (int dev_num)
2295 {
2296 struct gomp_offload_icv_list *l = gomp_offload_icv_list;
2297 while (l != NULL && l->device_num != dev_num)
2298 l = l->next;
2299
2300 return l;
2301 }
2302
2303 /* Helper function for 'gomp_load_image_to_device'. Returns the ICV values
2304 depending on the device num and the variable hierarchy
2305 (_DEV_42, _DEV, _ALL). If no ICV was initially configured for the given
2306 device and thus no item with that device number is contained in
2307 gomp_offload_icv_list, then a new item is created and added to the list. */
2308
2309 static struct gomp_offload_icvs *
2310 get_gomp_offload_icvs (int dev_num)
2311 {
2312 struct gomp_icv_list *dev
2313 = gomp_get_initial_icv_item (GOMP_DEVICE_NUM_FOR_DEV);
2314 struct gomp_icv_list *all
2315 = gomp_get_initial_icv_item (GOMP_DEVICE_NUM_FOR_ALL);
2316 struct gomp_icv_list *dev_x = gomp_get_initial_icv_item (dev_num);
2317 struct gomp_offload_icv_list *offload_icvs
2318 = gomp_get_offload_icv_item (dev_num);
2319
2320 if (offload_icvs != NULL)
2321 return &offload_icvs->icvs;
2322
2323 struct gomp_offload_icv_list *new
2324 = (struct gomp_offload_icv_list *) gomp_malloc (sizeof (struct gomp_offload_icv_list));
2325
2326 new->device_num = dev_num;
2327 new->icvs.device_num = dev_num;
2328 new->next = gomp_offload_icv_list;
2329
2330 if (dev_x != NULL && gomp_get_icv_flag (dev_x->flags, GOMP_ICV_NTEAMS))
2331 new->icvs.nteams = dev_x->icvs.nteams_var;
2332 else if (dev != NULL && gomp_get_icv_flag (dev->flags, GOMP_ICV_NTEAMS))
2333 new->icvs.nteams = dev->icvs.nteams_var;
2334 else if (all != NULL && gomp_get_icv_flag (all->flags, GOMP_ICV_NTEAMS))
2335 new->icvs.nteams = all->icvs.nteams_var;
2336 else
2337 new->icvs.nteams = gomp_default_icv_values.nteams_var;
2338
2339 if (dev_x != NULL
2340 && gomp_get_icv_flag (dev_x->flags, GOMP_ICV_TEAMS_THREAD_LIMIT))
2341 new->icvs.teams_thread_limit = dev_x->icvs.teams_thread_limit_var;
2342 else if (dev != NULL
2343 && gomp_get_icv_flag (dev->flags, GOMP_ICV_TEAMS_THREAD_LIMIT))
2344 new->icvs.teams_thread_limit = dev->icvs.teams_thread_limit_var;
2345 else if (all != NULL
2346 && gomp_get_icv_flag (all->flags, GOMP_ICV_TEAMS_THREAD_LIMIT))
2347 new->icvs.teams_thread_limit = all->icvs.teams_thread_limit_var;
2348 else
2349 new->icvs.teams_thread_limit
2350 = gomp_default_icv_values.teams_thread_limit_var;
2351
2352 if (dev_x != NULL
2353 && gomp_get_icv_flag (dev_x->flags, GOMP_ICV_DEFAULT_DEVICE))
2354 new->icvs.default_device = dev_x->icvs.default_device_var;
2355 else if (dev != NULL
2356 && gomp_get_icv_flag (dev->flags, GOMP_ICV_DEFAULT_DEVICE))
2357 new->icvs.default_device = dev->icvs.default_device_var;
2358 else if (all != NULL
2359 && gomp_get_icv_flag (all->flags, GOMP_ICV_DEFAULT_DEVICE))
2360 new->icvs.default_device = all->icvs.default_device_var;
2361 else
2362 new->icvs.default_device = gomp_default_icv_values.default_device_var;
2363
2364 gomp_offload_icv_list = new;
2365 return &new->icvs;
2366 }
2367
2368 /* Load image pointed by TARGET_DATA to the device, specified by DEVICEP.
2369 And insert to splay tree the mapping between addresses from HOST_TABLE and
2370 from loaded target image. We rely in the host and device compiler
2371 emitting variable and functions in the same order. */
2372
2373 static void
2374 gomp_load_image_to_device (struct gomp_device_descr *devicep, unsigned version,
2375 const void *host_table, const void *target_data,
2376 bool is_register_lock)
2377 {
2378 void **host_func_table = ((void ***) host_table)[0];
2379 void **host_funcs_end = ((void ***) host_table)[1];
2380 void **host_var_table = ((void ***) host_table)[2];
2381 void **host_vars_end = ((void ***) host_table)[3];
2382 void **host_ind_func_table = NULL;
2383 void **host_ind_funcs_end = NULL;
2384
2385 if (GOMP_VERSION_SUPPORTS_INDIRECT_FUNCS (version))
2386 {
2387 host_ind_func_table = ((void ***) host_table)[4];
2388 host_ind_funcs_end = ((void ***) host_table)[5];
2389 }
2390
2391 /* The func and ind_func tables contain only addresses, the var table
2392 contains addresses and corresponding sizes. */
2393 int num_funcs = host_funcs_end - host_func_table;
2394 int num_vars = (host_vars_end - host_var_table) / 2;
2395 int num_ind_funcs = (host_ind_funcs_end - host_ind_func_table);
2396
2397 /* Load image to device and get target addresses for the image. */
2398 struct addr_pair *target_table = NULL;
2399 uint64_t *rev_target_fn_table = NULL;
2400 int i, num_target_entries;
2401
2402 /* With reverse offload, insert also target-host addresses. */
2403 bool rev_lookup = omp_requires_mask & GOMP_REQUIRES_REVERSE_OFFLOAD;
2404
2405 num_target_entries
2406 = devicep->load_image_func (devicep->target_id, version,
2407 target_data, &target_table,
2408 rev_lookup ? &rev_target_fn_table : NULL,
2409 num_ind_funcs
2410 ? (uint64_t *) host_ind_func_table : NULL);
2411
2412 /* The "+1" is due to the additional ICV struct. */
2413 if (num_target_entries != num_funcs + num_vars + 1)
2414 {
2415 gomp_mutex_unlock (&devicep->lock);
2416 if (is_register_lock)
2417 gomp_mutex_unlock (&register_lock);
2418 gomp_fatal ("Cannot map target functions or variables"
2419 " (expected %u + %u + 1, have %u)", num_funcs, num_vars,
2420 num_target_entries);
2421 }
2422
2423 /* Insert host-target address mapping into splay tree. */
2424 struct target_mem_desc *tgt = gomp_malloc (sizeof (*tgt));
2425 /* "+1" due to the additional ICV struct. */
2426 tgt->array = gomp_malloc ((num_funcs + num_vars + 1)
2427 * sizeof (*tgt->array));
2428 if (rev_target_fn_table)
2429 tgt->rev_array = gomp_malloc (num_funcs * sizeof (*tgt->rev_array));
2430 else
2431 tgt->rev_array = NULL;
2432 tgt->refcount = REFCOUNT_INFINITY;
2433 tgt->tgt_start = 0;
2434 tgt->tgt_end = 0;
2435 tgt->to_free = NULL;
2436 tgt->prev = NULL;
2437 tgt->list_count = 0;
2438 tgt->device_descr = devicep;
2439 splay_tree_node array = tgt->array;
2440 reverse_splay_tree_node rev_array = tgt->rev_array;
2441
2442 for (i = 0; i < num_funcs; i++)
2443 {
2444 splay_tree_key k = &array->key;
2445 k->host_start = (uintptr_t) host_func_table[i];
2446 k->host_end = k->host_start + 1;
2447 k->tgt = tgt;
2448 k->tgt_offset = target_table[i].start;
2449 k->refcount = REFCOUNT_INFINITY;
2450 k->dynamic_refcount = 0;
2451 k->aux = NULL;
2452 array->left = NULL;
2453 array->right = NULL;
2454 splay_tree_insert (&devicep->mem_map, array);
2455 if (rev_target_fn_table)
2456 {
2457 reverse_splay_tree_key k2 = &rev_array->key;
2458 k2->dev = rev_target_fn_table[i];
2459 k2->k = k;
2460 rev_array->left = NULL;
2461 rev_array->right = NULL;
2462 if (k2->dev != 0)
2463 reverse_splay_tree_insert (&devicep->mem_map_rev, rev_array);
2464 rev_array++;
2465 }
2466 array++;
2467 }
2468
2469 /* Most significant bit of the size in host and target tables marks
2470 "omp declare target link" variables. */
2471 const uintptr_t link_bit = 1ULL << (sizeof (uintptr_t) * __CHAR_BIT__ - 1);
2472 const uintptr_t size_mask = ~link_bit;
2473
2474 for (i = 0; i < num_vars; i++)
2475 {
2476 struct addr_pair *target_var = &target_table[num_funcs + i];
2477 uintptr_t target_size = target_var->end - target_var->start;
2478 bool is_link_var = link_bit & (uintptr_t) host_var_table[i * 2 + 1];
2479
2480 if (!is_link_var && (uintptr_t) host_var_table[i * 2 + 1] != target_size)
2481 {
2482 gomp_mutex_unlock (&devicep->lock);
2483 if (is_register_lock)
2484 gomp_mutex_unlock (&register_lock);
2485 gomp_fatal ("Cannot map target variables (size mismatch)");
2486 }
2487
2488 splay_tree_key k = &array->key;
2489 k->host_start = (uintptr_t) host_var_table[i * 2];
2490 k->host_end
2491 = k->host_start + (size_mask & (uintptr_t) host_var_table[i * 2 + 1]);
2492 k->tgt = tgt;
2493 k->tgt_offset = target_var->start;
2494 k->refcount = is_link_var ? REFCOUNT_LINK : REFCOUNT_INFINITY;
2495 k->dynamic_refcount = 0;
2496 k->aux = NULL;
2497 array->left = NULL;
2498 array->right = NULL;
2499 splay_tree_insert (&devicep->mem_map, array);
2500 array++;
2501
2502 if (is_link_var
2503 && (omp_requires_mask
2504 & (GOMP_REQUIRES_UNIFIED_SHARED_MEMORY | GOMP_REQUIRES_SELF_MAPS)))
2505 gomp_copy_host2dev (devicep, NULL, (void *) target_var->start,
2506 &k->host_start, sizeof (void *), false, NULL);
2507 }
2508
2509 /* Last entry is for the ICV struct variable; if absent, start = end = 0. */
2510 struct addr_pair *icv_var = &target_table[num_funcs + num_vars];
2511 if (icv_var->start != 0)
2512 {
2513 /* The index of the devicep within devices[] is regarded as its
2514 'device number', which is different from the per-device type
2515 devicep->target_id. */
2516 int dev_num = (int) (devicep - &devices[0]);
2517 struct gomp_offload_icvs *icvs = get_gomp_offload_icvs (dev_num);
2518 size_t var_size = icv_var->end - icv_var->start;
2519 if (var_size != sizeof (struct gomp_offload_icvs))
2520 {
2521 gomp_mutex_unlock (&devicep->lock);
2522 if (is_register_lock)
2523 gomp_mutex_unlock (&register_lock);
2524 gomp_fatal ("offload plugin managed 'icv struct' not of expected "
2525 "format");
2526 }
2527 /* Copy the ICVs variable to place on device memory, hereby
2528 actually designating its device number into effect. */
2529 gomp_copy_host2dev (devicep, NULL, (void *) icv_var->start, icvs,
2530 var_size, false, NULL);
2531 splay_tree_key k = &array->key;
2532 k->host_start = (uintptr_t) icvs;
2533 k->host_end =
2534 k->host_start + (size_mask & sizeof (struct gomp_offload_icvs));
2535 k->tgt = tgt;
2536 k->tgt_offset = icv_var->start;
2537 k->refcount = REFCOUNT_INFINITY;
2538 k->dynamic_refcount = 0;
2539 k->aux = NULL;
2540 array->left = NULL;
2541 array->right = NULL;
2542 splay_tree_insert (&devicep->mem_map, array);
2543 array++;
2544 }
2545
2546 free (target_table);
2547 }
2548
2549 /* Unload the mappings described by target_data from device DEVICE_P.
2550 The device must be locked. */
2551
2552 static void
2553 gomp_unload_image_from_device (struct gomp_device_descr *devicep,
2554 unsigned version,
2555 const void *host_table, const void *target_data)
2556 {
2557 void **host_func_table = ((void ***) host_table)[0];
2558 void **host_funcs_end = ((void ***) host_table)[1];
2559 void **host_var_table = ((void ***) host_table)[2];
2560 void **host_vars_end = ((void ***) host_table)[3];
2561
2562 /* The func table contains only addresses, the var table contains addresses
2563 and corresponding sizes. */
2564 int num_funcs = host_funcs_end - host_func_table;
2565 int num_vars = (host_vars_end - host_var_table) / 2;
2566
2567 struct splay_tree_key_s k;
2568 splay_tree_key node = NULL;
2569
2570 /* Find mapping at start of node array */
2571 if (num_funcs || num_vars)
2572 {
2573 k.host_start = (num_funcs ? (uintptr_t) host_func_table[0]
2574 : (uintptr_t) host_var_table[0]);
2575 k.host_end = k.host_start + 1;
2576 node = splay_tree_lookup (&devicep->mem_map, &k);
2577 }
2578
2579 if (!devicep->unload_image_func (devicep->target_id, version, target_data))
2580 {
2581 gomp_mutex_unlock (&devicep->lock);
2582 gomp_fatal ("image unload fail");
2583 }
2584 if (devicep->mem_map_rev.root)
2585 {
2586 /* Free reverse offload splay tree + data; 'tgt->rev_array' is the only
2587 real allocation. */
2588 assert (node && node->tgt && node->tgt->rev_array);
2589 assert (devicep->mem_map_rev.root->key.k->tgt == node->tgt);
2590 free (node->tgt->rev_array);
2591 devicep->mem_map_rev.root = NULL;
2592 }
2593
2594 /* Remove mappings from splay tree. */
2595 int i;
2596 for (i = 0; i < num_funcs; i++)
2597 {
2598 k.host_start = (uintptr_t) host_func_table[i];
2599 k.host_end = k.host_start + 1;
2600 splay_tree_remove (&devicep->mem_map, &k);
2601 }
2602
2603 /* Most significant bit of the size in host and target tables marks
2604 "omp declare target link" variables. */
2605 const uintptr_t link_bit = 1ULL << (sizeof (uintptr_t) * __CHAR_BIT__ - 1);
2606 const uintptr_t size_mask = ~link_bit;
2607 bool is_tgt_unmapped = false;
2608
2609 for (i = 0; i < num_vars; i++)
2610 {
2611 k.host_start = (uintptr_t) host_var_table[i * 2];
2612 k.host_end
2613 = k.host_start + (size_mask & (uintptr_t) host_var_table[i * 2 + 1]);
2614
2615 if (!(link_bit & (uintptr_t) host_var_table[i * 2 + 1]))
2616 splay_tree_remove (&devicep->mem_map, &k);
2617 else
2618 {
2619 splay_tree_key n = splay_tree_lookup (&devicep->mem_map, &k);
2620 is_tgt_unmapped = gomp_remove_var (devicep, n);
2621 }
2622 }
2623
2624 if (node && !is_tgt_unmapped)
2625 {
2626 free (node->tgt);
2627 free (node);
2628 }
2629 }
2630
2631 static void
2632 gomp_requires_to_name (char *buf, size_t size, int requires_mask)
2633 {
2634 char *end = buf + size, *p = buf;
2635 if (requires_mask & GOMP_REQUIRES_UNIFIED_ADDRESS)
2636 p += snprintf (p, end - p, "unified_address");
2637 if (requires_mask & GOMP_REQUIRES_UNIFIED_SHARED_MEMORY)
2638 p += snprintf (p, end - p, "%sunified_shared_memory",
2639 (p == buf ? "" : ", "));
2640 if (requires_mask & GOMP_REQUIRES_SELF_MAPS)
2641 p += snprintf (p, end - p, "%sself_maps",
2642 (p == buf ? "" : ", "));
2643 if (requires_mask & GOMP_REQUIRES_REVERSE_OFFLOAD)
2644 p += snprintf (p, end - p, "%sreverse_offload",
2645 (p == buf ? "" : ", "));
2646 }
2647
2648 /* This function should be called from every offload image while loading.
2649 It gets the descriptor of the host func and var tables HOST_TABLE, TYPE of
2650 the target, and DATA. */
2651
2652 void
2653 GOMP_offload_register_ver (unsigned version, const void *host_table,
2654 int target_type, const void *data)
2655 {
2656 int i;
2657
2658 if (GOMP_VERSION_LIB (version) > GOMP_VERSION)
2659 gomp_fatal ("Library too old for offload (version %u < %u)",
2660 GOMP_VERSION, GOMP_VERSION_LIB (version));
2661
2662 int omp_req;
2663 const void *target_data;
2664 if (GOMP_VERSION_LIB (version) > 1)
2665 {
2666 omp_req = (int) (size_t) ((void **) data)[0];
2667 target_data = &((void **) data)[1];
2668 }
2669 else
2670 {
2671 omp_req = 0;
2672 target_data = data;
2673 }
2674
2675 gomp_mutex_lock (&register_lock);
2676
2677 if (omp_req && omp_requires_mask && omp_requires_mask != omp_req)
2678 {
2679 char buf1[sizeof ("unified_address, unified_shared_memory, "
2680 "self_maps, reverse_offload")];
2681 char buf2[sizeof ("unified_address, unified_shared_memory, "
2682 "self_maps, reverse_offload")];
2683 gomp_requires_to_name (buf2, sizeof (buf2),
2684 omp_req != GOMP_REQUIRES_TARGET_USED
2685 ? omp_req : omp_requires_mask);
2686 if (omp_req != GOMP_REQUIRES_TARGET_USED
2687 && omp_requires_mask != GOMP_REQUIRES_TARGET_USED)
2688 {
2689 gomp_requires_to_name (buf1, sizeof (buf1), omp_requires_mask);
2690 gomp_fatal ("OpenMP 'requires' directive with non-identical clauses "
2691 "in multiple compilation units: '%s' vs. '%s'",
2692 buf1, buf2);
2693 }
2694 else
2695 gomp_fatal ("OpenMP 'requires' directive with '%s' specified only in "
2696 "some compilation units", buf2);
2697 }
2698 omp_requires_mask = omp_req;
2699
2700 /* Load image to all initialized devices. */
2701 for (i = 0; i < num_devices; i++)
2702 {
2703 struct gomp_device_descr *devicep = &devices[i];
2704 gomp_mutex_lock (&devicep->lock);
2705 if (devicep->type == target_type
2706 && devicep->state == GOMP_DEVICE_INITIALIZED)
2707 gomp_load_image_to_device (devicep, version,
2708 host_table, target_data, true);
2709 gomp_mutex_unlock (&devicep->lock);
2710 }
2711
2712 /* Insert image to array of pending images. */
2713 offload_images
2714 = gomp_realloc_unlock (offload_images,
2715 (num_offload_images + 1)
2716 * sizeof (struct offload_image_descr));
2717 offload_images[num_offload_images].version = version;
2718 offload_images[num_offload_images].type = target_type;
2719 offload_images[num_offload_images].host_table = host_table;
2720 offload_images[num_offload_images].target_data = target_data;
2721
2722 num_offload_images++;
2723 gomp_mutex_unlock (&register_lock);
2724 }
2725
2726 /* Legacy entry point. */
2727
2728 void
2729 GOMP_offload_register (const void *host_table, int target_type,
2730 const void *target_data)
2731 {
2732 GOMP_offload_register_ver (0, host_table, target_type, target_data);
2733 }
2734
2735 /* This function should be called from every offload image while unloading.
2736 It gets the descriptor of the host func and var tables HOST_TABLE, TYPE of
2737 the target, and DATA. */
2738
2739 void
2740 GOMP_offload_unregister_ver (unsigned version, const void *host_table,
2741 int target_type, const void *data)
2742 {
2743 int i;
2744
2745 if (GOMP_VERSION_LIB (version) > GOMP_VERSION)
2746 gomp_fatal ("Library too old for offload (version %u < %u)",
2747 GOMP_VERSION, GOMP_VERSION_LIB (version));
2748
2749 const void *target_data;
2750 if (GOMP_VERSION_LIB (version) > 1)
2751 target_data = &((void **) data)[1];
2752 else
2753 target_data = data;
2754
2755 gomp_mutex_lock (&register_lock);
2756
2757 /* Unload image from all initialized devices. */
2758 for (i = 0; i < num_devices; i++)
2759 {
2760 struct gomp_device_descr *devicep = &devices[i];
2761 gomp_mutex_lock (&devicep->lock);
2762 if (devicep->type == target_type
2763 && devicep->state == GOMP_DEVICE_INITIALIZED)
2764 gomp_unload_image_from_device (devicep, version,
2765 host_table, target_data);
2766 gomp_mutex_unlock (&devicep->lock);
2767 }
2768
2769 /* Remove image from array of pending images. */
2770 for (i = 0; i < num_offload_images; i++)
2771 if (offload_images[i].target_data == target_data)
2772 {
2773 offload_images[i] = offload_images[--num_offload_images];
2774 break;
2775 }
2776
2777 gomp_mutex_unlock (&register_lock);
2778 }
2779
2780 /* Legacy entry point. */
2781
2782 void
2783 GOMP_offload_unregister (const void *host_table, int target_type,
2784 const void *target_data)
2785 {
2786 GOMP_offload_unregister_ver (0, host_table, target_type, target_data);
2787 }
2788
2789 /* This function initializes the target device, specified by DEVICEP. DEVICEP
2790 must be locked on entry, and remains locked on return. */
2791
2792 attribute_hidden void
2793 gomp_init_device (struct gomp_device_descr *devicep)
2794 {
2795 int i;
2796 if (!devicep->init_device_func (devicep->target_id))
2797 {
2798 gomp_mutex_unlock (&devicep->lock);
2799 gomp_fatal ("device initialization failed");
2800 }
2801
2802 /* Load to device all images registered by the moment. */
2803 for (i = 0; i < num_offload_images; i++)
2804 {
2805 struct offload_image_descr *image = &offload_images[i];
2806 if (image->type == devicep->type)
2807 gomp_load_image_to_device (devicep, image->version,
2808 image->host_table, image->target_data,
2809 false);
2810 }
2811
2812 /* Initialize OpenACC asynchronous queues. */
2813 goacc_init_asyncqueues (devicep);
2814
2815 devicep->state = GOMP_DEVICE_INITIALIZED;
2816 }
2817
2818 /* This function finalizes the target device, specified by DEVICEP. DEVICEP
2819 must be locked on entry, and remains locked on return. */
2820
2821 attribute_hidden bool
2822 gomp_fini_device (struct gomp_device_descr *devicep)
2823 {
2824 bool ret = goacc_fini_asyncqueues (devicep);
2825 ret &= devicep->fini_device_func (devicep->target_id);
2826 devicep->state = GOMP_DEVICE_FINALIZED;
2827 return ret;
2828 }
2829
2830 attribute_hidden void
2831 gomp_unload_device (struct gomp_device_descr *devicep)
2832 {
2833 if (devicep->state == GOMP_DEVICE_INITIALIZED)
2834 {
2835 unsigned i;
2836
2837 /* Unload from device all images registered at the moment. */
2838 for (i = 0; i < num_offload_images; i++)
2839 {
2840 struct offload_image_descr *image = &offload_images[i];
2841 if (image->type == devicep->type)
2842 gomp_unload_image_from_device (devicep, image->version,
2843 image->host_table,
2844 image->target_data);
2845 }
2846 }
2847 }
2848
2849 /* Host fallback for GOMP_target{,_ext} routines. */
2850
2851 static void
2852 gomp_target_fallback (void (*fn) (void *), void **hostaddrs,
2853 struct gomp_device_descr *devicep, void **args)
2854 {
2855 struct gomp_thread old_thr, *thr = gomp_thread ();
2856
2857 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY
2858 && devicep != NULL)
2859 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, but device cannot "
2860 "be used for offloading");
2861
2862 old_thr = *thr;
2863 memset (thr, '\0', sizeof (*thr));
2864 if (gomp_places_list)
2865 {
2866 thr->place = old_thr.place;
2867 thr->ts.place_partition_len = gomp_places_list_len;
2868 }
2869 if (args)
2870 while (*args)
2871 {
2872 intptr_t id = (intptr_t) *args++, val;
2873 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
2874 val = (intptr_t) *args++;
2875 else
2876 val = id >> GOMP_TARGET_ARG_VALUE_SHIFT;
2877 if ((id & GOMP_TARGET_ARG_DEVICE_MASK) != GOMP_TARGET_ARG_DEVICE_ALL)
2878 continue;
2879 id &= GOMP_TARGET_ARG_ID_MASK;
2880 if (id != GOMP_TARGET_ARG_THREAD_LIMIT)
2881 continue;
2882 val = val > INT_MAX ? INT_MAX : val;
2883 if (val)
2884 gomp_icv (true)->thread_limit_var = val;
2885 break;
2886 }
2887
2888 fn (hostaddrs);
2889 gomp_free_thread (thr);
2890 *thr = old_thr;
2891 }
2892
2893 /* Calculate alignment and size requirements of a private copy of data shared
2894 as GOMP_MAP_FIRSTPRIVATE and store them to TGT_ALIGN and TGT_SIZE. */
2895
2896 static inline void
2897 calculate_firstprivate_requirements (size_t mapnum, size_t *sizes,
2898 unsigned short *kinds, size_t *tgt_align,
2899 size_t *tgt_size)
2900 {
2901 size_t i;
2902 for (i = 0; i < mapnum; i++)
2903 if ((kinds[i] & 0xff) == GOMP_MAP_FIRSTPRIVATE)
2904 {
2905 size_t align = (size_t) 1 << (kinds[i] >> 8);
2906 if (*tgt_align < align)
2907 *tgt_align = align;
2908 *tgt_size = (*tgt_size + align - 1) & ~(align - 1);
2909 *tgt_size += sizes[i];
2910 }
2911 }
2912
2913 /* Copy data shared as GOMP_MAP_FIRSTPRIVATE to DST. */
2914
2915 static inline void
2916 copy_firstprivate_data (char *tgt, size_t mapnum, void **hostaddrs,
2917 size_t *sizes, unsigned short *kinds, size_t tgt_align,
2918 size_t tgt_size)
2919 {
2920 uintptr_t al = (uintptr_t) tgt & (tgt_align - 1);
2921 if (al)
2922 tgt += tgt_align - al;
2923 tgt_size = 0;
2924 size_t i;
2925 for (i = 0; i < mapnum; i++)
2926 if ((kinds[i] & 0xff) == GOMP_MAP_FIRSTPRIVATE && hostaddrs[i] != NULL)
2927 {
2928 size_t align = (size_t) 1 << (kinds[i] >> 8);
2929 tgt_size = (tgt_size + align - 1) & ~(align - 1);
2930 memcpy (tgt + tgt_size, hostaddrs[i], sizes[i]);
2931 hostaddrs[i] = tgt + tgt_size;
2932 tgt_size = tgt_size + sizes[i];
2933 if (i + 1 < mapnum && (kinds[i+1] & 0xff) == GOMP_MAP_ATTACH)
2934 {
2935 *(*(uintptr_t**) hostaddrs[i+1] + sizes[i+1]) = (uintptr_t) hostaddrs[i];
2936 ++i;
2937 }
2938 }
2939 }
2940
2941 /* Helper function of GOMP_target{,_ext} routines. */
2942
2943 static void *
2944 gomp_get_target_fn_addr (struct gomp_device_descr *devicep,
2945 void (*host_fn) (void *))
2946 {
2947 if (devicep->capabilities & GOMP_OFFLOAD_CAP_NATIVE_EXEC)
2948 return (void *) host_fn;
2949 else
2950 {
2951 gomp_mutex_lock (&devicep->lock);
2952 if (devicep->state == GOMP_DEVICE_FINALIZED)
2953 {
2954 gomp_mutex_unlock (&devicep->lock);
2955 return NULL;
2956 }
2957
2958 struct splay_tree_key_s k;
2959 k.host_start = (uintptr_t) host_fn;
2960 k.host_end = k.host_start + 1;
2961 splay_tree_key tgt_fn = splay_tree_lookup (&devicep->mem_map, &k);
2962 gomp_mutex_unlock (&devicep->lock);
2963 if (tgt_fn == NULL)
2964 return NULL;
2965
2966 return (void *) tgt_fn->tgt_offset;
2967 }
2968 }
2969
2970 /* Called when encountering a target directive. If DEVICE
2971 is GOMP_DEVICE_ICV, it means use device-var ICV. If it is
2972 GOMP_DEVICE_HOST_FALLBACK (or any value
2973 larger than last available hw device), use host fallback.
2974 FN is address of host code, UNUSED is part of the current ABI, but
2975 we're not actually using it. HOSTADDRS, SIZES and KINDS are arrays
2976 with MAPNUM entries, with addresses of the host objects,
2977 sizes of the host objects (resp. for pointer kind pointer bias
2978 and assumed sizeof (void *) size) and kinds. */
2979
2980 void
2981 GOMP_target (int device, void (*fn) (void *), const void *unused,
2982 size_t mapnum, void **hostaddrs, size_t *sizes,
2983 unsigned char *kinds)
2984 {
2985 struct gomp_device_descr *devicep = resolve_device (device, true);
2986
2987 void *fn_addr;
2988 if (devicep == NULL
2989 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
2990 /* All shared memory devices should use the GOMP_target_ext function. */
2991 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM
2992 || !(fn_addr = gomp_get_target_fn_addr (devicep, fn)))
2993 return gomp_target_fallback (fn, hostaddrs, devicep, NULL);
2994
2995 htab_t refcount_set = htab_create (mapnum);
2996 struct target_mem_desc *tgt_vars
2997 = gomp_map_vars (devicep, mapnum, hostaddrs, NULL, sizes, kinds, false,
2998 &refcount_set, GOMP_MAP_VARS_TARGET);
2999 devicep->run_func (devicep->target_id, fn_addr, (void *) tgt_vars->tgt_start,
3000 NULL);
3001 htab_clear (refcount_set);
3002 gomp_unmap_vars (tgt_vars, true, &refcount_set);
3003 htab_free (refcount_set);
3004 }
3005
3006 static inline unsigned int
3007 clear_unsupported_flags (struct gomp_device_descr *devicep, unsigned int flags)
3008 {
3009 /* If we cannot run asynchronously, simply ignore nowait. */
3010 if (devicep != NULL && devicep->async_run_func == NULL)
3011 flags &= ~GOMP_TARGET_FLAG_NOWAIT;
3012
3013 return flags;
3014 }
3015
3016 static void
3017 gomp_copy_back_icvs (struct gomp_device_descr *devicep, int device)
3018 {
3019 struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device);
3020 if (item == NULL)
3021 return;
3022
3023 gomp_mutex_lock (&devicep->lock);
3024
3025 struct splay_tree_s *mem_map = &devicep->mem_map;
3026 struct splay_tree_key_s cur_node;
3027 void *dev_ptr = NULL;
3028
3029 void *host_ptr = &item->icvs;
3030 cur_node.host_start = (uintptr_t) host_ptr;
3031 cur_node.host_end = cur_node.host_start;
3032 splay_tree_key n = gomp_map_0len_lookup (mem_map, &cur_node);
3033
3034 if (n)
3035 {
3036 uintptr_t offset = cur_node.host_start - n->host_start;
3037 dev_ptr = (void *) (n->tgt->tgt_start + n->tgt_offset + offset);
3038 }
3039
3040 gomp_mutex_unlock (&devicep->lock);
3041
3042 if (dev_ptr != NULL)
3043 gomp_copy_dev2host (devicep, NULL, host_ptr, dev_ptr,
3044 sizeof (struct gomp_offload_icvs));
3045 }
3046
3047 /* Like GOMP_target, but KINDS is 16-bit, UNUSED is no longer present,
3048 and several arguments have been added:
3049 FLAGS is a bitmask, see GOMP_TARGET_FLAG_* in gomp-constants.h.
3050 DEPEND is array of dependencies, see GOMP_task for details.
3051
3052 ARGS is a pointer to an array consisting of a variable number of both
3053 device-independent and device-specific arguments, which can take one two
3054 elements where the first specifies for which device it is intended, the type
3055 and optionally also the value. If the value is not present in the first
3056 one, the whole second element the actual value. The last element of the
3057 array is a single NULL. Among the device independent can be for example
3058 NUM_TEAMS and THREAD_LIMIT.
3059
3060 NUM_TEAMS is positive if GOMP_teams will be called in the body with
3061 that value, or 1 if teams construct is not present, or 0, if
3062 teams construct does not have num_teams clause and so the choice is
3063 implementation defined, and -1 if it can't be determined on the host
3064 what value will GOMP_teams have on the device.
3065 THREAD_LIMIT similarly is positive if GOMP_teams will be called in the
3066 body with that value, or 0, if teams construct does not have thread_limit
3067 clause or the teams construct is not present, or -1 if it can't be
3068 determined on the host what value will GOMP_teams have on the device. */
3069
3070 void
3071 GOMP_target_ext (int device, void (*fn) (void *), size_t mapnum,
3072 void **hostaddrs, size_t *sizes, unsigned short *kinds,
3073 unsigned int flags, void **depend, void **args)
3074 {
3075 struct gomp_device_descr *devicep = resolve_device (device, true);
3076 size_t tgt_align = 0, tgt_size = 0;
3077 bool fpc_done = false;
3078
3079 /* Obtain the original TEAMS and THREADS values from ARGS. */
3080 intptr_t orig_teams = 1, orig_threads = 0;
3081 size_t num_args = 0, len = 1, teams_len = 1, threads_len = 1;
3082 void **tmpargs = args;
3083 while (*tmpargs)
3084 {
3085 intptr_t id = (intptr_t) *tmpargs++, val;
3086 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
3087 {
3088 val = (intptr_t) *tmpargs++;
3089 len = 2;
3090 }
3091 else
3092 {
3093 val = id >> GOMP_TARGET_ARG_VALUE_SHIFT;
3094 len = 1;
3095 }
3096 num_args += len;
3097 if ((id & GOMP_TARGET_ARG_DEVICE_MASK) != GOMP_TARGET_ARG_DEVICE_ALL)
3098 continue;
3099 val = val > INT_MAX ? INT_MAX : val;
3100 if ((id & GOMP_TARGET_ARG_ID_MASK) == GOMP_TARGET_ARG_NUM_TEAMS)
3101 {
3102 orig_teams = val;
3103 teams_len = len;
3104 }
3105 else if ((id & GOMP_TARGET_ARG_ID_MASK) == GOMP_TARGET_ARG_THREAD_LIMIT)
3106 {
3107 orig_threads = val;
3108 threads_len = len;
3109 }
3110 }
3111
3112 intptr_t new_teams = orig_teams, new_threads = orig_threads;
3113 /* ORIG_TEAMS == -2: No explicit teams construct specified. Set to 1.
3114 ORIG_TEAMS == -1: TEAMS construct with NUM_TEAMS clause specified, but the
3115 value could not be determined. No change.
3116 ORIG_TEAMS == 0: TEAMS construct without NUM_TEAMS clause.
3117 Set device-specific value.
3118 ORIG_TEAMS > 0: Value was already set through e.g. NUM_TEAMS clause.
3119 No change. */
3120 if (orig_teams == -2)
3121 new_teams = 1;
3122 else if (orig_teams == 0)
3123 {
3124 struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device);
3125 if (item != NULL)
3126 new_teams = item->icvs.nteams;
3127 }
3128 /* The device-specific teams-thread-limit is only set if (a) an explicit TEAMS
3129 region exists, i.e. ORIG_TEAMS > -2, and (b) THREADS was not already set by
3130 e.g. a THREAD_LIMIT clause. */
3131 if (orig_teams > -2 && orig_threads == 0)
3132 {
3133 struct gomp_offload_icv_list *item = gomp_get_offload_icv_item (device);
3134 if (item != NULL)
3135 new_threads = item->icvs.teams_thread_limit;
3136 }
3137
3138 /* Copy and change the arguments list only if TEAMS or THREADS need to be
3139 updated. */
3140 void **new_args = args;
3141 if (orig_teams != new_teams || orig_threads != new_threads)
3142 {
3143 size_t tms_len = (orig_teams == new_teams
3144 ? teams_len
3145 : (new_teams > -(1 << 15) && new_teams < (1 << 15)
3146 ? 1 : 2));
3147 size_t ths_len = (orig_threads == new_threads
3148 ? threads_len
3149 : (new_threads > -(1 << 15) && new_threads < (1 << 15)
3150 ? 1 : 2));
3151 /* One additional item after the last arg must be NULL. */
3152 size_t new_args_cnt = num_args - teams_len - threads_len + tms_len
3153 + ths_len + 1;
3154 new_args = (void **) gomp_alloca (new_args_cnt * sizeof (void*));
3155
3156 tmpargs = args;
3157 void **tmp_new_args = new_args;
3158 /* Copy all args except TEAMS and THREADS. TEAMS and THREADS are copied
3159 too if they have not been changed and skipped otherwise. */
3160 while (*tmpargs)
3161 {
3162 intptr_t id = (intptr_t) *tmpargs;
3163 if (((id & GOMP_TARGET_ARG_ID_MASK) == GOMP_TARGET_ARG_NUM_TEAMS
3164 && orig_teams != new_teams)
3165 || ((id & GOMP_TARGET_ARG_ID_MASK) == GOMP_TARGET_ARG_THREAD_LIMIT
3166 && orig_threads != new_threads))
3167 {
3168 tmpargs++;
3169 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
3170 tmpargs++;
3171 }
3172 else
3173 {
3174 *tmp_new_args++ = *tmpargs++;
3175 if (id & GOMP_TARGET_ARG_SUBSEQUENT_PARAM)
3176 *tmp_new_args++ = *tmpargs++;
3177 }
3178 }
3179
3180 /* Add the new TEAMS arg to the new args list if it has been changed. */
3181 if (orig_teams != new_teams)
3182 {
3183 intptr_t new_val = new_teams;
3184 if (tms_len == 1)
3185 {
3186 new_val = (new_val << GOMP_TARGET_ARG_VALUE_SHIFT)
3187 | GOMP_TARGET_ARG_NUM_TEAMS;
3188 *tmp_new_args++ = (void *) new_val;
3189 }
3190 else
3191 {
3192 *tmp_new_args++ = (void *) (GOMP_TARGET_ARG_SUBSEQUENT_PARAM
3193 | GOMP_TARGET_ARG_NUM_TEAMS);
3194 *tmp_new_args++ = (void *) new_val;
3195 }
3196 }
3197
3198 /* Add the new THREADS arg to the new args list if it has been changed. */
3199 if (orig_threads != new_threads)
3200 {
3201 intptr_t new_val = new_threads;
3202 if (ths_len == 1)
3203 {
3204 new_val = (new_val << GOMP_TARGET_ARG_VALUE_SHIFT)
3205 | GOMP_TARGET_ARG_THREAD_LIMIT;
3206 *tmp_new_args++ = (void *) new_val;
3207 }
3208 else
3209 {
3210 *tmp_new_args++ = (void *) (GOMP_TARGET_ARG_SUBSEQUENT_PARAM
3211 | GOMP_TARGET_ARG_THREAD_LIMIT);
3212 *tmp_new_args++ = (void *) new_val;
3213 }
3214 }
3215
3216 *tmp_new_args = NULL;
3217 }
3218
3219 flags = clear_unsupported_flags (devicep, flags);
3220
3221 if (flags & GOMP_TARGET_FLAG_NOWAIT)
3222 {
3223 struct gomp_thread *thr = gomp_thread ();
3224 /* Create a team if we don't have any around, as nowait
3225 target tasks make sense to run asynchronously even when
3226 outside of any parallel. */
3227 if (__builtin_expect (thr->ts.team == NULL, 0))
3228 {
3229 struct gomp_team *team = gomp_new_team (1);
3230 struct gomp_task *task = thr->task;
3231 struct gomp_task **implicit_task = &task;
3232 struct gomp_task_icv *icv = task ? &task->icv : &gomp_global_icv;
3233 team->prev_ts = thr->ts;
3234 thr->ts.team = team;
3235 thr->ts.team_id = 0;
3236 thr->ts.work_share = &team->work_shares[0];
3237 thr->ts.last_work_share = NULL;
3238 #ifdef HAVE_SYNC_BUILTINS
3239 thr->ts.single_count = 0;
3240 #endif
3241 thr->ts.static_trip = 0;
3242 thr->task = &team->implicit_task[0];
3243 gomp_init_task (thr->task, NULL, icv);
3244 while (*implicit_task
3245 && (*implicit_task)->kind != GOMP_TASK_IMPLICIT)
3246 implicit_task = &(*implicit_task)->parent;
3247 if (*implicit_task)
3248 {
3249 thr->task = *implicit_task;
3250 gomp_end_task ();
3251 free (*implicit_task);
3252 thr->task = &team->implicit_task[0];
3253 }
3254 else
3255 pthread_setspecific (gomp_thread_destructor, thr);
3256 if (implicit_task != &task)
3257 {
3258 *implicit_task = thr->task;
3259 thr->task = task;
3260 }
3261 }
3262 if (thr->ts.team
3263 && !thr->task->final_task)
3264 {
3265 gomp_create_target_task (devicep, fn, mapnum, hostaddrs,
3266 sizes, kinds, flags, depend, new_args,
3267 GOMP_TARGET_TASK_BEFORE_MAP);
3268 return;
3269 }
3270 }
3271
3272 /* If there are depend clauses, but nowait is not present
3273 (or we are in a final task), block the parent task until the
3274 dependencies are resolved and then just continue with the rest
3275 of the function as if it is a merged task. */
3276 if (depend != NULL)
3277 {
3278 struct gomp_thread *thr = gomp_thread ();
3279 if (thr->task && thr->task->depend_hash)
3280 {
3281 /* If we might need to wait, copy firstprivate now. */
3282 calculate_firstprivate_requirements (mapnum, sizes, kinds,
3283 &tgt_align, &tgt_size);
3284 if (tgt_align)
3285 {
3286 char *tgt = gomp_alloca (tgt_size + tgt_align - 1);
3287 copy_firstprivate_data (tgt, mapnum, hostaddrs, sizes, kinds,
3288 tgt_align, tgt_size);
3289 }
3290 fpc_done = true;
3291 gomp_task_maybe_wait_for_dependencies (depend);
3292 }
3293 }
3294
3295 void *fn_addr;
3296 if (devicep == NULL
3297 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
3298 || !(fn_addr = gomp_get_target_fn_addr (devicep, fn))
3299 || (devicep->can_run_func && !devicep->can_run_func (fn_addr)))
3300 {
3301 if (!fpc_done)
3302 {
3303 calculate_firstprivate_requirements (mapnum, sizes, kinds,
3304 &tgt_align, &tgt_size);
3305 if (tgt_align)
3306 {
3307 char *tgt = gomp_alloca (tgt_size + tgt_align - 1);
3308 copy_firstprivate_data (tgt, mapnum, hostaddrs, sizes, kinds,
3309 tgt_align, tgt_size);
3310 }
3311 }
3312 gomp_target_fallback (fn, hostaddrs, devicep, new_args);
3313 return;
3314 }
3315
3316 struct target_mem_desc *tgt_vars;
3317 htab_t refcount_set = NULL;
3318
3319 if (devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
3320 {
3321 if (!fpc_done)
3322 {
3323 calculate_firstprivate_requirements (mapnum, sizes, kinds,
3324 &tgt_align, &tgt_size);
3325 if (tgt_align)
3326 {
3327 char *tgt = gomp_alloca (tgt_size + tgt_align - 1);
3328 copy_firstprivate_data (tgt, mapnum, hostaddrs, sizes, kinds,
3329 tgt_align, tgt_size);
3330 }
3331 }
3332 tgt_vars = NULL;
3333 }
3334 else
3335 {
3336 refcount_set = htab_create (mapnum);
3337 tgt_vars = gomp_map_vars (devicep, mapnum, hostaddrs, NULL, sizes, kinds,
3338 true, &refcount_set, GOMP_MAP_VARS_TARGET);
3339 }
3340 devicep->run_func (devicep->target_id, fn_addr,
3341 tgt_vars ? (void *) tgt_vars->tgt_start : hostaddrs,
3342 new_args);
3343 if (tgt_vars)
3344 {
3345 htab_clear (refcount_set);
3346 gomp_unmap_vars (tgt_vars, true, &refcount_set);
3347 }
3348 if (refcount_set)
3349 htab_free (refcount_set);
3350
3351 /* Copy back ICVs from device to host.
3352 HOST_PTR is expected to exist since it was added in
3353 gomp_load_image_to_device if not already available. */
3354 gomp_copy_back_icvs (devicep, device);
3355
3356 }
3357
3358
3359 /* Reverse lookup (device addr -> host addr) for reverse offload. We avoid
3360 keeping track of all variable handling - assuming that reverse offload occurs
3361 ony very rarely. Downside is that the reverse search is slow. */
3362
3363 struct gomp_splay_tree_rev_lookup_data {
3364 uintptr_t tgt_start;
3365 uintptr_t tgt_end;
3366 splay_tree_key key;
3367 };
3368
3369 static int
3370 gomp_splay_tree_rev_lookup (splay_tree_key key, void *d)
3371 {
3372 struct gomp_splay_tree_rev_lookup_data *data;
3373 data = (struct gomp_splay_tree_rev_lookup_data *)d;
3374 uintptr_t tgt_start = key->tgt->tgt_start + key->tgt_offset;
3375
3376 if (tgt_start > data->tgt_start || key->tgt->list_count == 0)
3377 return 0;
3378
3379 size_t j;
3380 for (j = 0; j < key->tgt->list_count; j++)
3381 if (key->tgt->list[j].key == key)
3382 break;
3383 assert (j < key->tgt->list_count);
3384 uintptr_t tgt_end = tgt_start + key->tgt->list[j].length;
3385
3386 if ((tgt_start == data->tgt_start && tgt_end == data->tgt_end)
3387 || (tgt_end > data->tgt_start && tgt_start < data->tgt_end))
3388 {
3389 data->key = key;
3390 return 1;
3391 }
3392 return 0;
3393 }
3394
3395 static inline splay_tree_key
3396 gomp_map_rev_lookup (splay_tree mem_map, uint64_t tgt_start, uint64_t tgt_end,
3397 bool zero_len)
3398 {
3399 struct gomp_splay_tree_rev_lookup_data data;
3400 data.key = NULL;
3401 data.tgt_start = tgt_start;
3402 data.tgt_end = tgt_end;
3403
3404 if (tgt_start != tgt_end)
3405 {
3406 splay_tree_foreach_lazy (mem_map, gomp_splay_tree_rev_lookup, &data);
3407 return data.key;
3408 }
3409
3410 data.tgt_end++;
3411 splay_tree_foreach_lazy (mem_map, gomp_splay_tree_rev_lookup, &data);
3412 if (data.key != NULL || zero_len)
3413 return data.key;
3414 data.tgt_end--;
3415
3416 data.tgt_start--;
3417 splay_tree_foreach_lazy (mem_map, gomp_splay_tree_rev_lookup, &data);
3418 return data.key;
3419 }
3420
3421 struct cpy_data
3422 {
3423 uint64_t devaddr;
3424 bool present, aligned;
3425 };
3426
3427
3428 /* Search just mapped reverse-offload data; returns index if found,
3429 otherwise >= n. */
3430
3431 static inline int
3432 gomp_map_cdata_lookup_int (struct cpy_data *d, uint64_t *devaddrs,
3433 unsigned short *kinds, uint64_t *sizes, size_t n,
3434 uint64_t tgt_start, uint64_t tgt_end)
3435 {
3436 const bool short_mapkind = true;
3437 const int typemask = short_mapkind ? 0xff : 0x7;
3438 size_t i;
3439 for (i = 0; i < n; i++)
3440 {
3441 bool is_struct = ((get_kind (short_mapkind, kinds, i) & typemask)
3442 == GOMP_MAP_STRUCT);
3443 uint64_t dev_end;
3444 if (!is_struct)
3445 dev_end = d[i].devaddr + sizes[i];
3446 else
3447 {
3448 if (i + sizes[i] < n)
3449 dev_end = d[i + sizes[i]].devaddr + sizes[i + sizes[i]];
3450 else
3451 dev_end = devaddrs[i + sizes[i]] + sizes[i + sizes[i]];
3452 }
3453 if ((d[i].devaddr == tgt_start && dev_end == tgt_end)
3454 || (dev_end > tgt_start && d[i].devaddr < tgt_end))
3455 break;
3456 if (is_struct)
3457 i += sizes[i];
3458 }
3459 return i;
3460 }
3461
3462 static inline int
3463 gomp_map_cdata_lookup (struct cpy_data *d, uint64_t *devaddrs,
3464 unsigned short *kinds, uint64_t *sizes,
3465 size_t n, uint64_t tgt_start, uint64_t tgt_end,
3466 bool zero_len)
3467 {
3468 size_t i;
3469 if (tgt_start != tgt_end)
3470 return gomp_map_cdata_lookup_int (d, devaddrs, kinds, sizes, n,
3471 tgt_start, tgt_end);
3472 tgt_end++;
3473 i = gomp_map_cdata_lookup_int (d, devaddrs, kinds, sizes, n,
3474 tgt_start, tgt_end);
3475 if (i < n || zero_len)
3476 return i;
3477 tgt_end--;
3478
3479 tgt_start--;
3480 return gomp_map_cdata_lookup_int (d, devaddrs, kinds, sizes, n,
3481 tgt_start, tgt_end);
3482 }
3483
3484 /* Handle reverse offload. This is called by the device plugins for a
3485 reverse offload; it is not called if the outer target runs on the host.
3486 The mapping is simplified device-affecting constructs (except for target
3487 with device(ancestor:1)) must not be encountered; in particular not
3488 target (enter/exit) data. */
3489
3490 void
3491 gomp_target_rev (uint64_t fn_ptr, uint64_t mapnum, uint64_t devaddrs_ptr,
3492 uint64_t sizes_ptr, uint64_t kinds_ptr, int dev_num,
3493 struct goacc_asyncqueue *aq)
3494 {
3495 /* Return early if there is no offload code. */
3496 if (sizeof (OFFLOAD_PLUGINS) == sizeof (""))
3497 return;
3498 /* Currently, this fails because of calculate_firstprivate_requirements
3499 below; it could be fixed but additional code needs to be updated to
3500 handle 32bit hosts - thus, it is not worthwhile. */
3501 if (sizeof (void *) != sizeof (uint64_t))
3502 gomp_fatal ("Reverse offload of 32bit hosts not supported.");
3503
3504 struct cpy_data *cdata = NULL;
3505 uint64_t *devaddrs;
3506 uint64_t *sizes;
3507 unsigned short *kinds;
3508 const bool short_mapkind = true;
3509 const int typemask = short_mapkind ? 0xff : 0x7;
3510 struct gomp_device_descr *devicep = resolve_device (dev_num, false);
3511
3512 reverse_splay_tree_key n;
3513 struct reverse_splay_tree_key_s k;
3514 k.dev = fn_ptr;
3515
3516 gomp_mutex_lock (&devicep->lock);
3517 n = gomp_map_lookup_rev (&devicep->mem_map_rev, &k);
3518 gomp_mutex_unlock (&devicep->lock);
3519
3520 if (n == NULL)
3521 gomp_fatal ("Cannot find reverse-offload function");
3522 void (*host_fn) (void *) = (void (*) (void *)) n->k->host_start;
3523
3524 if ((devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM) || mapnum == 0)
3525 {
3526 devaddrs = (uint64_t *) (uintptr_t) devaddrs_ptr;
3527 sizes = (uint64_t *) (uintptr_t) sizes_ptr;
3528 kinds = (unsigned short *) (uintptr_t) kinds_ptr;
3529 }
3530 else
3531 {
3532 devaddrs = (uint64_t *) gomp_malloc (mapnum * sizeof (uint64_t));
3533 sizes = (uint64_t *) gomp_malloc (mapnum * sizeof (uint64_t));
3534 kinds = (unsigned short *) gomp_malloc (mapnum * sizeof (unsigned short));
3535 gomp_copy_dev2host (devicep, aq, devaddrs,
3536 (const void *) (uintptr_t) devaddrs_ptr,
3537 mapnum * sizeof (uint64_t));
3538 gomp_copy_dev2host (devicep, aq, sizes,
3539 (const void *) (uintptr_t) sizes_ptr,
3540 mapnum * sizeof (uint64_t));
3541 gomp_copy_dev2host (devicep, aq, kinds,
3542 (const void *) (uintptr_t) kinds_ptr,
3543 mapnum * sizeof (unsigned short));
3544 if (aq && !devicep->openacc.async.synchronize_func (aq))
3545 exit (EXIT_FAILURE);
3546 }
3547
3548 size_t tgt_align = 0, tgt_size = 0;
3549
3550 /* If actually executed on 32bit systems, the casts lead to wrong code;
3551 but 32bit with offloading is not supported; see top of this function. */
3552 calculate_firstprivate_requirements (mapnum, (void *) (uintptr_t) sizes,
3553 (void *) (uintptr_t) kinds,
3554 &tgt_align, &tgt_size);
3555
3556 if (tgt_align)
3557 {
3558 char *tgt = gomp_alloca (tgt_size + tgt_align - 1);
3559 uintptr_t al = (uintptr_t) tgt & (tgt_align - 1);
3560 if (al)
3561 tgt += tgt_align - al;
3562 tgt_size = 0;
3563 for (uint64_t i = 0; i < mapnum; i++)
3564 if (get_kind (short_mapkind, kinds, i) == GOMP_MAP_FIRSTPRIVATE
3565 && devaddrs[i] != 0)
3566 {
3567 size_t align = (size_t) 1 << (kinds[i] >> 8);
3568 tgt_size = (tgt_size + align - 1) & ~(align - 1);
3569 if (devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
3570 memcpy (tgt + tgt_size, (void *) (uintptr_t) devaddrs[i],
3571 (size_t) sizes[i]);
3572 else
3573 {
3574 gomp_copy_dev2host (devicep, aq, tgt + tgt_size,
3575 (void *) (uintptr_t) devaddrs[i],
3576 (size_t) sizes[i]);
3577 if (aq && !devicep->openacc.async.synchronize_func (aq))
3578 exit (EXIT_FAILURE);
3579 }
3580 devaddrs[i] = (uint64_t) (uintptr_t) tgt + tgt_size;
3581 tgt_size = tgt_size + sizes[i];
3582 if ((devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
3583 && i + 1 < mapnum
3584 && ((get_kind (short_mapkind, kinds, i) & typemask)
3585 == GOMP_MAP_ATTACH))
3586 {
3587 *(uint64_t*) (uintptr_t) (devaddrs[i+1] + sizes[i+1])
3588 = (uint64_t) devaddrs[i];
3589 ++i;
3590 }
3591 }
3592 }
3593
3594 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM) && mapnum > 0)
3595 {
3596 size_t j, struct_cpy = 0;
3597 splay_tree_key n2;
3598 cdata = gomp_alloca (sizeof (*cdata) * mapnum);
3599 memset (cdata, '\0', sizeof (*cdata) * mapnum);
3600 gomp_mutex_lock (&devicep->lock);
3601 for (uint64_t i = 0; i < mapnum; i++)
3602 {
3603 if (devaddrs[i] == 0)
3604 continue;
3605 n = NULL;
3606 int kind = get_kind (short_mapkind, kinds, i) & typemask;
3607 switch (kind)
3608 {
3609 case GOMP_MAP_FIRSTPRIVATE:
3610 case GOMP_MAP_FIRSTPRIVATE_INT:
3611 continue;
3612
3613 case GOMP_MAP_DELETE:
3614 case GOMP_MAP_RELEASE:
3615 case GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION:
3616 /* Assume it is present; look it up - but ignore unless the
3617 present clause is there. */
3618 case GOMP_MAP_ALLOC:
3619 case GOMP_MAP_FROM:
3620 case GOMP_MAP_FORCE_ALLOC:
3621 case GOMP_MAP_FORCE_FROM:
3622 case GOMP_MAP_ALWAYS_FROM:
3623 case GOMP_MAP_TO:
3624 case GOMP_MAP_TOFROM:
3625 case GOMP_MAP_FORCE_TO:
3626 case GOMP_MAP_FORCE_TOFROM:
3627 case GOMP_MAP_ALWAYS_TO:
3628 case GOMP_MAP_ALWAYS_TOFROM:
3629 case GOMP_MAP_FORCE_PRESENT:
3630 case GOMP_MAP_ALWAYS_PRESENT_FROM:
3631 case GOMP_MAP_ALWAYS_PRESENT_TO:
3632 case GOMP_MAP_ALWAYS_PRESENT_TOFROM:
3633 case GOMP_MAP_ZERO_LEN_ARRAY_SECTION:
3634 cdata[i].devaddr = devaddrs[i];
3635 bool zero_len = (kind == GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION
3636 || kind == GOMP_MAP_ZERO_LEN_ARRAY_SECTION);
3637 j = gomp_map_cdata_lookup (cdata, devaddrs, kinds, sizes, i,
3638 devaddrs[i],
3639 devaddrs[i] + sizes[i], zero_len);
3640 if (j < i)
3641 {
3642 n2 = NULL;
3643 cdata[i].present = true;
3644 devaddrs[i] = devaddrs[j] + devaddrs[i] - cdata[j].devaddr;
3645 }
3646 else
3647 {
3648 n2 = gomp_map_rev_lookup (&devicep->mem_map,
3649 devaddrs[i],
3650 devaddrs[i] + sizes[i], zero_len);
3651 cdata[i].present = n2 != NULL;
3652 }
3653 if (!cdata[i].present && GOMP_MAP_PRESENT_P (kind))
3654 {
3655 gomp_mutex_unlock (&devicep->lock);
3656 #ifdef HAVE_INTTYPES_H
3657 gomp_fatal ("present clause: no corresponding data on "
3658 "parent device at %p with size %"PRIu64,
3659 (void *) (uintptr_t) devaddrs[i],
3660 (uint64_t) sizes[i]);
3661 #else
3662 gomp_fatal ("present clause: no corresponding data on "
3663 "parent device at %p with size %lu",
3664 (void *) (uintptr_t) devaddrs[i],
3665 (unsigned long) sizes[i]);
3666 #endif
3667 break;
3668 }
3669 else if (!cdata[i].present
3670 && kind != GOMP_MAP_DELETE
3671 && kind != GOMP_MAP_RELEASE
3672 && kind != GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION)
3673 {
3674 cdata[i].aligned = true;
3675 size_t align = (size_t) 1 << (kinds[i] >> 8);
3676 devaddrs[i]
3677 = (uint64_t) (uintptr_t) gomp_aligned_alloc (align,
3678 sizes[i]);
3679 }
3680 else if (n2 != NULL)
3681 devaddrs[i] = (n2->host_start + cdata[i].devaddr
3682 - (n2->tgt->tgt_start + n2->tgt_offset));
3683 if (((!cdata[i].present || struct_cpy)
3684 && (kind == GOMP_MAP_TO || kind == GOMP_MAP_TOFROM))
3685 || kind == GOMP_MAP_FORCE_TO
3686 || kind == GOMP_MAP_FORCE_TOFROM
3687 || GOMP_MAP_ALWAYS_TO_P (kind))
3688 {
3689 gomp_copy_dev2host (devicep, aq,
3690 (void *) (uintptr_t) devaddrs[i],
3691 (void *) (uintptr_t) cdata[i].devaddr,
3692 sizes[i]);
3693 if (aq && !devicep->openacc.async.synchronize_func (aq))
3694 {
3695 gomp_mutex_unlock (&devicep->lock);
3696 exit (EXIT_FAILURE);
3697 }
3698 }
3699 if (struct_cpy)
3700 struct_cpy--;
3701 break;
3702 case GOMP_MAP_ATTACH:
3703 case GOMP_MAP_POINTER:
3704 case GOMP_MAP_ALWAYS_POINTER:
3705 n2 = gomp_map_rev_lookup (&devicep->mem_map,
3706 devaddrs[i] + sizes[i],
3707 devaddrs[i] + sizes[i]
3708 + sizeof (void*), false);
3709 cdata[i].present = n2 != NULL;
3710 cdata[i].devaddr = devaddrs[i];
3711 if (n2)
3712 devaddrs[i] = (n2->host_start + cdata[i].devaddr
3713 - (n2->tgt->tgt_start + n2->tgt_offset));
3714 else
3715 {
3716 j = gomp_map_cdata_lookup (cdata, devaddrs, kinds, sizes, i,
3717 devaddrs[i] + sizes[i],
3718 devaddrs[i] + sizes[i]
3719 + sizeof (void*), false);
3720 if (j < i)
3721 {
3722 cdata[i].present = true;
3723 devaddrs[i] = (devaddrs[j] + devaddrs[i]
3724 - cdata[j].devaddr);
3725 }
3726 }
3727 if (!cdata[i].present)
3728 devaddrs[i] = (uintptr_t) gomp_malloc (sizeof (void*));
3729 /* Assume that when present, the pointer is already correct. */
3730 if (!n2)
3731 *(uint64_t *) (uintptr_t) (devaddrs[i] + sizes[i])
3732 = devaddrs[i-1];
3733 break;
3734 case GOMP_MAP_TO_PSET:
3735 /* Assume that when present, the pointers are fine and no 'to:'
3736 is required. */
3737 n2 = gomp_map_rev_lookup (&devicep->mem_map,
3738 devaddrs[i], devaddrs[i] + sizes[i],
3739 false);
3740 cdata[i].present = n2 != NULL;
3741 cdata[i].devaddr = devaddrs[i];
3742 if (n2)
3743 devaddrs[i] = (n2->host_start + cdata[i].devaddr
3744 - (n2->tgt->tgt_start + n2->tgt_offset));
3745 else
3746 {
3747 j = gomp_map_cdata_lookup (cdata, devaddrs, kinds, sizes, i,
3748 devaddrs[i],
3749 devaddrs[i] + sizes[i], false);
3750 if (j < i)
3751 {
3752 cdata[i].present = true;
3753 devaddrs[i] = (devaddrs[j] + devaddrs[i]
3754 - cdata[j].devaddr);
3755 }
3756 }
3757 if (!cdata[i].present)
3758 {
3759 cdata[i].aligned = true;
3760 size_t align = (size_t) 1 << (kinds[i] >> 8);
3761 devaddrs[i]
3762 = (uint64_t) (uintptr_t) gomp_aligned_alloc (align,
3763 sizes[i]);
3764 gomp_copy_dev2host (devicep, aq,
3765 (void *) (uintptr_t) devaddrs[i],
3766 (void *) (uintptr_t) cdata[i].devaddr,
3767 sizes[i]);
3768 if (aq && !devicep->openacc.async.synchronize_func (aq))
3769 {
3770 gomp_mutex_unlock (&devicep->lock);
3771 exit (EXIT_FAILURE);
3772 }
3773 }
3774 for (j = i + 1; j < mapnum; j++)
3775 {
3776 kind = get_kind (short_mapkind, kinds, j) & typemask;
3777 if (!GOMP_MAP_ALWAYS_POINTER_P (kind)
3778 && !GOMP_MAP_POINTER_P (kind))
3779 break;
3780 if (devaddrs[j] < devaddrs[i])
3781 break;
3782 if (cdata[i].present)
3783 continue;
3784 if (devaddrs[j] == 0)
3785 {
3786 *(uint64_t *) (uintptr_t) (devaddrs[i] + sizes[j]) = 0;
3787 continue;
3788 }
3789 int k;
3790 n2 = NULL;
3791 /* Dereference devaddrs[j] to get the device addr. */
3792 assert (devaddrs[j] - sizes[j] == cdata[i].devaddr);
3793 devaddrs[j] = *(uint64_t *) (uintptr_t) (devaddrs[i]
3794 + sizes[j]);
3795 cdata[j].present = true;
3796 cdata[j].devaddr = devaddrs[j];
3797 if (devaddrs[j] == 0)
3798 continue;
3799 k = gomp_map_cdata_lookup (cdata, devaddrs, kinds, sizes, j,
3800 devaddrs[j],
3801 devaddrs[j] + sizeof (void*),
3802 false);
3803 if (k < j)
3804 devaddrs[j] = (devaddrs[k] + devaddrs[j]
3805 - cdata[k].devaddr);
3806 else
3807 {
3808 n2 = gomp_map_rev_lookup (&devicep->mem_map,
3809 devaddrs[j],
3810 devaddrs[j] + sizeof (void*),
3811 false);
3812 if (n2 == NULL)
3813 {
3814 gomp_mutex_unlock (&devicep->lock);
3815 gomp_fatal ("Pointer target wasn't mapped");
3816 }
3817 devaddrs[j] = (n2->host_start + cdata[j].devaddr
3818 - (n2->tgt->tgt_start + n2->tgt_offset));
3819 }
3820 *(void **) (uintptr_t) (devaddrs[i] + sizes[j])
3821 = (void *) (uintptr_t) devaddrs[j];
3822 }
3823 i = j -1;
3824 break;
3825 case GOMP_MAP_STRUCT:
3826 n2 = gomp_map_rev_lookup (&devicep->mem_map, devaddrs[i+1],
3827 devaddrs[i + sizes[i]]
3828 + sizes[i + sizes[i]], false);
3829 cdata[i].present = n2 != NULL;
3830 cdata[i].devaddr = devaddrs[i];
3831 struct_cpy = cdata[i].present ? 0 : sizes[i];
3832 if (!n2)
3833 {
3834 size_t sz = (size_t) (devaddrs[i + sizes[i]]
3835 - devaddrs[i+1]
3836 + sizes[i + sizes[i]]);
3837 size_t align = (size_t) 1 << (kinds[i] >> 8);
3838 cdata[i].aligned = true;
3839 devaddrs[i] = (uintptr_t) gomp_aligned_alloc (align, sz);
3840 devaddrs[i] -= devaddrs[i+1] - cdata[i].devaddr;
3841 }
3842 else
3843 devaddrs[i] = (n2->host_start + cdata[i].devaddr
3844 - (n2->tgt->tgt_start + n2->tgt_offset));
3845 break;
3846 default:
3847 gomp_mutex_unlock (&devicep->lock);
3848 gomp_fatal ("gomp_target_rev unhandled kind 0x%.4x", kinds[i]);
3849 }
3850 }
3851 gomp_mutex_unlock (&devicep->lock);
3852 }
3853
3854 host_fn (devaddrs);
3855
3856 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM) && mapnum > 0)
3857 {
3858 uint64_t struct_cpy = 0;
3859 bool clean_struct = false;
3860 for (uint64_t i = 0; i < mapnum; i++)
3861 {
3862 if (cdata[i].devaddr == 0)
3863 continue;
3864 int kind = get_kind (short_mapkind, kinds, i) & typemask;
3865 bool copy = !cdata[i].present || struct_cpy;
3866 switch (kind)
3867 {
3868 case GOMP_MAP_FORCE_FROM:
3869 case GOMP_MAP_FORCE_TOFROM:
3870 case GOMP_MAP_ALWAYS_FROM:
3871 case GOMP_MAP_ALWAYS_TOFROM:
3872 case GOMP_MAP_ALWAYS_PRESENT_FROM:
3873 case GOMP_MAP_ALWAYS_PRESENT_TOFROM:
3874 copy = true;
3875 /* FALLTHRU */
3876 case GOMP_MAP_FROM:
3877 case GOMP_MAP_TOFROM:
3878 if (copy)
3879 {
3880 gomp_copy_host2dev (devicep, aq,
3881 (void *) (uintptr_t) cdata[i].devaddr,
3882 (void *) (uintptr_t) devaddrs[i],
3883 sizes[i], false, NULL);
3884 if (aq && !devicep->openacc.async.synchronize_func (aq))
3885 exit (EXIT_FAILURE);
3886 }
3887 default:
3888 break;
3889 }
3890 if (struct_cpy)
3891 {
3892 struct_cpy--;
3893 continue;
3894 }
3895 if (kind == GOMP_MAP_STRUCT && !cdata[i].present)
3896 {
3897 clean_struct = true;
3898 struct_cpy = sizes[i];
3899 }
3900 else if (!cdata[i].present && cdata[i].aligned)
3901 gomp_aligned_free ((void *) (uintptr_t) devaddrs[i]);
3902 else if (!cdata[i].present)
3903 free ((void *) (uintptr_t) devaddrs[i]);
3904 }
3905 if (clean_struct)
3906 for (uint64_t i = 0; i < mapnum; i++)
3907 if (!cdata[i].present
3908 && ((get_kind (short_mapkind, kinds, i) & typemask)
3909 == GOMP_MAP_STRUCT))
3910 {
3911 devaddrs[i] += cdata[i+1].devaddr - cdata[i].devaddr;
3912 gomp_aligned_free ((void *) (uintptr_t) devaddrs[i]);
3913 }
3914
3915 free (devaddrs);
3916 free (sizes);
3917 free (kinds);
3918 }
3919 }
3920
3921 /* Host fallback for GOMP_target_data{,_ext} routines. */
3922
3923 static void
3924 gomp_target_data_fallback (struct gomp_device_descr *devicep)
3925 {
3926 struct gomp_task_icv *icv = gomp_icv (false);
3927
3928 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_MANDATORY
3929 && devicep != NULL)
3930 gomp_fatal ("OMP_TARGET_OFFLOAD is set to MANDATORY, but device cannot "
3931 "be used for offloading");
3932
3933 if (icv->target_data)
3934 {
3935 /* Even when doing a host fallback, if there are any active
3936 #pragma omp target data constructs, need to remember the
3937 new #pragma omp target data, otherwise GOMP_target_end_data
3938 would get out of sync. */
3939 struct target_mem_desc *tgt
3940 = gomp_map_vars (NULL, 0, NULL, NULL, NULL, NULL, false,
3941 NULL, GOMP_MAP_VARS_DATA);
3942 tgt->prev = icv->target_data;
3943 icv->target_data = tgt;
3944 }
3945 }
3946
3947 void
3948 GOMP_target_data (int device, const void *unused, size_t mapnum,
3949 void **hostaddrs, size_t *sizes, unsigned char *kinds)
3950 {
3951 struct gomp_device_descr *devicep = resolve_device (device, true);
3952
3953 if (devicep == NULL
3954 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
3955 || (devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM))
3956 return gomp_target_data_fallback (devicep);
3957
3958 struct target_mem_desc *tgt
3959 = gomp_map_vars (devicep, mapnum, hostaddrs, NULL, sizes, kinds, false,
3960 NULL, GOMP_MAP_VARS_DATA);
3961 struct gomp_task_icv *icv = gomp_icv (true);
3962 tgt->prev = icv->target_data;
3963 icv->target_data = tgt;
3964 }
3965
3966 void
3967 GOMP_target_data_ext (int device, size_t mapnum, void **hostaddrs,
3968 size_t *sizes, unsigned short *kinds)
3969 {
3970 struct gomp_device_descr *devicep = resolve_device (device, true);
3971
3972 if (devicep == NULL
3973 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
3974 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
3975 return gomp_target_data_fallback (devicep);
3976
3977 struct target_mem_desc *tgt
3978 = gomp_map_vars (devicep, mapnum, hostaddrs, NULL, sizes, kinds, true,
3979 NULL, GOMP_MAP_VARS_DATA);
3980 struct gomp_task_icv *icv = gomp_icv (true);
3981 tgt->prev = icv->target_data;
3982 icv->target_data = tgt;
3983 }
3984
3985 void
3986 GOMP_target_end_data (void)
3987 {
3988 struct gomp_task_icv *icv = gomp_icv (false);
3989 if (icv->target_data)
3990 {
3991 struct target_mem_desc *tgt = icv->target_data;
3992 icv->target_data = tgt->prev;
3993 gomp_unmap_vars (tgt, true, NULL);
3994 }
3995 }
3996
3997 void
3998 GOMP_target_update (int device, const void *unused, size_t mapnum,
3999 void **hostaddrs, size_t *sizes, unsigned char *kinds)
4000 {
4001 struct gomp_device_descr *devicep = resolve_device (device, true);
4002
4003 if (devicep == NULL
4004 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4005 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4006 return;
4007
4008 gomp_update (devicep, mapnum, hostaddrs, sizes, kinds, false);
4009 }
4010
4011 void
4012 GOMP_target_update_ext (int device, size_t mapnum, void **hostaddrs,
4013 size_t *sizes, unsigned short *kinds,
4014 unsigned int flags, void **depend)
4015 {
4016 struct gomp_device_descr *devicep = resolve_device (device, true);
4017
4018 /* If there are depend clauses, but nowait is not present,
4019 block the parent task until the dependencies are resolved
4020 and then just continue with the rest of the function as if it
4021 is a merged task. Until we are able to schedule task during
4022 variable mapping or unmapping, ignore nowait if depend clauses
4023 are not present. */
4024 if (depend != NULL)
4025 {
4026 struct gomp_thread *thr = gomp_thread ();
4027 if (thr->task && thr->task->depend_hash)
4028 {
4029 if ((flags & GOMP_TARGET_FLAG_NOWAIT)
4030 && thr->ts.team
4031 && !thr->task->final_task)
4032 {
4033 if (gomp_create_target_task (devicep, (void (*) (void *)) NULL,
4034 mapnum, hostaddrs, sizes, kinds,
4035 flags | GOMP_TARGET_FLAG_UPDATE,
4036 depend, NULL, GOMP_TARGET_TASK_DATA))
4037 return;
4038 }
4039 else
4040 {
4041 struct gomp_team *team = thr->ts.team;
4042 /* If parallel or taskgroup has been cancelled, don't start new
4043 tasks. */
4044 if (__builtin_expect (gomp_cancel_var, 0) && team)
4045 {
4046 if (gomp_team_barrier_cancelled (&team->barrier))
4047 return;
4048 if (thr->task->taskgroup)
4049 {
4050 if (thr->task->taskgroup->cancelled)
4051 return;
4052 if (thr->task->taskgroup->workshare
4053 && thr->task->taskgroup->prev
4054 && thr->task->taskgroup->prev->cancelled)
4055 return;
4056 }
4057 }
4058
4059 gomp_task_maybe_wait_for_dependencies (depend);
4060 }
4061 }
4062 }
4063
4064 if (devicep == NULL
4065 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4066 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4067 return;
4068
4069 struct gomp_thread *thr = gomp_thread ();
4070 struct gomp_team *team = thr->ts.team;
4071 /* If parallel or taskgroup has been cancelled, don't start new tasks. */
4072 if (__builtin_expect (gomp_cancel_var, 0) && team)
4073 {
4074 if (gomp_team_barrier_cancelled (&team->barrier))
4075 return;
4076 if (thr->task->taskgroup)
4077 {
4078 if (thr->task->taskgroup->cancelled)
4079 return;
4080 if (thr->task->taskgroup->workshare
4081 && thr->task->taskgroup->prev
4082 && thr->task->taskgroup->prev->cancelled)
4083 return;
4084 }
4085 }
4086
4087 gomp_update (devicep, mapnum, hostaddrs, sizes, kinds, true);
4088 }
4089
4090 static void
4091 gomp_exit_data (struct gomp_device_descr *devicep, size_t mapnum,
4092 void **hostaddrs, size_t *sizes, unsigned short *kinds,
4093 htab_t *refcount_set)
4094 {
4095 const int typemask = 0xff;
4096 size_t i;
4097 gomp_mutex_lock (&devicep->lock);
4098 if (devicep->state == GOMP_DEVICE_FINALIZED)
4099 {
4100 gomp_mutex_unlock (&devicep->lock);
4101 return;
4102 }
4103
4104 for (i = 0; i < mapnum; i++)
4105 if ((kinds[i] & typemask) == GOMP_MAP_DETACH)
4106 {
4107 struct splay_tree_key_s cur_node;
4108 cur_node.host_start = (uintptr_t) hostaddrs[i];
4109 cur_node.host_end = cur_node.host_start + sizeof (void *);
4110 splay_tree_key n = splay_tree_lookup (&devicep->mem_map, &cur_node);
4111
4112 if (n)
4113 gomp_detach_pointer (devicep, NULL, n, (uintptr_t) hostaddrs[i],
4114 false, NULL);
4115 }
4116
4117 int nrmvars = 0;
4118 splay_tree_key remove_vars[mapnum];
4119
4120 for (i = 0; i < mapnum; i++)
4121 {
4122 struct splay_tree_key_s cur_node;
4123 unsigned char kind = kinds[i] & typemask;
4124 switch (kind)
4125 {
4126 case GOMP_MAP_FROM:
4127 case GOMP_MAP_ALWAYS_FROM:
4128 case GOMP_MAP_DELETE:
4129 case GOMP_MAP_RELEASE:
4130 case GOMP_MAP_ZERO_LEN_ARRAY_SECTION:
4131 case GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION:
4132 cur_node.host_start = (uintptr_t) hostaddrs[i];
4133 cur_node.host_end = cur_node.host_start + sizes[i];
4134 splay_tree_key k = (kind == GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION
4135 || kind == GOMP_MAP_ZERO_LEN_ARRAY_SECTION)
4136 ? gomp_map_0len_lookup (&devicep->mem_map, &cur_node)
4137 : splay_tree_lookup (&devicep->mem_map, &cur_node);
4138 if (!k)
4139 continue;
4140
4141 bool delete_p = (kind == GOMP_MAP_DELETE
4142 || kind == GOMP_MAP_DELETE_ZERO_LEN_ARRAY_SECTION);
4143 bool do_copy, do_remove;
4144 gomp_decrement_refcount (k, refcount_set, delete_p, &do_copy,
4145 &do_remove);
4146
4147 if ((kind == GOMP_MAP_FROM && do_copy)
4148 || kind == GOMP_MAP_ALWAYS_FROM)
4149 {
4150 if (k->aux && k->aux->attach_count)
4151 {
4152 /* We have to be careful not to overwrite still attached
4153 pointers during the copyback to host. */
4154 uintptr_t addr = k->host_start;
4155 while (addr < k->host_end)
4156 {
4157 size_t i = (addr - k->host_start) / sizeof (void *);
4158 if (k->aux->attach_count[i] == 0)
4159 gomp_copy_dev2host (devicep, NULL, (void *) addr,
4160 (void *) (k->tgt->tgt_start
4161 + k->tgt_offset
4162 + addr - k->host_start),
4163 sizeof (void *));
4164 addr += sizeof (void *);
4165 }
4166 }
4167 else
4168 gomp_copy_dev2host (devicep, NULL, (void *) cur_node.host_start,
4169 (void *) (k->tgt->tgt_start + k->tgt_offset
4170 + cur_node.host_start
4171 - k->host_start),
4172 cur_node.host_end - cur_node.host_start);
4173 }
4174
4175 /* Structure elements lists are removed altogether at once, which
4176 may cause immediate deallocation of the target_mem_desc, causing
4177 errors if we still have following element siblings to copy back.
4178 While we're at it, it also seems more disciplined to simply
4179 queue all removals together for processing below.
4180
4181 Structured block unmapping (i.e. gomp_unmap_vars_internal) should
4182 not have this problem, since they maintain an additional
4183 tgt->refcount = 1 reference to the target_mem_desc to start with.
4184 */
4185 if (do_remove)
4186 remove_vars[nrmvars++] = k;
4187 break;
4188
4189 case GOMP_MAP_DETACH:
4190 break;
4191 default:
4192 gomp_mutex_unlock (&devicep->lock);
4193 gomp_fatal ("GOMP_target_enter_exit_data unhandled kind 0x%.2x",
4194 kind);
4195 }
4196 }
4197
4198 for (int i = 0; i < nrmvars; i++)
4199 gomp_remove_var (devicep, remove_vars[i]);
4200
4201 gomp_mutex_unlock (&devicep->lock);
4202 }
4203
4204 void
4205 GOMP_target_enter_exit_data (int device, size_t mapnum, void **hostaddrs,
4206 size_t *sizes, unsigned short *kinds,
4207 unsigned int flags, void **depend)
4208 {
4209 struct gomp_device_descr *devicep = resolve_device (device, true);
4210
4211 /* If there are depend clauses, but nowait is not present,
4212 block the parent task until the dependencies are resolved
4213 and then just continue with the rest of the function as if it
4214 is a merged task. Until we are able to schedule task during
4215 variable mapping or unmapping, ignore nowait if depend clauses
4216 are not present. */
4217 if (depend != NULL)
4218 {
4219 struct gomp_thread *thr = gomp_thread ();
4220 if (thr->task && thr->task->depend_hash)
4221 {
4222 if ((flags & GOMP_TARGET_FLAG_NOWAIT)
4223 && thr->ts.team
4224 && !thr->task->final_task)
4225 {
4226 if (gomp_create_target_task (devicep, (void (*) (void *)) NULL,
4227 mapnum, hostaddrs, sizes, kinds,
4228 flags, depend, NULL,
4229 GOMP_TARGET_TASK_DATA))
4230 return;
4231 }
4232 else
4233 {
4234 struct gomp_team *team = thr->ts.team;
4235 /* If parallel or taskgroup has been cancelled, don't start new
4236 tasks. */
4237 if (__builtin_expect (gomp_cancel_var, 0) && team)
4238 {
4239 if (gomp_team_barrier_cancelled (&team->barrier))
4240 return;
4241 if (thr->task->taskgroup)
4242 {
4243 if (thr->task->taskgroup->cancelled)
4244 return;
4245 if (thr->task->taskgroup->workshare
4246 && thr->task->taskgroup->prev
4247 && thr->task->taskgroup->prev->cancelled)
4248 return;
4249 }
4250 }
4251
4252 gomp_task_maybe_wait_for_dependencies (depend);
4253 }
4254 }
4255 }
4256
4257 if (devicep == NULL
4258 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4259 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4260 return;
4261
4262 struct gomp_thread *thr = gomp_thread ();
4263 struct gomp_team *team = thr->ts.team;
4264 /* If parallel or taskgroup has been cancelled, don't start new tasks. */
4265 if (__builtin_expect (gomp_cancel_var, 0) && team)
4266 {
4267 if (gomp_team_barrier_cancelled (&team->barrier))
4268 return;
4269 if (thr->task->taskgroup)
4270 {
4271 if (thr->task->taskgroup->cancelled)
4272 return;
4273 if (thr->task->taskgroup->workshare
4274 && thr->task->taskgroup->prev
4275 && thr->task->taskgroup->prev->cancelled)
4276 return;
4277 }
4278 }
4279
4280 htab_t refcount_set = htab_create (mapnum);
4281
4282 /* The variables are mapped separately such that they can be released
4283 independently. */
4284 size_t i, j;
4285 if ((flags & GOMP_TARGET_FLAG_EXIT_DATA) == 0)
4286 for (i = 0; i < mapnum; i++)
4287 if ((kinds[i] & 0xff) == GOMP_MAP_STRUCT
4288 || (kinds[i] & 0xff) == GOMP_MAP_STRUCT_UNORD)
4289 {
4290 gomp_map_vars (devicep, sizes[i] + 1, &hostaddrs[i], NULL, &sizes[i],
4291 &kinds[i], true, &refcount_set,
4292 GOMP_MAP_VARS_ENTER_DATA);
4293 i += sizes[i];
4294 }
4295 else if ((kinds[i] & 0xff) == GOMP_MAP_TO_PSET)
4296 {
4297 for (j = i + 1; j < mapnum; j++)
4298 if (!GOMP_MAP_POINTER_P (get_kind (true, kinds, j) & 0xff)
4299 && !GOMP_MAP_ALWAYS_POINTER_P (get_kind (true, kinds, j) & 0xff))
4300 break;
4301 gomp_map_vars (devicep, j-i, &hostaddrs[i], NULL, &sizes[i],
4302 &kinds[i], true, &refcount_set,
4303 GOMP_MAP_VARS_ENTER_DATA);
4304 i += j - i - 1;
4305 }
4306 else if (i + 1 < mapnum
4307 && ((kinds[i + 1] & 0xff) == GOMP_MAP_ATTACH
4308 || ((kinds[i + 1] & 0xff) == GOMP_MAP_ALWAYS_POINTER
4309 && (kinds[i] & 0xff) != GOMP_MAP_ALWAYS_POINTER)))
4310 {
4311 /* An attach operation must be processed together with the mapped
4312 base-pointer list item. */
4313 gomp_map_vars (devicep, 2, &hostaddrs[i], NULL, &sizes[i], &kinds[i],
4314 true, &refcount_set, GOMP_MAP_VARS_ENTER_DATA);
4315 i += 1;
4316 }
4317 else
4318 gomp_map_vars (devicep, 1, &hostaddrs[i], NULL, &sizes[i], &kinds[i],
4319 true, &refcount_set, GOMP_MAP_VARS_ENTER_DATA);
4320 else
4321 gomp_exit_data (devicep, mapnum, hostaddrs, sizes, kinds, &refcount_set);
4322 htab_free (refcount_set);
4323 }
4324
4325 bool
4326 gomp_target_task_fn (void *data)
4327 {
4328 struct gomp_target_task *ttask = (struct gomp_target_task *) data;
4329 struct gomp_device_descr *devicep = ttask->devicep;
4330
4331 if (ttask->fn != NULL)
4332 {
4333 void *fn_addr;
4334 if (devicep == NULL
4335 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4336 || !(fn_addr = gomp_get_target_fn_addr (devicep, ttask->fn))
4337 || (devicep->can_run_func && !devicep->can_run_func (fn_addr)))
4338 {
4339 ttask->state = GOMP_TARGET_TASK_FALLBACK;
4340 gomp_target_fallback (ttask->fn, ttask->hostaddrs, devicep,
4341 ttask->args);
4342 return false;
4343 }
4344
4345 if (ttask->state == GOMP_TARGET_TASK_FINISHED)
4346 {
4347 if (ttask->tgt)
4348 gomp_unmap_vars (ttask->tgt, true, NULL);
4349 return false;
4350 }
4351
4352 void *actual_arguments;
4353 if (devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4354 {
4355 ttask->tgt = NULL;
4356 actual_arguments = ttask->hostaddrs;
4357 }
4358 else
4359 {
4360 ttask->tgt = gomp_map_vars (devicep, ttask->mapnum, ttask->hostaddrs,
4361 NULL, ttask->sizes, ttask->kinds, true,
4362 NULL, GOMP_MAP_VARS_TARGET);
4363 actual_arguments = (void *) ttask->tgt->tgt_start;
4364 }
4365 ttask->state = GOMP_TARGET_TASK_READY_TO_RUN;
4366
4367 assert (devicep->async_run_func);
4368 devicep->async_run_func (devicep->target_id, fn_addr, actual_arguments,
4369 ttask->args, (void *) ttask);
4370 return true;
4371 }
4372 else if (devicep == NULL
4373 || !(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4374 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4375 return false;
4376
4377 size_t i;
4378 if (ttask->flags & GOMP_TARGET_FLAG_UPDATE)
4379 gomp_update (devicep, ttask->mapnum, ttask->hostaddrs, ttask->sizes,
4380 ttask->kinds, true);
4381 else
4382 {
4383 htab_t refcount_set = htab_create (ttask->mapnum);
4384 if ((ttask->flags & GOMP_TARGET_FLAG_EXIT_DATA) == 0)
4385 for (i = 0; i < ttask->mapnum; i++)
4386 if ((ttask->kinds[i] & 0xff) == GOMP_MAP_STRUCT
4387 || (ttask->kinds[i] & 0xff) == GOMP_MAP_STRUCT_UNORD)
4388 {
4389 gomp_map_vars (devicep, ttask->sizes[i] + 1, &ttask->hostaddrs[i],
4390 NULL, &ttask->sizes[i], &ttask->kinds[i], true,
4391 &refcount_set, GOMP_MAP_VARS_ENTER_DATA);
4392 i += ttask->sizes[i];
4393 }
4394 else
4395 gomp_map_vars (devicep, 1, &ttask->hostaddrs[i], NULL, &ttask->sizes[i],
4396 &ttask->kinds[i], true, &refcount_set,
4397 GOMP_MAP_VARS_ENTER_DATA);
4398 else
4399 gomp_exit_data (devicep, ttask->mapnum, ttask->hostaddrs, ttask->sizes,
4400 ttask->kinds, &refcount_set);
4401 htab_free (refcount_set);
4402 }
4403 return false;
4404 }
4405
4406 /* Implement OpenMP 'teams' construct, legacy entry point. */
4407
4408 void
4409 GOMP_teams (unsigned int num_teams, unsigned int thread_limit)
4410 {
4411 if (thread_limit)
4412 {
4413 struct gomp_task_icv *icv = gomp_icv (true);
4414 icv->thread_limit_var
4415 = thread_limit > INT_MAX ? UINT_MAX : thread_limit;
4416 }
4417 (void) num_teams;
4418 }
4419
4420 /* Implement OpenMP 'teams' construct.
4421
4422 Initialize upon FIRST call. Return whether this invocation is active.
4423 Depending on whether NUM_TEAMS_LOW asks for more teams than are provided
4424 in hardware, we may need to loop multiple times; in that case make sure to
4425 update the team-level variable used by 'omp_get_team_num'. */
4426
4427 bool
4428 GOMP_teams4 (unsigned int num_teams_low, unsigned int num_teams_high,
4429 unsigned int thread_limit, bool first)
4430 {
4431 struct gomp_thread *thr = gomp_thread ();
4432 if (first)
4433 {
4434 if (thread_limit)
4435 {
4436 struct gomp_task_icv *icv = gomp_icv (true);
4437 icv->thread_limit_var
4438 = thread_limit > INT_MAX ? UINT_MAX : thread_limit;
4439 }
4440 (void) num_teams_high;
4441 if (num_teams_low == 0)
4442 num_teams_low = 1;
4443 thr->num_teams = num_teams_low - 1;
4444 thr->team_num = 0;
4445 }
4446 else if (thr->team_num == thr->num_teams)
4447 return false;
4448 else
4449 ++thr->team_num;
4450 return true;
4451 }
4452
4453 void *
4454 omp_target_alloc (size_t size, int device_num)
4455 {
4456 if (device_num == omp_initial_device
4457 || device_num == gomp_get_num_devices ())
4458 return malloc (size);
4459
4460 struct gomp_device_descr *devicep = resolve_device (device_num, false);
4461 if (devicep == NULL)
4462 return NULL;
4463
4464 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4465 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4466 return malloc (size);
4467
4468 gomp_mutex_lock (&devicep->lock);
4469 void *ret = devicep->alloc_func (devicep->target_id, size);
4470 gomp_mutex_unlock (&devicep->lock);
4471 return ret;
4472 }
4473
4474 void
4475 omp_target_free (void *device_ptr, int device_num)
4476 {
4477 if (device_num == omp_initial_device
4478 || device_num == gomp_get_num_devices ())
4479 {
4480 free (device_ptr);
4481 return;
4482 }
4483
4484 struct gomp_device_descr *devicep = resolve_device (device_num, false);
4485 if (devicep == NULL || device_ptr == NULL)
4486 return;
4487
4488 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4489 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4490 {
4491 free (device_ptr);
4492 return;
4493 }
4494
4495 gomp_mutex_lock (&devicep->lock);
4496 gomp_free_device_memory (devicep, device_ptr);
4497 gomp_mutex_unlock (&devicep->lock);
4498 }
4499
4500 int
4501 omp_target_is_present (const void *ptr, int device_num)
4502 {
4503 if (device_num == omp_initial_device
4504 || device_num == gomp_get_num_devices ())
4505 return 1;
4506
4507 struct gomp_device_descr *devicep = resolve_device (device_num, false);
4508 if (devicep == NULL)
4509 return 0;
4510
4511 if (ptr == NULL)
4512 return 1;
4513
4514 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4515 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4516 return 1;
4517
4518 gomp_mutex_lock (&devicep->lock);
4519 struct splay_tree_s *mem_map = &devicep->mem_map;
4520 struct splay_tree_key_s cur_node;
4521
4522 cur_node.host_start = (uintptr_t) ptr;
4523 cur_node.host_end = cur_node.host_start;
4524 splay_tree_key n = gomp_map_0len_lookup (mem_map, &cur_node);
4525 int ret = n != NULL;
4526 gomp_mutex_unlock (&devicep->lock);
4527 return ret;
4528 }
4529
4530 static int
4531 omp_target_memcpy_check (int dst_device_num, int src_device_num,
4532 struct gomp_device_descr **dst_devicep,
4533 struct gomp_device_descr **src_devicep)
4534 {
4535 if (dst_device_num != gomp_get_num_devices ()
4536 /* Above gomp_get_num_devices has to be called unconditionally. */
4537 && dst_device_num != omp_initial_device)
4538 {
4539 *dst_devicep = resolve_device (dst_device_num, false);
4540 if (*dst_devicep == NULL)
4541 return EINVAL;
4542
4543 if (!((*dst_devicep)->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4544 || (*dst_devicep)->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4545 *dst_devicep = NULL;
4546 }
4547
4548 if (src_device_num != num_devices_openmp
4549 && src_device_num != omp_initial_device)
4550 {
4551 *src_devicep = resolve_device (src_device_num, false);
4552 if (*src_devicep == NULL)
4553 return EINVAL;
4554
4555 if (!((*src_devicep)->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
4556 || (*src_devicep)->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
4557 *src_devicep = NULL;
4558 }
4559
4560 return 0;
4561 }
4562
4563 static int
4564 omp_target_memcpy_copy (void *dst, const void *src, size_t length,
4565 size_t dst_offset, size_t src_offset,
4566 struct gomp_device_descr *dst_devicep,
4567 struct gomp_device_descr *src_devicep)
4568 {
4569 bool ret;
4570 if (src_devicep == NULL && dst_devicep == NULL)
4571 {
4572 memcpy ((char *) dst + dst_offset, (char *) src + src_offset, length);
4573 return 0;
4574 }
4575 if (src_devicep == NULL)
4576 {
4577 gomp_mutex_lock (&dst_devicep->lock);
4578 ret = dst_devicep->host2dev_func (dst_devicep->target_id,
4579 (char *) dst + dst_offset,
4580 (char *) src + src_offset, length);
4581 gomp_mutex_unlock (&dst_devicep->lock);
4582 return (ret ? 0 : EINVAL);
4583 }
4584 if (dst_devicep == NULL)
4585 {
4586 gomp_mutex_lock (&src_devicep->lock);
4587 ret = src_devicep->dev2host_func (src_devicep->target_id,
4588 (char *) dst + dst_offset,
4589 (char *) src + src_offset, length);
4590 gomp_mutex_unlock (&src_devicep->lock);
4591 return (ret ? 0 : EINVAL);
4592 }
4593 if (src_devicep == dst_devicep)
4594 {
4595 gomp_mutex_lock (&src_devicep->lock);
4596 ret = src_devicep->dev2dev_func (src_devicep->target_id,
4597 (char *) dst + dst_offset,
4598 (char *) src + src_offset, length);
4599 gomp_mutex_unlock (&src_devicep->lock);
4600 return (ret ? 0 : EINVAL);
4601 }
4602 return EINVAL;
4603 }
4604
4605 int
4606 omp_target_memcpy (void *dst, const void *src, size_t length, size_t dst_offset,
4607 size_t src_offset, int dst_device_num, int src_device_num)
4608 {
4609 struct gomp_device_descr *dst_devicep = NULL, *src_devicep = NULL;
4610 int ret = omp_target_memcpy_check (dst_device_num, src_device_num,
4611 &dst_devicep, &src_devicep);
4612
4613 if (ret)
4614 return ret;
4615
4616 ret = omp_target_memcpy_copy (dst, src, length, dst_offset, src_offset,
4617 dst_devicep, src_devicep);
4618
4619 return ret;
4620 }
4621
4622 typedef struct
4623 {
4624 void *dst;
4625 const void *src;
4626 size_t length;
4627 size_t dst_offset;
4628 size_t src_offset;
4629 struct gomp_device_descr *dst_devicep;
4630 struct gomp_device_descr *src_devicep;
4631 } omp_target_memcpy_data;
4632
4633 static void
4634 omp_target_memcpy_async_helper (void *args)
4635 {
4636 omp_target_memcpy_data *a = args;
4637 if (omp_target_memcpy_copy (a->dst, a->src, a->length, a->dst_offset,
4638 a->src_offset, a->dst_devicep, a->src_devicep))
4639 gomp_fatal ("omp_target_memcpy failed");
4640 }
4641
4642 int
4643 omp_target_memcpy_async (void *dst, const void *src, size_t length,
4644 size_t dst_offset, size_t src_offset,
4645 int dst_device_num, int src_device_num,
4646 int depobj_count, omp_depend_t *depobj_list)
4647 {
4648 struct gomp_device_descr *dst_devicep = NULL, *src_devicep = NULL;
4649 unsigned int flags = 0;
4650 void *depend[depobj_count + 5];
4651 int i;
4652 int check = omp_target_memcpy_check (dst_device_num, src_device_num,
4653 &dst_devicep, &src_devicep);
4654
4655 omp_target_memcpy_data s = {
4656 .dst = dst,
4657 .src = src,
4658 .length = length,
4659 .dst_offset = dst_offset,
4660 .src_offset = src_offset,
4661 .dst_devicep = dst_devicep,
4662 .src_devicep = src_devicep
4663 };
4664
4665 if (check)
4666 return check;
4667
4668 if (depobj_count > 0 && depobj_list != NULL)
4669 {
4670 flags |= GOMP_TASK_FLAG_DEPEND;
4671 depend[0] = 0;
4672 depend[1] = (void *) (uintptr_t) depobj_count;
4673 depend[2] = depend[3] = depend[4] = 0;
4674 for (i = 0; i < depobj_count; ++i)
4675 depend[i + 5] = &depobj_list[i];
4676 }
4677
4678 GOMP_task (omp_target_memcpy_async_helper, &s, NULL, sizeof (s),
4679 __alignof__ (s), true, flags, depend, 0, NULL);
4680
4681 return 0;
4682 }
4683
4684 static int
4685 omp_target_memcpy_rect_worker (void *dst, const void *src, size_t element_size,
4686 int num_dims, const size_t *volume,
4687 const size_t *dst_offsets,
4688 const size_t *src_offsets,
4689 const size_t *dst_dimensions,
4690 const size_t *src_dimensions,
4691 struct gomp_device_descr *dst_devicep,
4692 struct gomp_device_descr *src_devicep,
4693 size_t *tmp_size, void **tmp)
4694 {
4695 size_t dst_slice = element_size;
4696 size_t src_slice = element_size;
4697 size_t j, dst_off, src_off, length;
4698 int i, ret;
4699
4700 if (num_dims == 1)
4701 {
4702 if (__builtin_mul_overflow (element_size, volume[0], &length)
4703 || __builtin_mul_overflow (element_size, dst_offsets[0], &dst_off)
4704 || __builtin_mul_overflow (element_size, src_offsets[0], &src_off))
4705 return EINVAL;
4706 if (dst_devicep == NULL && src_devicep == NULL)
4707 {
4708 memcpy ((char *) dst + dst_off, (const char *) src + src_off,
4709 length);
4710 ret = 1;
4711 }
4712 else if (src_devicep == NULL)
4713 ret = dst_devicep->host2dev_func (dst_devicep->target_id,
4714 (char *) dst + dst_off,
4715 (const char *) src + src_off,
4716 length);
4717 else if (dst_devicep == NULL)
4718 ret = src_devicep->dev2host_func (src_devicep->target_id,
4719 (char *) dst + dst_off,
4720 (const char *) src + src_off,
4721 length);
4722 else if (src_devicep == dst_devicep)
4723 ret = src_devicep->dev2dev_func (src_devicep->target_id,
4724 (char *) dst + dst_off,
4725 (const char *) src + src_off,
4726 length);
4727 else
4728 {
4729 if (*tmp_size == 0)
4730 {
4731 *tmp_size = length;
4732 *tmp = malloc (length);
4733 if (*tmp == NULL)
4734 return ENOMEM;
4735 }
4736 else if (*tmp_size < length)
4737 {
4738 *tmp_size = length;
4739 free (*tmp);
4740 *tmp = malloc (length);
4741 if (*tmp == NULL)
4742 return ENOMEM;
4743 }
4744 ret = src_devicep->dev2host_func (src_devicep->target_id, *tmp,
4745 (const char *) src + src_off,
4746 length);
4747 if (ret == 1)
4748 ret = dst_devicep->host2dev_func (dst_devicep->target_id,
4749 (char *) dst + dst_off, *tmp,
4750 length);
4751 }
4752 return ret ? 0 : EINVAL;
4753 }
4754
4755 /* host->device, device->host and intra device. */
4756 if (num_dims == 2
4757 && ((src_devicep
4758 && src_devicep == dst_devicep
4759 && src_devicep->memcpy2d_func)
4760 || (!src_devicep != !dst_devicep
4761 && ((src_devicep && src_devicep->memcpy2d_func)
4762 || (dst_devicep && dst_devicep->memcpy2d_func)))))
4763 {
4764 size_t vol_sz1, dst_sz1, src_sz1, dst_off_sz1, src_off_sz1;
4765 int dst_id = dst_devicep ? dst_devicep->target_id : -1;
4766 int src_id = src_devicep ? src_devicep->target_id : -1;
4767 struct gomp_device_descr *devp = dst_devicep ? dst_devicep : src_devicep;
4768
4769 if (__builtin_mul_overflow (volume[1], element_size, &vol_sz1)
4770 || __builtin_mul_overflow (dst_dimensions[1], element_size, &dst_sz1)
4771 || __builtin_mul_overflow (src_dimensions[1], element_size, &src_sz1)
4772 || __builtin_mul_overflow (dst_offsets[1], element_size, &dst_off_sz1)
4773 || __builtin_mul_overflow (src_offsets[1], element_size,
4774 &src_off_sz1))
4775 return EINVAL;
4776 ret = devp->memcpy2d_func (dst_id, src_id, vol_sz1, volume[0],
4777 dst, dst_off_sz1, dst_offsets[0], dst_sz1,
4778 src, src_off_sz1, src_offsets[0], src_sz1);
4779 if (ret != -1)
4780 return ret ? 0 : EINVAL;
4781 }
4782 else if (num_dims == 3
4783 && ((src_devicep
4784 && src_devicep == dst_devicep
4785 && src_devicep->memcpy3d_func)
4786 || (!src_devicep != !dst_devicep
4787 && ((src_devicep && src_devicep->memcpy3d_func)
4788 || (dst_devicep && dst_devicep->memcpy3d_func)))))
4789 {
4790 size_t vol_sz2, dst_sz2, src_sz2, dst_off_sz2, src_off_sz2;
4791 int dst_id = dst_devicep ? dst_devicep->target_id : -1;
4792 int src_id = src_devicep ? src_devicep->target_id : -1;
4793 struct gomp_device_descr *devp = dst_devicep ? dst_devicep : src_devicep;
4794
4795 if (__builtin_mul_overflow (volume[2], element_size, &vol_sz2)
4796 || __builtin_mul_overflow (dst_dimensions[2], element_size, &dst_sz2)
4797 || __builtin_mul_overflow (src_dimensions[2], element_size, &src_sz2)
4798 || __builtin_mul_overflow (dst_offsets[2], element_size, &dst_off_sz2)
4799 || __builtin_mul_overflow (src_offsets[2], element_size,
4800 &src_off_sz2))
4801 return EINVAL;
4802 ret = devp->memcpy3d_func (dst_id, src_id, vol_sz2, volume[1], volume[0],
4803 dst, dst_off_sz2, dst_offsets[1],
4804 dst_offsets[0], dst_sz2, dst_dimensions[1],
4805 src, src_off_sz2, src_offsets[1],
4806 src_offsets[0], src_sz2, src_dimensions[1]);
4807 if (ret != -1)
4808 return ret ? 0 : EINVAL;
4809 }
4810
4811 for (i = 1; i < num_dims; i++)
4812 if (__builtin_mul_overflow (dst_slice, dst_dimensions[i], &dst_slice)
4813 || __builtin_mul_overflow (src_slice, src_dimensions[i], &src_slice))
4814 return EINVAL;
4815 if (__builtin_mul_overflow (dst_slice, dst_offsets[0], &dst_off)
4816 || __builtin_mul_overflow (src_slice, src_offsets[0], &src_off))
4817 return EINVAL;
4818 for (j = 0; j < volume[0]; j++)
4819 {
4820 ret = omp_target_memcpy_rect_worker ((char *) dst + dst_off,
4821 (const char *) src + src_off,
4822 element_size, num_dims - 1,
4823 volume + 1, dst_offsets + 1,
4824 src_offsets + 1, dst_dimensions + 1,
4825 src_dimensions + 1, dst_devicep,
4826 src_devicep, tmp_size, tmp);
4827 if (ret)
4828 return ret;
4829 dst_off += dst_slice;
4830 src_off += src_slice;
4831 }
4832 return 0;
4833 }
4834
4835 static int
4836 omp_target_memcpy_rect_check (void *dst, const void *src, int dst_device_num,
4837 int src_device_num,
4838 struct gomp_device_descr **dst_devicep,
4839 struct gomp_device_descr **src_devicep)
4840 {
4841 if (!dst && !src)
4842 return INT_MAX;
4843
4844 int ret = omp_target_memcpy_check (dst_device_num, src_device_num,
4845 dst_devicep, src_devicep);
4846 if (ret)
4847 return ret;
4848
4849 return 0;
4850 }
4851
4852 static int
4853 omp_target_memcpy_rect_copy (void *dst, const void *src,
4854 size_t element_size, int num_dims,
4855 const size_t *volume, const size_t *dst_offsets,
4856 const size_t *src_offsets,
4857 const size_t *dst_dimensions,
4858 const size_t *src_dimensions,
4859 struct gomp_device_descr *dst_devicep,
4860 struct gomp_device_descr *src_devicep)
4861 {
4862 size_t tmp_size = 0;
4863 void *tmp = NULL;
4864 bool lock_src;
4865 bool lock_dst;
4866
4867 lock_src = src_devicep != NULL;
4868 lock_dst = dst_devicep != NULL && src_devicep != dst_devicep;
4869 if (lock_src)
4870 gomp_mutex_lock (&src_devicep->lock);
4871 if (lock_dst)
4872 gomp_mutex_lock (&dst_devicep->lock);
4873 int ret = omp_target_memcpy_rect_worker (dst, src, element_size, num_dims,
4874 volume, dst_offsets, src_offsets,
4875 dst_dimensions, src_dimensions,
4876 dst_devicep, src_devicep,
4877 &tmp_size, &tmp);
4878 if (lock_src)
4879 gomp_mutex_unlock (&src_devicep->lock);
4880 if (lock_dst)
4881 gomp_mutex_unlock (&dst_devicep->lock);
4882 if (tmp)
4883 free (tmp);
4884
4885 return ret;
4886 }
4887
4888 int
4889 omp_target_memcpy_rect (void *dst, const void *src, size_t element_size,
4890 int num_dims, const size_t *volume,
4891 const size_t *dst_offsets,
4892 const size_t *src_offsets,
4893 const size_t *dst_dimensions,
4894 const size_t *src_dimensions,
4895 int dst_device_num, int src_device_num)
4896 {
4897 struct gomp_device_descr *dst_devicep = NULL, *src_devicep = NULL;
4898
4899 int check = omp_target_memcpy_rect_check (dst, src, dst_device_num,
4900 src_device_num, &dst_devicep,
4901 &src_devicep);
4902
4903 if (check)
4904 return check;
4905
4906 int ret = omp_target_memcpy_rect_copy (dst, src, element_size, num_dims,
4907 volume, dst_offsets, src_offsets,
4908 dst_dimensions, src_dimensions,
4909 dst_devicep, src_devicep);
4910
4911 return ret;
4912 }
4913
4914 typedef struct
4915 {
4916 void *dst;
4917 const void *src;
4918 size_t element_size;
4919 const size_t *volume;
4920 const size_t *dst_offsets;
4921 const size_t *src_offsets;
4922 const size_t *dst_dimensions;
4923 const size_t *src_dimensions;
4924 struct gomp_device_descr *dst_devicep;
4925 struct gomp_device_descr *src_devicep;
4926 int num_dims;
4927 } omp_target_memcpy_rect_data;
4928
4929 static void
4930 omp_target_memcpy_rect_async_helper (void *args)
4931 {
4932 omp_target_memcpy_rect_data *a = args;
4933 int ret = omp_target_memcpy_rect_copy (a->dst, a->src, a->element_size,
4934 a->num_dims, a->volume, a->dst_offsets,
4935 a->src_offsets, a->dst_dimensions,
4936 a->src_dimensions, a->dst_devicep,
4937 a->src_devicep);
4938 if (ret)
4939 gomp_fatal ("omp_target_memcpy_rect failed");
4940 }
4941
4942 int
4943 omp_target_memcpy_rect_async (void *dst, const void *src, size_t element_size,
4944 int num_dims, const size_t *volume,
4945 const size_t *dst_offsets,
4946 const size_t *src_offsets,
4947 const size_t *dst_dimensions,
4948 const size_t *src_dimensions,
4949 int dst_device_num, int src_device_num,
4950 int depobj_count, omp_depend_t *depobj_list)
4951 {
4952 struct gomp_device_descr *dst_devicep = NULL, *src_devicep = NULL;
4953 unsigned flags = 0;
4954 int check = omp_target_memcpy_rect_check (dst, src, dst_device_num,
4955 src_device_num, &dst_devicep,
4956 &src_devicep);
4957 void *depend[depobj_count + 5];
4958 int i;
4959
4960 omp_target_memcpy_rect_data s = {
4961 .dst = dst,
4962 .src = src,
4963 .element_size = element_size,
4964 .num_dims = num_dims,
4965 .volume = volume,
4966 .dst_offsets = dst_offsets,
4967 .src_offsets = src_offsets,
4968 .dst_dimensions = dst_dimensions,
4969 .src_dimensions = src_dimensions,
4970 .dst_devicep = dst_devicep,
4971 .src_devicep = src_devicep
4972 };
4973
4974 if (check)
4975 return check;
4976
4977 if (depobj_count > 0 && depobj_list != NULL)
4978 {
4979 flags |= GOMP_TASK_FLAG_DEPEND;
4980 depend[0] = 0;
4981 depend[1] = (void *) (uintptr_t) depobj_count;
4982 depend[2] = depend[3] = depend[4] = 0;
4983 for (i = 0; i < depobj_count; ++i)
4984 depend[i + 5] = &depobj_list[i];
4985 }
4986
4987 GOMP_task (omp_target_memcpy_rect_async_helper, &s, NULL, sizeof (s),
4988 __alignof__ (s), true, flags, depend, 0, NULL);
4989
4990 return 0;
4991 }
4992
4993 int
4994 omp_target_associate_ptr (const void *host_ptr, const void *device_ptr,
4995 size_t size, size_t device_offset, int device_num)
4996 {
4997 if (device_num == omp_initial_device
4998 || device_num == gomp_get_num_devices ())
4999 return EINVAL;
5000
5001 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5002 if (devicep == NULL)
5003 return EINVAL;
5004
5005 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
5006 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
5007 return EINVAL;
5008
5009 gomp_mutex_lock (&devicep->lock);
5010
5011 struct splay_tree_s *mem_map = &devicep->mem_map;
5012 struct splay_tree_key_s cur_node;
5013 int ret = EINVAL;
5014
5015 cur_node.host_start = (uintptr_t) host_ptr;
5016 cur_node.host_end = cur_node.host_start + size;
5017 splay_tree_key n = gomp_map_lookup (mem_map, &cur_node);
5018 if (n)
5019 {
5020 if (n->tgt->tgt_start + n->tgt_offset
5021 == (uintptr_t) device_ptr + device_offset
5022 && n->host_start <= cur_node.host_start
5023 && n->host_end >= cur_node.host_end)
5024 ret = 0;
5025 }
5026 else
5027 {
5028 struct target_mem_desc *tgt = gomp_malloc (sizeof (*tgt));
5029 tgt->array = gomp_malloc (sizeof (*tgt->array));
5030 tgt->refcount = 1;
5031 tgt->tgt_start = 0;
5032 tgt->tgt_end = 0;
5033 tgt->to_free = NULL;
5034 tgt->prev = NULL;
5035 tgt->list_count = 0;
5036 tgt->device_descr = devicep;
5037 splay_tree_node array = tgt->array;
5038 splay_tree_key k = &array->key;
5039 k->host_start = cur_node.host_start;
5040 k->host_end = cur_node.host_end;
5041 k->tgt = tgt;
5042 k->tgt_offset = (uintptr_t) device_ptr + device_offset;
5043 k->refcount = REFCOUNT_INFINITY;
5044 k->dynamic_refcount = 0;
5045 k->aux = NULL;
5046 array->left = NULL;
5047 array->right = NULL;
5048 splay_tree_insert (&devicep->mem_map, array);
5049 ret = 0;
5050 }
5051 gomp_mutex_unlock (&devicep->lock);
5052 return ret;
5053 }
5054
5055 int
5056 omp_target_disassociate_ptr (const void *ptr, int device_num)
5057 {
5058 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5059 if (devicep == NULL)
5060 return EINVAL;
5061
5062 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400))
5063 return EINVAL;
5064
5065 gomp_mutex_lock (&devicep->lock);
5066
5067 struct splay_tree_s *mem_map = &devicep->mem_map;
5068 struct splay_tree_key_s cur_node;
5069 int ret = EINVAL;
5070
5071 cur_node.host_start = (uintptr_t) ptr;
5072 cur_node.host_end = cur_node.host_start;
5073 splay_tree_key n = gomp_map_lookup (mem_map, &cur_node);
5074 if (n
5075 && n->host_start == cur_node.host_start
5076 && n->refcount == REFCOUNT_INFINITY
5077 && n->tgt->tgt_start == 0
5078 && n->tgt->to_free == NULL
5079 && n->tgt->refcount == 1
5080 && n->tgt->list_count == 0)
5081 {
5082 splay_tree_remove (&devicep->mem_map, n);
5083 gomp_unmap_tgt (n->tgt);
5084 ret = 0;
5085 }
5086
5087 gomp_mutex_unlock (&devicep->lock);
5088 return ret;
5089 }
5090
5091 void *
5092 omp_get_mapped_ptr (const void *ptr, int device_num)
5093 {
5094 if (device_num == omp_initial_device
5095 || device_num == omp_get_initial_device ())
5096 return (void *) ptr;
5097
5098 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5099 if (devicep == NULL)
5100 return NULL;
5101
5102 if (!(devicep->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
5103 || devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM)
5104 return (void *) ptr;
5105
5106 gomp_mutex_lock (&devicep->lock);
5107
5108 struct splay_tree_s *mem_map = &devicep->mem_map;
5109 struct splay_tree_key_s cur_node;
5110 void *ret = NULL;
5111
5112 cur_node.host_start = (uintptr_t) ptr;
5113 cur_node.host_end = cur_node.host_start;
5114 splay_tree_key n = gomp_map_0len_lookup (mem_map, &cur_node);
5115
5116 if (n)
5117 {
5118 uintptr_t offset = cur_node.host_start - n->host_start;
5119 ret = (void *) (n->tgt->tgt_start + n->tgt_offset + offset);
5120 }
5121
5122 gomp_mutex_unlock (&devicep->lock);
5123
5124 return ret;
5125 }
5126
5127 int
5128 omp_target_is_accessible (const void *ptr, size_t size, int device_num)
5129 {
5130 if (device_num == omp_initial_device
5131 || device_num == gomp_get_num_devices ())
5132 return true;
5133
5134 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5135 if (devicep == NULL)
5136 return false;
5137
5138 /* TODO: Unified shared memory must be handled when available. */
5139
5140 return devicep->capabilities & GOMP_OFFLOAD_CAP_SHARED_MEM;
5141 }
5142
5143 int
5144 omp_pause_resource (omp_pause_resource_t kind, int device_num)
5145 {
5146 (void) kind;
5147 if (device_num == omp_initial_device
5148 || device_num == gomp_get_num_devices ())
5149 return gomp_pause_host ();
5150
5151 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5152 if (devicep == NULL)
5153 return -1;
5154
5155 /* Do nothing for target devices for now. */
5156 return 0;
5157 }
5158
5159 int
5160 omp_pause_resource_all (omp_pause_resource_t kind)
5161 {
5162 (void) kind;
5163 if (gomp_pause_host ())
5164 return -1;
5165 /* Do nothing for target devices for now. */
5166 return 0;
5167 }
5168
5169 ialias (omp_pause_resource)
5170 ialias (omp_pause_resource_all)
5171
5172 int
5173 omp_get_num_interop_properties (const omp_interop_t interop
5174 __attribute__ ((unused)))
5175 {
5176 /* Zero implementation defined. In total:
5177 omp_get_num_interop_properties () - omp_ipr_first. */
5178 return 0;
5179 }
5180
5181 omp_intptr_t
5182 omp_get_interop_int (const omp_interop_t interop,
5183 omp_interop_property_t property_id,
5184 omp_interop_rc_t *ret_code)
5185 {
5186 struct interop_obj_t *obj = (struct interop_obj_t *) interop;
5187 struct gomp_device_descr *devicep;
5188
5189 if (property_id < omp_ipr_first || property_id >= 0)
5190 {
5191 if (ret_code)
5192 *ret_code = omp_irc_out_of_range;
5193 return 0;
5194 }
5195 if (obj == NULL
5196 || (devicep = resolve_device (obj->device_num, false)) == NULL
5197 || devicep->get_interop_int_func == NULL)
5198 {
5199 if (ret_code)
5200 *ret_code = omp_irc_empty; /* Assume omp_interop_none. */
5201 return 0;
5202 }
5203 return devicep->get_interop_int_func (obj, property_id, ret_code);
5204 }
5205
5206 void *
5207 omp_get_interop_ptr (const omp_interop_t interop,
5208 omp_interop_property_t property_id,
5209 omp_interop_rc_t *ret_code)
5210 {
5211 struct interop_obj_t *obj = (struct interop_obj_t *) interop;
5212 struct gomp_device_descr *devicep;
5213
5214 if (property_id < omp_ipr_first || property_id >= 0)
5215 {
5216 if (ret_code)
5217 *ret_code = omp_irc_out_of_range;
5218 return 0;
5219 }
5220 if (obj == NULL
5221 || (devicep = resolve_device (obj->device_num, false)) == NULL
5222 || devicep->get_interop_int_func == NULL)
5223 {
5224 if (ret_code)
5225 *ret_code = omp_irc_empty; /* Assume omp_interop_none. */
5226 return 0;
5227 }
5228 return devicep->get_interop_ptr_func (obj, property_id, ret_code);
5229 }
5230
5231 const char *
5232 omp_get_interop_str (const omp_interop_t interop,
5233 omp_interop_property_t property_id,
5234 omp_interop_rc_t *ret_code)
5235 {
5236 struct interop_obj_t *obj = (struct interop_obj_t *) interop;
5237 struct gomp_device_descr *devicep;
5238
5239 if (property_id < omp_ipr_first || property_id >= 0)
5240 {
5241 if (ret_code)
5242 *ret_code = omp_irc_out_of_range;
5243 return 0;
5244 }
5245 if (obj == NULL
5246 || (devicep = resolve_device (obj->device_num, false)) == NULL
5247 || devicep->get_interop_int_func == NULL)
5248 {
5249 if (ret_code)
5250 *ret_code = omp_irc_empty; /* Assume omp_interop_none. */
5251 return 0;
5252 }
5253 return devicep->get_interop_str_func (obj, property_id, ret_code);
5254 }
5255
5256 const char *
5257 omp_get_interop_name (const omp_interop_t interop __attribute__ ((unused)),
5258 omp_interop_property_t property_id)
5259 {
5260 static const char *prop_string[0 - omp_ipr_first]
5261 = {"fr_id", "fr_name", "vendor", "vendor_name", "device_num", "platform",
5262 "device", "device_context", "targetsync"};
5263 if (property_id < omp_ipr_first || property_id >= 0)
5264 return NULL;
5265 return prop_string[omp_ipr_fr_id - property_id];
5266 }
5267
5268 const char *
5269 omp_get_interop_type_desc (const omp_interop_t interop,
5270 omp_interop_property_t property_id)
5271 {
5272 static const char *desc[omp_ipr_fr_id - omp_ipr_device_num + 1]
5273 = {"omp_interop_t", /* fr_id */
5274 "const char *", /* fr_name */
5275 "int", /* vendor */
5276 "const char *", /* vendor_name */
5277 "int"}; /* device_num */
5278
5279 struct interop_obj_t *obj = (struct interop_obj_t *) interop;
5280 struct gomp_device_descr *devicep;
5281
5282 if (property_id > omp_ipr_fr_id || property_id < omp_ipr_first)
5283 return NULL;
5284 if (obj == NULL
5285 || (devicep = resolve_device (obj->device_num, false)) == NULL
5286 || devicep->get_interop_int_func == NULL)
5287 return NULL;
5288 if (property_id >= omp_ipr_device_num)
5289 return desc[omp_ipr_fr_id - property_id];
5290 return devicep->get_interop_type_desc_func (obj, property_id);
5291 }
5292
5293 const char *
5294 omp_get_interop_rc_desc (const omp_interop_t interop __attribute__ ((unused)),
5295 omp_interop_rc_t ret_code)
5296 {
5297 static const char *rc_strings[omp_irc_no_value - omp_irc_other]
5298 = {"no meaningful value available",
5299 "successful",
5300 "provided interoperability object is equal to omp_interop_none",
5301 "property ID is out of range",
5302 "property type is integer; use omp_get_interop_int",
5303 "property type is pointer; use omp_get_interop_ptr",
5304 "property type is string; use omp_get_interop_str"};
5305
5306 /* omp_irc_other is returned by device-side omp_get_interop_{int,ptr,str};
5307 on the host it is not used, hence, return NULL here. */
5308 if (ret_code > omp_irc_no_value || ret_code <= omp_irc_other)
5309 return NULL;
5310 return rc_strings[omp_irc_no_value - ret_code];
5311 }
5312
5313 ialias (omp_get_num_interop_properties)
5314 ialias (omp_get_interop_int)
5315 ialias (omp_get_interop_ptr)
5316 ialias (omp_get_interop_str)
5317 ialias (omp_get_interop_name)
5318 ialias (omp_get_interop_type_desc)
5319 ialias (omp_get_interop_rc_desc)
5320
5321 struct interop_data_t
5322 {
5323 int device_num, n_init, n_use, n_destroy;
5324 struct interop_obj_t ***init;
5325 struct interop_obj_t **use;
5326 struct interop_obj_t ***destroy;
5327 const int *target_targetsync;
5328 const char **prefer_type;
5329 };
5330
5331 static void
5332 gomp_interop_internal (void *data)
5333 {
5334 struct interop_data_t *args = (struct interop_data_t *) data;
5335 struct gomp_device_descr *devicep;
5336
5337 /* Destroy objects to free resources. */
5338 for (int i = 0; i < args->n_destroy; i++)
5339 {
5340 struct interop_obj_t **obj = args->destroy[i];
5341 if (*obj == NULL /* omp_interop_none */)
5342 continue;
5343 devicep = resolve_device ((*obj)->device_num, false);
5344 if (devicep != NULL && devicep->interop_func)
5345 devicep->interop_func (*obj, devicep->target_id,
5346 gomp_interop_flag_destroy, false, NULL);
5347 free (*obj);
5348 *obj = NULL;
5349 }
5350
5351 /* Init streams next to give 'use' more time for completion. */
5352 if (args->n_init)
5353 {
5354 devicep = resolve_device (args->device_num, false);
5355 for (int i = 0; i < args->n_init; i++)
5356 {
5357 struct interop_obj_t **obj = args->init[i];
5358 bool targetsync
5359 = (args->target_targetsync[i] & GOMP_INTEROP_TARGETSYNC);
5360 const char *prefer_type
5361 = (args->prefer_type ? args->prefer_type[i] : NULL);
5362 if (devicep == NULL || !devicep->interop_func)
5363 {
5364 *obj = NULL;
5365 continue;
5366 }
5367 *obj =
5368 (struct interop_obj_t *) calloc (1, sizeof (struct interop_obj_t));
5369 (*obj)->device_num = devicep->target_id;
5370 devicep->interop_func (*obj, devicep->target_id,
5371 gomp_interop_flag_init, targetsync,
5372 prefer_type);
5373 }
5374 }
5375
5376 for (int i = 0; i < args->n_use; i++)
5377 {
5378 struct interop_obj_t *obj = args->use[i];
5379 if (obj == NULL)
5380 continue;
5381 devicep = resolve_device (obj->device_num, false);
5382 if (devicep != NULL && devicep->interop_func)
5383 devicep->interop_func (obj, devicep->target_id,
5384 gomp_interop_flag_use, false, NULL);
5385 }
5386 }
5387
5388 /* Process the OpenMP interop directive. 'init' and 'destroy' take an array
5389 of 'omp_interop_t *', 'use' an array of 'omp_interop_t', where
5390 'omp_interop_t' is internally 'struct interop_obj_t *';
5391 'flags' is used for the 'nowait' clause. */
5392
5393 void
5394 GOMP_interop (int device_num, int n_init, struct interop_obj_t ***init,
5395 const int *target_targetsync, const char **prefer_type, int n_use,
5396 struct interop_obj_t **use, int n_destroy,
5397 struct interop_obj_t ***destroy, unsigned int flags,
5398 void **depend)
5399 {
5400 struct interop_data_t args;
5401 args.device_num = device_num;
5402 args.n_init = n_init;
5403 args.n_use = n_use;
5404 args.n_destroy = n_destroy;
5405 args.init = init;
5406 args.target_targetsync = target_targetsync;
5407 args.prefer_type = prefer_type;
5408 args.use = use;
5409 args.destroy = destroy;
5410
5411 /* No need to create a task for 'init' as that should be fast. */
5412 bool use_task = false;
5413 if (flags & GOMP_INTEROP_FLAG_NOWAIT)
5414 {
5415 for (int i = 0; i < n_use && !use_task; i++)
5416 if (args.use[i])
5417 use_task |= args.use[i]->stream != NULL;
5418 for (int i = 0; i < n_destroy && !use_task; i++)
5419 if (*args.destroy[i])
5420 use_task |= (*args.destroy[i])->stream != NULL;
5421 }
5422
5423 if (use_task)
5424 GOMP_task (gomp_interop_internal, &args, NULL, sizeof (args),
5425 __alignof__ (args), true, depend ? GOMP_TASK_FLAG_DEPEND : 0,
5426 depend, 0, NULL);
5427 else
5428 {
5429 gomp_interop_internal (&args);
5430 if (depend)
5431 GOMP_taskwait_depend (depend);
5432 }
5433 }
5434
5435 static const char *
5436 gomp_get_uid_for_device (struct gomp_device_descr *devicep, int device_num)
5437 {
5438 if (devicep->uid)
5439 return devicep->uid;
5440
5441 if (devicep->get_uid_func)
5442 devicep->uid = devicep->get_uid_func (devicep->target_id);
5443 if (!devicep->uid)
5444 {
5445 size_t ln = strlen (STR_OMP_DEV_PREFIX) + 10 + 1;
5446 char *uid;
5447 uid = gomp_malloc (ln);
5448 snprintf (uid, ln, "%s%d", STR_OMP_DEV_PREFIX, device_num);
5449 devicep->uid = uid;
5450 }
5451 return devicep->uid;
5452 }
5453
5454 const char *
5455 omp_get_uid_from_device (int device_num)
5456 {
5457 if (device_num < omp_initial_device || device_num > gomp_get_num_devices ())
5458 return NULL;
5459
5460 if (device_num == omp_initial_device || device_num == gomp_get_num_devices ())
5461 return str_omp_initial_device;
5462
5463 struct gomp_device_descr *devicep = resolve_device (device_num, false);
5464 if (devicep == NULL)
5465 return NULL;
5466 return gomp_get_uid_for_device (devicep, device_num);
5467 }
5468
5469 int
5470 omp_get_device_from_uid (const char *uid)
5471 {
5472 if (uid == NULL)
5473 return omp_invalid_device;
5474 if (strcmp (uid, str_omp_initial_device) == 0)
5475 return omp_initial_device;
5476 for (int dev = 0; dev < gomp_get_num_devices (); dev++)
5477 {
5478 struct gomp_device_descr *devicep = resolve_device (dev, false);
5479 if (strcmp (uid, gomp_get_uid_for_device (devicep, dev)) == 0)
5480 return dev;
5481 }
5482 return omp_invalid_device;
5483 }
5484
5485 ialias (omp_get_uid_from_device)
5486 ialias (omp_get_device_from_uid)
5487
5488 #ifdef PLUGIN_SUPPORT
5489
5490 /* This function tries to load a plugin for DEVICE. Name of plugin is passed
5491 in PLUGIN_NAME.
5492 The handles of the found functions are stored in the corresponding fields
5493 of DEVICE. The function returns TRUE on success and FALSE otherwise. */
5494
5495 static bool
5496 gomp_load_plugin_for_device (struct gomp_device_descr *device,
5497 const char *plugin_name)
5498 {
5499 const char *err = NULL, *last_missing = NULL;
5500
5501 void *plugin_handle = dlopen (plugin_name, RTLD_LAZY);
5502 if (!plugin_handle)
5503 #if OFFLOAD_DEFAULTED
5504 return 0;
5505 #else
5506 goto dl_fail;
5507 #endif
5508
5509 /* Check if all required functions are available in the plugin and store
5510 their handlers. None of the symbols can legitimately be NULL,
5511 so we don't need to check dlerror all the time. */
5512 #define DLSYM(f) \
5513 if (!(device->f##_func = dlsym (plugin_handle, "GOMP_OFFLOAD_" #f))) \
5514 goto dl_fail
5515 /* Similar, but missing functions are not an error. Return false if
5516 failed, true otherwise. */
5517 #define DLSYM_OPT(f, n) \
5518 ((device->f##_func = dlsym (plugin_handle, "GOMP_OFFLOAD_" #n)) \
5519 || (last_missing = #n, 0))
5520
5521 DLSYM (version);
5522 if (device->version_func () != GOMP_VERSION)
5523 {
5524 err = "plugin version mismatch";
5525 goto fail;
5526 }
5527
5528 DLSYM (get_name);
5529 DLSYM_OPT (get_uid, get_uid);
5530 DLSYM (get_caps);
5531 DLSYM (get_type);
5532 DLSYM (get_num_devices);
5533 DLSYM (init_device);
5534 DLSYM (fini_device);
5535 DLSYM (load_image);
5536 DLSYM (unload_image);
5537 DLSYM (alloc);
5538 DLSYM (free);
5539 DLSYM (dev2host);
5540 DLSYM (host2dev);
5541 DLSYM_OPT (memcpy2d, memcpy2d);
5542 DLSYM_OPT (memcpy3d, memcpy3d);
5543 if (DLSYM_OPT (interop, interop))
5544 {
5545 DLSYM (get_interop_int);
5546 DLSYM (get_interop_ptr);
5547 DLSYM (get_interop_str);
5548 DLSYM (get_interop_type_desc);
5549 }
5550
5551 device->capabilities = device->get_caps_func ();
5552 if (device->capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
5553 {
5554 DLSYM (run);
5555 DLSYM_OPT (async_run, async_run);
5556 DLSYM_OPT (can_run, can_run);
5557 DLSYM (dev2dev);
5558 }
5559 if (device->capabilities & GOMP_OFFLOAD_CAP_OPENACC_200)
5560 {
5561 if (!DLSYM_OPT (openacc.exec, openacc_exec)
5562 || !DLSYM_OPT (openacc.create_thread_data,
5563 openacc_create_thread_data)
5564 || !DLSYM_OPT (openacc.destroy_thread_data,
5565 openacc_destroy_thread_data)
5566 || !DLSYM_OPT (openacc.async.construct, openacc_async_construct)
5567 || !DLSYM_OPT (openacc.async.destruct, openacc_async_destruct)
5568 || !DLSYM_OPT (openacc.async.test, openacc_async_test)
5569 || !DLSYM_OPT (openacc.async.synchronize, openacc_async_synchronize)
5570 || !DLSYM_OPT (openacc.async.serialize, openacc_async_serialize)
5571 || !DLSYM_OPT (openacc.async.queue_callback,
5572 openacc_async_queue_callback)
5573 || !DLSYM_OPT (openacc.async.exec, openacc_async_exec)
5574 || !DLSYM_OPT (openacc.async.dev2host, openacc_async_dev2host)
5575 || !DLSYM_OPT (openacc.async.host2dev, openacc_async_host2dev)
5576 || !DLSYM_OPT (openacc.get_property, openacc_get_property))
5577 {
5578 /* Require all the OpenACC handlers if we have
5579 GOMP_OFFLOAD_CAP_OPENACC_200. */
5580 err = "plugin missing OpenACC handler function";
5581 goto fail;
5582 }
5583
5584 unsigned cuda = 0;
5585 cuda += DLSYM_OPT (openacc.cuda.get_current_device,
5586 openacc_cuda_get_current_device);
5587 cuda += DLSYM_OPT (openacc.cuda.get_current_context,
5588 openacc_cuda_get_current_context);
5589 cuda += DLSYM_OPT (openacc.cuda.get_stream, openacc_cuda_get_stream);
5590 cuda += DLSYM_OPT (openacc.cuda.set_stream, openacc_cuda_set_stream);
5591 if (cuda && cuda != 4)
5592 {
5593 /* Make sure all the CUDA functions are there if any of them are. */
5594 err = "plugin missing OpenACC CUDA handler function";
5595 goto fail;
5596 }
5597 }
5598 #undef DLSYM
5599 #undef DLSYM_OPT
5600
5601 return 1;
5602
5603 dl_fail:
5604 err = dlerror ();
5605 fail:
5606 gomp_error ("while loading %s: %s", plugin_name, err);
5607 if (last_missing)
5608 gomp_error ("missing function was %s", last_missing);
5609 if (plugin_handle)
5610 dlclose (plugin_handle);
5611
5612 return 0;
5613 }
5614
5615 /* This function finalizes all initialized devices. */
5616
5617 static void
5618 gomp_target_fini (void)
5619 {
5620 int i;
5621 for (i = 0; i < num_devices; i++)
5622 {
5623 bool ret = true;
5624 struct gomp_device_descr *devicep = &devices[i];
5625 gomp_mutex_lock (&devicep->lock);
5626 if (devicep->state == GOMP_DEVICE_INITIALIZED)
5627 ret = gomp_fini_device (devicep);
5628 gomp_mutex_unlock (&devicep->lock);
5629 if (!ret)
5630 gomp_fatal ("device finalization failed");
5631 }
5632 }
5633
5634 /* This function initializes the runtime for offloading.
5635 It parses the list of offload plugins, and tries to load these.
5636 On return, the variables NUM_DEVICES and NUM_DEVICES_OPENMP
5637 will be set, and the array DEVICES initialized, containing descriptors for
5638 corresponding devices, first the GOMP_OFFLOAD_CAP_OPENMP_400 ones, follows
5639 by the others. */
5640
5641 static void
5642 gomp_target_init (void)
5643 {
5644 const char *prefix ="libgomp-plugin-";
5645 const char *suffix = SONAME_SUFFIX (1);
5646 const char *cur, *next;
5647 char *plugin_name;
5648 int i, new_num_devs;
5649 int num_devs = 0, num_devs_openmp;
5650 struct gomp_device_descr *devs = NULL;
5651
5652 if (gomp_target_offload_var == GOMP_TARGET_OFFLOAD_DISABLED)
5653 return;
5654
5655 cur = OFFLOAD_PLUGINS;
5656 if (*cur)
5657 do
5658 {
5659 struct gomp_device_descr current_device;
5660 size_t prefix_len, suffix_len, cur_len;
5661
5662 next = strchr (cur, ',');
5663
5664 prefix_len = strlen (prefix);
5665 cur_len = next ? next - cur : strlen (cur);
5666 suffix_len = strlen (suffix);
5667
5668 plugin_name = (char *) malloc (prefix_len + cur_len + suffix_len + 1);
5669 if (!plugin_name)
5670 {
5671 num_devs = 0;
5672 break;
5673 }
5674
5675 memcpy (plugin_name, prefix, prefix_len);
5676 memcpy (plugin_name + prefix_len, cur, cur_len);
5677 memcpy (plugin_name + prefix_len + cur_len, suffix, suffix_len + 1);
5678
5679 if (gomp_load_plugin_for_device (&current_device, plugin_name))
5680 {
5681 int omp_req = omp_requires_mask & ~GOMP_REQUIRES_TARGET_USED;
5682 new_num_devs = current_device.get_num_devices_func (omp_req);
5683 if (gomp_debug_var > 0 && new_num_devs < 0)
5684 {
5685 bool found = false;
5686 int type = current_device.get_type_func ();
5687 for (int img = 0; img < num_offload_images; img++)
5688 if (type == offload_images[img].type)
5689 found = true;
5690 if (found)
5691 {
5692 char buf[sizeof ("unified_address, unified_shared_memory, "
5693 "reverse_offload")];
5694 gomp_requires_to_name (buf, sizeof (buf), omp_req);
5695 char *name = (char *) malloc (cur_len + 1);
5696 memcpy (name, cur, cur_len);
5697 name[cur_len] = '\0';
5698 gomp_debug (1,
5699 "%s devices present but 'omp requires %s' "
5700 "cannot be fulfilled\n", name, buf);
5701 free (name);
5702 }
5703 }
5704 else if (new_num_devs >= 1)
5705 {
5706 /* Augment DEVICES and NUM_DEVICES. */
5707
5708 /* If USM has been requested and is supported by all devices
5709 of this type, set the capability accordingly. */
5710 if (omp_requires_mask
5711 & (GOMP_REQUIRES_UNIFIED_SHARED_MEMORY | GOMP_REQUIRES_SELF_MAPS))
5712 current_device.capabilities |= GOMP_OFFLOAD_CAP_SHARED_MEM;
5713
5714 devs = realloc (devs, (num_devs + new_num_devs)
5715 * sizeof (struct gomp_device_descr));
5716 if (!devs)
5717 {
5718 num_devs = 0;
5719 free (plugin_name);
5720 break;
5721 }
5722
5723 current_device.name = current_device.get_name_func ();
5724 /* Defer UID setting until needed + after gomp_init_device. */
5725 current_device.uid = NULL;
5726 /* current_device.capabilities has already been set. */
5727 current_device.type = current_device.get_type_func ();
5728 current_device.mem_map.root = NULL;
5729 current_device.mem_map_rev.root = NULL;
5730 current_device.state = GOMP_DEVICE_UNINITIALIZED;
5731 for (i = 0; i < new_num_devs; i++)
5732 {
5733 current_device.target_id = i;
5734 devs[num_devs] = current_device;
5735 gomp_mutex_init (&devs[num_devs].lock);
5736 num_devs++;
5737 }
5738 }
5739 }
5740
5741 free (plugin_name);
5742 cur = next + 1;
5743 }
5744 while (next);
5745
5746 /* In DEVICES, sort the GOMP_OFFLOAD_CAP_OPENMP_400 ones first, and set
5747 NUM_DEVICES_OPENMP. */
5748 struct gomp_device_descr *devs_s
5749 = malloc (num_devs * sizeof (struct gomp_device_descr));
5750 if (!devs_s)
5751 {
5752 num_devs = 0;
5753 free (devs);
5754 devs = NULL;
5755 }
5756 num_devs_openmp = 0;
5757 for (i = 0; i < num_devs; i++)
5758 if (devs[i].capabilities & GOMP_OFFLOAD_CAP_OPENMP_400)
5759 devs_s[num_devs_openmp++] = devs[i];
5760 int num_devs_after_openmp = num_devs_openmp;
5761 for (i = 0; i < num_devs; i++)
5762 if (!(devs[i].capabilities & GOMP_OFFLOAD_CAP_OPENMP_400))
5763 devs_s[num_devs_after_openmp++] = devs[i];
5764 free (devs);
5765 devs = devs_s;
5766
5767 for (i = 0; i < num_devs; i++)
5768 {
5769 /* The 'devices' array can be moved (by the realloc call) until we have
5770 found all the plugins, so registering with the OpenACC runtime (which
5771 takes a copy of the pointer argument) must be delayed until now. */
5772 if (devs[i].capabilities & GOMP_OFFLOAD_CAP_OPENACC_200)
5773 goacc_register (&devs[i]);
5774 }
5775 if (gomp_global_icv.default_device_var == INT_MIN)
5776 {
5777 /* This implies OMP_TARGET_OFFLOAD=mandatory. */
5778 struct gomp_icv_list *none;
5779 none = gomp_get_initial_icv_item (GOMP_DEVICE_NUM_FOR_NO_SUFFIX);
5780 gomp_global_icv.default_device_var = (num_devs_openmp
5781 ? 0 : omp_invalid_device);
5782 none->icvs.default_device_var = gomp_global_icv.default_device_var;
5783 }
5784
5785 num_devices = num_devs;
5786 num_devices_openmp = num_devs_openmp;
5787 devices = devs;
5788 if (atexit (gomp_target_fini) != 0)
5789 gomp_fatal ("atexit failed");
5790 }
5791
5792 #else /* PLUGIN_SUPPORT */
5793 /* If dlfcn.h is unavailable we always fallback to host execution.
5794 GOMP_target* routines are just stubs for this case. */
5795 static void
5796 gomp_target_init (void)
5797 {
5798 }
5799 #endif /* PLUGIN_SUPPORT */