blob: e87ff330aecf786616295ef81c2e549872187dbb [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 Cui5a00ba72018-01-26 17:32:31 -080034#include <stdlib.h>
Yabin Cui17393b02015-03-21 15:08:25 -070035#include <string.h>
Yabin Cui86fc96f2015-01-29 21:50:48 -080036#include <sys/cdefs.h>
Elliott Hughes84114c82013-07-17 13:33:19 -070037#include <sys/mman.h>
Pierre Peifferd0c884d2012-02-22 16:40:15 +010038#include <unistd.h>
39
Pierre Peifferd0c884d2012-02-22 16:40:15 +010040#include "pthread_internal.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070041
Elliott Hughes04303f52014-09-18 16:11:59 -070042#include "private/bionic_constants.h"
Yabin Cui9651fdf2018-03-14 12:02:21 -070043#include "private/bionic_fortify.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070044#include "private/bionic_futex.h"
Yabin Cui86fc96f2015-01-29 21:50:48 -080045#include "private/bionic_systrace.h"
Elliott Hughes04303f52014-09-18 16:11:59 -070046#include "private/bionic_time_conversions.h"
Elliott Hugheseb847bc2013-10-09 15:50:50 -070047#include "private/bionic_tls.h"
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080048
Yabin Cuie69c2452015-02-13 16:21:25 -080049/* a mutex attribute holds the following fields
50 *
51 * bits: name description
52 * 0-3 type type of mutex
53 * 4 shared process-shared flag
Yabin Cui6b9c85b2018-01-23 12:56:18 -080054 * 5 protocol whether it is a priority inherit mutex.
Yabin Cuie69c2452015-02-13 16:21:25 -080055 */
56#define MUTEXATTR_TYPE_MASK 0x000f
57#define MUTEXATTR_SHARED_MASK 0x0010
Yabin Cui6b9c85b2018-01-23 12:56:18 -080058#define MUTEXATTR_PROTOCOL_MASK 0x0020
59
60#define MUTEXATTR_PROTOCOL_SHIFT 5
Yabin Cuie69c2452015-02-13 16:21:25 -080061
62int pthread_mutexattr_init(pthread_mutexattr_t *attr)
63{
64 *attr = PTHREAD_MUTEX_DEFAULT;
65 return 0;
66}
67
68int pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
69{
70 *attr = -1;
71 return 0;
72}
73
74int pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type_p)
75{
76 int type = (*attr & MUTEXATTR_TYPE_MASK);
77
78 if (type < PTHREAD_MUTEX_NORMAL || type > PTHREAD_MUTEX_ERRORCHECK) {
79 return EINVAL;
80 }
81
82 *type_p = type;
83 return 0;
84}
85
86int pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
87{
88 if (type < PTHREAD_MUTEX_NORMAL || type > PTHREAD_MUTEX_ERRORCHECK ) {
89 return EINVAL;
90 }
91
92 *attr = (*attr & ~MUTEXATTR_TYPE_MASK) | type;
93 return 0;
94}
95
96/* process-shared mutexes are not supported at the moment */
97
98int pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
99{
100 switch (pshared) {
101 case PTHREAD_PROCESS_PRIVATE:
102 *attr &= ~MUTEXATTR_SHARED_MASK;
103 return 0;
104
105 case PTHREAD_PROCESS_SHARED:
106 /* our current implementation of pthread actually supports shared
107 * mutexes but won't cleanup if a process dies with the mutex held.
108 * Nevertheless, it's better than nothing. Shared mutexes are used
109 * by surfaceflinger and audioflinger.
110 */
111 *attr |= MUTEXATTR_SHARED_MASK;
112 return 0;
113 }
114 return EINVAL;
115}
116
117int pthread_mutexattr_getpshared(const pthread_mutexattr_t* attr, int* pshared) {
118 *pshared = (*attr & MUTEXATTR_SHARED_MASK) ? PTHREAD_PROCESS_SHARED : PTHREAD_PROCESS_PRIVATE;
119 return 0;
120}
121
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800122int pthread_mutexattr_setprotocol(pthread_mutexattr_t* attr, int protocol) {
123 if (protocol != PTHREAD_PRIO_NONE && protocol != PTHREAD_PRIO_INHERIT) {
124 return EINVAL;
125 }
126 *attr = (*attr & ~MUTEXATTR_PROTOCOL_MASK) | (protocol << MUTEXATTR_PROTOCOL_SHIFT);
127 return 0;
128}
129
130int pthread_mutexattr_getprotocol(const pthread_mutexattr_t* attr, int* protocol) {
131 *protocol = (*attr & MUTEXATTR_PROTOCOL_MASK) >> MUTEXATTR_PROTOCOL_SHIFT;
132 return 0;
133}
134
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800135// 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
Yabin Cui9651fdf2018-03-14 12:02:21 -0700175// Inlining this function in pthread_mutex_lock() adds the cost of stack frame instructions on
Yabin Cui5a00ba72018-01-26 17:32:31 -0800176// ARM/ARM64, which increases at most 20 percent overhead. So make it noinline.
177static int __attribute__((noinline)) PIMutexTimedLock(PIMutex& mutex,
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800178 bool use_realtime_clock,
Yabin Cui5a00ba72018-01-26 17:32:31 -0800179 const timespec* abs_timeout) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800180 int ret = PIMutexTryLock(mutex);
181 if (__predict_true(ret == 0)) {
182 return 0;
183 }
184 if (ret == EBUSY) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800185 ScopedTrace trace("Contending for pthread mutex");
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800186 ret = -__futex_pi_lock_ex(&mutex.owner_tid, mutex.shared, use_realtime_clock, abs_timeout);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800187 }
188 return ret;
189}
190
191static int PIMutexUnlock(PIMutex& mutex) {
192 pid_t tid = __get_thread()->tid;
193 int old_owner = tid;
194 // Handle common case first.
195 if (__predict_true(mutex.type == PTHREAD_MUTEX_NORMAL)) {
196 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex.owner_tid,
197 &old_owner, 0,
198 memory_order_release,
199 memory_order_relaxed))) {
200 return 0;
201 }
Ryan Prichardea722a02019-04-18 22:47:04 -0700202 } else {
203 old_owner = atomic_load_explicit(&mutex.owner_tid, memory_order_relaxed);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800204 }
205
206 if (tid != (old_owner & FUTEX_TID_MASK)) {
207 // The mutex can only be unlocked by the thread who owns it.
208 return EPERM;
209 }
210 if (mutex.type == PTHREAD_MUTEX_RECURSIVE) {
211 if (mutex.counter != 0u) {
212 --mutex.counter;
213 return 0;
214 }
215 }
216 if (old_owner == tid) {
217 // No thread is waiting.
218 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex.owner_tid,
219 &old_owner, 0,
220 memory_order_release,
221 memory_order_relaxed))) {
222 return 0;
223 }
224 }
225 return -__futex_pi_unlock(&mutex.owner_tid, mutex.shared);
226}
227
228static int PIMutexDestroy(PIMutex& mutex) {
229 // The mutex should be in unlocked state (owner_tid == 0) when destroyed.
230 // Store 0xffffffff to make the mutex unusable.
231 int old_owner = 0;
232 if (atomic_compare_exchange_strong_explicit(&mutex.owner_tid, &old_owner, 0xffffffff,
233 memory_order_relaxed, memory_order_relaxed)) {
234 return 0;
235 }
236 return EBUSY;
237}
Yabin Cui5a00ba72018-01-26 17:32:31 -0800238
239#if !defined(__LP64__)
240
241namespace PIMutexAllocator {
242// pthread_mutex_t has only 4 bytes in 32-bit programs, which are not enough to hold PIMutex.
243// So we use malloc to allocate PIMutexes and use 16-bit of pthread_mutex_t as indexes to find
244// the allocated PIMutexes. This allows at most 65536 PI mutexes.
245// When calling operations like pthread_mutex_lock/unlock, the 16-bit index is mapped to the
246// corresponding PIMutex. To make the map operation fast, we use a lockless mapping method:
247// Once a PIMutex is allocated, all the data used to map index to the PIMutex isn't changed until
248// it is destroyed.
249// Below are the data structures:
250// // struct Node contains a PIMutex.
251// typedef Node NodeArray[256];
252// typedef NodeArray* NodeArrayP;
253// NodeArrayP nodes[256];
254//
255// A 16-bit index is mapped to Node as below:
256// (*nodes[index >> 8])[index & 0xff]
257//
258// Also use a free list to allow O(1) finding recycled PIMutexes.
259
260union Node {
261 PIMutex mutex;
262 int next_free_id; // If not -1, refer to the next node in the free PIMutex list.
263};
264typedef Node NodeArray[256];
265typedef NodeArray* NodeArrayP;
266
267// lock_ protects below items.
268static Lock lock;
269static NodeArrayP* nodes;
270static int next_to_alloc_id;
271static int first_free_id = -1; // If not -1, refer to the first node in the free PIMutex list.
272
273static inline __always_inline Node& IdToNode(int id) {
274 return (*nodes[id >> 8])[id & 0xff];
275}
276
277static inline __always_inline PIMutex& IdToPIMutex(int id) {
278 return IdToNode(id).mutex;
279}
280
281static int AllocIdLocked() {
282 if (first_free_id != -1) {
283 int result = first_free_id;
284 first_free_id = IdToNode(result).next_free_id;
285 return result;
286 }
287 if (next_to_alloc_id >= 0x10000) {
288 return -1;
289 }
290 int array_pos = next_to_alloc_id >> 8;
291 int node_pos = next_to_alloc_id & 0xff;
292 if (node_pos == 0) {
293 if (array_pos == 0) {
294 nodes = static_cast<NodeArray**>(calloc(256, sizeof(NodeArray*)));
295 if (nodes == nullptr) {
296 return -1;
297 }
298 }
299 nodes[array_pos] = static_cast<NodeArray*>(malloc(sizeof(NodeArray)));
300 if (nodes[array_pos] == nullptr) {
301 return -1;
302 }
303 }
304 return next_to_alloc_id++;
305}
306
307// If succeed, return an id referring to a PIMutex, otherwise return -1.
308// A valid id is in range [0, 0xffff].
309static int AllocId() {
310 lock.lock();
311 int result = AllocIdLocked();
312 lock.unlock();
313 if (result != -1) {
314 memset(&IdToPIMutex(result), 0, sizeof(PIMutex));
315 }
316 return result;
317}
318
319static void FreeId(int id) {
320 lock.lock();
321 IdToNode(id).next_free_id = first_free_id;
322 first_free_id = id;
323 lock.unlock();
324}
325
326} // namespace PIMutexAllocator
327
328#endif // !defined(__LP64__)
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800329
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800330
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100331/* Convenience macro, creates a mask of 'bits' bits that starts from
332 * the 'shift'-th least significant bit in a 32-bit word.
333 *
334 * Examples: FIELD_MASK(0,4) -> 0xf
335 * FIELD_MASK(16,9) -> 0x1ff0000
336 */
337#define FIELD_MASK(shift,bits) (((1 << (bits))-1) << (shift))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800338
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100339/* This one is used to create a bit pattern from a given field value */
340#define FIELD_TO_BITS(val,shift,bits) (((val) & ((1 << (bits))-1)) << (shift))
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100341
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100342/* And this one does the opposite, i.e. extract a field's value from a bit pattern */
343#define FIELD_FROM_BITS(val,shift,bits) (((val) >> (shift)) & ((1 << (bits))-1))
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800344
Yabin Cuie69c2452015-02-13 16:21:25 -0800345/* Convenience macros.
346 *
347 * These are used to form or modify the bit pattern of a given mutex value
348 */
349
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100350/* Mutex state:
351 *
352 * 0 for unlocked
353 * 1 for locked, no waiters
354 * 2 for locked, maybe waiters
355 */
356#define MUTEX_STATE_SHIFT 0
357#define MUTEX_STATE_LEN 2
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800358
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100359#define MUTEX_STATE_MASK FIELD_MASK(MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
360#define MUTEX_STATE_FROM_BITS(v) FIELD_FROM_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
361#define MUTEX_STATE_TO_BITS(v) FIELD_TO_BITS(v, MUTEX_STATE_SHIFT, MUTEX_STATE_LEN)
362
Yabin Cui17393b02015-03-21 15:08:25 -0700363#define MUTEX_STATE_UNLOCKED 0 /* must be 0 to match PTHREAD_MUTEX_INITIALIZER */
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100364#define MUTEX_STATE_LOCKED_UNCONTENDED 1 /* must be 1 due to atomic dec in unlock operation */
365#define MUTEX_STATE_LOCKED_CONTENDED 2 /* must be 1 + LOCKED_UNCONTENDED due to atomic dec */
366
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100367#define MUTEX_STATE_BITS_UNLOCKED MUTEX_STATE_TO_BITS(MUTEX_STATE_UNLOCKED)
368#define MUTEX_STATE_BITS_LOCKED_UNCONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_UNCONTENDED)
369#define MUTEX_STATE_BITS_LOCKED_CONTENDED MUTEX_STATE_TO_BITS(MUTEX_STATE_LOCKED_CONTENDED)
370
Yabin Cui0307eee2015-11-16 20:19:31 -0800371// Return true iff the mutex is unlocked.
372#define MUTEX_STATE_BITS_IS_UNLOCKED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_UNLOCKED)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100373
Yabin Cui0307eee2015-11-16 20:19:31 -0800374// Return true iff the mutex is locked with no waiters.
375#define MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(v) (((v) & MUTEX_STATE_MASK) == MUTEX_STATE_BITS_LOCKED_UNCONTENDED)
376
377// return true iff the mutex is locked with maybe waiters.
378#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 +0100379
380/* used to flip from LOCKED_UNCONTENDED to LOCKED_CONTENDED */
381#define MUTEX_STATE_BITS_FLIP_CONTENTION(v) ((v) ^ (MUTEX_STATE_BITS_LOCKED_CONTENDED ^ MUTEX_STATE_BITS_LOCKED_UNCONTENDED))
382
383/* Mutex counter:
384 *
385 * We need to check for overflow before incrementing, and we also need to
386 * detect when the counter is 0
387 */
388#define MUTEX_COUNTER_SHIFT 2
389#define MUTEX_COUNTER_LEN 11
390#define MUTEX_COUNTER_MASK FIELD_MASK(MUTEX_COUNTER_SHIFT, MUTEX_COUNTER_LEN)
391
392#define MUTEX_COUNTER_BITS_WILL_OVERFLOW(v) (((v) & MUTEX_COUNTER_MASK) == MUTEX_COUNTER_MASK)
393#define MUTEX_COUNTER_BITS_IS_ZERO(v) (((v) & MUTEX_COUNTER_MASK) == 0)
394
395/* Used to increment the counter directly after overflow has been checked */
Yabin Cui86fc96f2015-01-29 21:50:48 -0800396#define MUTEX_COUNTER_BITS_ONE FIELD_TO_BITS(1, MUTEX_COUNTER_SHIFT,MUTEX_COUNTER_LEN)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100397
398/* Mutex shared bit flag
399 *
400 * This flag is set to indicate that the mutex is shared among processes.
401 * This changes the futex opcode we use for futex wait/wake operations
402 * (non-shared operations are much faster).
403 */
404#define MUTEX_SHARED_SHIFT 13
405#define MUTEX_SHARED_MASK FIELD_MASK(MUTEX_SHARED_SHIFT,1)
406
407/* Mutex type:
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100408 * We support normal, recursive and errorcheck mutexes.
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100409 */
410#define MUTEX_TYPE_SHIFT 14
411#define MUTEX_TYPE_LEN 2
412#define MUTEX_TYPE_MASK FIELD_MASK(MUTEX_TYPE_SHIFT,MUTEX_TYPE_LEN)
413
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100414#define MUTEX_TYPE_TO_BITS(t) FIELD_TO_BITS(t, MUTEX_TYPE_SHIFT, MUTEX_TYPE_LEN)
415
Yabin Cui17393b02015-03-21 15:08:25 -0700416#define MUTEX_TYPE_BITS_NORMAL MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_NORMAL)
417#define MUTEX_TYPE_BITS_RECURSIVE MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_RECURSIVE)
418#define MUTEX_TYPE_BITS_ERRORCHECK MUTEX_TYPE_TO_BITS(PTHREAD_MUTEX_ERRORCHECK)
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800419// Use a special mutex type to mark priority inheritance mutexes.
Yabin Cui9651fdf2018-03-14 12:02:21 -0700420#define PI_MUTEX_STATE MUTEX_TYPE_TO_BITS(3)
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100421
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800422// For a PI mutex, it includes below fields:
423// Atomic(uint16_t) state;
Yabin Cui5a00ba72018-01-26 17:32:31 -0800424// PIMutex pi_mutex; // uint16_t pi_mutex_id in 32-bit programs
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800425//
426// state holds the following fields:
427//
428// bits: name description
429// 15-14 type mutex type, should be 3
Yabin Cui9651fdf2018-03-14 12:02:21 -0700430// 13-0 padding should be 0
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800431//
432// pi_mutex holds the state of a PI mutex.
Yabin Cui5a00ba72018-01-26 17:32:31 -0800433// pi_mutex_id holds an integer to find the state of a PI mutex.
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800434//
435// For a Non-PI mutex, it includes below fields:
436// Atomic(uint16_t) state;
437// atomic_int owner_tid; // Atomic(uint16_t) in 32-bit programs
438//
439// state holds the following fields:
440//
441// bits: name description
442// 15-14 type mutex type, can be 0 (normal), 1 (recursive), 2 (errorcheck)
443// 13 shared process-shared flag
444// 12-2 counter <number of times a thread holding a recursive Non-PI mutex> - 1
445// 1-0 state lock state (0, 1 or 2)
446//
447// bits 15-13 are constant during the lifetime of the mutex.
448//
449// owner_tid is used only in recursive and errorcheck Non-PI mutexes to hold the mutex owner
450// thread id.
451//
452// PI mutexes and Non-PI mutexes are distinguished by checking type field in state.
Yabin Cui17393b02015-03-21 15:08:25 -0700453#if defined(__LP64__)
Yabin Cui5a00ba72018-01-26 17:32:31 -0800454struct pthread_mutex_internal_t {
455 _Atomic(uint16_t) state;
456 uint16_t __pad;
457 union {
458 atomic_int owner_tid;
459 PIMutex pi_mutex;
460 };
461 char __reserved[28];
462
463 PIMutex& ToPIMutex() {
464 return pi_mutex;
465 }
466
467 void FreePIMutex() {
468 }
Yabin Cuie69c2452015-02-13 16:21:25 -0800469} __attribute__((aligned(4)));
Yabin Cui86fc96f2015-01-29 21:50:48 -0800470
Yabin Cui5a00ba72018-01-26 17:32:31 -0800471#else
472struct pthread_mutex_internal_t {
473 _Atomic(uint16_t) state;
474 union {
475 _Atomic(uint16_t) owner_tid;
476 uint16_t pi_mutex_id;
477 };
478
479 PIMutex& ToPIMutex() {
480 return PIMutexAllocator::IdToPIMutex(pi_mutex_id);
481 }
482
483 void FreePIMutex() {
484 PIMutexAllocator::FreeId(pi_mutex_id);
485 }
486} __attribute__((aligned(4)));
487#endif
488
Yabin Cui17393b02015-03-21 15:08:25 -0700489static_assert(sizeof(pthread_mutex_t) == sizeof(pthread_mutex_internal_t),
490 "pthread_mutex_t should actually be pthread_mutex_internal_t in implementation.");
491
492// For binary compatibility with old version of pthread_mutex_t, we can't use more strict alignment
493// than 4-byte alignment.
494static_assert(alignof(pthread_mutex_t) == 4,
495 "pthread_mutex_t should fulfill the alignment of pthread_mutex_internal_t.");
496
497static inline pthread_mutex_internal_t* __get_internal_mutex(pthread_mutex_t* mutex_interface) {
498 return reinterpret_cast<pthread_mutex_internal_t*>(mutex_interface);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800499}
500
Yabin Cui17393b02015-03-21 15:08:25 -0700501int pthread_mutex_init(pthread_mutex_t* mutex_interface, const pthread_mutexattr_t* attr) {
502 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
503
504 memset(mutex, 0, sizeof(pthread_mutex_internal_t));
Yabin Cui86fc96f2015-01-29 21:50:48 -0800505
Yi Kong32bc0fc2018-08-02 17:31:13 -0700506 if (__predict_true(attr == nullptr)) {
Yabin Cui17393b02015-03-21 15:08:25 -0700507 atomic_init(&mutex->state, MUTEX_TYPE_BITS_NORMAL);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700508 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800509 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700510
Yabin Cuie69c2452015-02-13 16:21:25 -0800511 uint16_t state = 0;
Elliott Hughesdff72032013-12-11 14:54:00 -0800512 if ((*attr & MUTEXATTR_SHARED_MASK) != 0) {
Yabin Cui17393b02015-03-21 15:08:25 -0700513 state |= MUTEX_SHARED_MASK;
Elliott Hughesdff72032013-12-11 14:54:00 -0800514 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700515
516 switch (*attr & MUTEXATTR_TYPE_MASK) {
517 case PTHREAD_MUTEX_NORMAL:
Yabin Cuie69c2452015-02-13 16:21:25 -0800518 state |= MUTEX_TYPE_BITS_NORMAL;
519 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700520 case PTHREAD_MUTEX_RECURSIVE:
Yabin Cuie69c2452015-02-13 16:21:25 -0800521 state |= MUTEX_TYPE_BITS_RECURSIVE;
522 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700523 case PTHREAD_MUTEX_ERRORCHECK:
Yabin Cuie69c2452015-02-13 16:21:25 -0800524 state |= MUTEX_TYPE_BITS_ERRORCHECK;
525 break;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700526 default:
527 return EINVAL;
528 }
529
nx11161715062018-10-03 16:58:19 +0800530 if (((*attr & MUTEXATTR_PROTOCOL_MASK) >> MUTEXATTR_PROTOCOL_SHIFT) == PTHREAD_PRIO_INHERIT
531 && android_get_application_target_sdk_version() >= __ANDROID_API_P__) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800532#if !defined(__LP64__)
533 if (state & MUTEX_SHARED_MASK) {
534 return EINVAL;
535 }
536 int id = PIMutexAllocator::AllocId();
537 if (id == -1) {
538 return ENOMEM;
539 }
540 mutex->pi_mutex_id = id;
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800541#endif
Yabin Cui9651fdf2018-03-14 12:02:21 -0700542 atomic_init(&mutex->state, PI_MUTEX_STATE);
Yabin Cui5a00ba72018-01-26 17:32:31 -0800543 PIMutex& pi_mutex = mutex->ToPIMutex();
544 pi_mutex.type = *attr & MUTEXATTR_TYPE_MASK;
545 pi_mutex.shared = (*attr & MUTEXATTR_SHARED_MASK) != 0;
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800546 } else {
547 atomic_init(&mutex->state, state);
548 atomic_init(&mutex->owner_tid, 0);
549 }
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700550 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800551}
552
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800553// namespace for Non-PI mutex routines.
554namespace NonPI {
555
556static inline __always_inline int NormalMutexTryLock(pthread_mutex_internal_t* mutex,
557 uint16_t shared) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800558 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
559 const uint16_t locked_uncontended = shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800560
Yabin Cuie69c2452015-02-13 16:21:25 -0800561 uint16_t old_state = unlocked;
Yabin Cui17393b02015-03-21 15:08:25 -0700562 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
563 locked_uncontended, memory_order_acquire, memory_order_relaxed))) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800564 return 0;
565 }
566 return EBUSY;
567}
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800568
569/*
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800570 * Lock a normal Non-PI mutex.
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800571 *
572 * As noted above, there are three states:
573 * 0 (unlocked, no contention)
574 * 1 (locked, no contention)
575 * 2 (locked, contention)
576 *
577 * Non-recursive mutexes don't use the thread-id or counter fields, and the
578 * "type" value is zero, so the only bits that will be set are the ones in
579 * the lock state field.
580 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800581static inline __always_inline int NormalMutexLock(pthread_mutex_internal_t* mutex,
582 uint16_t shared,
583 bool use_realtime_clock,
584 const timespec* abs_timeout_or_null) {
585 if (__predict_true(NormalMutexTryLock(mutex, shared) == 0)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800586 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800587 }
Elliott Hughesdd586f22015-12-16 15:15:58 -0800588 int result = check_timespec(abs_timeout_or_null, true);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800589 if (result != 0) {
590 return result;
591 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800592
593 ScopedTrace trace("Contending for pthread mutex");
594
Yabin Cuie69c2452015-02-13 16:21:25 -0800595 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
596 const uint16_t locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800597
Yabin Cui86fc96f2015-01-29 21:50:48 -0800598 // We want to go to sleep until the mutex is available, which requires
599 // promoting it to locked_contended. We need to swap in the new state
Yabin Cui17393b02015-03-21 15:08:25 -0700600 // and then wait until somebody wakes us up.
Yabin Cui86fc96f2015-01-29 21:50:48 -0800601 // An atomic_exchange is used to compete with other threads for the lock.
602 // If it returns unlocked, we have acquired the lock, otherwise another
603 // thread still holds the lock and we should wait again.
604 // If lock is acquired, an acquire fence is needed to make all memory accesses
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800605 // made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700606 while (atomic_exchange_explicit(&mutex->state, locked_contended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800607 memory_order_acquire) != unlocked) {
Yabin Cuic9a659c2015-11-05 15:36:08 -0800608 if (__futex_wait_ex(&mutex->state, shared, locked_contended, use_realtime_clock,
609 abs_timeout_or_null) == -ETIMEDOUT) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800610 return ETIMEDOUT;
611 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800612 }
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800613 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800614}
615
616/*
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800617 * Release a normal Non-PI mutex. The caller is responsible for determining
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800618 * that we are in fact the owner of this lock.
619 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800620static inline __always_inline void NormalMutexUnlock(pthread_mutex_internal_t* mutex,
621 uint16_t shared) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800622 const uint16_t unlocked = shared | MUTEX_STATE_BITS_UNLOCKED;
623 const uint16_t locked_contended = shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
Andy McFaddenfcd00eb2010-05-28 13:31:45 -0700624
Yabin Cui86fc96f2015-01-29 21:50:48 -0800625 // We use an atomic_exchange to release the lock. If locked_contended state
626 // is returned, some threads is waiting for the lock and we need to wake up
627 // one of them.
628 // A release fence is required to make previous stores visible to next
629 // lock owner threads.
Yabin Cui17393b02015-03-21 15:08:25 -0700630 if (atomic_exchange_explicit(&mutex->state, unlocked,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800631 memory_order_release) == locked_contended) {
632 // Wake up one waiting thread. We don't know which thread will be
633 // woken or when it'll start executing -- futexes make no guarantees
634 // here. There may not even be a thread waiting.
635 //
636 // The newly-woken thread will replace the unlocked state we just set above
637 // with locked_contended state, which means that when it eventually releases
638 // the mutex it will also call FUTEX_WAKE. This results in one extra wake
639 // call whenever a lock is contended, but let us avoid forgetting anyone
640 // without requiring us to track the number of sleepers.
641 //
642 // It's possible for another thread to sneak in and grab the lock between
643 // the exchange above and the wake call below. If the new thread is "slow"
644 // and holds the lock for a while, we'll wake up a sleeper, which will swap
645 // in locked_uncontended state and then go back to sleep since the lock is
646 // still held. If the new thread is "fast", running to completion before
647 // we call wake, the thread we eventually wake will find an unlocked mutex
648 // and will execute. Either way we have correct behavior and nobody is
649 // orphaned on the wait queue.
Yabin Cui17393b02015-03-21 15:08:25 -0700650 __futex_wake_ex(&mutex->state, shared, 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800651 }
652}
653
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800654/* This common inlined function is used to increment the counter of a recursive Non-PI mutex.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100655 *
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800656 * If the counter overflows, it will return EAGAIN.
657 * Otherwise, it atomically increments the counter and returns 0.
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100658 *
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100659 */
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800660static inline __always_inline int RecursiveIncrement(pthread_mutex_internal_t* mutex,
661 uint16_t old_state) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800662 // Detect recursive lock overflow and return EAGAIN.
663 // This is safe because only the owner thread can modify the
664 // counter bits in the mutex value.
Yabin Cui17393b02015-03-21 15:08:25 -0700665 if (MUTEX_COUNTER_BITS_WILL_OVERFLOW(old_state)) {
David 'Digit' Turner022d3032011-12-07 14:02:17 +0100666 return EAGAIN;
667 }
668
Yabin Cuie69c2452015-02-13 16:21:25 -0800669 // Other threads are able to change the lower bits (e.g. promoting it to "contended"),
670 // but the mutex counter will not overflow. So we use atomic_fetch_add operation here.
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800671 // The mutex is already locked by current thread, so we don't need an acquire fence.
Yabin Cui17393b02015-03-21 15:08:25 -0700672 atomic_fetch_add_explicit(&mutex->state, MUTEX_COUNTER_BITS_ONE, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800673 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800674}
675
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800676// Wait on a recursive or errorcheck Non-PI mutex.
677static inline __always_inline int RecursiveOrErrorcheckMutexWait(pthread_mutex_internal_t* mutex,
678 uint16_t shared,
679 uint16_t old_state,
680 bool use_realtime_clock,
681 const timespec* abs_timeout) {
Yabin Cuif7969852015-04-02 17:47:48 -0700682// __futex_wait always waits on a 32-bit value. But state is 16-bit. For a normal mutex, the owner_tid
683// field in mutex is not used. On 64-bit devices, the __pad field in mutex is not used.
684// But when a recursive or errorcheck mutex is used on 32-bit devices, we need to add the
685// owner_tid value in the value argument for __futex_wait, otherwise we may always get EAGAIN error.
686
687#if defined(__LP64__)
Yabin Cuic9a659c2015-11-05 15:36:08 -0800688 return __futex_wait_ex(&mutex->state, shared, old_state, use_realtime_clock, abs_timeout);
Yabin Cuif7969852015-04-02 17:47:48 -0700689
690#else
691 // This implementation works only when the layout of pthread_mutex_internal_t matches below expectation.
692 // And it is based on the assumption that Android is always in little-endian devices.
693 static_assert(offsetof(pthread_mutex_internal_t, state) == 0, "");
694 static_assert(offsetof(pthread_mutex_internal_t, owner_tid) == 2, "");
695
696 uint32_t owner_tid = atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800697 return __futex_wait_ex(&mutex->state, shared, (owner_tid << 16) | old_state,
698 use_realtime_clock, abs_timeout);
Yabin Cuif7969852015-04-02 17:47:48 -0700699#endif
700}
701
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800702// Lock a Non-PI mutex.
703static int MutexLockWithTimeout(pthread_mutex_internal_t* mutex, bool use_realtime_clock,
704 const timespec* abs_timeout_or_null) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800705 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
706 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
707 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
Fabrice Di Meglio86418332010-03-11 14:47:47 -0800708
Yabin Cui86fc96f2015-01-29 21:50:48 -0800709 // Handle common case first.
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700710 if ( __predict_true(mtype == MUTEX_TYPE_BITS_NORMAL) ) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800711 return NormalMutexLock(mutex, shared, use_realtime_clock, abs_timeout_or_null);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800712 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700713
Yabin Cui86fc96f2015-01-29 21:50:48 -0800714 // Do we already own this recursive or error-check mutex?
Yabin Cuie69c2452015-02-13 16:21:25 -0800715 pid_t tid = __get_thread()->tid;
716 if (tid == atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800717 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
718 return EDEADLK;
719 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800720 return RecursiveIncrement(mutex, old_state);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800721 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700722
Yabin Cuie69c2452015-02-13 16:21:25 -0800723 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
724 const uint16_t locked_uncontended = mtype | shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
725 const uint16_t locked_contended = mtype | shared | MUTEX_STATE_BITS_LOCKED_CONTENDED;
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700726
Yabin Cui86fc96f2015-01-29 21:50:48 -0800727 // First, if the mutex is unlocked, try to quickly acquire it.
728 // In the optimistic case where this works, set the state to locked_uncontended.
Yabin Cui17393b02015-03-21 15:08:25 -0700729 if (old_state == unlocked) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800730 // If exchanged successfully, an acquire fence is required to make
731 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700732 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
Yabin Cuie69c2452015-02-13 16:21:25 -0800733 locked_uncontended, memory_order_acquire, memory_order_relaxed))) {
734 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100735 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700736 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700737 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100738
Brigid Smitha406ee62014-07-21 15:38:06 -0700739 ScopedTrace trace("Contending for pthread mutex");
740
Yabin Cui86fc96f2015-01-29 21:50:48 -0800741 while (true) {
Yabin Cui17393b02015-03-21 15:08:25 -0700742 if (old_state == unlocked) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800743 // NOTE: We put the state to locked_contended since we _know_ there
744 // is contention when we are in this loop. This ensures all waiters
745 // will be unlocked.
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100746
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800747 // If exchanged successfully, an acquire fence is required to make
748 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700749 if (__predict_true(atomic_compare_exchange_weak_explicit(&mutex->state,
Yabin Cuie69c2452015-02-13 16:21:25 -0800750 &old_state, locked_contended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800751 memory_order_acquire,
752 memory_order_relaxed))) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800753 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800754 return 0;
755 }
756 continue;
Yabin Cui17393b02015-03-21 15:08:25 -0700757 } else if (MUTEX_STATE_BITS_IS_LOCKED_UNCONTENDED(old_state)) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800758 // We should set it to locked_contended beforing going to sleep. This can make
Yabin Cui86fc96f2015-01-29 21:50:48 -0800759 // sure waiters will be woken up eventually.
760
Yabin Cui17393b02015-03-21 15:08:25 -0700761 int new_state = MUTEX_STATE_BITS_FLIP_CONTENTION(old_state);
762 if (__predict_false(!atomic_compare_exchange_weak_explicit(&mutex->state,
763 &old_state, new_state,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800764 memory_order_relaxed,
765 memory_order_relaxed))) {
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100766 continue;
767 }
Yabin Cui17393b02015-03-21 15:08:25 -0700768 old_state = new_state;
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100769 }
770
Elliott Hughesdd586f22015-12-16 15:15:58 -0800771 int result = check_timespec(abs_timeout_or_null, true);
Yabin Cuic9a659c2015-11-05 15:36:08 -0800772 if (result != 0) {
773 return result;
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800774 }
Yabin Cuic9a659c2015-11-05 15:36:08 -0800775 // We are in locked_contended state, sleep until someone wakes us up.
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800776 if (RecursiveOrErrorcheckMutexWait(mutex, shared, old_state, use_realtime_clock,
777 abs_timeout_or_null) == -ETIMEDOUT) {
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800778 return ETIMEDOUT;
779 }
Yabin Cui17393b02015-03-21 15:08:25 -0700780 old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100781 }
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800782}
783
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800784} // namespace NonPI
785
Yabin Cui9651fdf2018-03-14 12:02:21 -0700786// Inlining this function in pthread_mutex_lock() adds the cost of stack frame instructions on
787// ARM64. So make it noinline.
nx11161715062018-10-03 16:58:19 +0800788static bool __attribute__((noinline)) IsMutexDestroyed(uint16_t mutex_state) {
789 // Checking for mutex destruction is a P-specific behavior. Bypass the
790 // check if the SDK version precedes P, so that no change in behavior
791 // that may cause crashes is introduced.
Elliott Hughesc0f46562018-11-09 15:38:52 -0800792 if (android_get_application_target_sdk_version() >= __ANDROID_API_P__) {
nx11161715062018-10-03 16:58:19 +0800793 return mutex_state == 0xffff;
794 } else {
795 return false;
Yabin Cui9651fdf2018-03-14 12:02:21 -0700796 }
nx11161715062018-10-03 16:58:19 +0800797}
798
799static int __always_inline HandleUsingDestroyedMutex(pthread_mutex_t* mutex,
800 const char* function_name) {
801 __fortify_fatal("%s called on a destroyed mutex (%p)", function_name, mutex);
Yabin Cui9651fdf2018-03-14 12:02:21 -0700802 return EBUSY;
803}
804
Yabin Cui17393b02015-03-21 15:08:25 -0700805int pthread_mutex_lock(pthread_mutex_t* mutex_interface) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700806#if !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -0700807 // Some apps depend on being able to pass NULL as a mutex and get EINVAL
808 // back. Don't need to worry about it for LP64 since the ABI is brand new,
809 // but keep compatibility for LP32. http://b/19995172.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700810 if (mutex_interface == nullptr) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700811 return EINVAL;
812 }
813#endif
814
Yabin Cui17393b02015-03-21 15:08:25 -0700815 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cuie69c2452015-02-13 16:21:25 -0800816 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
817 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800818 // Avoid slowing down fast path of normal mutex lock operation.
819 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800820 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
821 if (__predict_true(NonPI::NormalMutexTryLock(mutex, shared) == 0)) {
822 return 0;
823 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700824 }
825 if (old_state == PI_MUTEX_STATE) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800826 PIMutex& m = mutex->ToPIMutex();
827 // Handle common case first.
828 if (__predict_true(PIMutexTryLock(m) == 0)) {
829 return 0;
830 }
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800831 return PIMutexTimedLock(mutex->ToPIMutex(), false, nullptr);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800832 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700833 if (__predict_false(IsMutexDestroyed(old_state))) {
834 return HandleUsingDestroyedMutex(mutex_interface, __FUNCTION__);
835 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800836 return NonPI::MutexLockWithTimeout(mutex, false, nullptr);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800837}
838
Yabin Cui17393b02015-03-21 15:08:25 -0700839int pthread_mutex_unlock(pthread_mutex_t* mutex_interface) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700840#if !defined(__LP64__)
Dan Albertbaa2a972015-08-13 16:58:50 -0700841 // Some apps depend on being able to pass NULL as a mutex and get EINVAL
842 // back. Don't need to worry about it for LP64 since the ABI is brand new,
843 // but keep compatibility for LP32. http://b/19995172.
Yi Kong32bc0fc2018-08-02 17:31:13 -0700844 if (mutex_interface == nullptr) {
Christopher Ferris511cfd92015-06-09 18:46:15 -0700845 return EINVAL;
846 }
847#endif
848
Yabin Cui17393b02015-03-21 15:08:25 -0700849 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cuie69c2452015-02-13 16:21:25 -0800850 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
851 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
852 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800853
Yabin Cui86fc96f2015-01-29 21:50:48 -0800854 // Handle common case first.
Elliott Hughesd4e753f2013-07-16 12:45:46 -0700855 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800856 NonPI::NormalMutexUnlock(mutex, shared);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800857 return 0;
858 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700859 if (old_state == PI_MUTEX_STATE) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800860 return PIMutexUnlock(mutex->ToPIMutex());
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800861 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700862 if (__predict_false(IsMutexDestroyed(old_state))) {
863 return HandleUsingDestroyedMutex(mutex_interface, __FUNCTION__);
864 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700865
Yabin Cui86fc96f2015-01-29 21:50:48 -0800866 // Do we already own this recursive or error-check mutex?
Yabin Cuie69c2452015-02-13 16:21:25 -0800867 pid_t tid = __get_thread()->tid;
868 if ( tid != atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed) ) {
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700869 return EPERM;
Yabin Cuie69c2452015-02-13 16:21:25 -0800870 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700871
Yabin Cui86fc96f2015-01-29 21:50:48 -0800872 // If the counter is > 0, we can simply decrement it atomically.
873 // Since other threads can mutate the lower state bits (and only the
874 // lower state bits), use a compare_exchange loop to do it.
Yabin Cui17393b02015-03-21 15:08:25 -0700875 if (!MUTEX_COUNTER_BITS_IS_ZERO(old_state)) {
Yabin Cui86fc96f2015-01-29 21:50:48 -0800876 // We still own the mutex, so a release fence is not needed.
Yabin Cui17393b02015-03-21 15:08:25 -0700877 atomic_fetch_sub_explicit(&mutex->state, MUTEX_COUNTER_BITS_ONE, memory_order_relaxed);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800878 return 0;
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700879 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100880
Yabin Cui86fc96f2015-01-29 21:50:48 -0800881 // The counter is 0, so we'are going to unlock the mutex by resetting its
882 // state to unlocked, we need to perform a atomic_exchange inorder to read
883 // the current state, which will be locked_contended if there may have waiters
884 // to awake.
885 // A release fence is required to make previous stores visible to next
886 // lock owner threads.
Yabin Cuie69c2452015-02-13 16:21:25 -0800887 atomic_store_explicit(&mutex->owner_tid, 0, memory_order_relaxed);
888 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
Yabin Cui17393b02015-03-21 15:08:25 -0700889 old_state = atomic_exchange_explicit(&mutex->state, unlocked, memory_order_release);
890 if (MUTEX_STATE_BITS_IS_LOCKED_CONTENDED(old_state)) {
891 __futex_wake_ex(&mutex->state, shared, 1);
David 'Digit' Turner88f06cd2010-03-18 17:13:41 -0700892 }
Yabin Cui86fc96f2015-01-29 21:50:48 -0800893
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700894 return 0;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800895}
896
Yabin Cui17393b02015-03-21 15:08:25 -0700897int pthread_mutex_trylock(pthread_mutex_t* mutex_interface) {
898 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800899
Yabin Cuie69c2452015-02-13 16:21:25 -0800900 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
901 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800902
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700903 // Handle common case first.
904 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800905 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
906 return NonPI::NormalMutexTryLock(mutex, shared);
David 'Digit' Turnerba9c6f02010-03-10 16:44:08 -0800907 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700908 if (old_state == PI_MUTEX_STATE) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800909 return PIMutexTryLock(mutex->ToPIMutex());
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800910 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700911 if (__predict_false(IsMutexDestroyed(old_state))) {
912 return HandleUsingDestroyedMutex(mutex_interface, __FUNCTION__);
913 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700914
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700915 // Do we already own this recursive or error-check mutex?
916 pid_t tid = __get_thread()->tid;
Yabin Cuie69c2452015-02-13 16:21:25 -0800917 if (tid == atomic_load_explicit(&mutex->owner_tid, memory_order_relaxed)) {
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700918 if (mtype == MUTEX_TYPE_BITS_ERRORCHECK) {
919 return EBUSY;
920 }
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800921 return NonPI::RecursiveIncrement(mutex, old_state);
Elliott Hughes5b1111a2014-10-24 19:33:11 -0700922 }
David 'Digit' Turner40e6b822010-03-17 11:25:46 -0700923
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800924 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
925 const uint16_t unlocked = mtype | shared | MUTEX_STATE_BITS_UNLOCKED;
926 const uint16_t locked_uncontended = mtype | shared | MUTEX_STATE_BITS_LOCKED_UNCONTENDED;
927
Yabin Cui86fc96f2015-01-29 21:50:48 -0800928 // Same as pthread_mutex_lock, except that we don't want to wait, and
929 // the only operation that can succeed is a single compare_exchange to acquire the
930 // lock if it is released / not owned by anyone. No need for a complex loop.
Yabin Cui5b8e7cd2015-03-04 17:36:59 -0800931 // If exchanged successfully, an acquire fence is required to make
932 // all memory accesses made by other threads visible to the current CPU.
Yabin Cui17393b02015-03-21 15:08:25 -0700933 old_state = unlocked;
Yabin Cuie69c2452015-02-13 16:21:25 -0800934 if (__predict_true(atomic_compare_exchange_strong_explicit(&mutex->state, &old_state,
935 locked_uncontended,
Yabin Cui86fc96f2015-01-29 21:50:48 -0800936 memory_order_acquire,
937 memory_order_relaxed))) {
Yabin Cuie69c2452015-02-13 16:21:25 -0800938 atomic_store_explicit(&mutex->owner_tid, tid, memory_order_relaxed);
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100939 return 0;
940 }
David 'Digit' Turnere1414aa2012-01-24 15:26:54 +0100941 return EBUSY;
The Android Open Source Project1dc9e472009-03-03 19:28:35 -0800942}
943
Elliott Hughes0e714a52014-03-03 16:42:47 -0800944#if !defined(__LP64__)
Yabin Cui17393b02015-03-21 15:08:25 -0700945extern "C" int pthread_mutex_lock_timeout_np(pthread_mutex_t* mutex_interface, unsigned ms) {
Yabin Cuic9a659c2015-11-05 15:36:08 -0800946 timespec ts;
947 timespec_from_ms(ts, ms);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800948 timespec abs_timeout;
Yabin Cuic9a659c2015-11-05 15:36:08 -0800949 absolute_timespec_from_timespec(abs_timeout, ts, CLOCK_MONOTONIC);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800950 int error = NonPI::MutexLockWithTimeout(__get_internal_mutex(mutex_interface), false,
951 &abs_timeout);
Yabin Cui86fc96f2015-01-29 21:50:48 -0800952 if (error == ETIMEDOUT) {
953 error = EBUSY;
954 }
955 return error;
Elliott Hughes0e714a52014-03-03 16:42:47 -0800956}
957#endif
958
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800959static int __pthread_mutex_timedlock(pthread_mutex_t* mutex_interface, bool use_realtime_clock,
960 const timespec* abs_timeout, const char* function) {
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800961 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
962 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
963 uint16_t mtype = (old_state & MUTEX_TYPE_MASK);
964 // Handle common case first.
965 if (__predict_true(mtype == MUTEX_TYPE_BITS_NORMAL)) {
966 uint16_t shared = (old_state & MUTEX_SHARED_MASK);
967 if (__predict_true(NonPI::NormalMutexTryLock(mutex, shared) == 0)) {
968 return 0;
969 }
970 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700971 if (old_state == PI_MUTEX_STATE) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800972 return PIMutexTimedLock(mutex->ToPIMutex(), use_realtime_clock, abs_timeout);
Yabin Cui6b9c85b2018-01-23 12:56:18 -0800973 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700974 if (__predict_false(IsMutexDestroyed(old_state))) {
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800975 return HandleUsingDestroyedMutex(mutex_interface, function);
Yabin Cui9651fdf2018-03-14 12:02:21 -0700976 }
Tom Cherryc6b5bcd2018-03-05 14:14:44 -0800977 return NonPI::MutexLockWithTimeout(mutex, use_realtime_clock, abs_timeout);
978}
979
980int pthread_mutex_timedlock(pthread_mutex_t* mutex_interface, const struct timespec* abs_timeout) {
981 return __pthread_mutex_timedlock(mutex_interface, true, abs_timeout, __FUNCTION__);
982}
983
984int pthread_mutex_timedlock_monotonic_np(pthread_mutex_t* mutex_interface,
985 const struct timespec* abs_timeout) {
986 return __pthread_mutex_timedlock(mutex_interface, false, abs_timeout, __FUNCTION__);
Mathias Agopian7c0c3792011-09-05 23:54:55 -0700987}
988
Yabin Cui17393b02015-03-21 15:08:25 -0700989int pthread_mutex_destroy(pthread_mutex_t* mutex_interface) {
Yabin Cui0307eee2015-11-16 20:19:31 -0800990 pthread_mutex_internal_t* mutex = __get_internal_mutex(mutex_interface);
991 uint16_t old_state = atomic_load_explicit(&mutex->state, memory_order_relaxed);
Yabin Cui9651fdf2018-03-14 12:02:21 -0700992 if (__predict_false(IsMutexDestroyed(old_state))) {
993 return HandleUsingDestroyedMutex(mutex_interface, __FUNCTION__);
Yabin Cui2dec3d72018-02-02 15:45:24 -0800994 }
Yabin Cui9651fdf2018-03-14 12:02:21 -0700995 if (old_state == PI_MUTEX_STATE) {
Yabin Cui5a00ba72018-01-26 17:32:31 -0800996 int result = PIMutexDestroy(mutex->ToPIMutex());
997 if (result == 0) {
998 mutex->FreePIMutex();
Yabin Cui2dec3d72018-02-02 15:45:24 -0800999 atomic_store(&mutex->state, 0xffff);
Yabin Cui5a00ba72018-01-26 17:32:31 -08001000 }
1001 return result;
Yabin Cui6b9c85b2018-01-23 12:56:18 -08001002 }
Yabin Cui0307eee2015-11-16 20:19:31 -08001003 // Store 0xffff to make the mutex unusable. Although POSIX standard says it is undefined
1004 // behavior to destroy a locked mutex, we prefer not to change mutex->state in that situation.
1005 if (MUTEX_STATE_BITS_IS_UNLOCKED(old_state) &&
1006 atomic_compare_exchange_strong_explicit(&mutex->state, &old_state, 0xffff,
1007 memory_order_relaxed, memory_order_relaxed)) {
1008 return 0;
Yabin Cui86fc96f2015-01-29 21:50:48 -08001009 }
Yabin Cui0307eee2015-11-16 20:19:31 -08001010 return EBUSY;
Mathias Agopian7c0c3792011-09-05 23:54:55 -07001011}