aboutsummaryrefslogblamecommitdiffstats
path: root/erts/lib_src/common/ethr_mutex.c
blob: 4a588dd7057a1a7bf2ed29b5cd1d7adc832cd7bc (plain) (tree)
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
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
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
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779




































                                                                         
                                 





















































                                                                      
                                                                      






                                                                 
                                                                          














































                                                                         







                                                                          
                                





                                                                              





























































































































































































































































































































































































































































                                                                               
                                 

                           



                                                                

          
                                                           


                                                   











                                                                  




















































































































































































































































































































































































































































                                                                               
                     







































                                                                           
                     



































































                                                                               
                     
                                                           
                     


























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                               
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 2010. All Rights Reserved.
 *
 * The contents of this file are subject to the Erlang Public License,
 * Version 1.1, (the "License"); you may not use this file except in
 * compliance with the License. You should have received a copy of the
 * Erlang Public License along with this software. If not, it can be
 * retrieved online at http://www.erlang.org/.
 *
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
 * the License for the specific language governing rights and limitations
 * under the License.
 *
 * %CopyrightEnd%
 */

/*
 * Description: Mutex, rwmutex and condition variable implementation
 * Author: Rickard Green
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#define ETHR_INLINE_FUNC_NAME_(X) X ## __
#define ETHR_MUTEX_IMPL__

#include <limits.h>
#include "ethread.h"
#include "ethr_internal.h"

#define ETHR_SPIN_WITH_WAITERS 1

#define ETHR_MTX_MAX_FLGS_SPIN 10

#ifdef ETHR_USE_OWN_RWMTX_IMPL__
static int default_rwmtx_main_spincount;
static int default_rwmtx_aux_spincount;
#endif
#ifdef ETHR_USE_OWN_MTX_IMPL__
static int default_mtx_main_spincount;
static int default_mtx_aux_spincount;
static int default_cnd_main_spincount;
static int default_cnd_aux_spincount;
#endif

static int no_spin;

#ifndef ETHR_USE_OWN_RWMTX_IMPL__
static pthread_rwlockattr_t write_pref_attr_data;
static pthread_rwlockattr_t *write_pref_attr;
#endif

#if defined(ETHR_MTX_Q_LOCK_SPINLOCK__)
#  define ETHR_MTX_QLOCK_INIT ethr_spinlock_init
#  define ETHR_MTX_QLOCK_DESTROY ethr_spinlock_destroy
#  define ETHR_MTX_Q_LOCK ethr_spin_lock
#  define ETHR_MTX_Q_UNLOCK ethr_spin_unlock
#elif defined(ETHR_MTX_Q_LOCK_PTHREAD_MUTEX__)
#  define ETHR_MTX_QLOCK_INIT(QL) pthread_mutex_init((QL), NULL)
#  define ETHR_MTX_QLOCK_DESTROY pthread_mutex_destroy
#  define ETHR_MTX_Q_LOCK(L)					\
do {								\
    int res__ = pthread_mutex_lock(L);				\
    if (res__ != 0)						\
	ETHR_FATAL_ERROR__(res__);				\
} while (0)
#  define ETHR_MTX_Q_UNLOCK(L)					\
do {								\
    int res__ = pthread_mutex_unlock(L);			\
    if (res__ != 0)						\
	ETHR_FATAL_ERROR__(res__);				\
} while (0)
#elif defined(ETHR_MTX_Q_LOCK_CRITICAL_SECTION__)
#  define ETHR_MTX_QLOCK_INIT(QL) (InitializeCriticalSection((QL)), 0)
#  define ETHR_MTX_QLOCK_DESTROY(QL) (DeleteCriticalSection((QL)), 0)
#  define ETHR_MTX_Q_LOCK(QL) EnterCriticalSection((QL))
#  define ETHR_MTX_Q_UNLOCK(QL) LeaveCriticalSection((QL))
#endif

int
ethr_mutex_lib_init(int cpu_conf)
{
    int res = 0;

    no_spin = cpu_conf == 1;

#ifdef ETHR_USE_OWN_MTX_IMPL__
    default_mtx_main_spincount = ETHR_MTX_DEFAULT_MAIN_SPINCOUNT_BASE;
    default_mtx_aux_spincount = ETHR_MTX_DEFAULT_AUX_SPINCOUNT;
    default_cnd_main_spincount = ETHR_CND_DEFAULT_MAIN_SPINCOUNT;
    default_cnd_aux_spincount = ETHR_CND_DEFAULT_AUX_SPINCOUNT;
#endif

#ifdef ETHR_USE_OWN_RWMTX_IMPL__

    default_rwmtx_main_spincount = ETHR_RWMTX_DEFAULT_MAIN_SPINCOUNT_BASE;
    default_rwmtx_aux_spincount = ETHR_RWMTX_DEFAULT_AUX_SPINCOUNT;

#else

#if defined(ETHR_HAVE_PTHREAD_RWLOCKATTR_SETKIND_NP) \
    && defined(ETHR_HAVE_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP)
    res = pthread_rwlockattr_init(&write_pref_attr_data);
    if (res != 0)
	return res;
    res = pthread_rwlockattr_setkind_np(
	&write_pref_attr_data,
	PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
    write_pref_attr = &write_pref_attr_data;
#else
    write_pref_attr = NULL;
#endif

#endif

    return res;
}

#ifdef ETHR_USE_OWN_RWMTX_IMPL__

#ifdef ETHR_ATOMIC_HAVE_INC_DEC_INSTRUCTIONS
#if 0 /*
       * When inc and dec are real atomic instructions as on x86, the
       * ETHR_RLOCK_WITH_INC_DEC implementations performs better with
       * lots of read locks compared to the cmpxchg based implementation.
       * It, however, performs worse with lots of mixed reads and writes.
       * It could be used for rwlocks that are known to be read locked
       * much, but the readers array based implementation outperforms it
       * by far. Therefore, it has been disabled, and will probably be
       * removed some time in the future.
       */
#  define ETHR_RLOCK_WITH_INC_DEC
#endif
#endif

static int reader_groups_array_size = 0;
static int main_threads_array_size = 0;

#endif

int
ethr_mutex_lib_late_init(int no_reader_groups, int no_main_threads)
{

#ifdef ETHR_USE_OWN_MTX_IMPL__
    default_mtx_main_spincount += (no_main_threads
				   * ETHR_MTX_DEFAULT_MAIN_SPINCOUNT_INC);
    if (default_mtx_main_spincount > ETHR_MTX_DEFAULT_MAIN_SPINCOUNT_MAX)
	default_mtx_main_spincount = ETHR_MTX_DEFAULT_MAIN_SPINCOUNT_MAX;
#endif

#ifdef ETHR_USE_OWN_RWMTX_IMPL__

    default_rwmtx_main_spincount += (no_main_threads
				     * ETHR_RWMTX_DEFAULT_MAIN_SPINCOUNT_INC);
    if (default_rwmtx_main_spincount > ETHR_RWMTX_DEFAULT_MAIN_SPINCOUNT_MAX)
	default_rwmtx_main_spincount = ETHR_RWMTX_DEFAULT_MAIN_SPINCOUNT_MAX;

    reader_groups_array_size = (no_reader_groups <= 1
				? 1
				: no_reader_groups + 1);
    main_threads_array_size = (no_main_threads <= 1
			       ? 1
			       : no_main_threads + 1);
#endif
    return 0;
}

int
ethr_rwmutex_set_reader_group(int ix)
{
#ifdef ETHR_USE_OWN_RWMTX_IMPL__
    ethr_ts_event *tse;

    if (ix < 0 || reader_groups_array_size <= ix)
	return EINVAL;

    tse = ethr_get_ts_event();

    if ((tse->iflgs & ETHR_TS_EV_ETHREAD) == 0) {
	ethr_leave_ts_event(tse);
	return EINVAL;
    }

    tse->rgix = ix;
    
    ethr_leave_ts_event(tse);
#endif
    return 0;
}

#if defined(ETHR_MTX_HARD_DEBUG_Q) || defined(ETHR_MTX_HARD_DEBUG_WSQ)
static void hard_debug_chk_q__(struct ethr_mutex_base_ *, int);
#define ETHR_RWMTX_HARD_DEBUG_CHK_Q(RWMTX) hard_debug_chk_q__(&(RWMTX)->mtxb,1)
#define ETHR_MTX_HARD_DEBUG_CHK_Q(MTX) hard_debug_chk_q__(&(MTX)->mtxb, 0)
#else
#define ETHR_RWMTX_HARD_DEBUG_CHK_Q(RWMTX)
#define ETHR_MTX_HARD_DEBUG_CHK_Q(MTX)
#endif

#ifdef ETHR_USE_OWN_RWMTX_IMPL__
static void
rwmutex_unlock_wake(ethr_rwmutex *rwmtx,
		    int have_w,
		    long initial);
static int
rwmutex_try_complete_runlock(ethr_rwmutex *rwmtx,
			     long initial,
			     ethr_ts_event *tse,
			     int start_next_ix,
			     int check_before_try,
			     int try_write_lock);
#endif

#if defined(ETHR_USE_OWN_RWMTX_IMPL__) || defined(ETHR_USE_OWN_MTX_IMPL__)

/* -- Utilities operating both on ordinary mutexes and read write mutexes -- */

static ETHR_INLINE void
rwmutex_freqread_wtng_rdrs_inc(ethr_rwmutex *rwmtx, ethr_ts_event *tse)
{
    int ix = (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ
	      ? tse->rgix
	      : tse->mtix);
    rwmtx->tdata.ra[ix].data.waiting_readers++;
}

static ETHR_INLINE void
rwmutex_freqread_rdrs_add(ethr_rwmutex *rwmtx,
			  ethr_rwmutex_type type,
			  int ix,
			  int inc)
{
    if (type == ETHR_RWMUTEX_TYPE_FREQUENT_READ || ix == 0)
	ethr_atomic_add(&rwmtx->tdata.ra[ix].data.readers, inc);
    else {
	ETHR_ASSERT(type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ);
	ETHR_ASSERT(ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers) == 0);
	ETHR_ASSERT(inc == 1);
	ethr_atomic_set(&rwmtx->tdata.ra[ix].data.readers, (long) 1);
    }
}

