blob: ed90639e32aff0ac01a7ee81048dc085186a8eee [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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
13 * distribution.
14 *
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
26 * SUCH DAMAGE.
27 */
Pierre Peifferd0c884d2012-02-22 16:40:15 +010028
Elliott Hughes6f94de32013-02-12 06:06:22 +000029#include <pthread.h>
Elliott Hughes3e898472013-02-12 16:40:24 +000030
31#include <errno.h>
32#include <limits.h>
Yabin Cui86fc96f2015-01-29 21:50:48 -080033#include <stdatomic.h>
Yabin Cui17393b02015-03-21 15:08:25 -070034#include <string.h>
Yabin Cui86fc96f2015-01-29 21:50:48 -080035#include <sys/cdefs.h>
Elliott Hughes84114c82013-07-17 13:33:19 -070036#include <sys/mman.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010037#include <unistd.h>
38
Pierre Peifferd0c884d2012-02-22 16:40:15 +010039#include "pthread_internal.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070040
Elliott Hughes04303f52014-09-18 16:11:59 -070041#include "private/bionic_constants.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070042#include "private/bionic_futex.h"
Yabin Cui86fc96f2015-01-29 21:50:48 -080043#include "private/bionic_systrace.h"
Elliott Hughes04303f52014-09-18 16:11:59 -070044#include "private/bionic_time_conversions.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070045#include "private/bionic_tls.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080046
Yabin Cuie69c2452015-02-13 16:21:25 -080047/* a mutex attribute holds the following fields
48 *
49 * bits: name description
50 * 0-3 type type of mutex
51 * 4 shared process-shared flag
Yabin Cui6b9c85b2018-01-23 12:56:18 -080052 * 5 protocol whether it is a priority inherit mutex.
Yabin Cuie69c2452015-02-13 16:21:25 -080053 */
54#define MUTEXATTR_TYPE_MASK 0x000f
55#define MUTEXATTR_SHARED_MASK 0x0010
Yabin Cui6b9c85b2018-01-23 12:56:18 -080056#define MUTEXATTR_PROTOCOL_MASK 0x0020
57
58#define MUTEXATTR_PROTOCOL_SHIFT 5
Yabin Cuie69c2452015-02-13 16:21:25 -080059
60int pthread_mutexattr_init(pthread_mutexattr_t *attr)
61{
62 *attr = PTHREAD_MUTEX_DEFAULT;
63 return 0;
64}
65
66int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
67{
68 *attr = -1;
69 return 0;
70}
71
72int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type_p)
73{
74 int type = (*attr & MUTEXATTR_TYPE_MASK);
75
76 if (type < PTHREAD_MUTEX_NORMAL || type > PTHREAD_MUTEX_ERRORCHECK) {
77 return EINVAL;
78 }
79
80 *type_p = type;
81 return 0;
82}
83
84int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
85{
86 if (type < PTHREAD_MUTEX_NORMAL || type > PTHREAD_MUTEX_ERRORCHECK ) {
87 return EINVAL;
88 }
89
90 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
91 return 0;
92}
93
94/* process-shared mutexes are not supported at the moment */
95
96int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
97{
98 switch (pshared) {
99 case PTHREAD_PROCESS_PRIVATE:
100 *attr &= ~MUTEXATTR_SHARED_MASK;
101 return 0;
102
103 case PTHREAD_PROCESS_SHARED:
104 /* our current implementation of pthread actually supports shared
105 * mutexes but won't cleanup if a process dies with the mutex held.
106 * Nevertheless, it's better than nothing. Shared mutexes are used
107 * by surfaceflinger and audioflinger.
108 */
109 *attr |= MUTEXATTR_SHARED_MASK;
110 return 0;
111 }
112 return EINVAL;
113}
114
115int pthread_mutexattr_getpshared(const pthread_mutexattr_t* attr, int* pshared) {
116 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED : PTHREAD_PROCESS_PRIVATE;
117 return 0;
118}
119
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800120int pthread_mutexattr_setprotocol(pthread_mutexattr_t* attr, int protocol) {
121 if (protocol != PTHREAD_PRIO_NONE && protocol != PTHREAD_PRIO_INHERIT) {
122 return EINVAL;
123 }
124 *attr = (*attr & ~MUTEXATTR_PROTOCOL_MASK) | (protocol << MUTEXATTR_PROTOCOL_SHIFT);
125 return 0;
126}
127
128int pthread_mutexattr_getprotocol(const pthread_mutexattr_t* attr, int* protocol) {
129 *protocol = (*attr & MUTEXATTR_PROTOCOL_MASK) >> MUTEXATTR_PROTOCOL_SHIFT;
130 return 0;
131}
132
133#if defined(__LP64__)
134
135// Priority Inheritance mutex implementation
136struct PIMutex {
137 // mutex type, can be 0 (normal), 1 (recursive), 2 (errorcheck), constant during lifetime
138 uint8_t type;
139 // process-shared flag, constant during lifetime
140 bool shared;
141 // <number of times a thread holding a recursive PI mutex> - 1
142 uint16_t counter;
143 // owner_tid is read/written by both userspace code and kernel code. It includes three fields:
144 // FUTEX_WAITERS, FUTEX_OWNER_DIED and FUTEX_TID_MASK.
145 atomic_int owner_tid;
146};
147
148static inline __always_inline int PIMutexTryLock(PIMutex& mutex) {
149 pid_t tid = __get_thread()->tid;
150 // Handle common case first.
151 int old_owner = 0;
152 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex.owner_tid,
153 &old_owner, tid,
154 memory_order_acquire,
155 memory_order_relaxed))) {
156 return 0;
157 }
158 if (tid == (old_owner & FUTEX_TID_MASK)) {
159 // We already own this mutex.
160 if (mutex.type == PTHREAD_MUTEX_NORMAL) {
161 return EBUSY;
162 }
163 if (mutex.type == PTHREAD_MUTEX_ERRORCHECK) {
164 return EDEADLK;
165 }
166 if (mutex.counter == 0xffff) {
167 return EAGAIN;
168 }
169 mutex.counter++;
170 return 0;
171 }
172 return EBUSY;
173}
174
175static int PIMutexTimedLock(PIMutex& mutex, const timespec* abs_timeout) {
176 int ret = PIMutexTryLock(mutex);
177 if (__predict_true(ret == 0)) {
178 return 0;
179 }
180 if (ret == EBUSY) {
181 ret = -__futex_pi_lock_ex(&mutex.owner_tid, mutex.shared, true, abs_timeout);
182 }
183 return ret;
184}
185
186static int PIMutexUnlock(PIMutex& mutex) {
187 pid_t tid = __get_thread()->tid;
188 int old_owner = tid;
189 // Handle common case first.
190 if (__predict_true(mutex.type == PTHREAD_MUTEX_NORMAL)) {
191 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex.owner_tid,
192 &old_owner, 0,
193 memory_order_release,
194 memory_order_relaxed))) {
195 return 0;
196 }
197 }
198
199 if (tid != (old_owner & FUTEX_TID_MASK)) {
200 // The mutex can only be unlocked by the thread who owns it.
201 return EPERM;
202 }
203 if (mutex.type == PTHREAD_MUTEX_RECURSIVE) {
204 if (mutex.counter != 0u) {
205 --mutex.counter;
206 return 0;
207 }
208 }
209 if (old_owner == tid) {
210 // No thread is waiting.
211 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex.owner_tid,
212 &old_owner, 0,
213 memory_order_release,
214 memory_order_relaxed))) {
215 return 0;
216 }
217 }
218 return -__futex_pi_unlock(&mutex.owner_tid, mutex.shared);
219}
220
221static int PIMutexDestroy(PIMutex& mutex) {
222 // The mutex should be in unlocked state (owner_tid == 0) when destroyed.
223 // Store 0xffffffff to make the mutex unusable.
224 int old_owner = 0;
225 if (atomic_compare_exchange_strong_explicit(&mutex.owner_tid, &old_owner, 0xffffffff,
226 memory_order_relaxed, memory_order_relaxed)) {
227 return 0;
228 }
229 return EBUSY;
230}
231#endif // defined(__LP64__)
232
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800233
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100234/* Convenience macro, creates a mask of 'bits' bits that starts from
235 * the 'shift'-th least significant bit in a 32-bit word.
236 *
237 * Examples: FIELD_MASK(0,4) -> 0xf
238 * FIELD_MASK(16,9) -> 0x1ff0000
239 */
240#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800241
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100242/* This one is used to create a bit pattern from a given field value */
243#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100244
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100245/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
246#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800247
Yabin Cuie69c2452015-02-13 16:21:25 -0800248/* Convenience macros.
249 *
250 * These are used to form or modify the bit pattern of a given mutex value
251 */
252
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100253/* Mutex state:
254 *
255 * 0 for unlocked
256 * 1 for locked, no waiters
257 * 2 for locked, maybe waiters
258 */
259#define MUTEX_STATE_SHIFT 0
260#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800261
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100262#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
263#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
264#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
265
Yabin Cui17393b02015-03-21 15:08:25 -0700266#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match PTHREAD_MUTEX_INITIALIZER */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100267#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
268#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
269
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100270#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
271#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
272#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
273
Yabin Cui0307eee2015-11-16 20:19:31 -0800274// Return true iff the mutex is unlocked.
275#define MUTEX_STATE_BITS_IS_UNLOCKED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_UNLOCKED)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100276
Yabin Cui0307eee2015-11-16 20:19:31 -0800277// Return true iff the mutex is locked with no waiters.
278#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
279
280// return true iff the mutex is locked with maybe waiters.
281#define MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_CONTENDED)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100282
283/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
284#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
285
286/* Mutex counter:
287 *
288 * We need to check for overflow before incrementing, and we also need to
289 * detect when the counter is 0
290 */
291#define MUTEX_COUNTER_SHIFT 2
292#define MUTEX_COUNTER_LEN 11
293#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
294
295#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
296#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
297
298/* Used to increment the counter directly after overflow has been checked */
Yabin Cui86fc96f2015-01-29 21:50:48 -0800299#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1, MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100300
301/* Mutex shared bit flag
302 *
303 * This flag is set to indicate that the mutex is shared among processes.
304 * This changes the futex opcode we use for futex wait/wake operations
305 * (non-shared operations are much faster).
306 */
307#define MUTEX_SHARED_SHIFT 13
308#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
309
310/* Mutex type:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100311 * We support normal, recursive and errorcheck mutexes.
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100312 */
313#define MUTEX_TYPE_SHIFT 14
314#define MUTEX_TYPE_LEN 2
315#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
316
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100317#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
318
Yabin Cui17393b02015-03-21 15:08:25 -0700319#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_NORMAL)
320#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_RECURSIVE)
321#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_ERRORCHECK)
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800322// Use a special mutex type to mark priority inheritance mutexes.
323#define MUTEX_TYPE_BITS_WITH_PI MUTEX_TYPE_TO_BITS(3)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100324
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800325// For a PI mutex, it includes below fields:
326// Atomic(uint16_t) state;
327// PIMutex pi_mutex;
328//
329// state holds the following fields:
330//
331// bits: name description
332// 15-14 type mutex type, should be 3
333//
334// pi_mutex holds the state of a PI mutex.
335//
336// For a Non-PI mutex, it includes below fields:
337// Atomic(uint16_t) state;
338// atomic_int owner_tid; // Atomic(uint16_t) in 32-bit programs
339//
340// state holds the following fields:
341//
342// bits: name description
343// 15-14 type mutex type, can be 0 (normal), 1 (recursive), 2 (errorcheck)
344// 13 shared process-shared flag
345// 12-2 counter <number of times a thread holding a recursive Non-PI mutex> - 1
346// 1-0 state lock state (0, 1 or 2)
347//
348// bits 15-13 are constant during the lifetime of the mutex.
349//
350// owner_tid is used only in recursive and errorcheck Non-PI mutexes to hold the mutex owner
351// thread id.
352//
353// PI mutexes and Non-PI mutexes are distinguished by checking type field in state.
Yabin Cui17393b02015-03-21 15:08:25 -0700354struct pthread_mutex_internal_t {
Yabin Cuie69c2452015-02-13 16:21:25 -0800355 _Atomic(uint16_t) state;
Yabin Cui17393b02015-03-21 15:08:25 -0700356#if defined(__LP64__)
Yabin Cuie69c2452015-02-13 16:21:25 -0800357 uint16_t __pad;
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800358 union {
359 atomic_int owner_tid;
360 PIMutex pi_mutex;
361 };
362 char __reserved[28];
Yabin Cuie69c2452015-02-13 16:21:25 -0800363#else
364 _Atomic(uint16_t) owner_tid;
Yabin Cui17393b02015-03-21 15:08:25 -0700365#endif
Yabin Cuie69c2452015-02-13 16:21:25 -0800366} __attribute__((aligned(4)));
Yabin Cui86fc96f2015-01-29 21:50:48 -0800367
Yabin Cui17393b02015-03-21 15:08:25 -0700368static_assert(sizeof(pthread_mutex_t) == sizeof(pthread_mutex_internal_t),
369 "pthread_mutex_t should actually be pthread_mutex_internal_t in implementation.");
370
371// For binary compatibility with old version of pthread_mutex_t, we can't use more strict alignment
372// than 4-byte alignment.
373static_assert(alignof(pthread_mutex_t) == 4,
374 "pthread_mutex_t should fulfill the alignment of pthread_mutex_internal_t.");
375
376static inline pthread_mutex_internal_t* __get_internal_mutex(pthread_mutex_t* mutex_interface) {
377 return reinterpret_cast<pthread_mutex_internal_t*>(mutex_interface);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800378}
379
Yabin Cui17393b02015-03-21 15:08:25 -0700380int pthread_mutex_init(pthread_mutex_t* mutex_interface, const pthread_mutexattr_t* attr) {
381 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
382
383 memset(mutex, 0, sizeof(pthread_mutex_internal_t));
Yabin Cui86fc96f2015-01-29 21:50:48 -0800384
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700385 if (__predict_true(attr == NULL)) {
Yabin Cui17393b02015-03-21 15:08:25 -0700386 atomic_init(&mutex->state, MUTEX_TYPE_BITS_NORMAL);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700387 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800388 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700389
Yabin Cuie69c2452015-02-13 16:21:25 -0800390 uint16_t state = 0;
Elliott Hughesdff72032013-12-11 14:54:00 -0800391 if ((*attr & MUTEXATTR_SHARED_MASK) != 0) {
Yabin Cui17393b02015-03-21 15:08:25 -0700392 state |= MUTEX_SHARED_MASK;
Elliott Hughesdff72032013-12-11 14:54:00 -0800393 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700394
395 switch (*attr & MUTEXATTR_TYPE_MASK) {
396 case PTHREAD_MUTEX_NORMAL:
Yabin Cuie69c2452015-02-13 16:21:25 -0800397 state |= MUTEX_TYPE_BITS_NORMAL;
398 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700399 case PTHREAD_MUTEX_RECURSIVE:
Yabin Cuie69c2452015-02-13 16:21:25 -0800400 state |= MUTEX_TYPE_BITS_RECURSIVE;
401 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700402 case PTHREAD_MUTEX_ERRORCHECK:
Yabin Cuie69c2452015-02-13 16:21:25 -0800403 state |= MUTEX_TYPE_BITS_ERRORCHECK;
404 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700405 default:
406 return EINVAL;
407 }
408
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800409 if (((*attr & MUTEXATTR_PROTOCOL_MASK) >> MUTEXATTR_PROTOCOL_SHIFT) == PTHREAD_PRIO_INHERIT) {
410#if defined(__LP64__)
411 atomic_init(&mutex->state, MUTEX_TYPE_BITS_WITH_PI);
412 mutex->pi_mutex.type = *attr & MUTEXATTR_TYPE_MASK;
413 mutex->pi_mutex.shared = (*attr & MUTEXATTR_SHARED_MASK) != 0;
414#else
415 return EINVAL;
416#endif
417 } else {
418 atomic_init(&mutex->state, state);
419 atomic_init(&mutex->owner_tid, 0);
420 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700421 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800422}
423
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800424// namespace for Non-PI mutex routines.
425namespace NonPI {
426
427static inline __always_inline int NormalMutexTryLock(pthread_mutex_internal_t* mutex,
428 uint16_t shared) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800429 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
430 const uint16_t locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800431
Yabin Cuie69c2452015-02-13 16:21:25 -0800432 uint16_t old_state = unlocked;
Yabin Cui17393b02015-03-21 15:08:25 -0700433 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
434 locked_uncontended, memory_order_acquire, memory_order_relaxed))) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800435 return 0;
436 }
437 return EBUSY;
438}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800439
440/*
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800441 * Lock a normal Non-PI mutex.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800442 *
443 * As noted above, there are three states:
444 * 0 (unlocked, no contention)
445 * 1 (locked, no contention)
446 * 2 (locked, contention)
447 *
448 * Non-recursive mutexes don't use the thread-id or counter fields, and the
449 * "type" value is zero, so the only bits that will be set are the ones in
450 * the lock state field.
451 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800452static inline __always_inline int NormalMutexLock(pthread_mutex_internal_t* mutex,
453 uint16_t shared,
454 bool use_realtime_clock,
455 const timespec* abs_timeout_or_null) {
456 if (__predict_true(NormalMutexTryLock(mutex, shared) == 0)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800457 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800458 }
Elliott Hughesdd586f22015-12-16 15:15:58 -0800459 int result = check_timespec(abs_timeout_or_null, true);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800460 if (result != 0) {
461 return result;
462 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800463
464 ScopedTrace trace("Contending for pthread mutex");
465
Yabin Cuie69c2452015-02-13 16:21:25 -0800466 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
467 const uint16_t locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800468
Yabin Cui86fc96f2015-01-29 21:50:48 -0800469 // We want to go to sleep until the mutex is available, which requires
470 // promoting it to locked_contended. We need to swap in the new state
Yabin Cui17393b02015-03-21 15:08:25 -0700471 // and then wait until somebody wakes us up.
Yabin Cui86fc96f2015-01-29 21:50:48 -0800472 // An atomic_exchange is used to compete with other threads for the lock.
473 // If it returns unlocked, we have acquired the lock, otherwise another
474 // thread still holds the lock and we should wait again.
475 // If lock is acquired, an acquire fence is needed to make all memory accesses
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800476 // made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700477 while (atomic_exchange_explicit(&mutex->state, locked_contended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800478 memory_order_acquire) != unlocked) {
Yabin Cuic9a659c2015-11-05 15:36:08 -0800479 if (__futex_wait_ex(&mutex->state, shared, locked_contended, use_realtime_clock,
480 abs_timeout_or_null) == -ETIMEDOUT) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800481 return ETIMEDOUT;
482 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800483 }
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800484 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800485}
486
487/*
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800488 * Release a normal Non-PI mutex. The caller is responsible for determining
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800489 * that we are in fact the owner of this lock.
490 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800491static inline __always_inline void NormalMutexUnlock(pthread_mutex_internal_t* mutex,
492 uint16_t shared) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800493 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
494 const uint16_t locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700495
Yabin Cui86fc96f2015-01-29 21:50:48 -0800496 // We use an atomic_exchange to release the lock. If locked_contended state
497 // is returned, some threads is waiting for the lock and we need to wake up
498 // one of them.
499 // A release fence is required to make previous stores visible to next
500 // lock owner threads.
Yabin Cui17393b02015-03-21 15:08:25 -0700501 if (atomic_exchange_explicit(&mutex->state, unlocked,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800502 memory_order_release) == locked_contended) {
503 // Wake up one waiting thread. We don't know which thread will be
504 // woken or when it'll start executing -- futexes make no guarantees
505 // here. There may not even be a thread waiting.
506 //
507 // The newly-woken thread will replace the unlocked state we just set above
508 // with locked_contended state, which means that when it eventually releases
509 // the mutex it will also call FUTEX_WAKE. This results in one extra wake
510 // call whenever a lock is contended, but let us avoid forgetting anyone
511 // without requiring us to track the number of sleepers.
512 //
513 // It's possible for another thread to sneak in and grab the lock between
514 // the exchange above and the wake call below. If the new thread is "slow"
515 // and holds the lock for a while, we'll wake up a sleeper, which will swap
516 // in locked_uncontended state and then go back to sleep since the lock is
517 // still held. If the new thread is "fast", running to completion before
518 // we call wake, the thread we eventually wake will find an unlocked mutex
519 // and will execute. Either way we have correct behavior and nobody is
520 // orphaned on the wait queue.
Yabin Cui17393b02015-03-21 15:08:25 -0700521 __futex_wake_ex(&mutex->state, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800522 }
523}
524
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800525/* This common inlined function is used to increment the counter of a recursive Non-PI mutex.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100526 *
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800527 * If the counter overflows, it will return EAGAIN.
528 * Otherwise, it atomically increments the counter and returns 0.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100529 *
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100530 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800531static inline __always_inline int RecursiveIncrement(pthread_mutex_internal_t* mutex,
532 uint16_t old_state) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800533 // Detect recursive lock overflow and return EAGAIN.
534 // This is safe because only the owner thread can modify the
535 // counter bits in the mutex value.
Yabin Cui17393b02015-03-21 15:08:25 -0700536 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(old_state)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100537 return EAGAIN;
538 }
539
Yabin Cuie69c2452015-02-13 16:21:25 -0800540 // Other threads are able to change the lower bits (e.g. promoting it to "contended"),
541 // but the mutex counter will not overflow. So we use atomic_fetch_add operation here.
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800542 // The mutex is already locked by current thread, so we don't need an acquire fence.
Yabin Cui17393b02015-03-21 15:08:25 -0700543 atomic_fetch_add_explicit(&mutex->state, MUTEX_COUNTER_BITS_ONE, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800544 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800545}
546
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800547// Wait on a recursive or errorcheck Non-PI mutex.
548static inline __always_inline int RecursiveOrErrorcheckMutexWait(pthread_mutex_internal_t* mutex,
549 uint16_t shared,
550 uint16_t old_state,
551 bool use_realtime_clock,
552 const timespec* abs_timeout) {
Yabin Cuif7969852015-04-02 17:47:48 -0700553// __futex_wait always waits on a 32-bit value. But state is 16-bit. For a normal mutex, the owner_tid
554// field in mutex is not used. On 64-bit devices, the __pad field in mutex is not used.
555// But when a recursive or errorcheck mutex is used on 32-bit devices, we need to add the
556// owner_tid value in the value argument for __futex_wait, otherwise we may always get EAGAIN error.
557
558#if defined(__LP64__)
Yabin Cuic9a659c2015-11-05 15:36:08 -0800559 return __futex_wait_ex(&mutex->state, shared, old_state, use_realtime_clock, abs_timeout);
Yabin Cuif7969852015-04-02 17:47:48 -0700560
561#else
562 // This implementation works only when the layout of pthread_mutex_internal_t matches below expectation.
563 // And it is based on the assumption that Android is always in little-endian devices.
564 static_assert(offsetof(pthread_mutex_internal_t, state) == 0, "");
565 static_assert(offsetof(pthread_mutex_internal_t, owner_tid) == 2, "");
566
567 uint32_t owner_tid = atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800568 return __futex_wait_ex(&mutex->state, shared, (owner_tid << 16) | old_state,
569 use_realtime_clock, abs_timeout);
Yabin Cuif7969852015-04-02 17:47:48 -0700570#endif
571}
572
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800573// Lock a Non-PI mutex.
574static int MutexLockWithTimeout(pthread_mutex_internal_t* mutex, bool use_realtime_clock,
575 const timespec* abs_timeout_or_null) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800576 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
577 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
578 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800579
Yabin Cui86fc96f2015-01-29 21:50:48 -0800580 // Handle common case first.
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700581 if ( __predict_true(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800582 return NormalMutexLock(mutex, shared, use_realtime_clock, abs_timeout_or_null);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800583 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700584
Yabin Cui86fc96f2015-01-29 21:50:48 -0800585 // Do we already own this recursive or error-check mutex?
Yabin Cuie69c2452015-02-13 16:21:25 -0800586 pid_t tid = __get_thread()->tid;
587 if (tid == atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800588 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
589 return EDEADLK;
590 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800591 return RecursiveIncrement(mutex, old_state);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800592 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700593
Yabin Cuie69c2452015-02-13 16:21:25 -0800594 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
595 const uint16_t locked_uncontended = mtype | shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
596 const uint16_t locked_contended = mtype | shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700597
Yabin Cui86fc96f2015-01-29 21:50:48 -0800598 // First, if the mutex is unlocked, try to quickly acquire it.
599 // In the optimistic case where this works, set the state to locked_uncontended.
Yabin Cui17393b02015-03-21 15:08:25 -0700600 if (old_state == unlocked) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800601 // If exchanged successfully, an acquire fence is required to make
602 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700603 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
Yabin Cuie69c2452015-02-13 16:21:25 -0800604 locked_uncontended, memory_order_acquire, memory_order_relaxed))) {
605 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100606 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700607 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700608 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100609
Brigid Smitha406ee62014-07-21 15:38:06 -0700610 ScopedTrace trace("Contending for pthread mutex");
611
Yabin Cui86fc96f2015-01-29 21:50:48 -0800612 while (true) {
Yabin Cui17393b02015-03-21 15:08:25 -0700613 if (old_state == unlocked) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800614 // NOTE: We put the state to locked_contended since we _know_ there
615 // is contention when we are in this loop. This ensures all waiters
616 // will be unlocked.
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100617
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800618 // If exchanged successfully, an acquire fence is required to make
619 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700620 if (__predict_true(atomic_compare_exchange_weak_explicit(&mutex->state,
Yabin Cuie69c2452015-02-13 16:21:25 -0800621 &old_state, locked_contended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800622 memory_order_acquire,
623 memory_order_relaxed))) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800624 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800625 return 0;
626 }
627 continue;
Yabin Cui17393b02015-03-21 15:08:25 -0700628 } else if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(old_state)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800629 // We should set it to locked_contended beforing going to sleep. This can make
Yabin Cui86fc96f2015-01-29 21:50:48 -0800630 // sure waiters will be woken up eventually.
631
Yabin Cui17393b02015-03-21 15:08:25 -0700632 int new_state = MUTEX_STATE_BITS_FLIP_CONTENTION(old_state);
633 if (__predict_false(!atomic_compare_exchange_weak_explicit(&mutex->state,
634 &old_state, new_state,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800635 memory_order_relaxed,
636 memory_order_relaxed))) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100637 continue;
638 }
Yabin Cui17393b02015-03-21 15:08:25 -0700639 old_state = new_state;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100640 }
641
Elliott Hughesdd586f22015-12-16 15:15:58 -0800642 int result = check_timespec(abs_timeout_or_null, true);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800643 if (result != 0) {
644 return result;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800645 }
Yabin Cuic9a659c2015-11-05 15:36:08 -0800646 // We are in locked_contended state, sleep until someone wakes us up.
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800647 if (RecursiveOrErrorcheckMutexWait(mutex, shared, old_state, use_realtime_clock,
648 abs_timeout_or_null) == -ETIMEDOUT) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800649 return ETIMEDOUT;
650 }
Yabin Cui17393b02015-03-21 15:08:25 -0700651 old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100652 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800653}
654
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800655} // namespace NonPI
656
Yabin Cui17393b02015-03-21 15:08:25 -0700657int pthread_mutex_lock(pthread_mutex_t* mutex_interface) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700658#if !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -0700659 // Some apps depend on being able to pass NULL as a mutex and get EINVAL
660 // back. Don't need to worry about it for LP64 since the ABI is brand new,
661 // but keep compatibility for LP32. http://b/19995172.
Christopher Ferris511cfd92015-06-09 18:46:15 -0700662 if (mutex_interface == NULL) {
663 return EINVAL;
664 }
665#endif
666
Yabin Cui17393b02015-03-21 15:08:25 -0700667 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800668
Yabin Cuie69c2452015-02-13 16:21:25 -0800669 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
670 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
671 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800672 // Avoid slowing down fast path of normal mutex lock operation.
673 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800674 if (__predict_true(NonPI::NormalMutexTryLock(mutex, shared) == 0)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800675 return 0;
676 }
677 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800678#if defined(__LP64__)
679 if (mtype == MUTEX_TYPE_BITS_WITH_PI) {
680 return PIMutexTimedLock(mutex->pi_mutex, nullptr);
681 }
682#endif
683 return NonPI::MutexLockWithTimeout(mutex, false, nullptr);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800684}
685
Yabin Cui17393b02015-03-21 15:08:25 -0700686int pthread_mutex_unlock(pthread_mutex_t* mutex_interface) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700687#if !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -0700688 // Some apps depend on being able to pass NULL as a mutex and get EINVAL
689 // back. Don't need to worry about it for LP64 since the ABI is brand new,
690 // but keep compatibility for LP32. http://b/19995172.
Christopher Ferris511cfd92015-06-09 18:46:15 -0700691 if (mutex_interface == NULL) {
692 return EINVAL;
693 }
694#endif
695
Yabin Cui17393b02015-03-21 15:08:25 -0700696 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800697
Yabin Cuie69c2452015-02-13 16:21:25 -0800698 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
699 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
700 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800701
Yabin Cui86fc96f2015-01-29 21:50:48 -0800702 // Handle common case first.
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700703 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800704 NonPI::NormalMutexUnlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800705 return 0;
706 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800707#if defined(__LP64__)
708 if (mtype == MUTEX_TYPE_BITS_WITH_PI) {
709 return PIMutexUnlock(mutex->pi_mutex);
710 }
711#endif
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700712
Yabin Cui86fc96f2015-01-29 21:50:48 -0800713 // Do we already own this recursive or error-check mutex?
Yabin Cuie69c2452015-02-13 16:21:25 -0800714 pid_t tid = __get_thread()->tid;
715 if ( tid != atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed) ) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700716 return EPERM;
Yabin Cuie69c2452015-02-13 16:21:25 -0800717 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700718
Yabin Cui86fc96f2015-01-29 21:50:48 -0800719 // If the counter is > 0, we can simply decrement it atomically.
720 // Since other threads can mutate the lower state bits (and only the
721 // lower state bits), use a compare_exchange loop to do it.
Yabin Cui17393b02015-03-21 15:08:25 -0700722 if (!MUTEX_COUNTER_BITS_IS_ZERO(old_state)) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800723 // We still own the mutex, so a release fence is not needed.
Yabin Cui17393b02015-03-21 15:08:25 -0700724 atomic_fetch_sub_explicit(&mutex->state, MUTEX_COUNTER_BITS_ONE, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800725 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700726 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100727
Yabin Cui86fc96f2015-01-29 21:50:48 -0800728 // The counter is 0, so we'are going to unlock the mutex by resetting its
729 // state to unlocked, we need to perform a atomic_exchange inorder to read
730 // the current state, which will be locked_contended if there may have waiters
731 // to awake.
732 // A release fence is required to make previous stores visible to next
733 // lock owner threads.
Yabin Cuie69c2452015-02-13 16:21:25 -0800734 atomic_store_explicit(&mutex->owner_tid, 0, memory_order_relaxed);
735 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
Yabin Cui17393b02015-03-21 15:08:25 -0700736 old_state = atomic_exchange_explicit(&mutex->state, unlocked, memory_order_release);
737 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(old_state)) {
738 __futex_wake_ex(&mutex->state, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700739 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800740
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700741 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800742}
743
Yabin Cui17393b02015-03-21 15:08:25 -0700744int pthread_mutex_trylock(pthread_mutex_t* mutex_interface) {
745 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800746
Yabin Cuie69c2452015-02-13 16:21:25 -0800747 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
748 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800749
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700750 // Handle common case first.
751 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800752 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
753 return NonPI::NormalMutexTryLock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800754 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800755#if defined(__LP64__)
756 if (mtype == MUTEX_TYPE_BITS_WITH_PI) {
757 return PIMutexTryLock(mutex->pi_mutex);
758 }
759#endif
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700760
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700761 // Do we already own this recursive or error-check mutex?
762 pid_t tid = __get_thread()->tid;
Yabin Cuie69c2452015-02-13 16:21:25 -0800763 if (tid == atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed)) {
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700764 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
765 return EBUSY;
766 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800767 return NonPI::RecursiveIncrement(mutex, old_state);
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700768 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700769
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800770 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
771 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
772 const uint16_t locked_uncontended = mtype | shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
773
Yabin Cui86fc96f2015-01-29 21:50:48 -0800774 // Same as pthread_mutex_lock, except that we don't want to wait, and
775 // the only operation that can succeed is a single compare_exchange to acquire the
776 // lock if it is released / not owned by anyone. No need for a complex loop.
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800777 // If exchanged successfully, an acquire fence is required to make
778 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700779 old_state = unlocked;
Yabin Cuie69c2452015-02-13 16:21:25 -0800780 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
781 locked_uncontended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800782 memory_order_acquire,
783 memory_order_relaxed))) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800784 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100785 return 0;
786 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100787 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800788}
789
Elliott Hughes0e714a52014-03-03 16:42:47 -0800790#if !defined(__LP64__)
Yabin Cui17393b02015-03-21 15:08:25 -0700791extern "C" int pthread_mutex_lock_timeout_np(pthread_mutex_t* mutex_interface, unsigned ms) {
Yabin Cuic9a659c2015-11-05 15:36:08 -0800792 timespec ts;
793 timespec_from_ms(ts, ms);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800794 timespec abs_timeout;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800795 absolute_timespec_from_timespec(abs_timeout, ts, CLOCK_MONOTONIC);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800796 int error = NonPI::MutexLockWithTimeout(__get_internal_mutex(mutex_interface), false,
797 &abs_timeout);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800798 if (error == ETIMEDOUT) {
799 error = EBUSY;
800 }
801 return error;
Elliott Hughes0e714a52014-03-03 16:42:47 -0800802}
803#endif
804
Yabin Cui17393b02015-03-21 15:08:25 -0700805int pthread_mutex_timedlock(pthread_mutex_t* mutex_interface, const timespec* abs_timeout) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800806 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
807 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
808 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
809 // Handle common case first.
810 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
811 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
812 if (__predict_true(NonPI::NormalMutexTryLock(mutex, shared) == 0)) {
813 return 0;
814 }
815 }
816#if defined(__LP64__)
817 if (mtype == MUTEX_TYPE_BITS_WITH_PI) {
818 return PIMutexTimedLock(mutex->pi_mutex, abs_timeout);
819 }
820#endif
821 return NonPI::MutexLockWithTimeout(mutex, true, abs_timeout);
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700822}
823
Yabin Cui17393b02015-03-21 15:08:25 -0700824int pthread_mutex_destroy(pthread_mutex_t* mutex_interface) {
Yabin Cui0307eee2015-11-16 20:19:31 -0800825 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
826 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800827#if defined(__LP64__)
828 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
829 if (mtype == MUTEX_TYPE_BITS_WITH_PI) {
830 return PIMutexDestroy(mutex->pi_mutex);
831 }
832#endif
Yabin Cui0307eee2015-11-16 20:19:31 -0800833 // Store 0xffff to make the mutex unusable. Although POSIX standard says it is undefined
834 // behavior to destroy a locked mutex, we prefer not to change mutex->state in that situation.
835 if (MUTEX_STATE_BITS_IS_UNLOCKED(old_state) &&
836 atomic_compare_exchange_strong_explicit(&mutex->state, &old_state, 0xffff,
837 memory_order_relaxed, memory_order_relaxed)) {
838 return 0;
Yabin Cui86fc96f2015-01-29 21:50:48 -0800839 }
Yabin Cui0307eee2015-11-16 20:19:31 -0800840 return EBUSY;
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700841}