1/* Copyright (C) 2005-2022 Free Software Foundation, Inc. 2 Contributed by Richard Henderson <rth@redhat.com>. 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 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. */ 29 30#include "wait.h" 31 32void 33gomp_sem_wait_slow (gomp_sem_t *sem, int count) 34{ 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)) 41 { 42 futex_wait (sem, SEM_WAIT); 43 count = *sem; 44 break; 45 } 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)) 49 { 50 if (__atomic_compare_exchange_n (sem, &count, count - SEM_INC, false, 51 MEMMODEL_ACQUIRE, MEMMODEL_RELAXED)) 52 return; 53 } 54 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) 58 { 59 unsigned int wake = count & ~SEM_WAIT; 60 int newval = SEM_WAIT; 61 62 if (wake != 0) 63 newval |= wake - SEM_INC; 64 if (__atomic_compare_exchange_n (sem, &count, newval, false, 65 MEMMODEL_ACQUIRE, MEMMODEL_RELAXED)) 66 { 67 if (wake != 0) 68 { 69 /* If we can wake more threads, do so now. */ 70 if (wake > SEM_INC) 71 gomp_sem_post_slow (sem); 72 break; 73 } 74 do_wait (sem, SEM_WAIT); 75 count = *sem; 76 } 77 } 78} 79 80void 81gomp_sem_post_slow (gomp_sem_t *sem) 82{ 83 futex_wake (sem, 1); 84} 85