static ETHR_INLINE void
rwmutex_freqread_rdrs_inc(ethr_rwmutex *rwmtx, ethr_ts_event *tse)
{
    int ix;
    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
	ix = tse->rgix;
    atomic_inc:
	ethr_atomic_inc(&rwmtx->tdata.ra[ix].data.readers);
    }
    else {
	ix = tse->mtix;
	if (ix == 0)
	    goto atomic_inc;
	ETHR_ASSERT(rwmtx->type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ);
	ETHR_ASSERT(ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers) == 0);
	ethr_atomic_set(&rwmtx->tdata.ra[ix].data.readers, (long) 1);
    }
}

static ETHR_INLINE void
rwmutex_freqread_rdrs_dec(ethr_rwmutex *rwmtx, ethr_ts_event *tse)
{
    int ix;
    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
	ix = tse->rgix;
    atomic_dec:
	ethr_atomic_dec(&rwmtx->tdata.ra[ix].data.readers);
    }
    else {
	ix = tse->mtix;
	if (ix == 0)
	    goto atomic_dec;
	ETHR_ASSERT(rwmtx->type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ);
	ETHR_ASSERT(ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers) == 1);
	ethr_atomic_set(&rwmtx->tdata.ra[ix].data.readers, (long) 0);
    }
}

static ETHR_INLINE long
rwmutex_freqread_rdrs_dec_read(ethr_rwmutex *rwmtx, ethr_ts_event *tse)
{
    int ix;
    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
	ix = tse->rgix;
    atomic_dec_read:
	return ethr_atomic_dec_read(&rwmtx->tdata.ra[ix].data.readers);
    }
    else {
	ix = tse->mtix;
	if (ix == 0)
	    goto atomic_dec_read;
	ETHR_ASSERT(rwmtx->type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ);
	ETHR_ASSERT(ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers) == 1);
	ethr_atomic_set(&rwmtx->tdata.ra[ix].data.readers, (long) 0);
	return (long) 0;
    }
}

static ETHR_INLINE long
rwmutex_freqread_rdrs_dec_read_relb(ethr_rwmutex *rwmtx, ethr_ts_event *tse)
{
    int ix;
    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
	ix = tse->rgix;
    atomic_dec_read:
	return ethr_atomic_dec_read_relb(&rwmtx->tdata.ra[ix].data.readers);
    }
    else {
	ix = tse->mtix;
	if (ix == 0)
	    goto atomic_dec_read;
	ETHR_ASSERT(rwmtx->type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ);
	ETHR_ASSERT(ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers) == 1);
	ethr_atomic_set_relb(&rwmtx->tdata.ra[ix].data.readers, (long) 0);
	return (long) 0;
    }
}

static ETHR_INLINE long
rwmutex_freqread_rdrs_read(ethr_rwmutex *rwmtx, int ix)
{
    long res = ethr_atomic_read(&rwmtx->tdata.ra[ix].data.readers);
#ifdef ETHR_DEBUG
    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
	ETHR_ASSERT(res >= 0);
	break;
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ:
	ETHR_ASSERT(res == 0 || res == 1);
	break;
    default:
	ETHR_ASSERT(0);
	break;
    }
#endif
    return res;
}


static ETHR_INLINE void
enqueue(ethr_ts_event **queue,
	ethr_ts_event *tse_start,
	ethr_ts_event *tse_end)
{
    if (!*queue) {
	*queue = tse_start;
	tse_start->prev = tse_end;
	tse_end->next = tse_start;
    }
    else {
	tse_end->next = *queue;
	tse_start->prev = (*queue)->prev;
	(*queue)->prev->next = tse_start;
	(*queue)->prev = tse_end;
    }
}

static ETHR_INLINE void
insert(ethr_ts_event *tse_pred, ethr_ts_event *tse)
{
    tse->next = tse_pred->next;
    tse->prev = tse_pred;
    tse_pred->next->prev = tse;
    tse_pred->next = tse;
}

static ETHR_INLINE void
dequeue(ethr_ts_event **queue,
	ethr_ts_event *tse_start,
	ethr_ts_event *tse_end)
{
    if (tse_start->prev == tse_end) {
	ETHR_ASSERT(*queue == tse_start && tse_end->next == tse_start);
	*queue = NULL;
    }
    else {
	if (*queue == tse_start)
	    *queue = tse_end->next;
	tse_end->next->prev = tse_start->prev;
	tse_start->prev->next = tse_end->next;
    }
}

static void
event_wait(struct ethr_mutex_base_ *mtxb,
	   ethr_ts_event *tse,
	   int spincount,
	   long type,
	   int is_rwmtx,
	   int is_freq_read)
{
    int locked = 0;
    long act;
    int need_try_complete_runlock = 0;

    /* Need to enqueue and wait... */

    tse->uflgs = type;
    ethr_atomic_set(&tse->uaflgs, type);

    ETHR_MTX_Q_LOCK(&mtxb->qlck);
    locked = 1;

#ifdef ETHR_MTX_HARD_DEBUG_Q
    hard_debug_chk_q__(mtxb, is_rwmtx);
#endif

    act = ethr_atomic_read(&mtxb->flgs);

    if (act & type) {

	/* Wait bit already there; enqueue... */

	ETHR_ASSERT(mtxb->q);
	if (type == ETHR_RWMTX_W_WAIT_FLG__) {
	    enqueue(&mtxb->q, tse, tse);
#ifdef ETHR_MTX_HARD_DEBUG_WSQ
	    mtxb->ws++;
#endif
	}
	else {
	    ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	    ETHR_ASSERT(is_rwmtx);
	    ETHR_ASSERT(rwmtx->rq_end);
	    insert(rwmtx->rq_end, tse);
	    rwmtx->rq_end = tse;
	    if (is_freq_read)
		rwmutex_freqread_wtng_rdrs_inc(rwmtx, tse);
	    else
		rwmtx->tdata.rs++;
	}
    }
    else {

	/* Set wait bit */

	while (1) {
	    long new, exp = act;
	    int freqread_tryrlock = 0;
	    need_try_complete_runlock = 0;

	    if (type == ETHR_RWMTX_W_WAIT_FLG__) {
		if (is_freq_read && act == ETHR_RWMTX_R_FLG__)
		    need_try_complete_runlock = 1;
		if (act != 0)
		    new = act | ETHR_RWMTX_W_WAIT_FLG__;
		else
		    new = ETHR_RWMTX_W_FLG__; /* Try to get it */
	    }
	    else {
		ETHR_ASSERT(is_rwmtx);

		if (!is_freq_read) {
		    if (act & (ETHR_RWMTX_W_FLG__| ETHR_RWMTX_W_WAIT_FLG__))
			new = act | ETHR_RWMTX_R_WAIT_FLG__;
		    else
			new = act + 1; /* Try to get it */
		}
		else {
		    if (act & ~ETHR_RWMTX_R_FLG__)
			new = act | ETHR_RWMTX_R_WAIT_FLG__;
		    else { /* Try to get it */
			ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
			rwmutex_freqread_rdrs_inc(rwmtx, tse);
			ETHR_MEMORY_BARRIER;
			new = act | ETHR_RWMTX_R_FLG__;
			freqread_tryrlock = 1;
		    }
		}
	    }

	    act = ethr_atomic_cmpxchg_acqb(&mtxb->flgs, new, exp);
	    if (exp == act) {
		if (new & type) {
		    act = new;
		    break;
		}
		else {
		    /* Got it */
		    goto done;
		}
	    }

	    if (freqread_tryrlock) {
		ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;

		/* We didn't set ETHR_RWMTX_R_FLG__, however someone
		   else might have */
		if (act == ETHR_RWMTX_R_FLG__)
		    goto done; /* Got it by help from someone else */

		ETHR_ASSERT((act & ETHR_RWMTX_WAIT_FLGS__) == 0);
		/*
		 * We know that no waiter flags have been set, i.e.,
		 * we cannot get into a situation where we need to wake
		 * someone up here. Just restore the readers counter
		 * and do it over again...
		 */
		rwmutex_freqread_rdrs_dec(rwmtx, tse);
	    }
	}

	/* Enqueue */

	if (type == ETHR_RWMTX_R_WAIT_FLG__) {
	    ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	    ETHR_ASSERT(is_rwmtx);
	    ETHR_ASSERT(!rwmtx->rq_end);
	    rwmtx->rq_end =  tse;
	    if (is_freq_read)
		rwmutex_freqread_wtng_rdrs_inc(rwmtx, tse);
	    else
		rwmtx->tdata.rs++;
	}
#ifdef ETHR_MTX_HARD_DEBUG_WSQ
	else {
	    mtxb->ws++;
	}
#endif

	enqueue(&mtxb->q, tse, tse);
    }

#ifdef ETHR_MTX_HARD_DEBUG_Q
    hard_debug_chk_q__(mtxb, is_rwmtx);
#endif

    /* Wait */
    locked = 0;
    ETHR_MTX_Q_UNLOCK(&mtxb->qlck);

    if (need_try_complete_runlock) {
	ETHR_ASSERT(((ethr_rwmutex *) mtxb)->type
		    != ETHR_RWMUTEX_TYPE_NORMAL);
	/*
	 * We were the only one in queue when we enqueued, and it
	 * was seemingly read locked. We need to try to complete a
	 * runlock otherwise we might be hanging forever. If the
	 * runlock could be completed we will be dequeued and
	 * woken by ourselves.
	 */
	rwmutex_try_complete_runlock((ethr_rwmutex *) mtxb,
				     act, tse, 0, 1, 0);
    }

    while (1) {
	ethr_event_reset(&tse->event);

	act = ethr_atomic_read_acqb(&tse->uaflgs);
	if (!act)
	    goto done; /* Got it */

	ETHR_ASSERT(act == type);
	ethr_event_swait(&tse->event, spincount);
	/* swait result: 0 || EINTR */

	act = ethr_atomic_read_acqb(&tse->uaflgs);
	if (!act)
	    goto done; /* Got it */
    }

 done:
    if (locked)
	ETHR_MTX_Q_UNLOCK(&mtxb->qlck);
}

