summaryrefslogtreecommitdiffstats
path: root/lib/libpthread/thread/thr_mutex.c
blob: b502c15af818c9530117d582291d155084c64090 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
/*
 * Copyright (c) 1995 John Birrell <jb@cimlogic.com.au>.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by John Birrell.
 * 4. Neither the name of the author nor the names of any co-contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY JOHN BIRRELL AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 * $FreeBSD$
 */
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/param.h>
#include <sys/queue.h>
#include <pthread.h>
#include "thr_private.h"

#if defined(_PTHREADS_INVARIANTS)
#define MUTEX_INIT_LINK(m) 		do {		\
	(m)->m_qe.tqe_prev = NULL;			\
	(m)->m_qe.tqe_next = NULL;			\
} while (0)
#define MUTEX_ASSERT_IS_OWNED(m)	do {		\
	if ((m)->m_qe.tqe_prev == NULL)			\
		PANIC("mutex is not on list");		\
} while (0)
#define MUTEX_ASSERT_NOT_OWNED(m)	do {		\
	if (((m)->m_qe.tqe_prev != NULL) ||		\
	    ((m)->m_qe.tqe_next != NULL))		\
		PANIC("mutex is on list");		\
} while (0)
#define	THR_ASSERT_NOT_IN_SYNCQ(thr)	do {		\
	THR_ASSERT(((thr)->sflags & THR_FLAGS_IN_SYNCQ) == 0, \
	    "thread in syncq when it shouldn't be.");	\
} while (0);
#else
#define MUTEX_INIT_LINK(m)
#define MUTEX_ASSERT_IS_OWNED(m)
#define MUTEX_ASSERT_NOT_OWNED(m)
#define	THR_ASSERT_NOT_IN_SYNCQ(thr)
#endif

#define THR_IN_MUTEXQ(thr)	(((thr)->sflags & THR_FLAGS_IN_SYNCQ) != 0)
#define	MUTEX_DESTROY(m) do {		\
	_lock_destroy(&(m)->m_lock);	\
	free(m);			\
} while (0)


/*
 * Prototypes
 */
static struct kse_mailbox *mutex_handoff(struct pthread *,
			    struct pthread_mutex *);
static inline int	mutex_self_trylock(struct pthread *, pthread_mutex_t);
static inline int	mutex_self_lock(struct pthread *, pthread_mutex_t);
static int		mutex_unlock_common(pthread_mutex_t *, int);
static void		mutex_priority_adjust(struct pthread *, pthread_mutex_t);
static void		mutex_rescan_owned (struct pthread *, struct pthread *,
			    struct pthread_mutex *);
static inline pthread_t	mutex_queue_deq(pthread_mutex_t);
static inline void	mutex_queue_remove(pthread_mutex_t, pthread_t);
static inline void	mutex_queue_enq(pthread_mutex_t, pthread_t);
static void		mutex_lock_backout(void *arg);

static struct pthread_mutex_attr	static_mutex_attr =
    PTHREAD_MUTEXATTR_STATIC_INITIALIZER;
static pthread_mutexattr_t		static_mattr = &static_mutex_attr;

/* Single underscore versions provided for libc internal usage: */
__weak_reference(__pthread_mutex_init, pthread_mutex_init);
__weak_reference(__pthread_mutex_lock, pthread_mutex_lock);
__weak_reference(__pthread_mutex_timedlock, pthread_mutex_timedlock);
__weak_reference(__pthread_mutex_trylock, pthread_mutex_trylock);

/* No difference between libc and application usage of these: */
__weak_reference(_pthread_mutex_destroy, pthread_mutex_destroy);
__weak_reference(_pthread_mutex_unlock, pthread_mutex_unlock);



int
__pthread_mutex_init(pthread_mutex_t *mutex,
    const pthread_mutexattr_t *mutex_attr)
{
	struct pthread_mutex *pmutex;
	enum pthread_mutextype type;
	int		protocol;
	int		ceiling;
	int		flags;
	int		ret = 0;

	if (mutex == NULL)
		ret = EINVAL;

	/* Check if default mutex attributes: */
	else if (mutex_attr == NULL || *mutex_attr == NULL) {
		/* Default to a (error checking) POSIX mutex: */
		type = PTHREAD_MUTEX_ERRORCHECK;
		protocol = PTHREAD_PRIO_NONE;
		ceiling = THR_MAX_PRIORITY;
		flags = 0;
	}

	/* Check mutex type: */
	else if (((*mutex_attr)->m_type < PTHREAD_MUTEX_ERRORCHECK) ||
	    ((*mutex_attr)->m_type >= MUTEX_TYPE_MAX))
		/* Return an invalid argument error: */
		ret = EINVAL;

	/* Check mutex protocol: */
	else if (((*mutex_attr)->m_protocol < PTHREAD_PRIO_NONE) ||
	    ((*mutex_attr)->m_protocol > PTHREAD_MUTEX_RECURSIVE))
		/* Return an invalid argument error: */
		ret = EINVAL;

	else {
		/* Use the requested mutex type and protocol: */
		type = (*mutex_attr)->m_type;
		protocol = (*mutex_attr)->m_protocol;
		ceiling = (*mutex_attr)->m_ceiling;
		flags = (*mutex_attr)->m_flags;
	}

	/* Check no errors so far: */
	if (ret == 0) {
		if ((pmutex = (pthread_mutex_t)
		    malloc(sizeof(struct pthread_mutex))) == NULL)
			ret = ENOMEM;
		else if (_lock_init(&pmutex->m_lock, LCK_ADAPTIVE,
		    _thr_lock_wait, _thr_lock_wakeup) != 0) {
			free(pmutex);
			*mutex = NULL;
			ret = ENOMEM;
		} else {
			/* Set the mutex flags: */
			pmutex->m_flags = flags;

			/* Process according to mutex type: */
			switch (type) {
			/* case PTHREAD_MUTEX_DEFAULT: */
			case PTHREAD_MUTEX_ERRORCHECK:
			case PTHREAD_MUTEX_NORMAL:
				/* Nothing to do here. */
				break;

			/* Single UNIX Spec 2 recursive mutex: */
			case PTHREAD_MUTEX_RECURSIVE:
				/* Reset the mutex count: */
				pmutex->m_count = 0;
				break;

			/* Trap invalid mutex types: */
			default:
				/* Return an invalid argument error: */
				ret = EINVAL;
				break;
			}
			if (ret == 0) {
				/* Initialise the rest of the mutex: */
				TAILQ_INIT(&pmutex->m_queue);
				pmutex->m_flags |= MUTEX_FLAGS_INITED;
				pmutex->m_owner = NULL;
				pmutex->m_type = type;
				pmutex->m_protocol = protocol;
				pmutex->m_refcount = 0;
				if (protocol == PTHREAD_PRIO_PROTECT)
					pmutex->m_prio = ceiling;
				else
					pmutex->m_prio = -1;
				pmutex->m_saved_prio = 0;
				MUTEX_INIT_LINK(pmutex);
				*mutex = pmutex;
			} else {
				/* Free the mutex lock structure: */
				MUTEX_DESTROY(pmutex);
				*mutex = NULL;
			}
		}
	}
	/* Return the completion status: */
	return (ret);
}

