Support for OpenACC acc_on_device in offloading configurations.
[official-gcc.git] / libgomp / config / linux / sem.c
blob885d04dcb3e3f7b833acd527ed1f22d7334754a6
1 /* Copyright (C) 2005-2014 Free Software Foundation, Inc.
2 Contributed by Richard Henderson <rth@redhat.com>.
4 This file is part of the GNU Offloading and Multi Processing Library
5 (libgomp).
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.
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.
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.
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/>. */
26 /* This is a Linux specific implementation of a semaphore synchronization
27 mechanism for libgomp. This type is private to the library. This
28 implementation uses atomic instructions and the futex syscall. */
30 #include "wait.h"
32 void
33 gomp_sem_wait_slow (gomp_sem_t *sem, int count)
35 /* First loop spins a while. */
36 while (count == 0)
37 if (do_spin (sem, 0)
38 /* Spin timeout, nothing changed. Set waiting flag. */
39 && __atomic_compare_exchange_n (sem, &count, SEM_WAIT, false,
40 MEMMODEL_ACQUIRE, MEMMODEL_RELAXED))
42 futex_wait (sem, SEM_WAIT);
43 count = *sem;
44 break;
46 /* Something changed. If it wasn't the wait flag, we're good to go. */
47 else if (__builtin_expect (((count = *sem) & SEM_WAIT) == 0 && count != 0,
48 1))
50 if (__atomic_compare_exchange_n (sem, &count, count - SEM_INC, false,
51 MEMMODEL_ACQUIRE, MEMMODEL_RELAXED))
52 return;
55 /* Second loop waits until semaphore is posted. We always exit this
56 loop with wait flag set, so next post will awaken a thread. */
57 while (1)
59 unsigned int wake = count & ~SEM_WAIT;
60 int newval = SEM_WAIT;
62 if (wake != 0)
63 newval |= wake - SEM_INC;
64 if (__atomic_compare_exchange_n (sem, &count, newval, false,
65 MEMMODEL_ACQUIRE, MEMMODEL_RELAXED))
67 if (wake != 0)
69 /* If we can wake more threads, do so now. */
70 if (wake > SEM_INC)
71 gomp_sem_post_slow (sem);
72 break;
74 do_wait (sem, SEM_WAIT);
75 count = *sem;
80 void
81 gomp_sem_post_slow (gomp_sem_t *sem)
83 futex_wake (sem, 1);