static void
wake_writer(struct ethr_mutex_base_ *mtxb, int is_rwmtx)
{
    ethr_ts_event *tse;

    tse = mtxb->q;
    ETHR_ASSERT(tse);
    dequeue(&mtxb->q, tse, tse);

    ETHR_ASSERT(tse->uflgs == ETHR_RWMTX_W_WAIT_FLG__);
    ETHR_ASSERT(ethr_atomic_read(&tse->uaflgs) == ETHR_RWMTX_W_WAIT_FLG__);
#ifdef ETHR_MTX_HARD_DEBUG_WSQ
    mtxb->ws--;
#endif
#if defined(ETHR_MTX_HARD_DEBUG_Q) || defined(ETHR_MTX_HARD_DEBUG_WSQ)
    hard_debug_chk_q__(mtxb, is_rwmtx);
#endif

    ETHR_MTX_Q_UNLOCK(&mtxb->qlck);

    ethr_atomic_set(&tse->uaflgs, 0);
    ethr_event_set(&tse->event);
}

static ETHR_INLINE int
initial_spincount(struct ethr_mutex_base_ *mtxb)
{
    return (mtxb->aux_scnt < ETHR_MTX_MAX_FLGS_SPIN
	    ? mtxb->aux_scnt
	    : ETHR_MTX_MAX_FLGS_SPIN);
}

static ETHR_INLINE int
update_spincount(struct ethr_mutex_base_ *mtxb,
		 ethr_ts_event *tse,
		 int *scnt_state,
		 int *scnt)
{
    int state = *scnt_state;
    if (state <= 0) {
	/* Here state is max spincount to do on event negated */
	*scnt = -state;
    }
    else {
	/* Here state is initial spincount made on flags */
	*scnt = ((tse->iflgs & ETHR_TS_EV_MAIN_THR)
		 ? mtxb->main_scnt
		 : mtxb->aux_scnt);
	if (*scnt <= state)
	    *scnt = 0;
	else {
	    if (*scnt <= ETHR_MTX_MAX_FLGS_SPIN)
		*scnt_state = 0; /* No spin on event */
	    else {
		 /* Spin on event after... */
		*scnt_state = -1*(*scnt - ETHR_MTX_MAX_FLGS_SPIN);
		/* ... we have spun on flags */
		*scnt = ETHR_MTX_MAX_FLGS_SPIN;
	    }
	    *scnt -= state;
	    return 0;
	}
    }
    return 1;
}

int check_readers_array(ethr_rwmutex *rwmtx,
			int start_rix,
			int length,
			int pre_check);

static ETHR_INLINE void
write_lock_wait(struct ethr_mutex_base_ *mtxb,
		long initial,
		int is_rwmtx,
		int is_freq_read)
{
    long act = initial;
    int scnt, start_scnt;
    ethr_ts_event *tse = NULL;
    int until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;
    int res;
    int freq_read_size = -1;
    int freq_read_start_ix = -1;

    ETHR_ASSERT(!is_freq_read || is_rwmtx);

    start_scnt = scnt = initial_spincount(mtxb);

    /*
     * Spin trying to write lock for a while. If unsuccessful,
     * wait on event.
     */

    while (1) {
	long exp;

	while (act != 0) {

	    if (is_freq_read && act == ETHR_RWMTX_R_FLG__) {
		ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
		if (!tse)
		    tse = ethr_get_ts_event();
		if (freq_read_size < 0) {
		    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
			freq_read_size = reader_groups_array_size;
			freq_read_start_ix = tse->rgix;
		    }
		    else {
			freq_read_size = main_threads_array_size;
			freq_read_start_ix = tse->mtix;
		    }
		}
		res = check_readers_array(rwmtx,
					  freq_read_start_ix,
					  freq_read_size,
					  1);
		scnt--;
		if (res == 0) {
		    act = ethr_atomic_read(&mtxb->flgs);
		    if (act & ETHR_RWMTX_R_MASK__) {
			res = rwmutex_try_complete_runlock(rwmtx, act,
							   tse, 0, 0,
							   1);
			if (res != EBUSY)
			    goto done; /* Got it */
		    }
		    if (scnt <= 0)
			goto chk_spin;
		    if (--until_yield == 0) {
			until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;
			ETHR_YIELD();
		    }
		    continue;
		}
	    }

	    if (scnt <= 0) {
	    chk_spin:
		scnt = 0;

		if (!tse)
		    tse = ethr_get_ts_event();
		if (update_spincount(mtxb, tse, &start_scnt, &scnt)) {
		    event_wait(mtxb, tse, scnt, ETHR_RWMTX_W_WAIT_FLG__,
			       is_rwmtx, is_freq_read);
		    goto done;
		}
	    }
	    ETHR_SPIN_BODY;
	    if (--until_yield == 0) {
		until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;
		ETHR_YIELD();
	    }
	    act = ethr_atomic_read(&mtxb->flgs);
	    scnt--;
	}
	ETHR_ASSERT(scnt >= 0);

	exp = act;

	act = ethr_atomic_cmpxchg_acqb(&mtxb->flgs,
				       ETHR_RWMTX_W_FLG__,
				       exp);
	if (act == 0)
	    goto done; /* Got it */
    }

 done:
    if (tse)
	ethr_leave_ts_event(tse);
}

static int
mtxb_init(struct ethr_mutex_base_ *mtxb,
	  int def_main_scnt,
	  int main_scnt,
	  int def_aux_scnt,
	  int aux_scnt)
{
    ETHR_MTX_HARD_DEBUG_LFS_INIT(mtxb);
#ifdef ETHR_MTX_HARD_DEBUG_WSQ
    mtxb->ws = 0;
#endif
    if (no_spin) {
	mtxb->main_scnt = 0;
	mtxb->aux_scnt = 0;
    }
    else {
	if (main_scnt > SHRT_MAX)
	    mtxb->main_scnt = SHRT_MAX;
	else if (main_scnt < 0)
	    mtxb->main_scnt = def_main_scnt;
	else
	    mtxb->main_scnt = (short) main_scnt;
	if (aux_scnt > SHRT_MAX)
	    mtxb->aux_scnt = SHRT_MAX;
	else if (aux_scnt < 0)
	    mtxb->aux_scnt = def_aux_scnt;
	else
	    mtxb->aux_scnt = (short) aux_scnt;
	if (mtxb->main_scnt < mtxb->aux_scnt)
	    mtxb->main_scnt = mtxb->aux_scnt;

    }
    mtxb->q = NULL;
    ethr_atomic_init(&mtxb->flgs, 0);
    return ETHR_MTX_QLOCK_INIT(&mtxb->qlck);
}

static int
mtxb_destroy(struct ethr_mutex_base_ *mtxb)
{
    long act;
    ETHR_MTX_Q_LOCK(&mtxb->qlck);
    act = ethr_atomic_read(&mtxb->flgs);
    ETHR_MTX_Q_UNLOCK(&mtxb->qlck);
    if (act != 0)
	return EINVAL;
    return ETHR_MTX_QLOCK_DESTROY(&mtxb->qlck);
}


#endif /* ETHR_USE_OWN_RWMTX_IMPL__ || ETHR_USE_OWN_MTX_IMPL__ */

/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
 * Mutex and condition variable implementation                               *
\*                                                                           */

#ifdef ETHR_USE_OWN_MTX_IMPL__

/* -- Mutex ---------------------------------------------------------------- */

int
ethr_mutex_init_opt(ethr_mutex *mtx, ethr_mutex_opt *opt)
{
    int res;
#if ETHR_XCHK
    if (!mtx) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    mtx->initialized = ETHR_MUTEX_INITIALIZED;
#endif
    ETHR_MTX_HARD_DEBUG_FENCE_INIT(mtx);
    res = mtxb_init(&mtx->mtxb,
		    default_mtx_main_spincount,
		    opt ? opt->main_spincount : -1,
		    default_mtx_aux_spincount,
		    opt ? opt->aux_spincount : -1);
#if ETHR_XCHK
    if (res != 0)
	mtx->initialized = 0;
#endif
    return res;
}

int
ethr_mutex_init(ethr_mutex *mtx)
{
    return ethr_mutex_init_opt(mtx, NULL);
}

int
ethr_mutex_destroy(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!mtx) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    mtx->initialized = 0;
#endif
    return mtxb_destroy(&mtx->mtxb);
}

void
ethr_mutex_lock_wait__(ethr_mutex *mtx, long initial)
{
    write_lock_wait(&mtx->mtxb, initial, 0, 0);
}

void
ethr_mutex_unlock_wake__(ethr_mutex *mtx, long initial)
{
    ethr_ts_event *tse;

    ETHR_MTX_Q_LOCK(&mtx->mtxb.qlck);
    tse = mtx->mtxb.q;

    ETHR_ASSERT(tse);
    ETHR_ASSERT(ethr_atomic_read(&mtx->mtxb.flgs)
		== (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__));
    ETHR_ASSERT(initial & ETHR_RWMTX_W_WAIT_FLG__);
    ETHR_MTX_HARD_DEBUG_CHK_Q(mtx);

    /*
     * If we have multiple waiters, there is no need to modify
     * mtxb->flgs; otherwise, we need to clear the write wait bit...
     */
    if (tse->next == mtx->mtxb.q)
	ethr_atomic_set(&mtx->mtxb.flgs, ETHR_RWMTX_W_FLG__);

    wake_writer(&mtx->mtxb, 0);
}

/* -- Condition variables -------------------------------------------------- */

