2 * Copyright (C) 2008 The Android Open Source Project
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 // Memory order requirements for POSIX semaphores appear unclear and are
30 // currently interpreted inconsistently.
31 // We conservatively prefer sequentially consistent operations for now.
32 // CAUTION: This is more conservative than some other major implementations,
33 // and may change if and when the issue is resolved.
35 #include <semaphore.h>
38 #include <stdatomic.h>
42 #include "private/bionic_constants.h"
43 #include "private/bionic_futex.h"
44 #include "private/bionic_sdk_version.h"
45 #include "private/bionic_time_conversions.h"
47 // In this implementation, a semaphore contains a
48 // 31-bit signed value and a 1-bit 'shared' flag
49 // (for process-sharing purpose).
51 // We use the value -1 to indicate contention on the
52 // semaphore, 0 or more to indicate uncontended state,
53 // any value lower than -2 is invalid at runtime.
59 // post(-1) ==> 1, then wake all waiters
63 // wait(0) ==> -1 then wait for a wake up + loop
64 // wait(-1) ==> -1 then wait for a wake up + loop
66 // Use the upper 31-bits for the counter, and the lower one
67 // for the shared flag.
68 #define SEMCOUNT_SHARED_MASK 0x00000001
69 #define SEMCOUNT_VALUE_MASK 0xfffffffe
70 #define SEMCOUNT_VALUE_SHIFT 1
72 // Convert a value into the corresponding sem->count bit pattern.
73 #define SEMCOUNT_FROM_VALUE(val) (((val) << SEMCOUNT_VALUE_SHIFT) & SEMCOUNT_VALUE_MASK)
75 // Convert a sem->count bit pattern into the corresponding signed value.
76 static inline int SEMCOUNT_TO_VALUE(unsigned int sval) {
77 return (static_cast<int>(sval) >> SEMCOUNT_VALUE_SHIFT);
80 // The value +1 as a sem->count bit-pattern.
81 #define SEMCOUNT_ONE SEMCOUNT_FROM_VALUE(1)
83 // The value -1 as a sem->count bit-pattern.
84 #define SEMCOUNT_MINUS_ONE SEMCOUNT_FROM_VALUE(~0U)
86 #define SEMCOUNT_DECREMENT(sval) (((sval) - (1U << SEMCOUNT_VALUE_SHIFT)) & SEMCOUNT_VALUE_MASK)
87 #define SEMCOUNT_INCREMENT(sval) (((sval) + (1U << SEMCOUNT_VALUE_SHIFT)) & SEMCOUNT_VALUE_MASK)
89 static inline atomic_uint* SEM_TO_ATOMIC_POINTER(sem_t* sem) {
90 static_assert(sizeof(atomic_uint) == sizeof(sem->count),
91 "sem->count should actually be atomic_uint in implementation.");
93 // We prefer casting to atomic_uint instead of declaring sem->count to be atomic_uint directly.
94 // Because using the second method pollutes semaphore.h.
95 return reinterpret_cast<atomic_uint*>(&sem->count);
98 // Return the shared bitflag from a semaphore counter.
99 static inline unsigned int SEM_GET_SHARED(atomic_uint* sem_count_ptr) {
100 // memory_order_relaxed is used as SHARED flag will not be changed after init.
101 return (atomic_load_explicit(sem_count_ptr, memory_order_relaxed) & SEMCOUNT_SHARED_MASK);
104 int sem_init(sem_t* sem, int pshared, unsigned int value) {
105 // Ensure that 'value' can be stored in the semaphore.
106 if (value > SEM_VALUE_MAX) {
111 unsigned int count = SEMCOUNT_FROM_VALUE(value);
113 count |= SEMCOUNT_SHARED_MASK;
116 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
117 atomic_init(sem_count_ptr, count);
121 int sem_destroy(sem_t*) {
125 sem_t* sem_open(const char*, int, ...) {
130 int sem_close(sem_t*) {
135 int sem_unlink(const char*) {
140 // Decrement a semaphore's value atomically,
141 // and return the old one. As a special case,
142 // this returns immediately if the value is
143 // negative (i.e. -1)
144 static int __sem_dec(atomic_uint* sem_count_ptr) {
145 unsigned int old_value = atomic_load_explicit(sem_count_ptr, memory_order_relaxed);
146 unsigned int shared = old_value & SEMCOUNT_SHARED_MASK;
148 // Use memory_order_seq_cst in atomic_compare_exchange operation to ensure all
149 // memory access made by other threads can be seen in current thread.
150 // An acquire fence may be sufficient, but it is still in discussion whether
151 // POSIX semaphores should provide sequential consistency.
153 if (SEMCOUNT_TO_VALUE(old_value) < 0) {
156 } while (!atomic_compare_exchange_weak(sem_count_ptr, &old_value,
157 SEMCOUNT_DECREMENT(old_value) | shared));
159 return SEMCOUNT_TO_VALUE(old_value);
162 // Same as __sem_dec, but will not touch anything if the
163 // value is already negative *or* 0. Returns the old value.
164 static int __sem_trydec(atomic_uint* sem_count_ptr) {
165 unsigned int old_value = atomic_load_explicit(sem_count_ptr, memory_order_relaxed);
166 unsigned int shared = old_value & SEMCOUNT_SHARED_MASK;
168 // Use memory_order_seq_cst in atomic_compare_exchange operation to ensure all
169 // memory access made by other threads can be seen in current thread.
170 // An acquire fence may be sufficient, but it is still in discussion whether
171 // POSIX semaphores should provide sequential consistency.
173 if (SEMCOUNT_TO_VALUE(old_value) <= 0) {
176 } while (!atomic_compare_exchange_weak(sem_count_ptr, &old_value,
177 SEMCOUNT_DECREMENT(old_value) | shared));
179 return SEMCOUNT_TO_VALUE(old_value);
182 // "Increment" the value of a semaphore atomically and
183 // return its old value. Note that this implements
184 // the special case of "incrementing" any negative
185 // value to +1 directly.
187 // NOTE: The value will _not_ wrap above SEM_VALUE_MAX
188 static int __sem_inc(atomic_uint* sem_count_ptr) {
189 unsigned int old_value = atomic_load_explicit(sem_count_ptr, memory_order_relaxed);
190 unsigned int shared = old_value & SEMCOUNT_SHARED_MASK;
191 unsigned int new_value;
193 // Use memory_order_seq_cst in atomic_compare_exchange operation to ensure all
194 // memory access made before can be seen in other threads.
195 // A release fence may be sufficient, but it is still in discussion whether
196 // POSIX semaphores should provide sequential consistency.
198 // Can't go higher than SEM_VALUE_MAX.
199 if (SEMCOUNT_TO_VALUE(old_value) == SEM_VALUE_MAX) {
203 // If the counter is negative, go directly to one, otherwise just increment.
204 if (SEMCOUNT_TO_VALUE(old_value) < 0) {
205 new_value = SEMCOUNT_ONE | shared;
207 new_value = SEMCOUNT_INCREMENT(old_value) | shared;
209 } while (!atomic_compare_exchange_weak(sem_count_ptr, &old_value,
212 return SEMCOUNT_TO_VALUE(old_value);
215 int sem_wait(sem_t* sem) {
216 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
217 unsigned int shared = SEM_GET_SHARED(sem_count_ptr);
220 if (__sem_dec(sem_count_ptr) > 0) {
224 int result = __futex_wait_ex(sem_count_ptr, shared, shared | SEMCOUNT_MINUS_ONE, false, nullptr);
225 if (bionic_get_application_target_sdk_version() >= __ANDROID_API_N__) {
226 if (result ==-EINTR) {
234 int sem_timedwait(sem_t* sem, const timespec* abs_timeout) {
235 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
237 // POSIX says we need to try to decrement the semaphore
238 // before checking the timeout value. Note that if the
239 // value is currently 0, __sem_trydec() does nothing.
240 if (__sem_trydec(sem_count_ptr) > 0) {
244 // Check it as per POSIX.
245 int result = check_timespec(abs_timeout, false);
251 unsigned int shared = SEM_GET_SHARED(sem_count_ptr);
254 // Try to grab the semaphore. If the value was 0, this will also change it to -1.
255 if (__sem_dec(sem_count_ptr) > 0) {
259 // Contention detected. Wait for a wakeup event.
260 int result = __futex_wait_ex(sem_count_ptr, shared, shared | SEMCOUNT_MINUS_ONE, true, abs_timeout);
262 // Return in case of timeout or interrupt.
263 if (result == -ETIMEDOUT || result == -EINTR) {
270 int sem_post(sem_t* sem) {
271 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
272 unsigned int shared = SEM_GET_SHARED(sem_count_ptr);
274 int old_value = __sem_inc(sem_count_ptr);
276 // Contention on the semaphore. Wake up all waiters.
277 __futex_wake_ex(sem_count_ptr, shared, INT_MAX);
278 } else if (old_value == SEM_VALUE_MAX) {
279 // Overflow detected.
287 int sem_trywait(sem_t* sem) {
288 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
289 if (__sem_trydec(sem_count_ptr) > 0) {
297 int sem_getvalue(sem_t* sem, int* sval) {
298 atomic_uint* sem_count_ptr = SEM_TO_ATOMIC_POINTER(sem);
300 // Use memory_order_seq_cst in atomic_load operation.
301 // memory_order_relaxed may be fine here, but it is still in discussion
302 // whether POSIX semaphores should provide sequential consistency.
303 int val = SEMCOUNT_TO_VALUE(atomic_load(sem_count_ptr));