2 * Copyright (c) 2000-2003, 2007, 2008 Apple Inc. All rights reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
24 * Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991
27 * Permission to use, copy, modify, and distribute this software and
28 * its documentation for any purpose and without fee is hereby granted,
29 * provided that the above copyright notice appears in all copies and
30 * that both the copyright notice and this permission notice appear in
31 * supporting documentation.
33 * OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
34 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
35 * FOR A PARTICULAR PURPOSE.
37 * IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
38 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
39 * LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
40 * NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
41 * WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
49 * POSIX Pthread Library
50 * -- Mutex variable support
55 #include "kern/kern_trace.h"
56 #include <sys/syscall.h>
58 #include "os/atomic.h"
61 #include "plockstat.h"
62 #else /* !PLOCKSTAT */
63 #define PLOCKSTAT_MUTEX_SPIN(x)
64 #define PLOCKSTAT_MUTEX_SPUN(x, y, z)
65 #define PLOCKSTAT_MUTEX_ERROR(x, y)
66 #define PLOCKSTAT_MUTEX_BLOCK(x)
67 #define PLOCKSTAT_MUTEX_BLOCKED(x, y)
68 #define PLOCKSTAT_MUTEX_ACQUIRE(x, y, z)
69 #define PLOCKSTAT_MUTEX_RELEASE(x, y)
70 #endif /* PLOCKSTAT */
72 #define PTHREAD_MUTEX_INIT_UNUSED 1
74 extern int __unix_conforming
;
76 #ifndef BUILDING_VARIANT
78 PTHREAD_NOEXPORT PTHREAD_WEAK
// prevent inlining of return value into callers
80 _pthread_mutex_unlock_slow(pthread_mutex_t
*omutex
);
82 PTHREAD_NOEXPORT PTHREAD_WEAK
// prevent inlining of return value into callers
84 _pthread_mutex_lock_slow(pthread_mutex_t
*omutex
, bool trylock
);
86 PTHREAD_NOEXPORT PTHREAD_WEAK
// prevent inlining of return value into _pthread_mutex_lock
88 _pthread_mutex_lock_wait(pthread_mutex_t
*omutex
, uint64_t newval64
, uint64_t oldtid
);
90 #endif /* BUILDING_VARIANT */
92 #define DEBUG_TRACE_POINTS 0
94 #if DEBUG_TRACE_POINTS
95 extern int __syscall(int number
, ...);
96 #define DEBUG_TRACE(x, a, b, c, d) __syscall(SYS_kdebug_trace, TRACE_##x, a, b, c, d)
98 #define DEBUG_TRACE(x, a, b, c, d) do { } while(0)
101 #include <machine/cpu_capabilities.h>
103 static inline int _pthread_mutex_init(_pthread_mutex
*mutex
, const pthread_mutexattr_t
*attr
, uint32_t static_type
);
105 #if !__LITTLE_ENDIAN__
106 #error MUTEX_GETSEQ_ADDR assumes little endian layout of 2 32-bit sequence words
109 PTHREAD_ALWAYS_INLINE
111 MUTEX_GETSEQ_ADDR(_pthread_mutex
*mutex
,
112 volatile uint64_t **seqaddr
)
114 // 64-bit aligned address inside m_seq array (&m_seq[0] for aligned mutex)
115 // We don't require more than byte alignment on OS X. rdar://22278325
116 *seqaddr
= (volatile uint64_t*)(((uintptr_t)mutex
->m_seq
+ 0x7ul
) & ~0x7ul
);
119 PTHREAD_ALWAYS_INLINE
121 MUTEX_GETTID_ADDR(_pthread_mutex
*mutex
,
122 volatile uint64_t **tidaddr
)
124 // 64-bit aligned address inside m_tid array (&m_tid[0] for aligned mutex)
125 // We don't require more than byte alignment on OS X. rdar://22278325
126 *tidaddr
= (volatile uint64_t*)(((uintptr_t)mutex
->m_tid
+ 0x7ul
) & ~0x7ul
);
129 #ifndef BUILDING_VARIANT /* [ */
130 #ifndef OS_UP_VARIANT_ONLY
132 #define BLOCK_FAIL_PLOCKSTAT 0
133 #define BLOCK_SUCCESS_PLOCKSTAT 1
136 /* This function is never called and exists to provide never-fired dtrace
137 * probes so that user d scripts don't get errors.
139 PTHREAD_NOEXPORT PTHREAD_USED
141 _plockstat_never_fired(void)
143 PLOCKSTAT_MUTEX_SPIN(NULL
);
144 PLOCKSTAT_MUTEX_SPUN(NULL
, 0, 0);
149 * Initialize a mutex variable, possibly with additional attributes.
150 * Public interface - so don't trust the lock - initialize it first.
153 pthread_mutex_init(pthread_mutex_t
*omutex
, const pthread_mutexattr_t
*attr
)
156 /* conformance tests depend on not having this behavior */
157 /* The test for this behavior is optional */
158 if (_pthread_mutex_check_signature(mutex
))
161 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
162 LOCK_INIT(mutex
->lock
);
163 return (_pthread_mutex_init(mutex
, attr
, 0x7));
167 pthread_mutex_getprioceiling(const pthread_mutex_t
*omutex
, int *prioceiling
)
170 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
171 if (_pthread_mutex_check_signature(mutex
)) {
173 *prioceiling
= mutex
->prioceiling
;
181 pthread_mutex_setprioceiling(pthread_mutex_t
*omutex
, int prioceiling
, int *old_prioceiling
)
184 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
185 if (_pthread_mutex_check_signature(mutex
)) {
187 if (prioceiling
>= -999 || prioceiling
<= 999) {
188 *old_prioceiling
= mutex
->prioceiling
;
189 mutex
->prioceiling
= prioceiling
;
198 pthread_mutexattr_getprioceiling(const pthread_mutexattr_t
*attr
, int *prioceiling
)
201 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
202 *prioceiling
= attr
->prioceiling
;
209 pthread_mutexattr_getprotocol(const pthread_mutexattr_t
*attr
, int *protocol
)
212 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
213 *protocol
= attr
->protocol
;
220 pthread_mutexattr_gettype(const pthread_mutexattr_t
*attr
, int *type
)
223 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
231 pthread_mutexattr_getpshared(const pthread_mutexattr_t
*attr
, int *pshared
)
234 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
235 *pshared
= (int)attr
->pshared
;
242 pthread_mutexattr_init(pthread_mutexattr_t
*attr
)
244 attr
->prioceiling
= _PTHREAD_DEFAULT_PRIOCEILING
;
245 attr
->protocol
= _PTHREAD_DEFAULT_PROTOCOL
;
246 attr
->policy
= _PTHREAD_MUTEX_POLICY_FAIRSHARE
;
247 attr
->type
= PTHREAD_MUTEX_DEFAULT
;
248 attr
->sig
= _PTHREAD_MUTEX_ATTR_SIG
;
249 attr
->pshared
= _PTHREAD_DEFAULT_PSHARED
;
254 pthread_mutexattr_setprioceiling(pthread_mutexattr_t
*attr
, int prioceiling
)
257 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
258 if (prioceiling
>= -999 || prioceiling
<= 999) {
259 attr
->prioceiling
= prioceiling
;
267 pthread_mutexattr_setprotocol(pthread_mutexattr_t
*attr
, int protocol
)
270 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
272 case PTHREAD_PRIO_NONE
:
273 case PTHREAD_PRIO_INHERIT
:
274 case PTHREAD_PRIO_PROTECT
:
275 attr
->protocol
= protocol
;
284 pthread_mutexattr_setpolicy_np(pthread_mutexattr_t
*attr
, int policy
)
287 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
289 case _PTHREAD_MUTEX_POLICY_FAIRSHARE
:
290 case _PTHREAD_MUTEX_POLICY_FIRSTFIT
:
291 attr
->policy
= policy
;
300 pthread_mutexattr_settype(pthread_mutexattr_t
*attr
, int type
)
303 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
305 case PTHREAD_MUTEX_NORMAL
:
306 case PTHREAD_MUTEX_ERRORCHECK
:
307 case PTHREAD_MUTEX_RECURSIVE
:
308 //case PTHREAD_MUTEX_DEFAULT:
325 pthread_yield_np(void)
332 * Temp: till pshared is fixed correctly
335 pthread_mutexattr_setpshared(pthread_mutexattr_t
*attr
, int pshared
)
339 if (__unix_conforming
== 0) {
340 __unix_conforming
= 1;
342 #endif /* __DARWIN_UNIX03 */
344 if (attr
->sig
== _PTHREAD_MUTEX_ATTR_SIG
) {
346 if (( pshared
== PTHREAD_PROCESS_PRIVATE
) || (pshared
== PTHREAD_PROCESS_SHARED
))
347 #else /* __DARWIN_UNIX03 */
348 if ( pshared
== PTHREAD_PROCESS_PRIVATE
)
349 #endif /* __DARWIN_UNIX03 */
351 attr
->pshared
= pshared
;
358 PTHREAD_NOEXPORT PTHREAD_WEAK
// prevent inlining of return value into callers
360 _pthread_mutex_corruption_abort(_pthread_mutex
*mutex
);
364 _pthread_mutex_corruption_abort(_pthread_mutex
*mutex
)
366 PTHREAD_ABORT("pthread_mutex corruption: mutex %p owner changed in the middle of lock/unlock");
367 return EINVAL
; // NOTREACHED
371 * Sequence numbers and TID:
373 * In steady (and uncontended) state, an unlocked mutex will
374 * look like A=[L4 U4 TID0]. When it is being locked, it transitions
375 * to B=[L5+KE U4 TID0] and then C=[L5+KE U4 TID940]. For an uncontended mutex,
376 * the unlock path will then transition to D=[L5 U4 TID0] and then finally
379 * If a contender comes in after B, the mutex will instead transition to E=[L6+KE U4 TID0]
380 * and then F=[L6+KE U4 TID940]. If a contender comes in after C, it will transition to
381 * F=[L6+KE U4 TID940] directly. In both cases, the contender will enter the kernel with either
382 * mutexwait(U4, TID0) or mutexwait(U4, TID940). The first owner will unlock the mutex
383 * by first updating the owner to G=[L6+KE U4 TID-1] and then doing the actual unlock to
384 * H=[L6+KE U5 TID=-1] before entering the kernel with mutexdrop(U5, -1) to signal the next waiter
385 * (potentially as a prepost). When the waiter comes out of the kernel, it will update the owner to
386 * I=[L6+KE U5 TID941]. An unlock at this point is simply J=[L6 U5 TID0] and then K=[L6 U6 TID0].
388 * At various points along these timelines, since the sequence words and TID are written independently,
389 * a thread may get preempted and another thread might see inconsistent data. In the worst case, another
390 * thread may see the TID in the SWITCHING (-1) state or unlocked (0) state for longer because the
391 * owning thread was preempted.
395 * Drop the mutex unlock references from cond_wait. or mutex_unlock.
397 PTHREAD_ALWAYS_INLINE
399 _pthread_mutex_unlock_updatebits(_pthread_mutex
*mutex
, uint32_t *flagsp
, uint32_t **pmtxp
, uint32_t *mgenp
, uint32_t *ugenp
)
401 bool firstfit
= (mutex
->mtxopts
.options
.policy
== _PTHREAD_MUTEX_POLICY_FIRSTFIT
);
402 uint32_t lgenval
, ugenval
, flags
;
403 uint64_t oldtid
, newtid
;
404 volatile uint64_t *tidaddr
;
405 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
407 flags
= mutex
->mtxopts
.value
;
408 flags
&= ~_PTHREAD_MTX_OPT_NOTIFY
; // no notification by default
410 if (mutex
->mtxopts
.options
.type
!= PTHREAD_MUTEX_NORMAL
) {
411 uint64_t selfid
= _pthread_selfid_direct();
413 if (*tidaddr
!= selfid
) {
414 //PTHREAD_ABORT("dropping recur or error mutex not owned by the thread");
415 PLOCKSTAT_MUTEX_ERROR((pthread_mutex_t
*)mutex
, EPERM
);
417 } else if (mutex
->mtxopts
.options
.type
== PTHREAD_MUTEX_RECURSIVE
&&
418 --mutex
->mtxopts
.options
.lock_count
) {
419 PLOCKSTAT_MUTEX_RELEASE((pthread_mutex_t
*)mutex
, 1);
420 if (flagsp
!= NULL
) {
427 uint64_t oldval64
, newval64
;
428 volatile uint64_t *seqaddr
;
429 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
431 bool clearprepost
, clearnotify
, spurious
;
435 lgenval
= (uint32_t)oldval64
;
436 ugenval
= (uint32_t)(oldval64
>> 32);
438 clearprepost
= false;
442 int numwaiters
= diff_genseq(lgenval
, ugenval
); // pending waiters
444 if (numwaiters
== 0) {
445 // spurious unlock; do not touch tid
448 ugenval
+= PTHRW_INC
;
450 if ((lgenval
& PTHRW_COUNT_MASK
) == (ugenval
& PTHRW_COUNT_MASK
)) {
451 // our unlock sequence matches to lock sequence, so if the CAS is successful, the mutex is unlocked
453 /* do not reset Ibit, just K&E */
454 lgenval
&= ~(PTH_RWL_KBIT
| PTH_RWL_EBIT
);
456 newtid
= 0; // clear owner
459 lgenval
&= ~PTH_RWL_EBIT
; // reset E bit so another can acquire meanwhile
462 newtid
= PTHREAD_MTX_TID_SWITCHING
;
464 // need to signal others waiting for mutex
465 flags
|= _PTHREAD_MTX_OPT_NOTIFY
;
468 if (newtid
!= oldtid
) {
469 // We're giving up the mutex one way or the other, so go ahead and update the owner to SWITCHING
470 // or 0 so that once the CAS below succeeds, there is no stale ownership information.
471 // If the CAS of the seqaddr fails, we may loop, but it's still valid for the owner
473 if (!os_atomic_cmpxchg(tidaddr
, oldtid
, newtid
, relaxed
)) {
474 // we own this mutex, nobody should be updating it except us
475 return _pthread_mutex_corruption_abort(mutex
);
480 if (clearnotify
|| spurious
) {
481 flags
&= ~_PTHREAD_MTX_OPT_NOTIFY
;
482 if (firstfit
&& ((lgenval
& PTH_RWL_PBIT
) != 0)) {
484 lgenval
&= ~PTH_RWL_PBIT
;
488 newval64
= (((uint64_t)ugenval
) << 32);
491 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, release
));
494 __psynch_cvclrprepost(mutex
, lgenval
, ugenval
, 0, 0, lgenval
, (flags
| _PTHREAD_MTX_OPT_MUTEX
));
504 *pmtxp
= (uint32_t *)mutex
;
506 if (flagsp
!= NULL
) {
515 __mtx_droplock(_pthread_mutex
*mutex
, uint32_t *flagsp
, uint32_t **pmtxp
, uint32_t *mgenp
, uint32_t *ugenp
)
517 return _pthread_mutex_unlock_updatebits(mutex
, flagsp
, pmtxp
, mgenp
, ugenp
);
520 PTHREAD_ALWAYS_INLINE
522 _pthread_mutex_lock_updatebits(_pthread_mutex
*mutex
, uint64_t selfid
)
525 int firstfit
= (mutex
->mtxopts
.options
.policy
== _PTHREAD_MUTEX_POLICY_FIRSTFIT
);
528 uint32_t lgenval
, ugenval
;
529 uint64_t oldval64
, newval64
;
530 volatile uint64_t *seqaddr
;
531 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
533 volatile uint64_t *tidaddr
;
534 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
540 lgenval
= (uint32_t)oldval64
;
541 ugenval
= (uint32_t)(oldval64
>> 32);
543 // E bit was set on first pass through the loop but is no longer
544 // set. Apparently we spin until it arrives.
545 // XXX: verify this is desired behavior.
546 } while (isebit
&& (lgenval
& PTH_RWL_EBIT
) == 0);
549 // first fit mutex now has the E bit set. Return 1.
555 isebit
= (lgenval
& PTH_RWL_EBIT
) != 0;
556 } else if ((lgenval
& (PTH_RWL_KBIT
|PTH_RWL_EBIT
)) == (PTH_RWL_KBIT
|PTH_RWL_EBIT
)) {
557 // fairshare mutex and the bits are already set, just update tid
561 // either first fit or no E bit set
563 lgenval
|= PTH_RWL_KBIT
| PTH_RWL_EBIT
;
565 newval64
= (((uint64_t)ugenval
) << 32);
569 // Retry if CAS fails, or if it succeeds with firstfit and E bit already set
570 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, acquire
) || (firstfit
&& isebit
));
573 if (!os_atomic_cmpxchg(tidaddr
, oldtid
, selfid
, relaxed
)) {
574 // we own this mutex, nobody should be updating it except us
575 return _pthread_mutex_corruption_abort(mutex
);
584 __mtx_markprepost(_pthread_mutex
*mutex
, uint32_t updateval
, int firstfit
)
587 uint32_t lgenval
, ugenval
;
588 uint64_t oldval64
, newval64
;
590 volatile uint64_t *seqaddr
;
591 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
593 if (firstfit
!= 0 && (updateval
& PTH_RWL_PBIT
) != 0) {
598 flags
= mutex
->mtxopts
.value
;
601 lgenval
= (uint32_t)oldval64
;
602 ugenval
= (uint32_t)(oldval64
>> 32);
604 /* update the bits */
605 if ((lgenval
& PTHRW_COUNT_MASK
) == (ugenval
& PTHRW_COUNT_MASK
)) {
607 lgenval
&= ~PTH_RWL_PBIT
;
609 lgenval
|= PTH_RWL_PBIT
;
611 newval64
= (((uint64_t)ugenval
) << 32);
613 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, release
));
615 if (clearprepost
!= 0) {
616 __psynch_cvclrprepost(mutex
, lgenval
, ugenval
, 0, 0, lgenval
, (flags
| _PTHREAD_MTX_OPT_MUTEX
));
624 _pthread_mutex_check_init_slow(pthread_mutex_t
*omutex
)
627 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
629 if (_pthread_mutex_check_signature_init(mutex
)) {
631 if (_pthread_mutex_check_signature_init(mutex
)) {
632 // initialize a statically initialized mutex to provide
633 // compatibility for misbehaving applications.
634 // (unlock should not be the first operation on a mutex)
635 res
= _pthread_mutex_init(mutex
, NULL
, (mutex
->sig
& 0xf));
636 } else if (_pthread_mutex_check_signature(mutex
)) {
640 } else if (_pthread_mutex_check_signature(mutex
)) {
644 PLOCKSTAT_MUTEX_ERROR(omutex
, res
);
649 PTHREAD_ALWAYS_INLINE
651 _pthread_mutex_check_init(pthread_mutex_t
*omutex
)
654 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
656 if (!_pthread_mutex_check_signature(mutex
)) {
657 return _pthread_mutex_check_init_slow(omutex
);
664 _pthread_mutex_lock_wait(pthread_mutex_t
*omutex
, uint64_t newval64
, uint64_t oldtid
)
666 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
667 uint32_t lgenval
= (uint32_t)newval64
;
668 uint32_t ugenval
= (uint32_t)(newval64
>> 32);
670 volatile uint64_t *tidaddr
;
671 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
672 uint64_t selfid
= _pthread_selfid_direct();
674 PLOCKSTAT_MUTEX_BLOCK(omutex
);
678 updateval
= __psynch_mutexwait(omutex
, lgenval
, ugenval
, oldtid
, mutex
->mtxopts
.value
);
680 } while (updateval
== (uint32_t)-1);
682 // returns 0 on succesful update; in firstfit it may fail with 1
683 } while (_pthread_mutex_lock_updatebits(mutex
, selfid
) == 1);
684 PLOCKSTAT_MUTEX_BLOCKED(omutex
, BLOCK_SUCCESS_PLOCKSTAT
);
690 _pthread_mutex_lock_slow(pthread_mutex_t
*omutex
, bool trylock
)
693 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
695 res
= _pthread_mutex_check_init(omutex
);
701 volatile uint64_t *tidaddr
;
702 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
703 uint64_t selfid
= _pthread_selfid_direct();
705 if (mutex
->mtxopts
.options
.type
!= PTHREAD_MUTEX_NORMAL
) {
706 if (*tidaddr
== selfid
) {
707 if (mutex
->mtxopts
.options
.type
== PTHREAD_MUTEX_RECURSIVE
) {
708 if (mutex
->mtxopts
.options
.lock_count
< USHRT_MAX
) {
709 mutex
->mtxopts
.options
.lock_count
++;
710 PLOCKSTAT_MUTEX_ACQUIRE(omutex
, 1, 0);
714 PLOCKSTAT_MUTEX_ERROR(omutex
, res
);
716 } else if (trylock
) { /* PTHREAD_MUTEX_ERRORCHECK */
717 // <rdar://problem/16261552> as per OpenGroup, trylock cannot
718 // return EDEADLK on a deadlock, it should return EBUSY.
720 PLOCKSTAT_MUTEX_ERROR(omutex
, res
);
721 } else { /* PTHREAD_MUTEX_ERRORCHECK */
723 PLOCKSTAT_MUTEX_ERROR(omutex
, res
);
729 uint64_t oldval64
, newval64
;
730 volatile uint64_t *seqaddr
;
731 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
733 uint32_t lgenval
, ugenval
;
734 bool gotlock
= false;
739 lgenval
= (uint32_t)oldval64
;
740 ugenval
= (uint32_t)(oldval64
>> 32);
742 gotlock
= ((lgenval
& PTH_RWL_EBIT
) == 0);
744 if (trylock
&& !gotlock
) {
745 // A trylock on a held lock will fail immediately. But since
746 // we did not load the sequence words atomically, perform a
747 // no-op CAS64 to ensure that nobody has unlocked concurrently.
749 // Increment the lock sequence number and force the lock into E+K
750 // mode, whether "gotlock" is true or not.
751 lgenval
+= PTHRW_INC
;
752 lgenval
|= PTH_RWL_EBIT
| PTH_RWL_KBIT
;
755 newval64
= (((uint64_t)ugenval
) << 32);
759 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, acquire
));
762 os_atomic_store(tidaddr
, selfid
, relaxed
);
764 DEBUG_TRACE(psynch_mutex_ulock
, omutex
, lgenval
, ugenval
, selfid
);
765 PLOCKSTAT_MUTEX_ACQUIRE(omutex
, 0, 0);
766 } else if (trylock
) {
768 DEBUG_TRACE(psynch_mutex_utrylock_failed
, omutex
, lgenval
, ugenval
, oldtid
);
769 PLOCKSTAT_MUTEX_ERROR(omutex
, res
);
771 res
= _pthread_mutex_lock_wait(omutex
, newval64
, oldtid
);
774 if (res
== 0 && mutex
->mtxopts
.options
.type
== PTHREAD_MUTEX_RECURSIVE
) {
775 mutex
->mtxopts
.options
.lock_count
= 1;
778 PLOCKSTAT_MUTEX_ACQUIRE(omutex
, 0, 0);
783 #endif // OS_UP_VARIANT_ONLY
785 PTHREAD_ALWAYS_INLINE
787 _pthread_mutex_lock(pthread_mutex_t
*omutex
, bool trylock
)
789 #if PLOCKSTAT || DEBUG_TRACE_POINTS
790 if (PLOCKSTAT_MUTEX_ACQUIRE_ENABLED() || PLOCKSTAT_MUTEX_ERROR_ENABLED() ||
791 DEBUG_TRACE_POINTS
) {
792 return _pthread_mutex_lock_slow(omutex
, trylock
);
795 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
796 if (!_pthread_mutex_check_signature_fast(mutex
)) {
797 return _pthread_mutex_lock_slow(omutex
, trylock
);
801 volatile uint64_t *tidaddr
;
802 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
803 uint64_t selfid
= _pthread_selfid_direct();
805 uint64_t oldval64
, newval64
;
806 volatile uint64_t *seqaddr
;
807 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
809 uint32_t lgenval
, ugenval
;
810 bool gotlock
= false;
815 lgenval
= (uint32_t)oldval64
;
816 ugenval
= (uint32_t)(oldval64
>> 32);
818 gotlock
= ((lgenval
& PTH_RWL_EBIT
) == 0);
820 if (trylock
&& !gotlock
) {
821 // A trylock on a held lock will fail immediately. But since
822 // we did not load the sequence words atomically, perform a
823 // no-op CAS64 to ensure that nobody has unlocked concurrently.
825 // Increment the lock sequence number and force the lock into E+K
826 // mode, whether "gotlock" is true or not.
827 lgenval
+= PTHRW_INC
;
828 lgenval
|= PTH_RWL_EBIT
| PTH_RWL_KBIT
;
831 newval64
= (((uint64_t)ugenval
) << 32);
835 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, acquire
));
837 if (os_fastpath(gotlock
)) {
838 os_atomic_store(tidaddr
, selfid
, relaxed
);
840 } else if (trylock
) {
843 return _pthread_mutex_lock_wait(omutex
, newval64
, oldtid
);
847 PTHREAD_NOEXPORT_VARIANT
849 pthread_mutex_lock(pthread_mutex_t
*mutex
)
851 return _pthread_mutex_lock(mutex
, false);
854 PTHREAD_NOEXPORT_VARIANT
856 pthread_mutex_trylock(pthread_mutex_t
*mutex
)
858 return _pthread_mutex_lock(mutex
, true);
861 #ifndef OS_UP_VARIANT_ONLY
864 * TODO: Priority inheritance stuff
869 _pthread_mutex_unlock_drop(pthread_mutex_t
*omutex
, uint64_t newval64
, uint32_t flags
)
872 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
873 uint32_t lgenval
= (uint32_t)newval64
;
874 uint32_t ugenval
= (uint32_t)(newval64
>> 32);
877 int firstfit
= (mutex
->mtxopts
.options
.policy
== _PTHREAD_MUTEX_POLICY_FIRSTFIT
);
878 volatile uint64_t *tidaddr
;
879 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
881 updateval
= __psynch_mutexdrop(omutex
, lgenval
, ugenval
, *tidaddr
, flags
);
883 if (updateval
== (uint32_t)-1) {
890 PTHREAD_ABORT("__p_mutexdrop failed with error %d", res
);
893 } else if (firstfit
== 1) {
894 if ((updateval
& PTH_RWL_PBIT
) != 0) {
895 __mtx_markprepost(mutex
, updateval
, firstfit
);
903 _pthread_mutex_unlock_slow(pthread_mutex_t
*omutex
)
906 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
907 uint32_t mtxgen
, mtxugen
, flags
;
909 // Initialize static mutexes for compatibility with misbehaving
910 // applications (unlock should not be the first operation on a mutex).
911 res
= _pthread_mutex_check_init(omutex
);
916 res
= _pthread_mutex_unlock_updatebits(mutex
, &flags
, NULL
, &mtxgen
, &mtxugen
);
921 if ((flags
& _PTHREAD_MTX_OPT_NOTIFY
) != 0) {
923 newval64
= (((uint64_t)mtxugen
) << 32);
925 return _pthread_mutex_unlock_drop(omutex
, newval64
, flags
);
927 volatile uint64_t *tidaddr
;
928 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
929 DEBUG_TRACE(psynch_mutex_uunlock
, omutex
, mtxgen
, mtxugen
, *tidaddr
);
935 #endif // OS_UP_VARIANT_ONLY
937 PTHREAD_NOEXPORT_VARIANT
939 pthread_mutex_unlock(pthread_mutex_t
*omutex
)
941 #if PLOCKSTAT || DEBUG_TRACE_POINTS
942 if (PLOCKSTAT_MUTEX_RELEASE_ENABLED() || PLOCKSTAT_MUTEX_ERROR_ENABLED() ||
943 DEBUG_TRACE_POINTS
) {
944 return _pthread_mutex_unlock_slow(omutex
);
947 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
948 if (!_pthread_mutex_check_signature_fast(mutex
)) {
949 return _pthread_mutex_unlock_slow(omutex
);
952 volatile uint64_t *tidaddr
;
953 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
955 uint64_t oldval64
, newval64
;
956 volatile uint64_t *seqaddr
;
957 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
959 uint32_t lgenval
, ugenval
;
963 lgenval
= (uint32_t)oldval64
;
964 ugenval
= (uint32_t)(oldval64
>> 32);
966 int numwaiters
= diff_genseq(lgenval
, ugenval
); // pending waiters
968 if (numwaiters
== 0) {
969 // spurious unlock; do not touch tid
971 ugenval
+= PTHRW_INC
;
973 if ((lgenval
& PTHRW_COUNT_MASK
) == (ugenval
& PTHRW_COUNT_MASK
)) {
974 // our unlock sequence matches to lock sequence, so if the CAS is successful, the mutex is unlocked
976 /* do not reset Ibit, just K&E */
977 lgenval
&= ~(PTH_RWL_KBIT
| PTH_RWL_EBIT
);
979 return _pthread_mutex_unlock_slow(omutex
);
982 // We're giving up the mutex one way or the other, so go ahead and update the owner
983 // to 0 so that once the CAS below succeeds, there is no stale ownership information.
984 // If the CAS of the seqaddr fails, we may loop, but it's still valid for the owner
986 os_atomic_store(tidaddr
, 0, relaxed
);
989 newval64
= (((uint64_t)ugenval
) << 32);
992 } while (!os_atomic_cmpxchg(seqaddr
, oldval64
, newval64
, release
));
997 #ifndef OS_UP_VARIANT_ONLY
1001 _pthread_mutex_init(_pthread_mutex
*mutex
, const pthread_mutexattr_t
*attr
,
1002 uint32_t static_type
)
1004 mutex
->mtxopts
.value
= 0;
1005 mutex
->mtxopts
.options
.mutex
= 1;
1007 if (attr
->sig
!= _PTHREAD_MUTEX_ATTR_SIG
) {
1010 mutex
->prioceiling
= attr
->prioceiling
;
1011 mutex
->mtxopts
.options
.protocol
= attr
->protocol
;
1012 mutex
->mtxopts
.options
.policy
= attr
->policy
;
1013 mutex
->mtxopts
.options
.type
= attr
->type
;
1014 mutex
->mtxopts
.options
.pshared
= attr
->pshared
;
1016 switch (static_type
) {
1018 mutex
->mtxopts
.options
.type
= PTHREAD_MUTEX_ERRORCHECK
;
1021 mutex
->mtxopts
.options
.type
= PTHREAD_MUTEX_RECURSIVE
;
1024 /* firstfit fall thru */
1026 mutex
->mtxopts
.options
.type
= PTHREAD_MUTEX_DEFAULT
;
1032 mutex
->prioceiling
= _PTHREAD_DEFAULT_PRIOCEILING
;
1033 mutex
->mtxopts
.options
.protocol
= _PTHREAD_DEFAULT_PROTOCOL
;
1034 if (static_type
!= 3) {
1035 mutex
->mtxopts
.options
.policy
= _PTHREAD_MUTEX_POLICY_FAIRSHARE
;
1037 mutex
->mtxopts
.options
.policy
= _PTHREAD_MUTEX_POLICY_FIRSTFIT
;
1039 mutex
->mtxopts
.options
.pshared
= _PTHREAD_DEFAULT_PSHARED
;
1041 mutex
->priority
= 0;
1043 volatile uint64_t *seqaddr
;
1044 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
1045 volatile uint64_t *tidaddr
;
1046 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
1047 #if PTHREAD_MUTEX_INIT_UNUSED
1048 if ((uint32_t*)tidaddr
!= mutex
->m_tid
) {
1049 mutex
->mtxopts
.options
.misalign
= 1;
1050 __builtin_memset(mutex
->m_tid
, 0xff, sizeof(mutex
->m_tid
));
1052 __builtin_memset(mutex
->m_mis
, 0xff, sizeof(mutex
->m_mis
));
1053 #endif // PTHREAD_MUTEX_INIT_UNUSED
1057 long sig
= _PTHREAD_MUTEX_SIG
;
1058 if (mutex
->mtxopts
.options
.type
== PTHREAD_MUTEX_NORMAL
&&
1059 mutex
->mtxopts
.options
.policy
== _PTHREAD_MUTEX_POLICY_FAIRSHARE
) {
1060 // rdar://18148854 _pthread_mutex_lock & pthread_mutex_unlock fastpath
1061 sig
= _PTHREAD_MUTEX_SIG_fast
;
1064 #if PTHREAD_MUTEX_INIT_UNUSED
1065 // For detecting copied mutexes and smashes during debugging
1066 uint32_t sig32
= (uint32_t)sig
;
1067 #if defined(__LP64__)
1068 uintptr_t guard
= ~(uintptr_t)mutex
; // use ~ to hide from leaks
1069 __builtin_memcpy(mutex
->_reserved
, &guard
, sizeof(guard
));
1070 mutex
->_reserved
[2] = sig32
;
1071 mutex
->_reserved
[3] = sig32
;
1072 mutex
->_pad
= sig32
;
1074 mutex
->_reserved
[0] = sig32
;
1076 #endif // PTHREAD_MUTEX_INIT_UNUSED
1078 // Ensure all contents are properly set before setting signature.
1079 #if defined(__LP64__)
1080 // For binary compatibility reasons we cannot require natural alignment of
1081 // the 64bit 'sig' long value in the struct. rdar://problem/21610439
1082 uint32_t *sig32_ptr
= (uint32_t*)&mutex
->sig
;
1083 uint32_t *sig32_val
= (uint32_t*)&sig
;
1084 *(sig32_ptr
+1) = *(sig32_val
+1);
1085 os_atomic_store(sig32_ptr
, *sig32_val
, release
);
1087 os_atomic_store2o(mutex
, sig
, sig
, release
);
1094 pthread_mutex_destroy(pthread_mutex_t
*omutex
)
1096 _pthread_mutex
*mutex
= (_pthread_mutex
*)omutex
;
1101 if (_pthread_mutex_check_signature(mutex
)) {
1102 uint32_t lgenval
, ugenval
;
1104 volatile uint64_t *seqaddr
;
1105 MUTEX_GETSEQ_ADDR(mutex
, &seqaddr
);
1106 volatile uint64_t *tidaddr
;
1107 MUTEX_GETTID_ADDR(mutex
, &tidaddr
);
1109 oldval64
= *seqaddr
;
1110 lgenval
= (uint32_t)oldval64
;
1111 ugenval
= (uint32_t)(oldval64
>> 32);
1112 if ((*tidaddr
== (uint64_t)0) &&
1113 ((lgenval
& PTHRW_COUNT_MASK
) == (ugenval
& PTHRW_COUNT_MASK
))) {
1114 mutex
->sig
= _PTHREAD_NO_SIG
;
1119 } else if (_pthread_mutex_check_signature_init(mutex
)) {
1120 mutex
->sig
= _PTHREAD_NO_SIG
;
1123 UNLOCK(mutex
->lock
);
1128 #endif // OS_UP_VARIANT_ONLY
1130 #endif /* !BUILDING_VARIANT ] */
1132 #ifndef OS_UP_VARIANT_ONLY
1134 * Destroy a mutex attribute structure.
1137 pthread_mutexattr_destroy(pthread_mutexattr_t
*attr
)
1140 if (__unix_conforming
== 0) {
1141 __unix_conforming
= 1;
1143 if (attr
->sig
!= _PTHREAD_MUTEX_ATTR_SIG
) {
1146 #endif /* __DARWIN_UNIX03 */
1148 attr
->sig
= _PTHREAD_NO_SIG
;
1152 #endif // OS_UP_VARIANT_ONLY