static void
enqueue_mtx(ethr_mutex *mtx, ethr_ts_event *tse_start, ethr_ts_event *tse_end)
{
    long act;

    /*
     * `ethr_cond_signal()' and `ethr_cond_broadcast()' end up here. If `mtx'
     * is not currently locked by current thread, we almost certainly have a
     * hard to debug race condition. There might however be some (strange)
     * use for it. POSIX also allow a call to `pthread_cond_signal' or
     * `pthread_cond_broadcast' even though the the associated mutex isn't
     * locked by the caller. Therefore, we also allow this kind of strange
     * usage, but optimize for the case where the mutex is locked by the
     * calling thread.
     */

    ETHR_MTX_Q_LOCK(&mtx->mtxb.qlck);

    ETHR_MTX_HARD_DEBUG_CHK_Q(mtx);

#ifdef ETHR_MTX_HARD_DEBUG_WSQ
    {
	int dbg_nws__ = 0;
	ethr_ts_event *dbg_tse__;
	for (dbg_tse__ = tse_start;
	     dbg_tse__ != tse_end;
	     dbg_tse__ = dbg_tse__->next)
	    dbg_nws__++;
	mtx->mtxb.ws += dbg_nws__ + 1;
    }
#endif

    act = ethr_atomic_read(&mtx->mtxb.flgs);
    ETHR_ASSERT(act == 0
		|| act == ETHR_RWMTX_W_FLG__
		|| act == (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__));
    if (act & ETHR_RWMTX_W_FLG__) {
	/* The normal sane case */
	if (!(act & ETHR_RWMTX_W_WAIT_FLG__)) {
	    ETHR_ASSERT(!mtx->mtxb.q);
	    act = ethr_atomic_cmpxchg(&mtx->mtxb.flgs,
				      (ETHR_RWMTX_W_FLG__
				       | ETHR_RWMTX_W_WAIT_FLG__),
				      ETHR_RWMTX_W_FLG__);
	    if (act != ETHR_RWMTX_W_FLG__) {
		/*
		 * Sigh... this wasn't so sane after all since, the mutex was
		 * obviously not locked by the current thread....
		 */
		ETHR_ASSERT(act == 0);
		goto mtx_unlocked;
	    }
	}

#ifdef ETHR_DEBUG
	if (act & ETHR_RWMTX_W_WAIT_FLG__)
	    ETHR_ASSERT(mtx->mtxb.q);
	else
	    ETHR_ASSERT(!mtx->mtxb.q);
#endif

	enqueue(&mtx->mtxb.q, tse_start, tse_end);

	ETHR_MTX_HARD_DEBUG_CHK_Q(mtx);
	ETHR_MTX_Q_UNLOCK(&mtx->mtxb.qlck);

    }
    else {
	int multi;
    mtx_unlocked:
	/* Sigh... mutex isn't locked... */

	multi = tse_start != tse_end;

	while (1) {
	    long new, exp = act;

	    if (multi || (act & ETHR_RWMTX_W_FLG__))
		new = ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__;
	    else
		new = ETHR_RWMTX_W_FLG__;

	    act = ethr_atomic_cmpxchg(&mtx->mtxb.flgs, new, exp);
	    if (exp == act) {
		ETHR_ASSERT(!mtx->mtxb.q);
		if (act & ETHR_RWMTX_W_FLG__) {
		    enqueue(&mtx->mtxb.q, tse_start, tse_end);

		    ETHR_MTX_HARD_DEBUG_CHK_Q(mtx);
		    ETHR_MTX_Q_UNLOCK(&mtx->mtxb.qlck);

		}
		else {
		    ETHR_ASSERT(!mtx->mtxb.q);
		    /*
		     * Acquired the mutex on behalf of the
		     * first thread in the queue; wake
		     * it and enqueue the rest...
		     */
#ifdef ETHR_MTX_HARD_DEBUG_WSQ
		    mtx->mtxb.ws--;
#endif
		    if (multi) {
			enqueue(&mtx->mtxb.q, tse_start->next, tse_end);
			ETHR_ASSERT(mtx->mtxb.q);
		    }

		    ETHR_MTX_HARD_DEBUG_CHK_Q(mtx);
		    ETHR_MTX_Q_UNLOCK(&mtx->mtxb.qlck);

		    ethr_atomic_set(&tse_start->uaflgs, 0);
		    ethr_event_set(&tse_start->event);
		}
		break;
	    }
	}
    }
}

int
ethr_cond_init_opt(ethr_cond *cnd, ethr_cond_opt *opt)
{
    int res;
#if ETHR_XCHK
    if (!cnd) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    cnd->initialized = ETHR_COND_INITIALIZED;
#endif
    ETHR_MTX_HARD_DEBUG_FENCE_INIT(cnd);
    cnd->q = NULL;
    if (no_spin) {
	cnd->main_scnt = 0;
	cnd->aux_scnt = 0;
    }
    else {
	if (!opt || opt->main_spincount < 0)
	    cnd->main_scnt = default_cnd_main_spincount;
	else if (opt->main_spincount > SHRT_MAX)
	    cnd->main_scnt = SHRT_MAX;
	else
	    cnd->main_scnt = (short) opt->main_spincount;
	if (!opt || opt->aux_spincount < 0)
	    cnd->aux_scnt = default_cnd_aux_spincount;
	else if (opt->aux_spincount > SHRT_MAX)
	    cnd->aux_scnt = SHRT_MAX;
	else
	    cnd->aux_scnt = (short) opt->aux_spincount;
	if (cnd->main_scnt < cnd->aux_scnt)
	    cnd->main_scnt = cnd->aux_scnt;
    }
    ETHR_MTX_QLOCK_INIT(&cnd->qlck);
    return 0;
}

int
ethr_cond_init(ethr_cond *cnd)
{
    return ethr_cond_init_opt(cnd, NULL);
}

int
ethr_cond_destroy(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!cnd || cnd->initialized != ETHR_COND_INITIALIZED) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    cnd->initialized = 0;
#endif
    return ETHR_MTX_QLOCK_DESTROY(&cnd->qlck);
}

void
ethr_cond_signal(ethr_cond *cnd)
{
    ethr_ts_event *tse;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);

    ETHR_MTX_Q_LOCK(&cnd->qlck);

    tse = cnd->q;

    if (!tse) {
	ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
	ETHR_MTX_Q_UNLOCK(&cnd->qlck);
    }
    else {
	ethr_mutex *mtx = (ethr_mutex *) tse->udata;

	ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);
	ETHR_ASSERT(tse->uflgs == ETHR_RWMTX_W_WAIT_FLG__);
	ETHR_ASSERT(ethr_atomic_read(&tse->uaflgs) == ETHR_CND_WAIT_FLG__);

	ethr_atomic_set(&tse->uaflgs, ETHR_RWMTX_W_WAIT_FLG__);

	dequeue(&cnd->q, tse, tse);

	ETHR_MTX_Q_UNLOCK(&cnd->qlck);

	tse->next = tse->prev = NULL;

	enqueue_mtx(mtx, tse, tse);

	ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
	ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);
    }
}

void
ethr_cond_broadcast(ethr_cond *cnd)
{
    int res;
    int got_all;
    ethr_ts_event *tse;
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
    do {
	got_all = 1;

	ETHR_MTX_Q_LOCK(&cnd->qlck);

	tse = cnd->q;

	if (!tse) {
	    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
	    ETHR_MTX_Q_UNLOCK(&cnd->qlck);
	}
	else {
	    ethr_mutex *mtx = (ethr_mutex *) tse->udata;
	    ethr_ts_event *tse_tmp, *tse_end;

	    ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);
	    tse_end = cnd->q->prev;

	    tse_tmp = tse;

	    do {

		if (mtx == (ethr_mutex *) tse_tmp->udata) {
		    /* The normal case */

		    ETHR_ASSERT(tse_tmp->uflgs == ETHR_RWMTX_W_WAIT_FLG__);
		    ETHR_ASSERT(ethr_atomic_read(&tse_tmp->uaflgs)
				== ETHR_CND_WAIT_FLG__);

		    ethr_atomic_set(&tse_tmp->uaflgs, ETHR_RWMTX_W_WAIT_FLG__);
		}
		else {
		    /* Should be very unusual */
		    ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);
		    tse_end = tse_tmp->prev;
		    got_all = 0;
		    break;
		}

		tse_tmp = tse_tmp->next;

	    } while (tse_tmp != cnd->q);

	    dequeue(&cnd->q, tse, tse_end);

	    ETHR_MTX_Q_UNLOCK(&cnd->qlck);

	    enqueue_mtx(mtx, tse, tse_end);
	}

    } while (!got_all);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
}

int
ethr_cond_wait(ethr_cond *cnd, ethr_mutex *mtx)
{
    int woken;
    int scnt;
    int res;
    void *udata = NULL;
    ethr_ts_event *tse;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);
    ETHR_ASSERT(mtx);
    ETHR_ASSERT(mtx->initialized == ETHR_MUTEX_INITIALIZED);

    tse = ethr_get_ts_event();

    scnt = ((tse->iflgs & ETHR_TS_EV_MAIN_THR)
	    ? cnd->main_scnt
	    : cnd->aux_scnt);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);

    udata = tse->udata; /* Got to restore udata before returning */
    tse->udata = (void *) mtx;

    tse->uflgs = ETHR_RWMTX_W_WAIT_FLG__; /* Prep for mutex lock op */
    ethr_atomic_set(&tse->uaflgs, ETHR_CND_WAIT_FLG__);

    ETHR_MTX_Q_LOCK(&cnd->qlck);

    enqueue(&cnd->q, tse, tse);

    ETHR_MTX_Q_UNLOCK(&cnd->qlck);

    ethr_mutex_unlock(mtx);

    /* Wait */
    woken = 0;
    while (1) {
	long act;

	ethr_event_reset(&tse->event);

	act = ethr_atomic_read_acqb(&tse->uaflgs);
	if (!act)
	    break; /* Mtx locked */

	/* First time, got EINTR, or spurious wakeup... */

	ETHR_ASSERT(act == ETHR_CND_WAIT_FLG__
		    || act == ETHR_RWMTX_W_WAIT_FLG__);

	if (woken) {
	    /*
	     * If act == ETHR_RWMTX_W_WAIT_FLG__, we have already been enqueued
	     * on the mutex; continue wait until locked...
	     */
	    if (act == ETHR_CND_WAIT_FLG__) {
		ETHR_MTX_Q_LOCK(&cnd->qlck);
		act = ethr_atomic_read(&tse->uaflgs);
		ETHR_ASSERT(act == ETHR_CND_WAIT_FLG__
			    || act == ETHR_RWMTX_W_WAIT_FLG__);
		/*
		 * If act == ETHR_RWMTX_W_WAIT_FLG__, we have already
		 * enqueued on the mutex; continue wait until locked...
		 */
		if (act == ETHR_CND_WAIT_FLG__)
		    dequeue(&cnd->q, tse, tse);

		ETHR_MTX_Q_UNLOCK(&cnd->qlck);

		if (act == ETHR_CND_WAIT_FLG__) {
		    tse->udata = udata;
		    ethr_leave_ts_event(tse);
		    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
		    ethr_mutex_lock(mtx);
		    return EINTR;
		}
	    }
	    ETHR_ASSERT(act == ETHR_RWMTX_W_WAIT_FLG__);
	}
	ethr_event_swait(&tse->event, scnt);
	/* swait result: 0 || EINTR */
	woken = 1;
    }

    ETHR_MTX_HARD_DEBUG_LFS_RWLOCK(&mtx->mtxb);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(cnd);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(mtx);

    tse->udata = udata;
    ethr_leave_ts_event(tse);
    return 0;
}

