Fix semaphore destruction (bug 12674).
[platform/upstream/glibc.git] / nptl / sem_wait.c
1 /* sem_wait -- wait on a semaphore.  Generic futex-using version.
2    Copyright (C) 2003-2015 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4    Contributed by Paul Mackerras <paulus@au.ibm.com>, 2003.
5
6    The GNU C Library is free software; you can redistribute it and/or
7    modify it under the terms of the GNU Lesser General Public
8    License as published by the Free Software Foundation; either
9    version 2.1 of the License, or (at your option) any later version.
10
11    The GNU C Library is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14    Lesser General Public License for more details.
15
16    You should have received a copy of the GNU Lesser General Public
17    License along with the GNU C Library; if not, see
18    <http://www.gnu.org/licenses/>.  */
19
20 #include "sem_waitcommon.c"
21
22 int
23 __new_sem_wait (sem_t *sem)
24 {
25   if (__new_sem_wait_fast ((struct new_sem *) sem, 0) == 0)
26     return 0;
27   else
28     return __new_sem_wait_slow((struct new_sem *) sem, NULL);
29 }
30 versioned_symbol (libpthread, __new_sem_wait, sem_wait, GLIBC_2_1);
31
32 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
33 int
34 attribute_compat_text_section
35 __old_sem_wait (sem_t *sem)
36 {
37   int *futex = (int *) sem;
38   int err;
39
40   do
41     {
42       if (atomic_decrement_if_positive (futex) > 0)
43         return 0;
44
45       /* Enable asynchronous cancellation.  Required by the standard.  */
46       int oldtype = __pthread_enable_asynccancel ();
47
48       /* Always assume the semaphore is shared.  */
49       err = lll_futex_wait (futex, 0, LLL_SHARED);
50
51       /* Disable asynchronous cancellation.  */
52       __pthread_disable_asynccancel (oldtype);
53     }
54   while (err == 0 || err == -EWOULDBLOCK);
55
56   __set_errno (-err);
57   return -1;
58 }
59
60 compat_symbol (libpthread, __old_sem_wait, sem_wait, GLIBC_2_0);
61 #endif
62
63 int
64 __new_sem_trywait (sem_t *sem)
65 {
66   /* We must not fail spuriously, so require a definitive result even if this
67      may lead to a long execution time.  */
68   if (__new_sem_wait_fast ((struct new_sem *) sem, 1) == 0)
69     return 0;
70   __set_errno (EAGAIN);
71   return -1;
72 }
73 versioned_symbol (libpthread, __new_sem_trywait, sem_trywait, GLIBC_2_1);
74 #if SHLIB_COMPAT (libpthread, GLIBC_2_0, GLIBC_2_1)
75 int
76 __old_sem_trywait (sem_t *sem)
77 {
78   int *futex = (int *) sem;
79   int val;
80
81   if (*futex > 0)
82     {
83       val = atomic_decrement_if_positive (futex);
84       if (val > 0)
85         return 0;
86     }
87
88   __set_errno (EAGAIN);
89   return -1;
90 }
91 compat_symbol (libpthread, __old_sem_trywait, sem_trywait, GLIBC_2_0);
92 #endif