int
_pthread_mutex_init(pthread_mutex_t *mutex,
    const pthread_mutexattr_t *mutex_attr)
{
	struct pthread_mutex_attr mattr, *mattrp;

	if ((mutex_attr == NULL) || (*mutex_attr == NULL))
		return (__pthread_mutex_init(mutex, &static_mattr));
	else {
		mattr = **mutex_attr;
		mattr.m_flags |= MUTEX_FLAGS_PRIVATE;
		mattrp = &mattr;
		return (__pthread_mutex_init(mutex, &mattrp));
	}
}

void
_thr_mutex_reinit(pthread_mutex_t *mutex)
{
	_lock_reinit(&(*mutex)->m_lock, LCK_ADAPTIVE,
	    _thr_lock_wait, _thr_lock_wakeup);
	TAILQ_INIT(&(*mutex)->m_queue);
	(*mutex)->m_owner = NULL;
	(*mutex)->m_count = 0;
	(*mutex)->m_refcount = 0;
	(*mutex)->m_prio = 0;
	(*mutex)->m_saved_prio = 0;
}

int
_pthread_mutex_destroy(pthread_mutex_t *mutex)
{
	struct pthread	*curthread = _get_curthread();
	pthread_mutex_t m;
	int ret = 0;

	if (mutex == NULL || *mutex == NULL)
		ret = EINVAL;
	else {
		/* Lock the mutex structure: */
		THR_LOCK_ACQUIRE(curthread, &(*mutex)->m_lock);

		/*
		 * Check to see if this mutex is in use:
		 */
		if (((*mutex)->m_owner != NULL) ||
		    (TAILQ_FIRST(&(*mutex)->m_queue) != NULL) ||
		    ((*mutex)->m_refcount != 0)) {
			ret = EBUSY;

			/* Unlock the mutex structure: */
			THR_LOCK_RELEASE(curthread, &(*mutex)->m_lock);
		} else {
			/*
			 * Save a pointer to the mutex so it can be free'd
			 * and set the caller's pointer to NULL:
			 */
			m = *mutex;
			*mutex = NULL;

			/* Unlock the mutex structure: */
			THR_LOCK_RELEASE(curthread, &m->m_lock);

			/*
			 * Free the memory allocated for the mutex
			 * structure:
			 */
			MUTEX_ASSERT_NOT_OWNED(m);
			MUTEX_DESTROY(m);
		}
	}

	/* Return the completion status: */
	return (ret);
}

static int
init_static(struct pthread *thread, pthread_mutex_t *mutex)
{
	int ret;

	THR_LOCK_ACQUIRE(thread, &_mutex_static_lock);

	if (*mutex == NULL)
		ret = pthread_mutex_init(mutex, NULL);
	else
		ret = 0;

	THR_LOCK_RELEASE(thread, &_mutex_static_lock);

	return (ret);
}

static int
init_static_private(struct pthread *thread, pthread_mutex_t *mutex)
{
	int ret;

	THR_LOCK_ACQUIRE(thread, &_mutex_static_lock);

	if (*mutex == NULL)
		ret = pthread_mutex_init(mutex, &static_mattr);
	else
		ret = 0;

	THR_LOCK_RELEASE(thread, &_mutex_static_lock);

	return (ret);
}

static int
mutex_trylock_common(struct pthread *curthread, pthread_mutex_t *mutex)
{
	int private;
	int ret = 0;

	THR_ASSERT((mutex != NULL) && (*mutex != NULL),
	    "Uninitialized mutex in pthread_mutex_trylock_basic");

	/* Lock the mutex structure: */
	THR_LOCK_ACQUIRE(curthread, &(*mutex)->m_lock);
	private = (*mutex)->m_flags & MUTEX_FLAGS_PRIVATE;

	/*
	 * If the mutex was statically allocated, properly
	 * initialize the tail queue.
	 */
	if (((*mutex)->m_flags & MUTEX_FLAGS_INITED) == 0) {
		TAILQ_INIT(&(*mutex)->m_queue);
		MUTEX_INIT_LINK(*mutex);
		(*mutex)->m_flags |= MUTEX_FLAGS_INITED;
	}

	/* Process according to mutex type: */
	switch ((*mutex)->m_protocol) {
	/* Default POSIX mutex: */
	case PTHREAD_PRIO_NONE:	
		/* Check if this mutex is not locked: */
		if ((*mutex)->m_owner == NULL) {
			/* Lock the mutex for the running thread: */
			(*mutex)->m_owner = curthread;

			/* Add to the list of owned mutexes: */
			MUTEX_ASSERT_NOT_OWNED(*mutex);
			TAILQ_INSERT_TAIL(&curthread->mutexq,
			    (*mutex), m_qe);
		} else if ((*mutex)->m_owner == curthread)
			ret = mutex_self_trylock(curthread, *mutex);
		else
			/* Return a busy error: */
			ret = EBUSY;
		break;

	/* POSIX priority inheritence mutex: */
	case PTHREAD_PRIO_INHERIT:
		/* Check if this mutex is not locked: */
		if ((*mutex)->m_owner == NULL) {
			/* Lock the mutex for the running thread: */
			(*mutex)->m_owner = curthread;

			THR_SCHED_LOCK(curthread, curthread);
			/* Track number of priority mutexes owned: */
			curthread->priority_mutex_count++;

			/*
			 * The mutex takes on the attributes of the
			 * running thread when there are no waiters.
			 */
			(*mutex)->m_prio = curthread->active_priority;
			(*mutex)->m_saved_prio =
			    curthread->inherited_priority;
			curthread->inherited_priority = (*mutex)->m_prio;
			THR_SCHED_UNLOCK(curthread, curthread);

			/* Add to the list of owned mutexes: */
			MUTEX_ASSERT_NOT_OWNED(*mutex);
			TAILQ_INSERT_TAIL(&curthread->mutexq,
			    (*mutex), m_qe);
		} else if ((*mutex)->m_owner == curthread)
			ret = mutex_self_trylock(curthread, *mutex);
		else
			/* Return a busy error: */
			ret = EBUSY;
		break;

	/* POSIX priority protection mutex: */
	case PTHREAD_PRIO_PROTECT:
		/* Check for a priority ceiling violation: */
		if (curthread->active_priority > (*mutex)->m_prio)
			ret = EINVAL;

		/* Check if this mutex is not locked: */
		else if ((*mutex)->m_owner == NULL) {
			/* Lock the mutex for the running thread: */
			(*mutex)->m_owner = curthread;

			THR_SCHED_LOCK(curthread, curthread);
			/* Track number of priority mutexes owned: */
			curthread->priority_mutex_count++;

			/*
			 * The running thread inherits the ceiling
			 * priority of the mutex and executes at that
			 * priority.
			 */
			curthread->active_priority = (*mutex)->m_prio;
			(*mutex)->m_saved_prio =
			    curthread->inherited_priority;
			curthread->inherited_priority =
			    (*mutex)->m_prio;
			THR_SCHED_UNLOCK(curthread, curthread);
			/* Add to the list of owned mutexes: */
			MUTEX_ASSERT_NOT_OWNED(*mutex);
			TAILQ_INSERT_TAIL(&curthread->mutexq,
			    (*mutex), m_qe);
		} else if ((*mutex)->m_owner == curthread)
			ret = mutex_self_trylock(curthread, *mutex);
		else
			/* Return a busy error: */
			ret = EBUSY;
		break;

	/* Trap invalid mutex types: */
	default:
		/* Return an invalid argument error: */
		ret = EINVAL;
		break;
	}

	if (ret == 0 && private)
		THR_CRITICAL_ENTER(curthread);

	/* Unlock the mutex structure: */
	THR_LOCK_RELEASE(curthread, &(*mutex)->m_lock);

	/* Return the completion status: */
	return (ret);
}