#else
/* -- pthread mutex and condition variables -------------------------------- */

int
ethr_mutex_init(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (!mtx) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    mtx->initialized = ETHR_MUTEX_INITIALIZED;
#endif
    return pthread_mutex_init(&mtx->pt_mtx, NULL);
}

int
ethr_mutex_destroy(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
#endif
#if ETHR_XCHK
    mtx->initialized = 0;
#endif
    return pthread_mutex_destroy(&mtx->pt_mtx);
}

int
ethr_cond_init(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (!cnd) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    cnd->initialized = ETHR_COND_INITIALIZED;
#endif
    return pthread_cond_init(&cnd->pt_cnd, NULL);
}

int
ethr_cond_destroy(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!cnd || cnd->initialized != ETHR_COND_INITIALIZED) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    cnd->initialized = 0;
#endif
    return pthread_cond_destroy(&cnd->pt_cnd);
}

void
ethr_cond_signal(ethr_cond *cnd)
{
    int res;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);

    res = pthread_cond_signal(&cnd->pt_cnd);
    if (res != 0)
	ETHR_FATAL_ERROR__(res);
}

void
ethr_cond_broadcast(ethr_cond *cnd)
{
    int res;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);

    res = pthread_cond_broadcast(&cnd->pt_cnd);
    if (res != 0)
	ETHR_FATAL_ERROR__(res);
}

int
ethr_cond_wait(ethr_cond *cnd, ethr_mutex *mtx)
{
    int res;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(cnd);
    ETHR_ASSERT(cnd->initialized == ETHR_COND_INITIALIZED);
    ETHR_ASSERT(mtx);
    ETHR_ASSERT(mtx->initialized == ETHR_MUTEX_INITIALIZED);

    res = pthread_cond_wait(&cnd->pt_cnd, &mtx->pt_mtx);
    if (res != 0 && res != EINTR)
	ETHR_FATAL_ERROR__(res);
    return res;
}

#endif /* pthread_mutex */

/* -- Exported symbols of inline functions --------------------------------- */

int
ethr_mutex_trylock(ethr_mutex *mtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(mtx);
    ETHR_ASSERT(mtx->initialized == ETHR_MUTEX_INITIALIZED);

    return ethr_mutex_trylock__(mtx);
}

void
ethr_mutex_lock(ethr_mutex *mtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(mtx);
    ETHR_ASSERT(mtx->initialized == ETHR_MUTEX_INITIALIZED);

    ethr_mutex_lock__(mtx);
}

void
ethr_mutex_unlock(ethr_mutex *mtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(mtx);
    ETHR_ASSERT(mtx->initialized == ETHR_MUTEX_INITIALIZED);

    ethr_mutex_unlock__(mtx);
}


#ifdef ETHR_USE_OWN_RWMTX_IMPL__
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
 * Read/Write Mutex                                                          *
\*                                                                           */

static void
wake_readers(ethr_rwmutex *rwmtx, int rs)
{
    ethr_ts_event *tse;
#ifdef ETHR_DEBUG
    int drs = 0;
#endif

    tse = rwmtx->mtxb.q;
    ETHR_ASSERT(tse);
    ETHR_ASSERT(rwmtx->rq_end);
    dequeue(&rwmtx->mtxb.q, tse, rwmtx->rq_end);
    rwmtx->rq_end->next = NULL;
    rwmtx->rq_end = NULL;

    ETHR_ASSERT(!rwmtx->mtxb.q
		|| (ethr_atomic_read(&rwmtx->mtxb.q->uaflgs)
		    == ETHR_RWMTX_W_WAIT_FLG__));

    ETHR_RWMTX_HARD_DEBUG_CHK_Q(rwmtx);
    ETHR_MTX_Q_UNLOCK(&rwmtx->mtxb.qlck);

    while (tse) {
	ethr_ts_event *tse_next;

#ifdef ETHR_DEBUG
	ETHR_ASSERT(tse->uflgs == ETHR_RWMTX_R_WAIT_FLG__);
	ETHR_ASSERT(ethr_atomic_read(&tse->uaflgs)
		    == ETHR_RWMTX_R_WAIT_FLG__);
	drs++;
#endif

	tse_next = tse->next; /* we aren't allowed to read tse->next
				 after we have reset uaflgs */

	ethr_atomic_set(&tse->uaflgs, 0);
	ethr_event_set(&tse->event);
	tse = tse_next;
    }

    ETHR_ASSERT(rs == drs);
}

static ETHR_INLINE int
is_w_waiter(ethr_ts_event *tse)
{
    ETHR_ASSERT(tse->uflgs == ETHR_RWMTX_W_WAIT_FLG__
		|| tse->uflgs == ETHR_RWMTX_R_WAIT_FLG__);
    return tse->uflgs == ETHR_RWMTX_W_WAIT_FLG__;
}

static ETHR_INLINE int
multiple_w_waiters(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(rwmtx->mtxb.q);
    ETHR_ASSERT(rwmtx->mtxb.q->uflgs == ETHR_RWMTX_W_WAIT_FLG__);

    if (!rwmtx->rq_end)
	return rwmtx->mtxb.q->next != rwmtx->mtxb.q;
    else {
	ETHR_ASSERT(rwmtx->mtxb.q->next != rwmtx->mtxb.q);
	if (rwmtx->mtxb.q->next->uflgs == ETHR_RWMTX_W_WAIT_FLG__)
	    return 1;
	ETHR_ASSERT(rwmtx->rq_end->next == rwmtx->mtxb.q
		    || rwmtx->rq_end->next->uflgs == ETHR_RWMTX_W_WAIT_FLG__);
	return rwmtx->rq_end->next != rwmtx->mtxb.q;
    }
}

int check_readers_array(ethr_rwmutex *rwmtx,
			int start_rix,
			int length,
			int pre_check)
{
    int ix = start_rix;

#ifndef ETHR_READ_MEMORY_BARRIER_IS_FULL
    if (pre_check)
	ETHR_READ_MEMORY_BARRIER;
    else
#endif
	ETHR_MEMORY_BARRIER;

    do {
	long act = rwmutex_freqread_rdrs_read(rwmtx, ix);
	if (act != 0)
	    return EBUSY;
	ix++;
	if (ix == length)
	    ix = 0;
    } while (ix != start_rix);

    return 0;
}

static ETHR_INLINE void
rwmutex_freqread_restore_failed_tryrlock(ethr_rwmutex *rwmtx,
					 ethr_ts_event *tse)
{
    long act;
    /*
     * Restore failed increment
     */
    act = rwmutex_freqread_rdrs_dec_read(rwmtx, tse);

    ETHR_WRITE_MEMORY_BARRIER;

    if (act == 0) {

#ifndef ETHR_WRITE_MEMORY_BARRIER_IS_FULL
	ETHR_READ_MEMORY_BARRIER;
#endif

	act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	if ((act & ETHR_RWMTX_W_FLG__) == 0
	    && act & (ETHR_RWMTX_WAIT_FLGS__|ETHR_RWMTX_R_PEND_UNLCK_MASK__)) {
	    /*
	     * We either got waiters, or someone else trying
	     * to read unlock which we might have to help.
	     */
	    rwmutex_try_complete_runlock(rwmtx, act, tse, 1, 1, 0);
	}
    }
}

static int
rwmutex_try_complete_runlock(ethr_rwmutex *rwmtx,
			     long initial,
			     ethr_ts_event *tse,
			     int start_next_ix,
			     int check_before_try,
			     int try_write_lock)
{
    ethr_ts_event *tse_tmp;
    long act = initial;
    int six, res, length;

    tse_tmp = tse;
    if (!tse_tmp)
	tse_tmp = ethr_get_ts_event();

    if ((act & ETHR_RWMTX_WAIT_FLGS__)
	&& (act & ~ETHR_RWMTX_WAIT_FLGS__) == 0)
	goto check_waiters;

    if (rwmtx->type == ETHR_RWMUTEX_TYPE_FREQUENT_READ) {
	length = reader_groups_array_size;
	six = tse_tmp->rgix;
    }
    else {
	length = main_threads_array_size;
	six = tse_tmp->mtix;
    }
    if (start_next_ix) {
	six++;
	if (six >= length)
	    six = 0;
    }

    if (!tse)
	ethr_leave_ts_event(tse_tmp);

    if (check_before_try) {
	res = check_readers_array(rwmtx, six, length, 1);
	if (res == EBUSY)
	    return try_write_lock ? EBUSY : 0;
    }

    while (1) {
	long exp = act;
	long new = act+1;

	ETHR_ASSERT((act & ETHR_RWMTX_R_PEND_UNLCK_MASK__)
		    < ETHR_RWMTX_R_PEND_UNLCK_MASK__);

	act = ethr_atomic_cmpxchg(&rwmtx->mtxb.flgs, new, exp);
	if (exp == act) {
	    act = new;
	    break;
	}
	if (!try_write_lock) {
	    if (act == ETHR_RWMTX_W_FLG__ || act == 0)
		return 0;
	    if ((act & ETHR_RWMTX_WAIT_FLGS__) == 0) {
		if ((act & ETHR_RWMTX_R_FLG__) == 0)
		    return 0;
	    }
	    else if ((act & ETHR_RWMTX_R_FLG__) == 0) {
		if (act & ETHR_RWMTX_R_PEND_UNLCK_MASK__)
		    return 0;
		goto check_waiters;
	    }
	}
	else {
	    if (act == 0)
		goto tryrwlock;
	    if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_WAIT_FLGS__))
		return EBUSY;
	}
    }

    res = check_readers_array(rwmtx, six, length, 0);
    if (res == EBUSY) {
	act = ethr_atomic_dec_read(&rwmtx->mtxb.flgs);
	if (act & ETHR_RWMTX_R_MASK__)
	    return try_write_lock ? EBUSY : 0;
    }
    else {
	while (1) {
	    long exp = act;
	    long new = act;
	    new &= ~ETHR_RWMTX_R_FLG__;
	    new--;

	    ETHR_ASSERT(act & ETHR_RWMTX_R_PEND_UNLCK_MASK__);

	    act = ethr_atomic_cmpxchg(&rwmtx->mtxb.flgs, new, exp);
	    if (exp == act) {
		if (new & ETHR_RWMTX_R_PEND_UNLCK_MASK__)
		    return try_write_lock ? EBUSY : 0;
		act = new;
		break;
	    }
	}
    }

    /*
     * Read unlock completed, but we have to check if
     * threads have to be woken (or if we should try
     * to write lock it).
     */

    if (act & ETHR_RWMTX_W_FLG__)
	return try_write_lock ? EBUSY : 0;

    if (act & ETHR_RWMTX_WAIT_FLGS__) {
    check_waiters:
	rwmutex_unlock_wake(rwmtx, 0, act);
	return try_write_lock ? EBUSY : 0;
    }

    if (!try_write_lock)
	return 0;

 tryrwlock:
    /* Try to write lock it */

    act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs,
				   ETHR_RWMTX_W_FLG__,
				   0);
    return act == 0 ? 0 : EBUSY;
}

