-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathpthread_mutex.c
1894 lines (1628 loc) · 49.8 KB
/
pthread_mutex.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2000-2003, 2007, 2008 Apple Inc. All rights reserved.
*
* @APPLE_LICENSE_HEADER_START@
*
* This file contains Original Code and/or Modifications of Original Code
* as defined in and that are subject to the Apple Public Source License
* Version 2.0 (the 'License'). You may not use this file except in
* compliance with the License. Please obtain a copy of the License at
* http://www.opensource.apple.com/apsl/ and read it before using this
* file.
*
* The Original Code and all software distributed under the License are
* distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
* EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
* INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
* Please see the License for the specific language governing rights and
* limitations under the License.
*
* @APPLE_LICENSE_HEADER_END@
*/
/*
* Copyright 1996 1995 by Open Software Foundation, Inc. 1997 1996 1995 1994 1993 1992 1991
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appears in all copies and
* that both the copyright notice and this permission notice appear in
* supporting documentation.
*
* OSF DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL OSF BE LIABLE FOR ANY SPECIAL, INDIRECT, OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN ACTION OF CONTRACT,
* NEGLIGENCE, OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/*
* MkLinux
*/
/*
* POSIX Pthread Library
* -- Mutex variable support
*/
#include "resolver.h"
#include "internal.h"
#include "kern/kern_trace.h"
#ifndef BUILDING_VARIANT /* [ */
#ifdef PLOCKSTAT
#include "plockstat.h"
/* This function is never called and exists to provide never-fired dtrace
* probes so that user d scripts don't get errors.
*/
OS_USED static void
_plockstat_never_fired(void);
static void
_plockstat_never_fired(void)
{
PLOCKSTAT_MUTEX_SPIN(NULL);
PLOCKSTAT_MUTEX_SPUN(NULL, 0, 0);
}
#else /* !PLOCKSTAT */
#define PLOCKSTAT_MUTEX_SPIN(x)
#define PLOCKSTAT_MUTEX_SPUN(x, y, z)
#define PLOCKSTAT_MUTEX_ERROR(x, y)
#define PLOCKSTAT_MUTEX_BLOCK(x)
#define PLOCKSTAT_MUTEX_BLOCKED(x, y)
#define PLOCKSTAT_MUTEX_ACQUIRE(x, y, z)
#define PLOCKSTAT_MUTEX_RELEASE(x, y)
#endif /* PLOCKSTAT */
#define BLOCK_FAIL_PLOCKSTAT 0
#define BLOCK_SUCCESS_PLOCKSTAT 1
#define PTHREAD_MUTEX_INIT_UNUSED 1
#if !VARIANT_DYLD
int __pthread_mutex_default_opt_policy = _PTHREAD_MTX_OPT_POLICY_DEFAULT;
bool __pthread_mutex_use_ulock = _PTHREAD_MTX_OPT_ULOCK_DEFAULT;
bool __pthread_mutex_ulock_adaptive_spin = _PTHREAD_MTX_OPT_ADAPTIVE_DEFAULT;
static inline bool
_pthread_mutex_policy_validate(int policy)
{
return (policy >= 0 && policy < _PTHREAD_MUTEX_POLICY_LAST);
}
static inline int
_pthread_mutex_policy_to_opt(int policy)
{
switch (policy) {
case PTHREAD_MUTEX_POLICY_FAIRSHARE_NP:
return _PTHREAD_MTX_OPT_POLICY_FAIRSHARE;
case PTHREAD_MUTEX_POLICY_FIRSTFIT_NP:
return _PTHREAD_MTX_OPT_POLICY_FIRSTFIT;
default:
__builtin_unreachable();
}
}
void
_pthread_mutex_global_init(const char *envp[],
struct _pthread_registration_data *registration_data)
{
int opt = _PTHREAD_MTX_OPT_POLICY_DEFAULT;
if (registration_data->mutex_default_policy) {
int policy = registration_data->mutex_default_policy &
_PTHREAD_REG_DEFAULT_POLICY_MASK;
if (_pthread_mutex_policy_validate(policy)) {
opt = _pthread_mutex_policy_to_opt(policy);
}
}
const char *envvar = _simple_getenv(envp, "PTHREAD_MUTEX_DEFAULT_POLICY");
if (envvar) {
int policy = envvar[0] - '0';
if (_pthread_mutex_policy_validate(policy)) {
opt = _pthread_mutex_policy_to_opt(policy);
}
}
if (opt != __pthread_mutex_default_opt_policy) {
__pthread_mutex_default_opt_policy = opt;
}
bool use_ulock = _PTHREAD_MTX_OPT_ULOCK_DEFAULT;
if (_os_xbs_chrooted) {
use_ulock = false;
} else {
envvar = _simple_getenv(envp, "PTHREAD_MUTEX_USE_ULOCK");
if (envvar) {
use_ulock = (envvar[0] == '1');
} else if (registration_data->mutex_default_policy) {
use_ulock = registration_data->mutex_default_policy &
_PTHREAD_REG_DEFAULT_USE_ULOCK;
}
}
if (use_ulock != __pthread_mutex_use_ulock) {
__pthread_mutex_use_ulock = use_ulock;
}
bool adaptive_spin = _PTHREAD_MTX_OPT_ADAPTIVE_DEFAULT;
envvar = _simple_getenv(envp, "PTHREAD_MUTEX_ADAPTIVE_SPIN");
if (envvar) {
adaptive_spin = (envvar[0] == '1');
} else if (registration_data->mutex_default_policy) {
adaptive_spin = registration_data->mutex_default_policy &
_PTHREAD_REG_DEFAULT_USE_ADAPTIVE_SPIN;
}
if (adaptive_spin != __pthread_mutex_ulock_adaptive_spin) {
__pthread_mutex_ulock_adaptive_spin = adaptive_spin;
}
}
#endif // !VARIANT_DYLD
OS_ALWAYS_INLINE
static inline int _pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *attr, uint32_t static_type);
typedef union mutex_seq {
uint32_t seq[2];
struct { uint32_t lgenval; uint32_t ugenval; };
struct { uint32_t mgen; uint32_t ugen; };
uint64_t seq_LU;
uint64_t _Atomic atomic_seq_LU;
} mutex_seq;
_Static_assert(sizeof(mutex_seq) == 2 * sizeof(uint32_t),
"Incorrect mutex_seq size");
#if !__LITTLE_ENDIAN__
#error MUTEX_GETSEQ_ADDR assumes little endian layout of 2 32-bit sequence words
#endif
OS_ALWAYS_INLINE
static inline void
MUTEX_GETSEQ_ADDR(pthread_mutex_t *mutex, mutex_seq **seqaddr)
{
// 64-bit aligned address inside m_seq array (&m_seq[0] for aligned mutex)
// We don't require more than byte alignment on OS X. rdar://22278325
*seqaddr = (void *)(((uintptr_t)mutex->psynch.m_seq + 0x7ul) & ~0x7ul);
}
OS_ALWAYS_INLINE
static inline void
MUTEX_GETTID_ADDR(pthread_mutex_t *mutex, uint64_t **tidaddr)
{
// 64-bit aligned address inside m_tid array (&m_tid[0] for aligned mutex)
// We don't require more than byte alignment on OS X. rdar://22278325
*tidaddr = (void*)(((uintptr_t)mutex->psynch.m_tid + 0x7ul) & ~0x7ul);
}
OS_ALWAYS_INLINE
static inline void
mutex_seq_load(mutex_seq *seqaddr, mutex_seq *oldseqval)
{
oldseqval->seq_LU = seqaddr->seq_LU;
}
#define mutex_seq_atomic_load(seqaddr, oldseqval, m) \
mutex_seq_atomic_load_##m(seqaddr, oldseqval)
OS_ALWAYS_INLINE OS_USED
static inline bool
mutex_seq_atomic_cmpxchgv_relaxed(mutex_seq *seqaddr, mutex_seq *oldseqval,
mutex_seq *newseqval)
{
return os_atomic_cmpxchgv(&seqaddr->atomic_seq_LU, oldseqval->seq_LU,
newseqval->seq_LU, &oldseqval->seq_LU, relaxed);
}
OS_ALWAYS_INLINE OS_USED
static inline bool
mutex_seq_atomic_cmpxchgv_acquire(mutex_seq *seqaddr, mutex_seq *oldseqval,
mutex_seq *newseqval)
{
return os_atomic_cmpxchgv(&seqaddr->atomic_seq_LU, oldseqval->seq_LU,
newseqval->seq_LU, &oldseqval->seq_LU, acquire);
}
OS_ALWAYS_INLINE OS_USED
static inline bool
mutex_seq_atomic_cmpxchgv_release(mutex_seq *seqaddr, mutex_seq *oldseqval,
mutex_seq *newseqval)
{
return os_atomic_cmpxchgv(&seqaddr->atomic_seq_LU, oldseqval->seq_LU,
newseqval->seq_LU, &oldseqval->seq_LU, release);
}
#define mutex_seq_atomic_cmpxchgv(seqaddr, oldseqval, newseqval, m)\
mutex_seq_atomic_cmpxchgv_##m(seqaddr, oldseqval, newseqval)
/*
* Initialize a mutex variable, possibly with additional attributes.
* Public interface - so don't trust the lock - initialize it first.
*/
PTHREAD_NOEXPORT_VARIANT
int
pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr)
{
#if 0
/* conformance tests depend on not having this behavior */
/* The test for this behavior is optional */
if (_pthread_mutex_check_signature(mutex))
return EBUSY;
#endif
_pthread_lock_init(&mutex->lock);
return (_pthread_mutex_init(mutex, attr, 0x7));
}
int
pthread_mutex_getprioceiling(const pthread_mutex_t *omutex, int *prioceiling)
{
int res = EINVAL;
pthread_mutex_t *mutex = (pthread_mutex_t *)omutex;
if (_pthread_mutex_check_signature(mutex)) {
_pthread_lock_lock(&mutex->lock);
*prioceiling = mutex->prioceiling;
res = 0;
_pthread_lock_unlock(&mutex->lock);
}
return res;
}
int
pthread_mutex_setprioceiling(pthread_mutex_t *mutex, int prioceiling,
int *old_prioceiling)
{
int res = EINVAL;
if (_pthread_mutex_check_signature(mutex)) {
_pthread_lock_lock(&mutex->lock);
if (prioceiling >= -999 && prioceiling <= 999) {
*old_prioceiling = mutex->prioceiling;
mutex->prioceiling = (int16_t)prioceiling;
res = 0;
}
_pthread_lock_unlock(&mutex->lock);
}
return res;
}
int
pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *attr,
int *prioceiling)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
*prioceiling = attr->prioceiling;
res = 0;
}
return res;
}
int
pthread_mutexattr_getprotocol(const pthread_mutexattr_t *attr, int *protocol)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
*protocol = attr->protocol;
res = 0;
}
return res;
}
int
pthread_mutexattr_getpolicy_np(const pthread_mutexattr_t *attr, int *policy)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
switch (attr->opt) {
case _PTHREAD_MTX_OPT_POLICY_FAIRSHARE:
*policy = PTHREAD_MUTEX_POLICY_FAIRSHARE_NP;
res = 0;
break;
case _PTHREAD_MTX_OPT_POLICY_FIRSTFIT:
*policy = PTHREAD_MUTEX_POLICY_FIRSTFIT_NP;
res = 0;
break;
}
}
return res;
}
int
pthread_mutexattr_gettype(const pthread_mutexattr_t *attr, int *type)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
*type = attr->type;
res = 0;
}
return res;
}
int
pthread_mutexattr_getpshared(const pthread_mutexattr_t *attr, int *pshared)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
*pshared = (int)attr->pshared;
res = 0;
}
return res;
}
int
pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
attr->prioceiling = _PTHREAD_DEFAULT_PRIOCEILING;
attr->protocol = _PTHREAD_DEFAULT_PROTOCOL;
attr->opt = __pthread_mutex_default_opt_policy;
attr->type = PTHREAD_MUTEX_DEFAULT;
attr->sig = _PTHREAD_MUTEX_ATTR_SIG;
attr->pshared = _PTHREAD_DEFAULT_PSHARED;
return 0;
}
int
pthread_mutexattr_setprioceiling(pthread_mutexattr_t *attr, int prioceiling)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
if (prioceiling >= -999 && prioceiling <= 999) {
attr->prioceiling = prioceiling;
res = 0;
}
}
return res;
}
int
pthread_mutexattr_setprotocol(pthread_mutexattr_t *attr, int protocol)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
switch (protocol) {
case PTHREAD_PRIO_NONE:
case PTHREAD_PRIO_INHERIT:
case PTHREAD_PRIO_PROTECT:
attr->protocol = protocol;
res = 0;
break;
}
}
return res;
}
int
pthread_mutexattr_setpolicy_np(pthread_mutexattr_t *attr, int policy)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
// <rdar://problem/35844519> the first-fit implementation was broken
// pre-Liberty so this mapping exists to ensure that the old first-fit
// define (2) is no longer valid when used on older systems.
switch (policy) {
case PTHREAD_MUTEX_POLICY_FAIRSHARE_NP:
attr->opt = _PTHREAD_MTX_OPT_POLICY_FAIRSHARE;
res = 0;
break;
case PTHREAD_MUTEX_POLICY_FIRSTFIT_NP:
attr->opt = _PTHREAD_MTX_OPT_POLICY_FIRSTFIT;
res = 0;
break;
}
}
return res;
}
int
pthread_mutexattr_settype(pthread_mutexattr_t *attr, int type)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
switch (type) {
case PTHREAD_MUTEX_NORMAL:
case PTHREAD_MUTEX_ERRORCHECK:
case PTHREAD_MUTEX_RECURSIVE:
//case PTHREAD_MUTEX_DEFAULT:
attr->type = type;
res = 0;
break;
}
}
return res;
}
int
pthread_mutexattr_setpshared(pthread_mutexattr_t *attr, int pshared)
{
int res = EINVAL;
if (attr->sig == _PTHREAD_MUTEX_ATTR_SIG) {
if (( pshared == PTHREAD_PROCESS_PRIVATE) ||
(pshared == PTHREAD_PROCESS_SHARED))
{
attr->pshared = pshared;
res = 0;
}
}
return res;
}
OS_NOINLINE
int
_pthread_mutex_corruption_abort(pthread_mutex_t *mutex)
{
PTHREAD_CLIENT_CRASH(0, "pthread_mutex corruption: mutex owner changed "
"in the middle of lock/unlock");
}
OS_NOINLINE
static int
_pthread_mutex_check_init_slow(pthread_mutex_t *mutex)
{
int res = EINVAL;
if (_pthread_mutex_check_signature_init(mutex)) {
_pthread_lock_lock(&mutex->lock);
if (_pthread_mutex_check_signature_init(mutex)) {
// initialize a statically initialized mutex to provide
// compatibility for misbehaving applications.
// (unlock should not be the first operation on a mutex)
res = _pthread_mutex_init(mutex, NULL, (mutex->sig & 0xf));
} else if (_pthread_mutex_check_signature(mutex)) {
res = 0;
}
_pthread_lock_unlock(&mutex->lock);
} else if (_pthread_mutex_check_signature(mutex)) {
res = 0;
}
if (res != 0) {
PLOCKSTAT_MUTEX_ERROR((pthread_mutex_t *)mutex, res);
}
return res;
}
OS_ALWAYS_INLINE
static inline int
_pthread_mutex_check_init(pthread_mutex_t *mutex)
{
int res = 0;
if (!_pthread_mutex_check_signature(mutex)) {
return _pthread_mutex_check_init_slow(mutex);
}
return res;
}
OS_ALWAYS_INLINE
static inline bool
_pthread_mutex_is_fairshare(pthread_mutex_t *mutex)
{
return (mutex->mtxopts.options.policy == _PTHREAD_MTX_OPT_POLICY_FAIRSHARE);
}
OS_ALWAYS_INLINE
static inline bool
_pthread_mutex_is_firstfit(pthread_mutex_t *mutex)
{
return (mutex->mtxopts.options.policy == _PTHREAD_MTX_OPT_POLICY_FIRSTFIT);
}
OS_ALWAYS_INLINE
static inline bool
_pthread_mutex_is_recursive(pthread_mutex_t *mutex)
{
return (mutex->mtxopts.options.type == PTHREAD_MUTEX_RECURSIVE);
}
OS_ALWAYS_INLINE
static int
_pthread_mutex_lock_handle_options(pthread_mutex_t *mutex, bool trylock,
uint64_t *tidaddr)
{
if (mutex->mtxopts.options.type == PTHREAD_MUTEX_NORMAL) {
// NORMAL does not do EDEADLK checking
return 0;
}
uint64_t selfid = _pthread_threadid_self_np_direct();
if (os_atomic_load_wide(tidaddr, relaxed) == selfid) {
if (_pthread_mutex_is_recursive(mutex)) {
if (mutex->mtxopts.options.lock_count < USHRT_MAX) {
mutex->mtxopts.options.lock_count += 1;
return mutex->mtxopts.options.lock_count;
} else {
return -EAGAIN;
}
} else if (trylock) { /* PTHREAD_MUTEX_ERRORCHECK */
// <rdar://problem/16261552> as per OpenGroup, trylock cannot
// return EDEADLK on a deadlock, it should return EBUSY.
return -EBUSY;
} else { /* PTHREAD_MUTEX_ERRORCHECK */
return -EDEADLK;
}
}
// Not recursive, or recursive but first lock.
return 0;
}
OS_ALWAYS_INLINE
static int
_pthread_mutex_unlock_handle_options(pthread_mutex_t *mutex, uint64_t *tidaddr)
{
if (mutex->mtxopts.options.type == PTHREAD_MUTEX_NORMAL) {
// NORMAL does not do EDEADLK checking
return 0;
}
uint64_t selfid = _pthread_threadid_self_np_direct();
if (os_atomic_load_wide(tidaddr, relaxed) != selfid) {
return -EPERM;
} else if (_pthread_mutex_is_recursive(mutex) &&
--mutex->mtxopts.options.lock_count) {
return 1;
}
return 0;
}
/*
* Sequence numbers and TID:
*
* In steady (and uncontended) state, an unlocked mutex will
* look like A=[L4 U4 TID0]. When it is being locked, it transitions
* to B=[L5+KE U4 TID0] and then C=[L5+KE U4 TID940]. For an uncontended mutex,
* the unlock path will then transition to D=[L5 U4 TID0] and then finally
* E=[L5 U5 TID0].
*
* If a contender comes in after B, the mutex will instead transition to
* E=[L6+KE U4 TID0] and then F=[L6+KE U4 TID940]. If a contender comes in after
* C, it will transition to F=[L6+KE U4 TID940] directly. In both cases, the
* contender will enter the kernel with either mutexwait(U4, TID0) or
* mutexwait(U4, TID940). The first owner will unlock the mutex by first
* updating the owner to G=[L6+KE U4 TID-1] and then doing the actual unlock to
* H=[L6+KE U5 TID=-1] before entering the kernel with mutexdrop(U5, -1) to
* signal the next waiter (potentially as a prepost). When the waiter comes out
* of the kernel, it will update the owner to I=[L6+KE U5 TID941]. An unlock at
* this point is simply J=[L6 U5 TID0] and then K=[L6 U6 TID0].
*
* At various points along these timelines, since the sequence words and TID are
* written independently, a thread may get preempted and another thread might
* see inconsistent data. In the worst case, another thread may see the TID in
* the SWITCHING (-1) state or unlocked (0) state for longer because the owning
* thread was preempted.
*/
/*
* Drop the mutex unlock references from cond_wait or mutex_unlock.
*/
OS_ALWAYS_INLINE
static inline int
_pthread_mutex_fairshare_unlock_updatebits(pthread_mutex_t *mutex,
uint32_t *flagsp, uint32_t **pmtxp, uint32_t *mgenp, uint32_t *ugenp)
{
uint32_t flags = mutex->mtxopts.value;
flags &= ~_PTHREAD_MTX_OPT_NOTIFY; // no notification by default
mutex_seq *seqaddr;
MUTEX_GETSEQ_ADDR(mutex, &seqaddr);
mutex_seq oldseq, newseq;
mutex_seq_load(seqaddr, &oldseq);
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
uint64_t oldtid, newtid;
int res = _pthread_mutex_unlock_handle_options(mutex, tidaddr);
if (res > 0) {
// Valid recursive unlock
if (flagsp) {
*flagsp = flags;
}
PLOCKSTAT_MUTEX_RELEASE((pthread_mutex_t *)mutex, 1);
return 0;
} else if (res < 0) {
PLOCKSTAT_MUTEX_ERROR((pthread_mutex_t *)mutex, -res);
return -res;
}
bool clearnotify, spurious;
do {
newseq = oldseq;
oldtid = os_atomic_load_wide(tidaddr, relaxed);
clearnotify = false;
spurious = false;
// pending waiters
int numwaiters = diff_genseq(oldseq.lgenval, oldseq.ugenval);
if (numwaiters == 0) {
// spurious unlock (unlock of unlocked lock)
spurious = true;
} else {
newseq.ugenval += PTHRW_INC;
if ((oldseq.lgenval & PTHRW_COUNT_MASK) ==
(newseq.ugenval & PTHRW_COUNT_MASK)) {
// our unlock sequence matches to lock sequence, so if the
// CAS is successful, the mutex is unlocked
/* do not reset Ibit, just K&E */
newseq.lgenval &= ~(PTH_RWL_KBIT | PTH_RWL_EBIT);
clearnotify = true;
newtid = 0; // clear owner
} else {
newtid = PTHREAD_MTX_TID_SWITCHING;
// need to signal others waiting for mutex
flags |= _PTHREAD_MTX_OPT_NOTIFY;
}
if (newtid != oldtid) {
// We're giving up the mutex one way or the other, so go ahead
// and update the owner to 0 so that once the CAS below
// succeeds, there is no stale ownership information. If the
// CAS of the seqaddr fails, we may loop, but it's still valid
// for the owner to be SWITCHING/0
if (!os_atomic_cmpxchg(tidaddr, oldtid, newtid, relaxed)) {
// we own this mutex, nobody should be updating it except us
return _pthread_mutex_corruption_abort(mutex);
}
}
}
if (clearnotify || spurious) {
flags &= ~_PTHREAD_MTX_OPT_NOTIFY;
}
} while (!mutex_seq_atomic_cmpxchgv(seqaddr, &oldseq, &newseq, release));
PTHREAD_TRACE(psynch_mutex_unlock_updatebits, mutex, oldseq.lgenval,
newseq.lgenval, oldtid);
if (mgenp != NULL) {
*mgenp = newseq.lgenval;
}
if (ugenp != NULL) {
*ugenp = newseq.ugenval;
}
if (pmtxp != NULL) {
*pmtxp = (uint32_t *)mutex;
}
if (flagsp != NULL) {
*flagsp = flags;
}
return 0;
}
OS_ALWAYS_INLINE
static inline int
_pthread_mutex_fairshare_lock_updatebits(pthread_mutex_t *mutex, uint64_t selfid)
{
bool firstfit = _pthread_mutex_is_firstfit(mutex);
bool gotlock = true;
mutex_seq *seqaddr;
MUTEX_GETSEQ_ADDR(mutex, &seqaddr);
mutex_seq oldseq, newseq;
mutex_seq_load(seqaddr, &oldseq);
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
do {
newseq = oldseq;
if (firstfit) {
// firstfit locks can have the lock stolen out from under a locker
// between the unlock from the kernel and this lock path. When this
// happens, we still want to set the K bit before leaving the loop
// (or notice if the lock unlocks while we try to update).
gotlock = !is_rwl_ebit_set(oldseq.lgenval);
} else if ((oldseq.lgenval & (PTH_RWL_KBIT | PTH_RWL_EBIT)) ==
(PTH_RWL_KBIT | PTH_RWL_EBIT)) {
// bit are already set, just update the owner tidaddr
break;
}
newseq.lgenval |= PTH_RWL_KBIT | PTH_RWL_EBIT;
} while (!mutex_seq_atomic_cmpxchgv(seqaddr, &oldseq, &newseq,
acquire));
if (gotlock) {
os_atomic_store_wide(tidaddr, selfid, relaxed);
}
PTHREAD_TRACE(psynch_mutex_lock_updatebits, mutex, oldseq.lgenval,
newseq.lgenval, 0);
// failing to take the lock in firstfit returns 1 to force the caller
// to wait in the kernel
return gotlock ? 0 : 1;
}
OS_NOINLINE
static int
_pthread_mutex_fairshare_lock_wait(pthread_mutex_t *mutex, mutex_seq newseq,
uint64_t oldtid)
{
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
uint64_t selfid = _pthread_threadid_self_np_direct();
PLOCKSTAT_MUTEX_BLOCK((pthread_mutex_t *)mutex);
do {
uint32_t updateval;
do {
updateval = __psynch_mutexwait(mutex, newseq.lgenval,
newseq.ugenval, oldtid, mutex->mtxopts.value);
oldtid = os_atomic_load_wide(tidaddr, relaxed);
} while (updateval == (uint32_t)-1);
// returns 0 on succesful update; in firstfit it may fail with 1
} while (_pthread_mutex_fairshare_lock_updatebits(mutex, selfid) == 1);
PLOCKSTAT_MUTEX_BLOCKED((pthread_mutex_t *)mutex, BLOCK_SUCCESS_PLOCKSTAT);
return 0;
}
OS_NOINLINE
int
_pthread_mutex_fairshare_lock_slow(pthread_mutex_t *mutex, bool trylock)
{
int res, recursive = 0;
mutex_seq *seqaddr;
MUTEX_GETSEQ_ADDR(mutex, &seqaddr);
mutex_seq oldseq, newseq;
mutex_seq_load(seqaddr, &oldseq);
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
uint64_t oldtid, selfid = _pthread_threadid_self_np_direct();
res = _pthread_mutex_lock_handle_options(mutex, trylock, tidaddr);
if (res > 0) {
recursive = 1;
res = 0;
goto out;
} else if (res < 0) {
res = -res;
goto out;
}
bool gotlock;
do {
newseq = oldseq;
oldtid = os_atomic_load_wide(tidaddr, relaxed);
gotlock = ((oldseq.lgenval & PTH_RWL_EBIT) == 0);
if (trylock && !gotlock) {
// A trylock on a held lock will fail immediately. But since
// we did not load the sequence words atomically, perform a
// no-op CAS64 to ensure that nobody has unlocked concurrently.
} else {
// Increment the lock sequence number and force the lock into E+K
// mode, whether "gotlock" is true or not.
newseq.lgenval += PTHRW_INC;
newseq.lgenval |= PTH_RWL_EBIT | PTH_RWL_KBIT;
}
} while (!mutex_seq_atomic_cmpxchgv(seqaddr, &oldseq, &newseq, acquire));
PTHREAD_TRACE(psynch_mutex_lock_updatebits, mutex, oldseq.lgenval,
newseq.lgenval, 0);
if (gotlock) {
os_atomic_store_wide(tidaddr, selfid, relaxed);
res = 0;
PTHREAD_TRACE(psynch_mutex_ulock, mutex, newseq.lgenval,
newseq.ugenval, selfid);
} else if (trylock) {
res = EBUSY;
PTHREAD_TRACE(psynch_mutex_utrylock_failed, mutex, newseq.lgenval,
newseq.ugenval, oldtid);
} else {
PTHREAD_TRACE(psynch_mutex_ulock | DBG_FUNC_START, mutex,
newseq.lgenval, newseq.ugenval, oldtid);
res = _pthread_mutex_fairshare_lock_wait(mutex, newseq, oldtid);
PTHREAD_TRACE(psynch_mutex_ulock | DBG_FUNC_END, mutex,
newseq.lgenval, newseq.ugenval, oldtid);
}
if (res == 0 && _pthread_mutex_is_recursive(mutex)) {
mutex->mtxopts.options.lock_count = 1;
}
out:
#if PLOCKSTAT
if (res == 0) {
PLOCKSTAT_MUTEX_ACQUIRE((pthread_mutex_t *)mutex, recursive, 0);
} else {
PLOCKSTAT_MUTEX_ERROR((pthread_mutex_t *)mutex, res);
}
#endif
return res;
}
OS_NOINLINE
static inline int
_pthread_mutex_fairshare_lock(pthread_mutex_t *mutex, bool trylock)
{
#if ENABLE_USERSPACE_TRACE
return _pthread_mutex_fairshare_lock_slow(mutex, trylock);
#elif PLOCKSTAT
if (PLOCKSTAT_MUTEX_ACQUIRE_ENABLED() || PLOCKSTAT_MUTEX_ERROR_ENABLED()) {
return _pthread_mutex_fairshare_lock_slow(mutex, trylock);
}
#endif
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
uint64_t selfid = _pthread_threadid_self_np_direct();
mutex_seq *seqaddr;
MUTEX_GETSEQ_ADDR(mutex, &seqaddr);
mutex_seq oldseq, newseq;
mutex_seq_load(seqaddr, &oldseq);
if (os_unlikely(oldseq.lgenval & PTH_RWL_EBIT)) {
return _pthread_mutex_fairshare_lock_slow(mutex, trylock);
}
bool gotlock;
do {
newseq = oldseq;
gotlock = ((oldseq.lgenval & PTH_RWL_EBIT) == 0);
if (trylock && !gotlock) {
// A trylock on a held lock will fail immediately. But since
// we did not load the sequence words atomically, perform a
// no-op CAS64 to ensure that nobody has unlocked concurrently.
} else if (os_likely(gotlock)) {
// Increment the lock sequence number and force the lock into E+K
// mode, whether "gotlock" is true or not.
newseq.lgenval += PTHRW_INC;
newseq.lgenval |= PTH_RWL_EBIT | PTH_RWL_KBIT;
} else {
return _pthread_mutex_fairshare_lock_slow(mutex, trylock);
}
} while (os_unlikely(!mutex_seq_atomic_cmpxchgv(seqaddr, &oldseq, &newseq,
acquire)));
if (os_likely(gotlock)) {
os_atomic_store_wide(tidaddr, selfid, relaxed);
return 0;
} else if (trylock) {
return EBUSY;
} else {
__builtin_trap();
}
}
OS_NOINLINE
static int
_pthread_mutex_fairshare_unlock_drop(pthread_mutex_t *mutex, mutex_seq newseq,
uint32_t flags)
{
int res;
uint32_t updateval;
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
PTHREAD_TRACE(psynch_mutex_uunlock | DBG_FUNC_START, mutex, newseq.lgenval,
newseq.ugenval, os_atomic_load_wide(tidaddr, relaxed));
updateval = __psynch_mutexdrop(mutex, newseq.lgenval, newseq.ugenval,
os_atomic_load_wide(tidaddr, relaxed), flags);
PTHREAD_TRACE(psynch_mutex_uunlock | DBG_FUNC_END, mutex, updateval, 0, 0);
if (updateval == (uint32_t)-1) {
res = errno;
if (res == EINTR) {
res = 0;
}
if (res != 0) {
PTHREAD_INTERNAL_CRASH(res, "__psynch_mutexdrop failed");
}
return res;
}
return 0;
}
OS_NOINLINE
int
_pthread_mutex_fairshare_unlock_slow(pthread_mutex_t *mutex)
{
int res;
mutex_seq newseq;
uint32_t flags;
res = _pthread_mutex_fairshare_unlock_updatebits(mutex, &flags, NULL,
&newseq.lgenval, &newseq.ugenval);
if (res != 0) return res;
if ((flags & _PTHREAD_MTX_OPT_NOTIFY) != 0) {
return _pthread_mutex_fairshare_unlock_drop(mutex, newseq, flags);
} else {
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
PTHREAD_TRACE(psynch_mutex_uunlock, mutex, newseq.lgenval,
newseq.ugenval, os_atomic_load_wide(tidaddr, relaxed));
}
return 0;
}
OS_NOINLINE
static int
_pthread_mutex_fairshare_unlock(pthread_mutex_t *mutex)
{
#if ENABLE_USERSPACE_TRACE
return _pthread_mutex_fairshare_unlock_slow(mutex);
#elif PLOCKSTAT
if (PLOCKSTAT_MUTEX_RELEASE_ENABLED() || PLOCKSTAT_MUTEX_ERROR_ENABLED()) {
return _pthread_mutex_fairshare_unlock_slow(mutex);
}
#endif
uint64_t *tidaddr;
MUTEX_GETTID_ADDR(mutex, &tidaddr);
mutex_seq *seqaddr;
MUTEX_GETSEQ_ADDR(mutex, &seqaddr);
mutex_seq oldseq, newseq;
mutex_seq_load(seqaddr, &oldseq);
int numwaiters = diff_genseq(oldseq.lgenval, oldseq.ugenval);
if (os_unlikely(numwaiters == 0)) {
// spurious unlock (unlock of unlocked lock)
return 0;
}