int
__pthread_mutex_trylock(pthread_mutex_t *mutex)
{
	struct pthread *curthread = _get_curthread();
	int ret = 0;

	if (mutex == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization:
	 */
	else if ((*mutex != NULL) ||
	    ((ret = init_static(curthread, mutex)) == 0))
		ret = mutex_trylock_common(curthread, mutex);

	return (ret);
}

int
_pthread_mutex_trylock(pthread_mutex_t *mutex)
{
	struct pthread	*curthread = _get_curthread();
	int	ret = 0;

	if (mutex == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization marking the mutex private (delete safe):
	 */
	else if ((*mutex != NULL) ||
	    ((ret = init_static_private(curthread, mutex)) == 0))
		ret = mutex_trylock_common(curthread, mutex);

	return (ret);
}

static int
mutex_lock_common(struct pthread *curthread, pthread_mutex_t *m,
	const struct timespec * abstime)
{
	int	private;
	int	ret = 0;

	THR_ASSERT((m != NULL) && (*m != NULL),
	    "Uninitialized mutex in pthread_mutex_trylock_basic");

	if (abstime != NULL && (abstime->tv_sec < 0 || abstime->tv_nsec < 0 ||
	    abstime->tv_nsec >= 1000000000))
		return (EINVAL);

	/* Reset the interrupted flag: */
	curthread->interrupted = 0;
	curthread->timeout = 0;
	curthread->wakeup_time.tv_sec = -1;

	private = (*m)->m_flags & MUTEX_FLAGS_PRIVATE;

	/*
	 * Enter a loop waiting to become the mutex owner.  We need a
	 * loop in case the waiting thread is interrupted by a signal
	 * to execute a signal handler.  It is not (currently) possible
	 * to remain in the waiting queue while running a handler.
	 * Instead, the thread is interrupted and backed out of the
	 * waiting queue prior to executing the signal handler.
	 */
	do {
		/* Lock the mutex structure: */
		THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);

		/*
		 * If the mutex was statically allocated, properly
		 * initialize the tail queue.
		 */
		if (((*m)->m_flags & MUTEX_FLAGS_INITED) == 0) {
			TAILQ_INIT(&(*m)->m_queue);
			(*m)->m_flags |= MUTEX_FLAGS_INITED;
			MUTEX_INIT_LINK(*m);
		}

		/* Process according to mutex type: */
		switch ((*m)->m_protocol) {
		/* Default POSIX mutex: */
		case PTHREAD_PRIO_NONE:
			if ((*m)->m_owner == NULL) {
				/* Lock the mutex for this thread: */
				(*m)->m_owner = curthread;

				/* Add to the list of owned mutexes: */
				MUTEX_ASSERT_NOT_OWNED(*m);
				TAILQ_INSERT_TAIL(&curthread->mutexq,
				    (*m), m_qe);
				if (private)
					THR_CRITICAL_ENTER(curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else if ((*m)->m_owner == curthread) {
				ret = mutex_self_lock(curthread, *m);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else {
				/* Set the wakeup time: */
				if (abstime) {
					curthread->wakeup_time.tv_sec =
						abstime->tv_sec;
					curthread->wakeup_time.tv_nsec =
						abstime->tv_nsec;
				}

				/*
				 * Join the queue of threads waiting to lock
				 * the mutex and save a pointer to the mutex.
				 */
				mutex_queue_enq(*m, curthread);
				curthread->data.mutex = *m;
				curthread->sigbackout = mutex_lock_backout;
				/*
				 * This thread is active and is in a critical
				 * region (holding the mutex lock); we should
				 * be able to safely set the state.
				 */
				THR_SCHED_LOCK(curthread, curthread);
				THR_SET_STATE(curthread, PS_MUTEX_WAIT);
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

				/* Schedule the next thread: */
				_thr_sched_switch(curthread);

				if (THR_IN_MUTEXQ(curthread)) {
					THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);
					mutex_queue_remove(*m, curthread);
					THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
				}
				/*
				 * Only clear these after assuring the
				 * thread is dequeued.
				 */
				curthread->data.mutex = NULL;
				curthread->sigbackout = NULL;
			}
			break;

		/* POSIX priority inheritence mutex: */
		case PTHREAD_PRIO_INHERIT:
			/* Check if this mutex is not locked: */
			if ((*m)->m_owner == NULL) {
				/* Lock the mutex for this thread: */
				(*m)->m_owner = curthread;

				THR_SCHED_LOCK(curthread, curthread);
				/* Track number of priority mutexes owned: */
				curthread->priority_mutex_count++;

				/*
				 * The mutex takes on attributes of the
				 * running thread when there are no waiters.
				 * Make sure the thread's scheduling lock is
				 * held while priorities are adjusted.
				 */
				(*m)->m_prio = curthread->active_priority;
				(*m)->m_saved_prio =
				    curthread->inherited_priority;
				curthread->inherited_priority = (*m)->m_prio;
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Add to the list of owned mutexes: */
				MUTEX_ASSERT_NOT_OWNED(*m);
				TAILQ_INSERT_TAIL(&curthread->mutexq,
				    (*m), m_qe);
				if (private)
					THR_CRITICAL_ENTER(curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else if ((*m)->m_owner == curthread) {
				ret = mutex_self_lock(curthread, *m);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else {
				/* Set the wakeup time: */
				if (abstime) {
					curthread->wakeup_time.tv_sec =
						abstime->tv_sec;
					curthread->wakeup_time.tv_nsec =
						abstime->tv_nsec;
				}

				/*
				 * Join the queue of threads waiting to lock
				 * the mutex and save a pointer to the mutex.
				 */
				mutex_queue_enq(*m, curthread);
				curthread->data.mutex = *m;
				curthread->sigbackout = mutex_lock_backout;

				/*
				 * This thread is active and is in a critical
				 * region (holding the mutex lock); we should
				 * be able to safely set the state.
				 */
				if (curthread->active_priority > (*m)->m_prio)
					/* Adjust priorities: */
					mutex_priority_adjust(curthread, *m);

				THR_SCHED_LOCK(curthread, curthread);
				THR_SET_STATE(curthread, PS_MUTEX_WAIT);
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

				/* Schedule the next thread: */
				_thr_sched_switch(curthread);

				if (THR_IN_MUTEXQ(curthread)) {
					THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);
					mutex_queue_remove(*m, curthread);
					THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
				}
				/*
				 * Only clear these after assuring the
				 * thread is dequeued.
				 */
				curthread->data.mutex = NULL;
				curthread->sigbackout = NULL;
			}
			break;

		/* POSIX priority protection mutex: */
		case PTHREAD_PRIO_PROTECT:
			/* Check for a priority ceiling violation: */
			if (curthread->active_priority > (*m)->m_prio) {
				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
				ret = EINVAL;
			}
			/* Check if this mutex is not locked: */
			else if ((*m)->m_owner == NULL) {
				/*
				 * Lock the mutex for the running
				 * thread:
				 */
				(*m)->m_owner = curthread;

				THR_SCHED_LOCK(curthread, curthread);
				/* Track number of priority mutexes owned: */
				curthread->priority_mutex_count++;

				/*
				 * The running thread inherits the ceiling
				 * priority of the mutex and executes at that
				 * priority.  Make sure the thread's
				 * scheduling lock is held while priorities
				 * are adjusted.
				 */
				curthread->active_priority = (*m)->m_prio;
				(*m)->m_saved_prio =
				    curthread->inherited_priority;
				curthread->inherited_priority = (*m)->m_prio;
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Add to the list of owned mutexes: */
				MUTEX_ASSERT_NOT_OWNED(*m);
				TAILQ_INSERT_TAIL(&curthread->mutexq,
				    (*m), m_qe);
				if (private)
					THR_CRITICAL_ENTER(curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else if ((*m)->m_owner == curthread) {
				ret = mutex_self_lock(curthread, *m);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
			} else {
				/* Set the wakeup time: */
				if (abstime) {
					curthread->wakeup_time.tv_sec =
						abstime->tv_sec;
					curthread->wakeup_time.tv_nsec =
						abstime->tv_nsec;
				}

				/*
				 * Join the queue of threads waiting to lock
				 * the mutex and save a pointer to the mutex.
				 */
				mutex_queue_enq(*m, curthread);
				curthread->data.mutex = *m;
				curthread->sigbackout = mutex_lock_backout;

				/* Clear any previous error: */
				curthread->error = 0;

				/*
				 * This thread is active and is in a critical
				 * region (holding the mutex lock); we should
				 * be able to safely set the state.
				 */

				THR_SCHED_LOCK(curthread, curthread);
				THR_SET_STATE(curthread, PS_MUTEX_WAIT);
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Unlock the mutex structure: */
				THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

				/* Schedule the next thread: */
				_thr_sched_switch(curthread);

				if (THR_IN_MUTEXQ(curthread)) {
					THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);
					mutex_queue_remove(*m, curthread);
					THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
				}
				/*
				 * Only clear these after assuring the
				 * thread is dequeued.
				 */
				curthread->data.mutex = NULL;
				curthread->sigbackout = NULL;

				/*
				 * The threads priority may have changed while
				 * waiting for the mutex causing a ceiling
				 * violation.
				 */
				ret = curthread->error;
				curthread->error = 0;
			}
			break;

		/* Trap invalid mutex types: */
		default:
			/* Unlock the mutex structure: */
			THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

			/* Return an invalid argument error: */
			ret = EINVAL;
			break;
		}

	} while (((*m)->m_owner != curthread) && (ret == 0) &&
	    (curthread->interrupted == 0) && (curthread->timeout == 0));

	if (ret == 0 && (*m)->m_owner != curthread && curthread->timeout)
		ret = ETIMEDOUT;

	/*
	 * Check to see if this thread was interrupted and
	 * is still in the mutex queue of waiting threads:
	 */
	if (curthread->interrupted != 0) {
		/* Remove this thread from the mutex queue. */
		THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);
		if (THR_IN_SYNCQ(curthread))
			mutex_queue_remove(*m, curthread);
		THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

		/* Check for asynchronous cancellation. */
		if (curthread->continuation != NULL)
			curthread->continuation((void *) curthread);
	}

	/* Return the completion status: */
	return (ret);
}

int
__pthread_mutex_lock(pthread_mutex_t *m)
{
	struct pthread *curthread;
	int	ret = 0;

	if (_thr_initial == NULL)
		_libpthread_init(NULL);

	curthread = _get_curthread();
	if (m == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization:
	 */
	else if ((*m != NULL) || ((ret = init_static(curthread, m)) == 0))
		ret = mutex_lock_common(curthread, m, NULL);

	return (ret);
}

__strong_reference(__pthread_mutex_lock, _thr_mutex_lock);

int
_pthread_mutex_lock(pthread_mutex_t *m)
{
	struct pthread *curthread;
	int	ret = 0;

	if (_thr_initial == NULL)
		_libpthread_init(NULL);
	curthread = _get_curthread();

	if (m == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization marking it private (delete safe):
	 */
	else if ((*m != NULL) ||
	    ((ret = init_static_private(curthread, m)) == 0))
		ret = mutex_lock_common(curthread, m, NULL);

	return (ret);
}

int
__pthread_mutex_timedlock(pthread_mutex_t *m,
	const struct timespec *abs_timeout)
{
	struct pthread *curthread;
	int	ret = 0;

	if (_thr_initial == NULL)
		_libpthread_init(NULL);

	curthread = _get_curthread();
	if (m == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization:
	 */
	else if ((*m != NULL) || ((ret = init_static(curthread, m)) == 0))
		ret = mutex_lock_common(curthread, m, abs_timeout);

	return (ret);
}

int
_pthread_mutex_timedlock(pthread_mutex_t *m,
	const struct timespec *abs_timeout)
{
	struct pthread *curthread;
	int	ret = 0;

	if (_thr_initial == NULL)
		_libpthread_init(NULL);
	curthread = _get_curthread();

	if (m == NULL)
		ret = EINVAL;

	/*
	 * If the mutex is statically initialized, perform the dynamic
	 * initialization marking it private (delete safe):
	 */
	else if ((*m != NULL) ||
	    ((ret = init_static_private(curthread, m)) == 0))
		ret = mutex_lock_common(curthread, m, abs_timeout);

	return (ret);
}

int
_pthread_mutex_unlock(pthread_mutex_t *m)
{
	return (mutex_unlock_common(m, /* add reference */ 0));
}

__strong_reference(_pthread_mutex_unlock, _thr_mutex_unlock);

int
_mutex_cv_unlock(pthread_mutex_t *m)
{
	return (mutex_unlock_common(m, /* add reference */ 1));
}

int
_mutex_cv_lock(pthread_mutex_t *m)
{
	struct  pthread *curthread;
	int	ret;

	curthread = _get_curthread();
	if ((ret = _pthread_mutex_lock(m)) == 0) {
		THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);
		(*m)->m_refcount--;
		THR_LOCK_RELEASE(curthread, &(*m)->m_lock);
	}
	return (ret);
}

static inline int
mutex_self_trylock(struct pthread *curthread, pthread_mutex_t m)
{
	int	ret = 0;

	switch (m->m_type) {
	/* case PTHREAD_MUTEX_DEFAULT: */
	case PTHREAD_MUTEX_ERRORCHECK:
	case PTHREAD_MUTEX_NORMAL:
		ret = EBUSY; 
		break;

	case PTHREAD_MUTEX_RECURSIVE:
		/* Increment the lock count: */
		m->m_count++;
		break;

	default:
		/* Trap invalid mutex types; */
		ret = EINVAL;
	}

	return (ret);
}

static inline int
mutex_self_lock(struct pthread *curthread, pthread_mutex_t m)
{
	int ret = 0;

	/*
	 * Don't allow evil recursive mutexes for private use
	 * in libc and libpthread.
	 */
	if (m->m_flags & MUTEX_FLAGS_PRIVATE)
		PANIC("Recurse on a private mutex.");

	switch (m->m_type) {
	/* case PTHREAD_MUTEX_DEFAULT: */
	case PTHREAD_MUTEX_ERRORCHECK:
		/*
		 * POSIX specifies that mutexes should return EDEADLK if a
		 * recursive lock is detected.
		 */
		ret = EDEADLK; 
		break;

	case PTHREAD_MUTEX_NORMAL:
		/*
		 * What SS2 define as a 'normal' mutex.  Intentionally
		 * deadlock on attempts to get a lock you already own.
		 */

		THR_SCHED_LOCK(curthread, curthread);
		THR_SET_STATE(curthread, PS_DEADLOCK);
		THR_SCHED_UNLOCK(curthread, curthread);

		/* Unlock the mutex structure: */
		THR_LOCK_RELEASE(curthread, &m->m_lock);

		/* Schedule the next thread: */
		_thr_sched_switch(curthread);
		break;

	case PTHREAD_MUTEX_RECURSIVE:
		/* Increment the lock count: */
		m->m_count++;
		break;

	default:
		/* Trap invalid mutex types; */
		ret = EINVAL;
	}

	return (ret);
}

static int
mutex_unlock_common(pthread_mutex_t *m, int add_reference)
{
	struct pthread *curthread = _get_curthread();
	struct kse_mailbox *kmbx = NULL;
	int ret = 0;

	if (m == NULL || *m == NULL)
		ret = EINVAL;
	else {
		/* Lock the mutex structure: */
		THR_LOCK_ACQUIRE(curthread, &(*m)->m_lock);

		/* Process according to mutex type: */
		switch ((*m)->m_protocol) {
		/* Default POSIX mutex: */
		case PTHREAD_PRIO_NONE:
			/*
			 * Check if the running thread is not the owner of the
			 * mutex:
			 */
			if ((*m)->m_owner != curthread)
				ret = EPERM;
			else if (((*m)->m_type == PTHREAD_MUTEX_RECURSIVE) &&
			    ((*m)->m_count > 0))
				/* Decrement the count: */
				(*m)->m_count--;
			else {
				/*
				 * Clear the count in case this is a recursive
				 * mutex.
				 */
				(*m)->m_count = 0;

				/* Remove the mutex from the threads queue. */
				MUTEX_ASSERT_IS_OWNED(*m);
				TAILQ_REMOVE(&(*m)->m_owner->mutexq,
				    (*m), m_qe);
				MUTEX_INIT_LINK(*m);

				/*
				 * Hand off the mutex to the next waiting
				 * thread:
				 */
				kmbx = mutex_handoff(curthread, *m);
			}
			break;

		/* POSIX priority inheritence mutex: */
		case PTHREAD_PRIO_INHERIT:
			/*
			 * Check if the running thread is not the owner of the
			 * mutex:
			 */
			if ((*m)->m_owner != curthread)
				ret = EPERM;
			else if (((*m)->m_type == PTHREAD_MUTEX_RECURSIVE) &&
			    ((*m)->m_count > 0))
				/* Decrement the count: */
				(*m)->m_count--;
			else {
				/*
				 * Clear the count in case this is recursive
				 * mutex.
				 */
				(*m)->m_count = 0;

				/*
				 * Restore the threads inherited priority and
				 * recompute the active priority (being careful
				 * not to override changes in the threads base
				 * priority subsequent to locking the mutex).
				 */
				THR_SCHED_LOCK(curthread, curthread);
				curthread->inherited_priority =
					(*m)->m_saved_prio;
				curthread->active_priority =
				    MAX(curthread->inherited_priority,
				    curthread->base_priority);

				/*
				 * This thread now owns one less priority mutex.
				 */
				curthread->priority_mutex_count--;
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Remove the mutex from the threads queue. */
				MUTEX_ASSERT_IS_OWNED(*m);
				TAILQ_REMOVE(&(*m)->m_owner->mutexq,
				    (*m), m_qe);
				MUTEX_INIT_LINK(*m);

				/*
				 * Hand off the mutex to the next waiting
				 * thread:
				 */
				kmbx = mutex_handoff(curthread, *m);
			}
			break;

		/* POSIX priority ceiling mutex: */
		case PTHREAD_PRIO_PROTECT:
			/*
			 * Check if the running thread is not the owner of the
			 * mutex:
			 */
			if ((*m)->m_owner != curthread)
				ret = EPERM;
			else if (((*m)->m_type == PTHREAD_MUTEX_RECURSIVE) &&
			    ((*m)->m_count > 0))
				/* Decrement the count: */
				(*m)->m_count--;
			else {
				/*
				 * Clear the count in case this is a recursive
				 * mutex.
				 */
				(*m)->m_count = 0;

				/*
				 * Restore the threads inherited priority and
				 * recompute the active priority (being careful
				 * not to override changes in the threads base
				 * priority subsequent to locking the mutex).
				 */
				THR_SCHED_LOCK(curthread, curthread);
				curthread->inherited_priority =
					(*m)->m_saved_prio;
				curthread->active_priority =
				    MAX(curthread->inherited_priority,
				    curthread->base_priority);

				/*
				 * This thread now owns one less priority mutex.
				 */
				curthread->priority_mutex_count--;
				THR_SCHED_UNLOCK(curthread, curthread);

				/* Remove the mutex from the threads queue. */
				MUTEX_ASSERT_IS_OWNED(*m);
				TAILQ_REMOVE(&(*m)->m_owner->mutexq,
				    (*m), m_qe);
				MUTEX_INIT_LINK(*m);

				/*
				 * Hand off the mutex to the next waiting
				 * thread:
				 */
				kmbx = mutex_handoff(curthread, *m);
			}
			break;

		/* Trap invalid mutex types: */
		default:
			/* Return an invalid argument error: */
			ret = EINVAL;
			break;
		}

		if ((ret == 0) && (add_reference != 0))
			/* Increment the reference count: */
			(*m)->m_refcount++;

		/* Leave the critical region if this is a private mutex. */
		if ((ret == 0) && ((*m)->m_flags & MUTEX_FLAGS_PRIVATE))
			THR_CRITICAL_LEAVE(curthread);

		/* Unlock the mutex structure: */
		THR_LOCK_RELEASE(curthread, &(*m)->m_lock);

		if (kmbx != NULL)
			kse_wakeup(kmbx);
	}

	/* Return the completion status: */
	return (ret);
}


/*
 * This function is called when a change in base priority occurs for
 * a thread that is holding or waiting for a priority protection or
 * inheritence mutex.  A change in a threads base priority can effect
 * changes to active priorities of other threads and to the ordering
 * of mutex locking by waiting threads.
 *
 * This must be called without the target thread's scheduling lock held.
 */
void
_mutex_notify_priochange(struct pthread *curthread, struct pthread *pthread,
    int propagate_prio)
{
	struct pthread_mutex *m;

	/* Adjust the priorites of any owned priority mutexes: */
	if (pthread->priority_mutex_count > 0) {
		/*
		 * Rescan the mutexes owned by this thread and correct
		 * their priorities to account for this threads change
		 * in priority.  This has the side effect of changing
		 * the threads active priority.
		 *
		 * Be sure to lock the first mutex in the list of owned
		 * mutexes.  This acts as a barrier against another
		 * simultaneous call to change the threads priority
		 * and from the owning thread releasing the mutex.
		 */
		m = TAILQ_FIRST(&pthread->mutexq);
		if (m != NULL) {
			THR_LOCK_ACQUIRE(curthread, &m->m_lock);
			/*
			 * Make sure the thread still owns the lock.
			 */
			if (m == TAILQ_FIRST(&pthread->mutexq))
				mutex_rescan_owned(curthread, pthread,
				    /* rescan all owned */ NULL);
			THR_LOCK_RELEASE(curthread, &m->m_lock);
		}
	}

	/*
	 * If this thread is waiting on a priority inheritence mutex,
	 * check for priority adjustments.  A change in priority can
	 * also cause a ceiling violation(*) for a thread waiting on
	 * a priority protection mutex; we don't perform the check here
	 * as it is done in pthread_mutex_unlock.
	 *
	 * (*) It should be noted that a priority change to a thread
	 *     _after_ taking and owning a priority ceiling mutex
	 *     does not affect ownership of that mutex; the ceiling
	 *     priority is only checked before mutex ownership occurs.
	 */
	if (propagate_prio != 0) {
		/*
		 * Lock the thread's scheduling queue.  This is a bit
		 * convoluted; the "in synchronization queue flag" can
		 * only be cleared with both the thread's scheduling and
		 * mutex locks held.  The thread's pointer to the wanted
		 * mutex is guaranteed to be valid during this time.
		 */
		THR_SCHED_LOCK(curthread, pthread);

		if (((pthread->sflags & THR_FLAGS_IN_SYNCQ) == 0) ||
		    ((m = pthread->data.mutex) == NULL))
			THR_SCHED_UNLOCK(curthread, pthread);
		else {
			/*
			 * This thread is currently waiting on a mutex; unlock
			 * the scheduling queue lock and lock the mutex.  We
			 * can't hold both at the same time because the locking
			 * order could cause a deadlock.
			 */
			THR_SCHED_UNLOCK(curthread, pthread);
			THR_LOCK_ACQUIRE(curthread, &m->m_lock);

			/*
			 * Check to make sure this thread is still in the
			 * same state (the lock above can yield the CPU to
			 * another thread or the thread may be running on
			 * another CPU).
			 */
			if (((pthread->sflags & THR_FLAGS_IN_SYNCQ) != 0) &&
			    (pthread->data.mutex == m)) {
				/*
				 * Remove and reinsert this thread into
				 * the list of waiting threads to preserve
				 * decreasing priority order.
				 */
				mutex_queue_remove(m, pthread);
				mutex_queue_enq(m, pthread);

				if (m->m_protocol == PTHREAD_PRIO_INHERIT)
					/* Adjust priorities: */
					mutex_priority_adjust(curthread, m);
			}

			/* Unlock the mutex structure: */
			THR_LOCK_RELEASE(curthread, &m->m_lock);
		}
	}
}

/*
 * Called when a new thread is added to the mutex waiting queue or
 * when a threads priority changes that is already in the mutex
 * waiting queue.
 *
 * This must be called with the mutex locked by the current thread.
 */
static void
mutex_priority_adjust(struct pthread *curthread, pthread_mutex_t mutex)
{
	pthread_mutex_t	m = mutex;
	struct pthread	*pthread_next, *pthread = mutex->m_owner;
	int		done, temp_prio;

	/*
	 * Calculate the mutex priority as the maximum of the highest
	 * active priority of any waiting threads and the owning threads
	 * active priority(*).
	 *
	 * (*) Because the owning threads current active priority may
	 *     reflect priority inherited from this mutex (and the mutex
	 *     priority may have changed) we must recalculate the active
	 *     priority based on the threads saved inherited priority
	 *     and its base priority.
	 */
	pthread_next = TAILQ_FIRST(&m->m_queue);  /* should never be NULL */
	temp_prio = MAX(pthread_next->active_priority,
	    MAX(m->m_saved_prio, pthread->base_priority));

	/* See if this mutex really needs adjusting: */
	if (temp_prio == m->m_prio)
		/* No need to propagate the priority: */
		return;

	/* Set new priority of the mutex: */
	m->m_prio = temp_prio;

	/*
	 * Don't unlock the mutex passed in as an argument.  It is
	 * expected to be locked and unlocked by the caller.
	 */
	done = 1;
	do {
		/*
		 * Save the threads priority before rescanning the
		 * owned mutexes:
		 */
		temp_prio = pthread->active_priority;

		/*
		 * Fix the priorities for all mutexes held by the owning
		 * thread since taking this mutex.  This also has a
		 * potential side-effect of changing the threads priority.
		 *
		 * At this point the mutex is locked by the current thread.
		 * The owning thread can't release the mutex until it is
		 * unlocked, so we should be able to safely walk its list
		 * of owned mutexes.
		 */
		mutex_rescan_owned(curthread, pthread, m);

		/*
		 * If this isn't the first time through the loop,
		 * the current mutex needs to be unlocked.
		 */
		if (done == 0)
			THR_LOCK_RELEASE(curthread, &m->m_lock);

		/* Assume we're done unless told otherwise: */
		done = 1;

		/*
		 * If the thread is currently waiting on a mutex, check
		 * to see if the threads new priority has affected the
		 * priority of the mutex.
		 */
		if ((temp_prio != pthread->active_priority) &&
		    ((pthread->sflags & THR_FLAGS_IN_SYNCQ) != 0) &&
		    ((m = pthread->data.mutex) != NULL) &&
		    (m->m_protocol == PTHREAD_PRIO_INHERIT)) {
			/* Lock the mutex structure: */
			THR_LOCK_ACQUIRE(curthread, &m->m_lock);

			/*
			 * Make sure the thread is still waiting on the
			 * mutex:
			 */
			if (((pthread->sflags & THR_FLAGS_IN_SYNCQ) != 0) &&
			    (m == pthread->data.mutex)) {
				/*
				 * The priority for this thread has changed.
				 * Remove and reinsert this thread into the
				 * list of waiting threads to preserve
				 * decreasing priority order.
				 */
				mutex_queue_remove(m, pthread);
				mutex_queue_enq(m, pthread);

				/*
				 * Grab the waiting thread with highest
				 * priority:
				 */
				pthread_next = TAILQ_FIRST(&m->m_queue);

				/*
				 * Calculate the mutex priority as the maximum
				 * of the highest active priority of any
				 * waiting threads and the owning threads
				 * active priority.
				 */
				temp_prio = MAX(pthread_next->active_priority,
				    MAX(m->m_saved_prio,
				    m->m_owner->base_priority));

				if (temp_prio != m->m_prio) {
					/*
					 * The priority needs to be propagated
					 * to the mutex this thread is waiting
					 * on and up to the owner of that mutex.
					 */
					m->m_prio = temp_prio;
					pthread = m->m_owner;

					/* We're not done yet: */
					done = 0;
				}
			}
			/* Only release the mutex if we're done: */
			if (done != 0)
				THR_LOCK_RELEASE(curthread, &m->m_lock);
		}
	} while (done == 0);
}

static void
mutex_rescan_owned(struct pthread *curthread, struct pthread *pthread,
    struct pthread_mutex *mutex)
{
	struct pthread_mutex	*m;
	struct pthread		*pthread_next;
	int			active_prio, inherited_prio;

	/*
	 * Start walking the mutexes the thread has taken since
	 * taking this mutex.
	 */
	if (mutex == NULL) {
		/*
		 * A null mutex means start at the beginning of the owned
		 * mutex list.
		 */
		m = TAILQ_FIRST(&pthread->mutexq);

		/* There is no inherited priority yet. */
		inherited_prio = 0;
	} else {
		/*
		 * The caller wants to start after a specific mutex.  It
		 * is assumed that this mutex is a priority inheritence
		 * mutex and that its priority has been correctly
		 * calculated.
		 */
		m = TAILQ_NEXT(mutex, m_qe);

		/* Start inheriting priority from the specified mutex. */
		inherited_prio = mutex->m_prio;
	}
	active_prio = MAX(inherited_prio, pthread->base_priority);

	for (; m != NULL; m = TAILQ_NEXT(m, m_qe)) {
		/*
		 * We only want to deal with priority inheritence
		 * mutexes.  This might be optimized by only placing
		 * priority inheritence mutexes into the owned mutex
		 * list, but it may prove to be useful having all
		 * owned mutexes in this list.  Consider a thread
		 * exiting while holding mutexes...
		 */
		if (m->m_protocol == PTHREAD_PRIO_INHERIT) {
			/*
			 * Fix the owners saved (inherited) priority to
			 * reflect the priority of the previous mutex.
			 */
			m->m_saved_prio = inherited_prio;

			if ((pthread_next = TAILQ_FIRST(&m->m_queue)) != NULL)
				/* Recalculate the priority of the mutex: */
				m->m_prio = MAX(active_prio,
				     pthread_next->active_priority);
			else
				m->m_prio = active_prio;

			/* Recalculate new inherited and active priorities: */
			inherited_prio = m->m_prio;
			active_prio = MAX(m->m_prio, pthread->base_priority);
		}
	}

	/*
	 * Fix the threads inherited priority and recalculate its
	 * active priority.
	 */
	pthread->inherited_priority = inherited_prio;
	active_prio = MAX(inherited_prio, pthread->base_priority);

	if (active_prio != pthread->active_priority) {
		/* Lock the thread's scheduling queue: */
		THR_SCHED_LOCK(curthread, pthread);

		if ((pthread->flags & THR_FLAGS_IN_RUNQ) == 0) {
			/*
			 * This thread is not in a run queue.  Just set
			 * its active priority.
			 */
			pthread->active_priority = active_prio;
		}
		else {
			/*
			 * This thread is in a run queue.  Remove it from
			 * the queue before changing its priority:
			 */
			THR_RUNQ_REMOVE(pthread);

			/*
			 * POSIX states that if the priority is being
			 * lowered, the thread must be inserted at the
			 * head of the queue for its priority if it owns
			 * any priority protection or inheritence mutexes.
			 */
			if ((active_prio < pthread->active_priority) &&
			    (pthread->priority_mutex_count > 0)) {
				/* Set the new active priority. */
				pthread->active_priority = active_prio;

				THR_RUNQ_INSERT_HEAD(pthread);
			} else {
				/* Set the new active priority. */
				pthread->active_priority = active_prio;

				THR_RUNQ_INSERT_TAIL(pthread);
			}
		}
		THR_SCHED_UNLOCK(curthread, pthread);
	}
}

void
_mutex_unlock_private(pthread_t pthread)
{
	struct pthread_mutex	*m, *m_next;

	for (m = TAILQ_FIRST(&pthread->mutexq); m != NULL; m = m_next) {
		m_next = TAILQ_NEXT(m, m_qe);
		if ((m->m_flags & MUTEX_FLAGS_PRIVATE) != 0)
			pthread_mutex_unlock(&m);
	}
}

/*
 * This is called by the current thread when it wants to back out of a
 * mutex_lock in order to run a signal handler.
 */
static void
mutex_lock_backout(void *arg)
{
	struct pthread *curthread = (struct pthread *)arg;
	struct pthread_mutex *m;

	if ((curthread->sflags & THR_FLAGS_IN_SYNCQ) != 0) {
		/*
		 * Any other thread may clear the "in sync queue flag",
		 * but only the current thread can clear the pointer
		 * to the mutex.  So if the flag is set, we can
		 * guarantee that the pointer to the mutex is valid.
		 * The only problem may be if the mutex is destroyed
		 * out from under us, but that should be considered
		 * an application bug.
		 */
		m = curthread->data.mutex;

		/* Lock the mutex structure: */
		THR_LOCK_ACQUIRE(curthread, &m->m_lock);


		/*
		 * Check to make sure this thread doesn't already own
		 * the mutex.  Since mutexes are unlocked with direct
		 * handoffs, it is possible the previous owner gave it
		 * to us after we checked the sync queue flag and before
		 * we locked the mutex structure.
		 */
		if (m->m_owner == curthread) {
			THR_LOCK_RELEASE(curthread, &m->m_lock);
			mutex_unlock_common(&m, /* add_reference */ 0);
		} else {
			/*
			 * Remove ourselves from the mutex queue and
			 * clear the pointer to the mutex.  We may no
			 * longer be in the mutex queue, but the removal
			 * function will DTRT.
			 */
			mutex_queue_remove(m, curthread);
			curthread->data.mutex = NULL;
			THR_LOCK_RELEASE(curthread, &m->m_lock);
		}
	}
	/* No need to call this again. */
	curthread->sigbackout = NULL;
}

/*
 * Dequeue a waiting thread from the head of a mutex queue in descending
 * priority order.
 *
 * In order to properly dequeue a thread from the mutex queue and
 * make it runnable without the possibility of errant wakeups, it
 * is necessary to lock the thread's scheduling queue while also
 * holding the mutex lock.
 */
static struct kse_mailbox *
mutex_handoff(struct pthread *curthread, struct pthread_mutex *mutex)
{
	struct kse_mailbox *kmbx = NULL;
	struct pthread *pthread;

	/* Keep dequeueing until we find a valid thread: */
	mutex->m_owner = NULL;
	pthread = TAILQ_FIRST(&mutex->m_queue);
	while (pthread != NULL) {
		/* Take the thread's scheduling lock: */
		THR_SCHED_LOCK(curthread, pthread);

		/* Remove the thread from the mutex queue: */
		TAILQ_REMOVE(&mutex->m_queue, pthread, sqe);
		pthread->sflags &= ~THR_FLAGS_IN_SYNCQ;

		/*
		 * Only exit the loop if the thread hasn't been
		 * cancelled.
		 */
		switch (mutex->m_protocol) {
		case PTHREAD_PRIO_NONE:
			/*
			 * Assign the new owner and add the mutex to the
			 * thread's list of owned mutexes.
			 */
			mutex->m_owner = pthread;
			TAILQ_INSERT_TAIL(&pthread->mutexq, mutex, m_qe);
			break;

		case PTHREAD_PRIO_INHERIT:
			/*
			 * Assign the new owner and add the mutex to the
			 * thread's list of owned mutexes.
			 */
			mutex->m_owner = pthread;
			TAILQ_INSERT_TAIL(&pthread->mutexq, mutex, m_qe);

			/* Track number of priority mutexes owned: */
			pthread->priority_mutex_count++;

			/*
			 * Set the priority of the mutex.  Since our waiting
			 * threads are in descending priority order, the
			 * priority of the mutex becomes the active priority
			 * of the thread we just dequeued.
			 */
			mutex->m_prio = pthread->active_priority;

			/* Save the owning threads inherited priority: */
			mutex->m_saved_prio = pthread->inherited_priority;

			/*
			 * The owning threads inherited priority now becomes
			 * his active priority (the priority of the mutex).
			 */
			pthread->inherited_priority = mutex->m_prio;
			break;

		case PTHREAD_PRIO_PROTECT:
			if (pthread->active_priority > mutex->m_prio) {
				/*
				 * Either the mutex ceiling priority has
				 * been lowered and/or this threads priority
			 	 * has been raised subsequent to the thread
				 * being queued on the waiting list.
				 */
				pthread->error = EINVAL;
			}
			else {
				/*
				 * Assign the new owner and add the mutex
				 * to the thread's list of owned mutexes.
				 */
				mutex->m_owner = pthread;
				TAILQ_INSERT_TAIL(&pthread->mutexq,
				    mutex, m_qe);

				/* Track number of priority mutexes owned: */
				pthread->priority_mutex_count++;

				/*
				 * Save the owning threads inherited
				 * priority:
				 */
				mutex->m_saved_prio =
				    pthread->inherited_priority;

				/*
				 * The owning thread inherits the ceiling
				 * priority of the mutex and executes at
				 * that priority:
				 */
				pthread->inherited_priority = mutex->m_prio;
				pthread->active_priority = mutex->m_prio;

			}
			break;
		}

		/* Make the thread runnable and unlock the scheduling queue: */
		kmbx = _thr_setrunnable_unlocked(pthread);

		/* Add a preemption point. */
		if ((curthread->kseg == pthread->kseg) &&
		    (pthread->active_priority > curthread->active_priority))
			curthread->critical_yield = 1;

		if (mutex->m_owner == pthread) {
			/* We're done; a valid owner was found. */
			if (mutex->m_flags & MUTEX_FLAGS_PRIVATE)
				THR_CRITICAL_ENTER(pthread);
			THR_SCHED_UNLOCK(curthread, pthread);
			break;
		}
		THR_SCHED_UNLOCK(curthread, pthread);
		/* Get the next thread from the waiting queue: */
		pthread = TAILQ_NEXT(pthread, sqe);
	}

	if ((pthread == NULL) && (mutex->m_protocol == PTHREAD_PRIO_INHERIT))
		/* This mutex has no priority: */
		mutex->m_prio = 0;
	return (kmbx);
}

/*
 * Dequeue a waiting thread from the head of a mutex queue in descending
 * priority order.
 */
static inline pthread_t
mutex_queue_deq(struct pthread_mutex *mutex)
{
	pthread_t pthread;

	while ((pthread = TAILQ_FIRST(&mutex->m_queue)) != NULL) {
		TAILQ_REMOVE(&mutex->m_queue, pthread, sqe);
		pthread->sflags &= ~THR_FLAGS_IN_SYNCQ;

		/*
		 * Only exit the loop if the thread hasn't been
		 * cancelled.
		 */
		if (pthread->interrupted == 0)
			break;
	}

	return (pthread);
}

/*
 * Remove a waiting thread from a mutex queue in descending priority order.
 */
static inline void
mutex_queue_remove(pthread_mutex_t mutex, pthread_t pthread)
{
	if ((pthread->sflags & THR_FLAGS_IN_SYNCQ) != 0) {
		TAILQ_REMOVE(&mutex->m_queue, pthread, sqe);
		pthread->sflags &= ~THR_FLAGS_IN_SYNCQ;
	}
}

/*
 * Enqueue a waiting thread to a queue in descending priority order.
 */
static inline void
mutex_queue_enq(pthread_mutex_t mutex, pthread_t pthread)
{
	pthread_t tid = TAILQ_LAST(&mutex->m_queue, mutex_head);

	THR_ASSERT_NOT_IN_SYNCQ(pthread);
	/*
	 * For the common case of all threads having equal priority,
	 * we perform a quick check against the priority of the thread
	 * at the tail of the queue.
	 */
	if ((tid == NULL) || (pthread->active_priority <= tid->active_priority))
		TAILQ_INSERT_TAIL(&mutex->m_queue, pthread, sqe);
	else {
		tid = TAILQ_FIRST(&mutex->m_queue);
		while (pthread->active_priority <= tid->active_priority)
			tid = TAILQ_NEXT(tid, sqe);
		TAILQ_INSERT_BEFORE(tid, pthread, sqe);
	}
	pthread->sflags |= THR_FLAGS_IN_SYNCQ;
}
OpenPOWER on IntegriCloud