#ifdef ETHR_RLOCK_WITH_INC_DEC

static ETHR_INLINE void
rwmutex_incdec_restore_failed_tryrlock(ethr_rwmutex *rwmtx)
{
    long act;
    /*
     * Restore failed increment
     */
    act = ethr_atomic_dec_read(&rwmtx->mtxb.flgs);
    if ((act & ETHR_RWMTX_WAIT_FLGS__)
	&& (act & ~ETHR_RWMTX_WAIT_FLGS__) == 0) {
	rwmutex_unlock_wake(rwmtx, 0, act);
    }
}

#endif

static void
rwmutex_normal_rlock_wait(ethr_rwmutex *rwmtx,
			  long initial)
{
    long act = initial, exp;
    int scnt, start_scnt;
    ethr_ts_event *tse = NULL;
    int until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;

    start_scnt = scnt = initial_spincount(&rwmtx->mtxb);

    /*
     * Spin trying to read lock for a while. If unsuccessful,
     * wait on event.
     */

    while (1) {

#ifdef ETHR_RLOCK_WITH_INC_DEC
	rwmutex_incdec_restore_failed_tryrlock(rwmtx);
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);
#endif

	while (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__)) {
	    if (scnt == 0) {
		tse = ethr_get_ts_event();
		if (update_spincount(&rwmtx->mtxb, tse, &start_scnt, &scnt)) {
		    event_wait(&rwmtx->mtxb, tse, scnt,
			       ETHR_RWMTX_R_WAIT_FLG__, 1, 0);
		    goto done;
		}
	    }
	    ETHR_SPIN_BODY;
	    if (--until_yield == 0) {
		until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;
		ETHR_YIELD();
	    }
	    act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	    scnt--;
	}
	exp = act;
	ETHR_ASSERT(scnt >= 0);

#ifdef ETHR_RLOCK_WITH_INC_DEC
	act = ethr_atomic_inc_read(&rwmtx->mtxb.flgs);
	if ((act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__)) == 0)
	    goto done; /* Got it */
#else
	act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs, exp+1, exp);
	if (act == exp)
	    goto done; /* Got it */
#endif
    }

 done:
    if (tse)
	ethr_leave_ts_event(tse);
}

static void
rwmutex_freqread_rlock_wait(ethr_rwmutex *rwmtx,
			    ethr_ts_event *tse,
			    long initial)
{
    long act = initial;
    int scnt, start_scnt;
    int until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;

    start_scnt = scnt = initial_spincount(&rwmtx->mtxb);

    /*
     * Spin trying to read lock for a while. If unsuccessful,
     * wait on event.
     */

    while (1) {

	rwmutex_freqread_restore_failed_tryrlock(rwmtx, tse);

	act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	while (act & ~(ETHR_RWMTX_R_FLG__|ETHR_RWMTX_R_WAIT_FLG__)) {
	    if (scnt == 0) {
		if (update_spincount(&rwmtx->mtxb, tse, &start_scnt, &scnt)) {
		    event_wait(&rwmtx->mtxb, tse, scnt,
			       ETHR_RWMTX_R_WAIT_FLG__, 1, 1);
		    return; /* Got it */
		}
	    }
	    ETHR_SPIN_BODY;
	    if (--until_yield == 0) {
		until_yield = ETHR_YIELD_AFTER_BUSY_LOOPS;
		ETHR_YIELD();
	    }
	    act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	    scnt--;
	}

	ETHR_ASSERT(scnt >= 0);

	rwmutex_freqread_rdrs_inc(rwmtx, tse);

	ETHR_MEMORY_BARRIER;

	act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	if (act == ETHR_RWMTX_R_FLG__)
	    return; /* Got it */

	while (1) {
	    long exp, new;

	    if (act & ~(ETHR_RWMTX_R_FLG__|ETHR_RWMTX_R_WAIT_FLG__))
		break; /* Busy (need to restore inc) */

	    if (act & ETHR_RWMTX_R_FLG__)
		return; /* Got it */

	    exp = act;
	    new = act | ETHR_RWMTX_R_FLG__;
	    act = ethr_atomic_cmpxchg(&rwmtx->mtxb.flgs, new, exp);
	    if (act == exp)
		return; /* Got it */
	}
    }
}

static void
rwmutex_normal_rwlock_wait(ethr_rwmutex *rwmtx, long initial)
{
    write_lock_wait(&rwmtx->mtxb, initial, 1, 0);
}

static void
rwmutex_freqread_rwlock_wait(ethr_rwmutex *rwmtx, long initial)
{
    write_lock_wait(&rwmtx->mtxb, initial, 1, 1);
}

static ETHR_INLINE void
rwlock_wake_set_flags(ethr_rwmutex *rwmtx, long new_initial, int act_initial)
{
    long act, act_mask;
    if (rwmtx->type != ETHR_RWMUTEX_TYPE_NORMAL) {
	/* r pend unlock mask may vary and must be retained */
	act_mask = ETHR_RWMTX_R_PEND_UNLCK_MASK__;
    }
    else {
#ifdef ETHR_RLOCK_WITH_INC_DEC
	/* rs mask may vary and must be retained */
	act_mask = ETHR_RWMTX_RS_MASK__;
#else
	/* rs mask always zero */
	ETHR_ASSERT((act_initial & ETHR_RWMTX_RS_MASK__) == 0);
	ethr_atomic_set(&rwmtx->mtxb.flgs, new_initial);
	return;
#endif
    }

    act = act_initial;
    while (1) {
	long exp = act;
	long new = new_initial + (act & act_mask);
	act = ethr_atomic_cmpxchg(&rwmtx->mtxb.flgs, new, exp);
	if (act == exp)
	    break;
	exp = act;
    }
}

#ifdef ETHR_DEBUG

static void
dbg_unlock_wake(ethr_rwmutex *rwmtx,
		int have_w,
		ethr_ts_event *tse)
{
    long exp, act, imask;

    exp = have_w ? ETHR_RWMTX_W_FLG__ : 0;

    if (rwmtx->type != ETHR_RWMUTEX_TYPE_NORMAL)
	imask = ETHR_RWMTX_R_PEND_UNLCK_MASK__;
    else {
#ifdef ETHR_RLOCK_WITH_INC_DEC
	imask = ETHR_RWMTX_RS_MASK__;
#else
	imask = 0;
#endif
    }

    ETHR_ASSERT(tse);

    if (is_w_waiter(tse)) {

	exp |= ETHR_RWMTX_W_WAIT_FLG__;
	if (rwmtx->rq_end) {
	    exp |= ETHR_RWMTX_R_WAIT_FLG__;
	}
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	ETHR_ASSERT((exp & ~imask) == (act & ~imask));

	ETHR_RWMTX_HARD_DEBUG_CHK_Q(rwmtx);

    }
    else {

	exp |= ETHR_RWMTX_R_WAIT_FLG__;
	if (rwmtx->rq_end->next != rwmtx->mtxb.q)
	    exp |= ETHR_RWMTX_W_WAIT_FLG__;
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	ETHR_ASSERT((exp & ~imask) == (act & ~imask));

	ETHR_RWMTX_HARD_DEBUG_CHK_Q(rwmtx);

    }
}

#endif

static void
rwmutex_unlock_wake(ethr_rwmutex *rwmtx, int have_w, long initial)
{
    long new, act = initial;
    ethr_ts_event *tse;

    if ((act & ETHR_RWMTX_WAIT_FLGS__) == 0) {
	if (!have_w)
	    return;
	else {
	    while ((act & ETHR_RWMTX_WAIT_FLGS__) == 0) {
		long exp = act;
		new = exp & ~ETHR_RWMTX_W_FLG__;
		act = ethr_atomic_cmpxchg(&rwmtx->mtxb.flgs, new, exp);
		if (act == exp)
		    return;
	    }
	}
    }

    ETHR_MTX_Q_LOCK(&rwmtx->mtxb.qlck);
    tse = rwmtx->mtxb.q;

    if (!have_w) {
	if (!tse) {
#ifdef ETHR_DEBUG
	    act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	    ETHR_ASSERT((act & ETHR_RWMTX_WAIT_FLGS__) == 0);
#endif
	    goto already_served;
	}
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	if (act & ~ETHR_RWMTX_WAIT_FLGS__) {
	already_served:
	    ETHR_MTX_Q_UNLOCK(&rwmtx->mtxb.qlck);
	    return;
	}
    }

#ifdef ETHR_DEBUG
    dbg_unlock_wake(rwmtx, have_w, tse);
#endif

    if (is_w_waiter(tse)) {

	if (!have_w) {
	    act = ethr_atomic_read_bor(&rwmtx->mtxb.flgs,
				       ETHR_RWMTX_W_FLG__);
	    ETHR_ASSERT((act & ~ETHR_RWMTX_WAIT_FLGS__) == 0);
	    ETHR_ASSERT(act & ETHR_RWMTX_W_WAIT_FLG__);
	    act |= ETHR_RWMTX_W_FLG__;
	}

	/*
	 * If we have multiple write waiters, there
	 * is no need to modify mtxb->flgs; otherwise,
	 * we need to clear the write wait bit...
	 */
	if (!multiple_w_waiters(rwmtx)) {
	    new = ETHR_RWMTX_W_FLG__;
	    if (tse->next != rwmtx->mtxb.q) {
		ETHR_ASSERT(tse->next->uflgs == ETHR_RWMTX_R_WAIT_FLG__);
		new |= ETHR_RWMTX_R_WAIT_FLG__;
	    }

	    rwlock_wake_set_flags(rwmtx, new, act);
	}

	wake_writer(&rwmtx->mtxb, 1);
    }
    else {
	int rs;

	if (rwmtx->type == ETHR_RWMUTEX_TYPE_NORMAL) {
	    rs = rwmtx->tdata.rs;
	    new = (long) rs;
	    rwmtx->tdata.rs = 0;
	}
	else {
	    ethr_rwmutex_type type = rwmtx->type;
	    int length = (type == ETHR_RWMUTEX_TYPE_FREQUENT_READ
			  ? reader_groups_array_size
			  : main_threads_array_size);
	    int ix;

	    rs = 0;
	    for (ix = 0; ix < length; ix++) {
		int wrs = rwmtx->tdata.ra[ix].data.waiting_readers;
		rwmtx->tdata.ra[ix].data.waiting_readers = 0;
		ETHR_ASSERT(wrs >= 0);
		if (wrs) {
		    rs += wrs;
		    rwmutex_freqread_rdrs_add(rwmtx, type, ix, wrs);
		}
	    }
	    new = ETHR_RWMTX_R_FLG__;
	}

	if (rwmtx->rq_end->next != rwmtx->mtxb.q)
	    new |= ETHR_RWMTX_W_WAIT_FLG__;

	rwlock_wake_set_flags(rwmtx, new, act);
	wake_readers(rwmtx, rs);
    }
}

static ethr_rwmtx_readers_array__ *
alloc_readers_array(int length, ethr_rwmutex_lived lived)
{
    ethr_rwmtx_readers_array__ *ra;
    size_t sz;
    void *mem;

    sz = sizeof(ethr_rwmtx_readers_array__) * (length + 1);

    switch (lived) {
    case ETHR_RWMUTEX_LONG_LIVED:
	mem = ethr_mem__.ll.alloc(sz);
	break;
    case ETHR_RWMUTEX_SHORT_LIVED:
	mem = ethr_mem__.sl.alloc(sz);
	break;
    default:
	mem = ethr_mem__.std.alloc(sz);
	break;
    }
    if (!mem)
	return NULL;

    if ((((unsigned long) mem) & ETHR_CACHE_LINE_MASK) == 0) {
	ra = (ethr_rwmtx_readers_array__ *) mem;
	ra->data.byte_offset = 0;
    }
    else {
	ra = ((ethr_rwmtx_readers_array__ *)
	      ((((unsigned long) mem) & ~ETHR_CACHE_LINE_MASK)
	       + ETHR_CACHE_LINE_SIZE));
	ra->data.byte_offset = (int) ((unsigned long) ra
				      - (unsigned long) mem);
    }
    ra->data.lived = lived;
    return ra;
}

static void
free_readers_array(ethr_rwmtx_readers_array__ *ra)
{
    void *ptr = (void *) (((char *) ra) - ra->data.byte_offset);
    switch (ra->data.lived) {
    case ETHR_RWMUTEX_LONG_LIVED:
	ethr_mem__.ll.free(ptr);
	break;
    case ETHR_RWMUTEX_SHORT_LIVED:
	ethr_mem__.sl.free(ptr);
	break;
    default:
	ethr_mem__.std.free(ptr);
	break;
    }
}

int
ethr_rwmutex_init_opt(ethr_rwmutex *rwmtx, ethr_rwmutex_opt *opt)
{
    int res;
    ethr_rwmtx_readers_array__ *ra = NULL;
#if ETHR_XCHK
    if (ethr_not_completely_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!rwmtx) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    rwmtx->initialized = ETHR_RWMUTEX_INITIALIZED;
#endif
    ETHR_MTX_HARD_DEBUG_FENCE_INIT(rwmtx);
    rwmtx->rq_end = NULL;
    rwmtx->type = opt ? opt->type : ETHR_RWMUTEX_TYPE_NORMAL;
    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
	if (main_threads_array_size <= reader_groups_array_size) {
	    /* No point using reader groups... */
	    rwmtx->type = ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ;
	}
	/* Fall through */
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ: {
	int length;

	length = (rwmtx->type == ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ
		  ? main_threads_array_size
		  : reader_groups_array_size);

	if (length == 1) {
	    /* No point using a frequent reader type... */
	    rwmtx->type = ETHR_RWMUTEX_TYPE_NORMAL;
	}
	else {
	    int ix;
	    ra = alloc_readers_array(length,
				     (opt
				      ? opt->lived
				      : ETHR_RWMUTEX_UNKNOWN_LIVED));
	    if (!ra) {
		res = ENOMEM;
		goto error;
	    }

	    rwmtx->tdata.ra = ra;

	    for (ix = 0; ix < length; ix++) {
		ethr_atomic_init(&rwmtx->tdata.ra[ix].data.readers, 0);
		rwmtx->tdata.ra[ix].data.waiting_readers = 0;
	    }
	    break;
	}
    }
    case ETHR_RWMUTEX_TYPE_NORMAL:
	rwmtx->tdata.rs = 0;
	break;
    default:
	res = EINVAL;
	goto error;
    }
    res = mtxb_init(&rwmtx->mtxb,
		    default_rwmtx_main_spincount,
		    opt ? opt->main_spincount : -1,
		    default_rwmtx_aux_spincount,
		    opt ? opt->aux_spincount : -1);
    if (res == 0)
	return 0;

 error:

    if (ra)
	free_readers_array(ra);

#if ETHR_XCHK
    rwmtx->initialized = 0;
#endif
    return res;
}

int
ethr_rwmutex_init(ethr_rwmutex *rwmtx)
{
    return ethr_rwmutex_init_opt(rwmtx, NULL);
}

int
ethr_rwmutex_destroy(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
#endif
    if (rwmtx->type != ETHR_RWMUTEX_TYPE_NORMAL) {
	long act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	if (act == ETHR_RWMTX_R_FLG__)
	    rwmutex_try_complete_runlock(rwmtx, act, NULL, 0, 0, 0);
    }
    res = mtxb_destroy(&rwmtx->mtxb);
    if (res != 0)
	return res;
    if (rwmtx->type != ETHR_RWMUTEX_TYPE_NORMAL)
	free_readers_array(rwmtx->tdata.ra);
#if ETHR_XCHK
    rwmtx->initialized = 0;
#endif
    return 0;
}

#define ETHR_MAX_TRYRLOCK_TRIES 5

int
ethr_rwmutex_tryrlock(ethr_rwmutex *rwmtx)
{
    int res = 0;
    long act;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL: {
#ifdef ETHR_RLOCK_WITH_INC_DEC
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);
	if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__))
	    res = EBUSY;
	else {
	    act = ethr_atomic_inc_read_acqb(&rwmtx->mtxb.flgs);
	    if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__)) {
		rwmutex_incdec_restore_failed_tryrlock(rwmtx);
		res = EBUSY;
	    }
	}
#else
	long exp = 0;
	int tries = 0;

	while (1) {
	    act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs, exp+1, exp);
	    if (act == exp) {
		res = 0;
		break;
	    }
	    if (tries > ETHR_MAX_TRYRLOCK_TRIES
		|| (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__))) {
		res = EBUSY;
		break;
	    }
	    tries++;
	    exp = act;
	}
#endif
	break;
    }

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ: {
	ethr_ts_event *tse = ethr_get_ts_event();

	rwmutex_freqread_rdrs_inc(rwmtx, tse);

	ETHR_MEMORY_BARRIER;

	act = ethr_atomic_read_acqb(&rwmtx->mtxb.flgs);

	if (act != ETHR_RWMTX_R_FLG__) {
	    while (1) {
		long exp, new;

		if (act & ~(ETHR_RWMTX_R_FLG__|ETHR_RWMTX_R_WAIT_FLG__)) {
		    rwmutex_freqread_restore_failed_tryrlock(rwmtx, tse);
		    res = EBUSY;
		    break;
		}

		if (act & ETHR_RWMTX_R_FLG__)
		    break;

		exp = act;
		new = act | ETHR_RWMTX_R_FLG__;
		act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs, new, exp);
		if (act == exp)
		    break;
	    }
	}

	ethr_leave_ts_event(tse);
	break;
    }
    }

    ETHR_MTX_HARD_DEBUG_LFS_TRYRLOCK(&rwmtx->mtxb, res);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    return res;
}

void
ethr_rwmutex_rlock(ethr_rwmutex *rwmtx)
{
    long act;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL: {
#ifdef ETHR_RLOCK_WITH_INC_DEC
	act = ethr_atomic_inc_read_acqb(&rwmtx->mtxb.flgs);
	if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__))
	    rwmutex_normal_rlock_wait(rwmtx, act);
#else
	long exp = 0;

	while (1) {
	    act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs, exp+1, exp);
	    if (act == exp) {
		break;
	    }

	    if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_W_WAIT_FLG__)) {
		rwmutex_normal_rlock_wait(rwmtx, act);
		break;
	    }
	    exp = act;
	}
#endif
	break;
    }

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ: {
	ethr_ts_event *tse = ethr_get_ts_event();

	rwmutex_freqread_rdrs_inc(rwmtx, tse);

	ETHR_MEMORY_BARRIER;

	act = ethr_atomic_read_acqb(&rwmtx->mtxb.flgs);

	if (act != ETHR_RWMTX_R_FLG__) {
	    while (1) {
		long exp, new;

		if (act & ~(ETHR_RWMTX_R_FLG__|ETHR_RWMTX_R_WAIT_FLG__)) {
		    rwmutex_freqread_rlock_wait(rwmtx, tse, act);
		    break;
		}

		if (act & ETHR_RWMTX_R_FLG__)
		    break;

		exp = act;
		new = act | ETHR_RWMTX_R_FLG__;
		act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs, new, exp);
		if (act == exp)
		    break;
	    }
	}

	ethr_leave_ts_event(tse);
	break;
    }
    }

    ETHR_MTX_HARD_DEBUG_LFS_RLOCK(&rwmtx->mtxb);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);
}

void
ethr_rwmutex_runlock(ethr_rwmutex *rwmtx)
{
    long act;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);
    ETHR_MTX_HARD_DEBUG_LFS_RUNLOCK(&rwmtx->mtxb);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL:
	act = ethr_atomic_dec_read_relb(&rwmtx->mtxb.flgs);
	if ((act & ETHR_RWMTX_WAIT_FLGS__)
	    && (act & ~ETHR_RWMTX_WAIT_FLGS__) == 0) {
	    ETHR_ASSERT((act & ETHR_RWMTX_W_FLG__) == 0);
	    rwmutex_unlock_wake(rwmtx, 0, act);
	}
	break;

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ: {
	ethr_ts_event *tse = ethr_get_ts_event();

	act = rwmutex_freqread_rdrs_dec_read_relb(rwmtx, tse);

	ETHR_ASSERT(act >= 0);

	ETHR_WRITE_MEMORY_BARRIER;

	if (act == 0) {

#ifndef ETHR_WRITE_MEMORY_BARRIER_IS_FULL
	    ETHR_READ_MEMORY_BARRIER;
#endif
	    act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	    if ((act & ETHR_RWMTX_W_FLG__) == 0
		&& (act & (ETHR_RWMTX_WAIT_FLGS__
			   | ETHR_RWMTX_R_PEND_UNLCK_MASK__))) {
		rwmutex_try_complete_runlock(rwmtx, act, tse, 1, 0, 0);
	    }

	}

	ethr_leave_ts_event(tse);
	break;
    }
    }

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);
}

int
ethr_rwmutex_tryrwlock(ethr_rwmutex *rwmtx)
{
    int res = 0;
    long act;

    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL:
	act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs,
				       ETHR_RWMTX_W_FLG__, 0);
	if (act != 0)
	    res = EBUSY;
	break;

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ:

	res = 0;
	act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	do {

	    if (act & (ETHR_RWMTX_W_FLG__|ETHR_RWMTX_WAIT_FLGS__)) {
		res = EBUSY;
		break;
	    }

	    if (act & ETHR_RWMTX_R_MASK__) {
		res = rwmutex_try_complete_runlock(rwmtx, act, NULL,
						   0, 1, 1);
		break;
	    }

	    act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs,
					   ETHR_RWMTX_W_FLG__, 0);

	} while (act != 0);

	break;
    }

    ETHR_MTX_HARD_DEBUG_LFS_TRYRWLOCK(&rwmtx->mtxb, res);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    return res;
}

void
ethr_rwmutex_rwlock(ethr_rwmutex *rwmtx)
{
    long act;
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL:
	act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs,
				       ETHR_RWMTX_W_FLG__, 0);
	if (act != 0)
	    rwmutex_normal_rwlock_wait(rwmtx, act);
	break;

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ:

	act = ethr_atomic_read(&rwmtx->mtxb.flgs);

	do {

	    if (act != 0) {
		rwmutex_freqread_rwlock_wait(rwmtx, act);
		break;
	    }

	    act = ethr_atomic_cmpxchg_acqb(&rwmtx->mtxb.flgs,
					   ETHR_RWMTX_W_FLG__, 0);

	} while (act != 0);

	break;
    }

    ETHR_MTX_HARD_DEBUG_LFS_RWLOCK(&rwmtx->mtxb);
    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);

}

void
ethr_rwmutex_rwunlock(ethr_rwmutex *rwmtx)
{
    long act;
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);
    ETHR_MTX_HARD_DEBUG_LFS_RWUNLOCK(&rwmtx->mtxb);

    switch (rwmtx->type) {
    case ETHR_RWMUTEX_TYPE_NORMAL:
	act = ethr_atomic_cmpxchg_relb(&rwmtx->mtxb.flgs,
				       0, ETHR_RWMTX_W_FLG__);
	if (act != ETHR_RWMTX_W_FLG__)
	    rwmutex_unlock_wake(rwmtx, 1, act);
	break;

    case ETHR_RWMUTEX_TYPE_FREQUENT_READ:
    case ETHR_RWMUTEX_TYPE_EXTREMELY_FREQUENT_READ:
	act = ethr_atomic_cmpxchg_relb(&rwmtx->mtxb.flgs, 0,
				       ETHR_RWMTX_W_FLG__);
	if (act != ETHR_RWMTX_W_FLG__)
	    rwmutex_unlock_wake(rwmtx, 1, act);
	break;
    }

    ETHR_MTX_HARD_DEBUG_FENCE_CHK(rwmtx);
}

#else
/* -- pthread read/write mutex --------------------------------------------- */

int
ethr_rwmutex_init(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (!rwmtx) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
    rwmtx->initialized = ETHR_RWMUTEX_INITIALIZED;
#endif
    return pthread_rwlock_init(&rwmtx->pt_rwlock, write_pref_attr);
}

int
ethr_rwmutex_init_opt(ethr_rwmutex *rwmtx, ethr_rwmutex_opt *opt)
{
    return ethr_rwmutex_init(rwmtx);
}

int
ethr_rwmutex_destroy(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (ethr_not_inited__) {
	ETHR_ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ETHR_ASSERT(0);
	return EINVAL;
    }
#endif
    res = pthread_rwlock_destroy(&rwmtx->pt_rwlock);
#if ETHR_XCHK
    rwmtx->initialized = 0;
#endif
    return res;
}

/* -- Exported symbols of inline functions --------------------------------- */

int
ethr_rwmutex_tryrlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    return ethr_rwmutex_tryrlock__(rwmtx);
}

void
ethr_rwmutex_rlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ethr_rwmutex_rlock__(rwmtx);
}

void
ethr_rwmutex_runlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ethr_rwmutex_runlock__(rwmtx);
}

int
ethr_rwmutex_tryrwlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    return ethr_rwmutex_tryrwlock__(rwmtx);
}

void
ethr_rwmutex_rwlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    return ethr_rwmutex_rwlock__(rwmtx);
}

void
ethr_rwmutex_rwunlock(ethr_rwmutex *rwmtx)
{
    ETHR_ASSERT(!ethr_not_inited__);
    ETHR_ASSERT(rwmtx);
    ETHR_ASSERT(rwmtx->initialized == ETHR_RWMUTEX_INITIALIZED);

    ethr_rwmutex_rwunlock__(rwmtx);
}

#endif /* pthread */


#if defined(ETHR_USE_OWN_RWMTX_IMPL__) || defined(ETHR_USE_OWN_MTX_IMPL__)

#ifdef ETHR_MTX_HARD_DEBUG_Q
static void
hard_debug_chk_q__(struct ethr_mutex_base_ *mtxb, int is_rwmtx)
{
    int res;
    long flgs = ethr_atomic_read(&mtxb->flgs);

    ETHR_MTX_HARD_ASSERT(res == 0);

    ETHR_MTX_HARD_ASSERT(!(flgs & ETHR_RWMTX_R_WAIT_FLG__) || is_rwmtx);

    if (!(flgs & ETHR_RWMTX_WAIT_FLGS__)) {
	ETHR_MTX_HARD_ASSERT(!mtxb->q);
	if (is_rwmtx) {
	    ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	    ETHR_MTX_HARD_ASSERT(!rwmtx->rq_end);
	    ETHR_MTX_HARD_ASSERT(!rwmtx->rs);
	}
    }
    else {
	ethr_ts_event *tse;
	int ws = 0, rs = 0, rsf = 0, ref = 0;

	ETHR_MTX_HARD_ASSERT(mtxb->q);

	tse = mtxb->q;

	do {
	    long type;

	    ETHR_MTX_HARD_ASSERT(tse->next->prev == tse);
	    ETHR_MTX_HARD_ASSERT(tse->prev->next == tse);

	    type = ethr_atomic_read(&tse->uaflgs);
	    ETHR_MTX_HARD_ASSERT(type == tse->uflgs);
	    switch (type) {
	    case ETHR_RWMTX_W_WAIT_FLG__:
		ws++;
		break;
	    case ETHR_RWMTX_R_WAIT_FLG__: {
		ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
		ETHR_MTX_HARD_ASSERT(is_rwmtx);
		if (!rsf)
		    rsf = 1;
		ETHR_MTX_HARD_ASSERT(!ref);
		if (rwmtx->rq_end == tse) {
		    ETHR_MTX_HARD_ASSERT(
			tse->next == rwmtx->mtxb.q
			|| tse->next->uflgs == ETHR_RWMTX_W_WAIT_FLG__);
		    ref = 1;
		}
		rs++;
		break;
	    }
	    default:
		ETHR_MTX_HARD_ASSERT(! "invalid wait type found");
	    }

	    tse = tse->next;
	} while (tse != mtxb->q);

	if (is_rwmtx) {
	    ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	    ETHR_MTX_HARD_ASSERT(rs == rwmtx->rs);
	}

#ifdef ETHR_MTX_HARD_DEBUG_WSQ
	ETHR_MTX_HARD_ASSERT(ws == mtxb->ws);
#endif

	if (flgs & ETHR_RWMTX_W_WAIT_FLG__)
	    ETHR_MTX_HARD_ASSERT(ws);
	else
	    ETHR_MTX_HARD_ASSERT(!ws);

	if (flgs & ETHR_RWMTX_R_WAIT_FLG__) {
	    ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	    ETHR_MTX_HARD_ASSERT(is_rwmtx);
	    ETHR_MTX_HARD_ASSERT(rwmtx->rq_end);
	    ETHR_MTX_HARD_ASSERT(rsf);
	    ETHR_MTX_HARD_ASSERT(ref);
	    ETHR_MTX_HARD_ASSERT(rs);
	}
	else {
	    if (is_rwmtx) {
		ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
		ETHR_MTX_HARD_ASSERT(!rwmtx->rq_end);
	    }
	    ETHR_MTX_HARD_ASSERT(!rsf);
	    ETHR_MTX_HARD_ASSERT(!ref);
	    ETHR_MTX_HARD_ASSERT(!rs);
	}
    }
}

#elif defined(ETHR_MTX_HARD_DEBUG_WSQ)

static void
hard_debug_chk_q__(struct ethr_mutex_base_ *mtxb, int is_rwmtx)
{
    int ws = 0;
    int rs = 0;

    if (mtxb->q) {
	ethr_ts_event *tse = mtxb->q;
	do {
	    switch (tse->uflgs) {
	    case ETHR_RWMTX_W_WAIT_FLG__:
		ws++;
		break;
	    case ETHR_RWMTX_R_WAIT_FLG__:
		rs++;
		break;
	    default:
		ETHR_MTX_HARD_ASSERT(0);
		break;
	    }
	    tse = tse->next;
	} while (tse != mtxb->q);
    }

    ETHR_MTX_HARD_ASSERT(mtxb->ws == ws);
    if (is_rwmtx) {
	ethr_rwmutex *rwmtx = (ethr_rwmutex *) mtxb;
	ETHR_MTX_HARD_ASSERT(rwmtx->rs == rs);
    }
}

#endif

#endif