aboutsummaryrefslogblamecommitdiffstats
path: root/erts/lib_src/common/ethread.c
blob: 9c88233934327d2af3ebf429b720e1fce89f8e99 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
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
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
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
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218

                   


                                                        




                                                                      
  



                                                                         
  






























































































































































































































































                                                                               




                                                 































































































































































































































































                                                                               

















                                                                      






















































































































































































































































































































































































































































































































































                                                                               
                                                                   



















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                
                                 





















































































































































                                                                   
/*
 * %CopyrightBegin%
 *
 * Copyright Ericsson AB 2004-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: A Thread library for use in the ERTS and other OTP
 *              applications.
 * Author: Rickard Green
 */

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

#undef ETHR_STACK_GUARD_SIZE 

#if defined(ETHR_PTHREADS)

#ifdef ETHR_TIME_WITH_SYS_TIME
#  include <time.h>
#  include <sys/time.h>
#else
#  ifdef ETHR_HAVE_SYS_TIME_H
#    include <sys/time.h>
#  else
#    include <time.h>
#  endif
#endif
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

#ifdef ETHR_HAVE_PTHREAD_ATTR_SETGUARDSIZE
#  define ETHR_STACK_GUARD_SIZE (pagesize)
#endif

#elif defined(ETHR_WIN32_THREADS)

#undef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <process.h>
#include <winerror.h>

#else
#error "Missing thread implementation"
#endif

#include <limits.h>

#define ETHR_FORCE_INLINE_FUNCS
#define ETHR_INLINE_FUNC_NAME_(X) X ## __
#include "ethread.h"

#ifndef ETHR_HAVE_ETHREAD_DEFINES
#error Missing configure defines
#endif

/*
 * ----------------------------------------------------------------------------
 * Common stuff
 * ----------------------------------------------------------------------------
 */

#define ETHR_MAX_THREADS 2048 /* Has to be an even power of 2 */

static int ethr_not_inited = 1;

#define ASSERT(A) ETHR_ASSERT((A))

static void *(*allocp)(size_t) = malloc;
static void *(*reallocp)(void *, size_t) = realloc;
static void (*freep)(void *) = free;

#ifndef ETHR_HAVE_OPTIMIZED_ATOMIC_OPS
ethr_atomic_protection_t ethr_atomic_protection__[1 << ETHR_ATOMIC_ADDR_BITS];
#endif

void *(*thread_create_prepare_func)(void) = NULL;
void (*thread_create_parent_func)(void *) = NULL;
void (*thread_create_child_func)(void *) = NULL;

typedef struct ethr_xhndl_list_ ethr_xhndl_list;
struct ethr_xhndl_list_ {
    ethr_xhndl_list *next;
    void (*funcp)(void);
};

static size_t pagesize;
#define ETHR_PAGE_ALIGN(SZ) (((((size_t) (SZ)) - 1)/pagesize + 1)*pagesize)
static size_t min_stack_size; /* kilo words */
static size_t max_stack_size; /* kilo words */
#define ETHR_B2KW(B) ((((size_t) (B)) - 1)/(sizeof(void *)*1024) + 1)
#define ETHR_KW2B(KW) (((size_t) (KW))*sizeof(void *)*1024)

ethr_mutex xhndl_mtx;
ethr_xhndl_list *xhndl_list;

static int
init_common(ethr_init_data *id)
{
    int res;
    if (id) {
	allocp				= id->alloc;
	reallocp			= id->realloc;
	freep				= id->free;
	thread_create_prepare_func	= id->thread_create_prepare_func;
	thread_create_parent_func	= id->thread_create_parent_func;
	thread_create_child_func	= id->thread_create_child_func;
    }
    if (!allocp || !reallocp || !freep)
	return EINVAL;

#ifdef _SC_PAGESIZE
    pagesize = (size_t) sysconf(_SC_PAGESIZE);
#elif defined(HAVE_GETPAGESIZE)
    pagesize = (size_t) getpagesize();
#else
    pagesize = (size_t) 4*1024; /* Guess 4 KB */
#endif

    /* User needs at least 4 KB */
    min_stack_size = 4*1024;
#if SIZEOF_VOID_P == 8
    /* Double that on 64-bit archs */
    min_stack_size *= 2;
#endif
    /* On some systems as much as about 4 KB is used by the system */
    min_stack_size += 4*1024;
    /* There should be room for signal handlers */
#ifdef SIGSTKSZ
    min_stack_size += SIGSTKSZ;
#else
    min_stack_size += pagesize;
#endif
    /* The system may think that we need more stack */
#if defined(PTHREAD_STACK_MIN)
    if (min_stack_size < PTHREAD_STACK_MIN)
	min_stack_size = PTHREAD_STACK_MIN;
#elif defined(_SC_THREAD_STACK_MIN)
    {
	size_t thr_min_stk_sz = (size_t) sysconf(_SC_THREAD_STACK_MIN);
	if (min_stack_size < thr_min_stk_sz)
	    min_stack_size = thr_min_stk_sz;
    }
#endif
    /* The guard is at least on some platforms included in the stack size
       passed when creating threads */
#ifdef ETHR_STACK_GUARD_SIZE
    min_stack_size += ETHR_STACK_GUARD_SIZE;
#endif
    min_stack_size = ETHR_PAGE_ALIGN(min_stack_size);

    min_stack_size = ETHR_B2KW(min_stack_size);

    max_stack_size = 32*1024*1024;
#if SIZEOF_VOID_P == 8
    max_stack_size *= 2;
#endif
    max_stack_size = ETHR_B2KW(max_stack_size);

    xhndl_list = NULL;

    res = ethr_mutex_init(&xhndl_mtx);
    if (res != 0)
	return res;

    res = ethr_mutex_set_forksafe(&xhndl_mtx);
    if (res != 0 && res != ENOTSUP)
	return res;

    return 0;
}

int
ethr_install_exit_handler(void (*funcp)(void))
{
    ethr_xhndl_list *xhp;
    int res;

#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif

    if (!funcp)
	return EINVAL;

    xhp = (ethr_xhndl_list *) (*allocp)(sizeof(ethr_xhndl_list));
    if (!xhp)
	return ENOMEM;

    res = ethr_mutex_lock__(&xhndl_mtx);
    if (res != 0) {
	(*freep)((void *) xhp);
	return res;
    }

    xhp->funcp = funcp;
    xhp->next = xhndl_list;
    xhndl_list = xhp;

    res = ethr_mutex_unlock__(&xhndl_mtx);
    if (res != 0)
	abort();

    return res;
}

static void
run_exit_handlers(void)
{
    int res;
    ethr_xhndl_list *xhp;

    res = ethr_mutex_lock__(&xhndl_mtx);
    if (res != 0)
	abort();

    xhp = xhndl_list;

    res = ethr_mutex_unlock__(&xhndl_mtx);
    if (res != 0)
	abort();

    for (; xhp; xhp = xhp->next)
	(*xhp->funcp)();
}

#if defined(ETHR_PTHREADS)
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
 * pthread implementation                                                    *
\*                                                                           */

typedef struct {
    pthread_mutex_t mtx;
    pthread_cond_t cnd;
    int initialized;
    void *(*thr_func)(void *);
    void *arg;
    void *prep_func_res;
} thr_wrap_data_;

static int no_ethreads;
static ethr_mutex no_ethrs_mtx;

#ifndef ETHR_HAVE_PTHREAD_ATFORK
#define ETHR_HAVE_PTHREAD_ATFORK 0
#endif

#if !ETHR_HAVE_PTHREAD_ATFORK
#warning "Cannot enforce fork-safety"
#endif

#ifdef ETHR_HAVE_PTHREAD_RWLOCK_INIT
static pthread_rwlockattr_t write_pref_attr_data;
static pthread_rwlockattr_t *write_pref_attr;
#endif

/*
 * ----------------------------------------------------------------------------
 * Static functions
 * ----------------------------------------------------------------------------
 */

/*
 * Functions with safe_ prefix aborts on failure. To be used when
 * we cannot recover after failure.
 */

static ETHR_INLINE void
safe_mutex_lock(pthread_mutex_t *mtxp)
{
    int res = pthread_mutex_lock(mtxp);
    if (res != 0)
	abort();
}

static ETHR_INLINE void
safe_mutex_unlock(pthread_mutex_t *mtxp)
{
    int res = pthread_mutex_unlock(mtxp);
    if (res != 0)
	abort();
}

static ETHR_INLINE void
safe_cond_signal(pthread_cond_t *cndp)
{
    int res = pthread_cond_signal(cndp);
    if (res != 0)
	abort();
}

#ifdef ETHR_HAVE_ETHR_REC_MUTEX_INIT

static volatile int rec_mtx_attr_need_init = 1;
static pthread_mutexattr_t rec_mtx_attr;

static int init_rec_mtx_attr(void);

#endif

#if ETHR_HAVE_PTHREAD_ATFORK

static ethr_mutex forksafe_mtx = ETHR_MUTEX_INITER;

static void lock_mutexes(void)
{
    ethr_mutex *m = &forksafe_mtx;
    do {

	safe_mutex_lock(&m->pt_mtx);

	m = m->next;

    } while (m != &forksafe_mtx);
}

static void unlock_mutexes(void)
{
    ethr_mutex *m = forksafe_mtx.prev;
    do {

	safe_mutex_unlock(&m->pt_mtx);

	m = m->prev;

    } while (m->next != &forksafe_mtx);
}

#if ETHR_INIT_MUTEX_IN_CHILD_AT_FORK

static void reinit_mutexes(void)
{
    ethr_mutex *m = forksafe_mtx.prev;
    do {
	pthread_mutexattr_t *attrp = NULL;

#ifdef ETHR_HAVE_ETHR_REC_MUTEX_INIT
	if (m->is_rec_mtx) {
	    if (rec_mtx_attr_need_init) {
		int res = init_rec_mtx_attr();
		if (res != 0)
		    abort();
	    }
	    attrp = &rec_mtx_attr;
	}
#endif
	if (pthread_mutex_init(&m->pt_mtx, attrp) != 0)
	    abort();

	m = m->prev;

    } while (m->next != &forksafe_mtx);
}

#endif

static int
init_forksafe(void)
{
    static int init_done = 0;
    int res = 0;

    if (init_done)
	return res;

    forksafe_mtx.prev = &forksafe_mtx;
    forksafe_mtx.next = &forksafe_mtx;

    res = pthread_atfork(lock_mutexes,
			 unlock_mutexes,
#if ETHR_INIT_MUTEX_IN_CHILD_AT_FORK
			 reinit_mutexes
#else
			 unlock_mutexes
#endif
	);

    init_done = 1;
    return res;
}

#endif


#ifdef ETHR_HAVE_ETHR_REC_MUTEX_INIT

#if defined(ETHR_HAVE_PTHREAD_MUTEXATTR_SETTYPE)

#define SET_REC_MUTEX_ATTR(AP) \
  pthread_mutexattr_settype((AP), PTHREAD_MUTEX_RECURSIVE);

#elif defined(ETHR_HAVE_PTHREAD_MUTEXATTR_SETKIND_NP)

#define SET_REC_MUTEX_ATTR(AP) \
  pthread_mutexattr_setkind_np((AP), PTHREAD_MUTEX_RECURSIVE_NP);

#else

#error "Don't know how to set recursive mutex attributes"

#endif

static int
init_rec_mtx_attr(void)
{
    int res, mres;
    static pthread_mutex_t attrinit_mtx = PTHREAD_MUTEX_INITIALIZER;

    mres = pthread_mutex_lock(&attrinit_mtx);
    if (mres != 0)
	return mres;
    /* Got here under race conditions; check again ... */
    if (!rec_mtx_attr_need_init)
	res = 0;
    else {
	res = pthread_mutexattr_init(&rec_mtx_attr);
	if (res == 0) {
	    res = SET_REC_MUTEX_ATTR(&rec_mtx_attr);
	    if (res == 0)
		rec_mtx_attr_need_init = 0;
	    else
		(void) pthread_mutexattr_destroy(&rec_mtx_attr);
	}
    }

    mres = pthread_mutex_unlock(&attrinit_mtx);
    if (mres != 0)
	return mres;
    return res;
}

#endif /* #if ETHR_HAVE_ETHR_REC_MUTEX_INIT */

static ETHR_INLINE void thr_exit_cleanup(void)
{
    run_exit_handlers();
    safe_mutex_lock(&no_ethrs_mtx.pt_mtx);
    ASSERT(no_ethreads > 0);
    no_ethreads--;
    safe_mutex_unlock(&no_ethrs_mtx.pt_mtx);
}

static void *thr_wrapper(void *vtwd)
{
    void *res;
    thr_wrap_data_ *twd = (thr_wrap_data_ *) vtwd;
    void *(*thr_func)(void *) = twd->thr_func;
    void *arg = twd->arg;

    safe_mutex_lock(&twd->mtx);

    if (thread_create_child_func)
	(*thread_create_child_func)(twd->prep_func_res);

    twd->initialized = 1;

    safe_cond_signal(&twd->cnd);
    safe_mutex_unlock(&twd->mtx);

    res = (*thr_func)(arg);
    thr_exit_cleanup();
    return res;
}


/*
 * ----------------------------------------------------------------------------
 * Exported functions
 * ----------------------------------------------------------------------------
 */

int
ethr_init(ethr_init_data *id)
{
    int res;

    if (!ethr_not_inited)
	return EINVAL;

    ethr_not_inited = 0;

    res = init_common(id);
    if (res != 0)
	goto error;

#if ETHR_HAVE_PTHREAD_ATFORK
    init_forksafe();
#endif

    no_ethreads = 1;
    res = ethr_mutex_init(&no_ethrs_mtx);
    if (res != 0)
	goto error;
    res = ethr_mutex_set_forksafe(&no_ethrs_mtx);
    if (res != 0 && res != ENOTSUP)
	goto error;

#ifndef ETHR_HAVE_OPTIMIZED_ATOMIC_OPS
    {
	int i;
	for (i = 0; i < (1 << ETHR_ATOMIC_ADDR_BITS); i++) {
#ifdef ETHR_HAVE_PTHREAD_SPIN_LOCK
	    res = pthread_spin_init(&ethr_atomic_protection__[i].u.spnlck, 0);
#else
	    res = ethr_mutex_init(&ethr_atomic_protection__[i].u.mtx);
#endif
	    if (res != 0)
		goto error;
	}
    }
#endif

#ifdef ETHR_HAVE_PTHREAD_RWLOCK_INIT
#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)
	goto error;
    res = pthread_rwlockattr_setkind_np(
	&write_pref_attr_data,
	PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
    if (res != 0)
	goto error;
    write_pref_attr = &write_pref_attr_data;
#else
    write_pref_attr = NULL;
#endif
#endif


    return 0;

 error:
    ethr_not_inited = 1;
    return res;

}

int
ethr_thr_create(ethr_tid *tid, void * (*func)(void *), void *arg,
		ethr_thr_opts *opts)
{
    thr_wrap_data_ twd;
    pthread_attr_t attr;
    int res, dres;
    int use_stack_size = (opts && opts->suggested_stack_size >= 0
			  ? opts->suggested_stack_size
			  : -1 /* Use system default */);

#ifdef ETHR_MODIFIED_DEFAULT_STACK_SIZE
    if (use_stack_size < 0)
	use_stack_size = ETHR_MODIFIED_DEFAULT_STACK_SIZE;
#endif

    twd.initialized = 0;
    twd.thr_func = func;
    twd.arg = arg;

#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!tid || !func) {
	ASSERT(0);
	return EINVAL;
    }
#endif

    /* Call prepare func if it exist */
    if (thread_create_prepare_func)
	twd.prep_func_res = (*thread_create_prepare_func)();
    else
	twd.prep_func_res = NULL;

    /* Set som thread attributes */
    res = pthread_attr_init(&attr);
    if (res != 0)
	goto cleanup_parent_func;
    res = pthread_mutex_init(&twd.mtx, NULL);
    if (res != 0)
	goto cleanup_attr_destroy;
    res = pthread_cond_init(&twd.cnd, NULL);
    if (res != 0)
	goto cleanup_mutex_destroy;

    /* Schedule child thread in system scope (if possible) ... */
    res = pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
    if (res != 0 && res != ENOTSUP)
	goto cleanup_cond_destroy;

    if (use_stack_size >= 0) {
	size_t suggested_stack_size = (size_t) use_stack_size;
	size_t stack_size;
#ifdef DEBUG
	suggested_stack_size /= 2; /* Make sure we got margin */
#endif
#ifdef ETHR_STACK_GUARD_SIZE
	/* The guard is at least on some platforms included in the stack size
	   passed when creating threads */
	suggested_stack_size += ETHR_B2KW(ETHR_STACK_GUARD_SIZE);
#endif
	if (suggested_stack_size < min_stack_size)
	    stack_size = ETHR_KW2B(min_stack_size);
	else if (suggested_stack_size > max_stack_size)
	    stack_size = ETHR_KW2B(max_stack_size);
	else
	    stack_size = ETHR_PAGE_ALIGN(ETHR_KW2B(suggested_stack_size));
	(void) pthread_attr_setstacksize(&attr, stack_size);
    }

#ifdef ETHR_STACK_GUARD_SIZE
    (void) pthread_attr_setguardsize(&attr, ETHR_STACK_GUARD_SIZE);
#endif

    /* Detached or joinable... */
    res = pthread_attr_setdetachstate(&attr,
				      (opts && opts->detached
				       ? PTHREAD_CREATE_DETACHED
				       : PTHREAD_CREATE_JOINABLE));
    if (res != 0)
	goto cleanup_cond_destroy;
    
    res = pthread_mutex_lock(&twd.mtx);

    if (res != 0)
	goto cleanup_cond_destroy;

    safe_mutex_lock(&no_ethrs_mtx.pt_mtx);
    if (no_ethreads < ETHR_MAX_THREADS) {
	no_ethreads++;
	safe_mutex_unlock(&no_ethrs_mtx.pt_mtx);
    }
    else {
	res = EAGAIN;
	safe_mutex_unlock(&no_ethrs_mtx.pt_mtx);
	goto cleanup_mutex_unlock;
    }

    res = pthread_create((pthread_t *) tid, &attr, thr_wrapper, (void *) &twd);

    if (res != 0) {
	safe_mutex_lock(&no_ethrs_mtx.pt_mtx);
	ASSERT(no_ethreads > 0);
	no_ethreads--;
	safe_mutex_unlock(&no_ethrs_mtx.pt_mtx);
    }
    else {

	/* Wait for child to initialize... */
	while (!twd.initialized) {
	    res = pthread_cond_wait(&twd.cnd, &twd.mtx);
	    if (res != 0 && res != EINTR)
		break;
	}

    }

    /* Cleanup... */
 cleanup_mutex_unlock:
    dres = pthread_mutex_unlock(&twd.mtx);
    if (res == 0)
	res = dres;
 cleanup_cond_destroy:
    dres = pthread_cond_destroy(&twd.cnd);
    if (res == 0)
	res = dres;
 cleanup_mutex_destroy:
    dres = pthread_mutex_destroy(&twd.mtx);
    if (res == 0)
	res = dres;
 cleanup_attr_destroy:
    dres = pthread_attr_destroy(&attr);
    if (res == 0)
	res = dres;
 cleanup_parent_func:
    if (thread_create_parent_func)
	(*thread_create_parent_func)(twd.prep_func_res);

    return res;
}

int
ethr_thr_join(ethr_tid tid, void **res)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return pthread_join((pthread_t) tid, res);
}

int
ethr_thr_detach(ethr_tid tid)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return pthread_detach((pthread_t) tid);
}

void
ethr_thr_exit(void *res)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return;
    }
#endif
    thr_exit_cleanup();
    pthread_exit(res);
}

ethr_tid
ethr_self(void)
{
    return (ethr_tid) pthread_self();
}

int
ethr_equal_tids(ethr_tid tid1, ethr_tid tid2)
{
    return pthread_equal((pthread_t) tid1, (pthread_t) tid2);
}


/*
 * Mutex functions
 */


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

#ifdef ETHR_HAVE_ETHR_REC_MUTEX_INIT

int
ethr_rec_mutex_init(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx) {
	ASSERT(0);
	return EINVAL;
    }
    mtx->initialized = ETHR_MUTEX_INITIALIZED;
#endif
    if (rec_mtx_attr_need_init)
	init_rec_mtx_attr();

    mtx->prev = NULL;
    mtx->next = NULL;
    mtx->is_rec_mtx = 1;
    return pthread_mutex_init(&mtx->pt_mtx, &rec_mtx_attr);
}

#endif /* #if ETHR_HAVE_ETHR_REC_MUTEX_INIT */

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

int ethr_mutex_set_forksafe(ethr_mutex *mtx)
{
    int res;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
#if ETHR_HAVE_PTHREAD_ATFORK
    res = pthread_mutex_lock(&forksafe_mtx.pt_mtx);
    if (res != 0)
	return res;
    if (!forksafe_mtx.next) {
	ASSERT(!forksafe_mtx.prev);
	init_forksafe();
    }
    if (mtx->next) {
	/* forksafe already set for this mutex */ 
	ASSERT(mtx->prev);
    }
    else {
	mtx->next = forksafe_mtx.next;
	mtx->prev = &forksafe_mtx;
	forksafe_mtx.next->prev = mtx;
	forksafe_mtx.next = mtx;
    }

    res = pthread_mutex_unlock(&forksafe_mtx.pt_mtx);

#else /* #if ETHR_HAVE_PTHREAD_ATFORK */
    res = ENOTSUP;
#endif /* #if ETHR_HAVE_PTHREAD_ATFORK */
    return res;
}

int ethr_mutex_unset_forksafe(ethr_mutex *mtx)
{
    int res;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
#if ETHR_HAVE_PTHREAD_ATFORK
    res = pthread_mutex_lock(&forksafe_mtx.pt_mtx);
    if (res != 0)
	return res;
    if (!forksafe_mtx.next) {
	ASSERT(!forksafe_mtx.prev);
	init_forksafe();
    }
    if (!mtx->next) {
	/* forksafe already unset for this mutex */ 
	ASSERT(!mtx->prev);
    }
    else {
	mtx->prev->next = mtx->next;
	mtx->next->prev = mtx->prev;
	mtx->next = NULL;
	mtx->prev = NULL;
    }
    res = pthread_mutex_unlock(&forksafe_mtx.pt_mtx);

#else /* #if ETHR_HAVE_PTHREAD_ATFORK */
    res = ENOTSUP;
#endif /* #if ETHR_HAVE_PTHREAD_ATFORK */
    return res;
}

int
ethr_mutex_trylock(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_mutex_trylock__(mtx);
}

int
ethr_mutex_lock(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_mutex_lock__(mtx);
}

int
ethr_mutex_unlock(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_mutex_unlock__(mtx);
}

/*
 * Condition variable functions
 */

int
ethr_cond_init(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd) {
	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) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd || cnd->initialized != ETHR_COND_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
    cnd->initialized = 0;
#endif
    return pthread_cond_destroy(&cnd->pt_cnd);
}

int
ethr_cond_signal(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd || cnd->initialized != ETHR_COND_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return pthread_cond_signal(&cnd->pt_cnd);
}

int
ethr_cond_broadcast(ethr_cond *cnd)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd || cnd->initialized != ETHR_COND_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return pthread_cond_broadcast(&cnd->pt_cnd);
}

int
ethr_cond_wait(ethr_cond *cnd, ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd
	|| cnd->initialized != ETHR_COND_INITIALIZED
	|| !mtx
	|| mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return pthread_cond_wait(&cnd->pt_cnd, &mtx->pt_mtx);
}

int
ethr_cond_timedwait(ethr_cond *cnd, ethr_mutex *mtx, ethr_timeval *timeout)
{
    struct timespec to;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd
	|| cnd->initialized != ETHR_COND_INITIALIZED
	|| !mtx
	|| mtx->initialized != ETHR_MUTEX_INITIALIZED
	|| !timeout) {
	ASSERT(0);
	return EINVAL;
    }
#endif

    to.tv_sec = timeout->tv_sec;
    to.tv_nsec = timeout->tv_nsec;

    return pthread_cond_timedwait(&cnd->pt_cnd, &mtx->pt_mtx, &to);
}


#ifdef ETHR_HAVE_PTHREAD_RWLOCK_INIT

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

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

int
ethr_rwmutex_tryrlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_tryrlock__(rwmtx);
}

int
ethr_rwmutex_rlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_rlock__(rwmtx);
}

int
ethr_rwmutex_runlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_runlock__(rwmtx);
}

int
ethr_rwmutex_tryrwlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_tryrwlock__(rwmtx);
}

int
ethr_rwmutex_rwlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_rwlock__(rwmtx);
}

int
ethr_rwmutex_rwunlock(ethr_rwmutex *rwmtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwmutex_rwunlock__(rwmtx);
}

#endif /* #ifdef ETHR_HAVE_PTHREAD_RWLOCK_INIT */

/*
 * Current time
 */

int
ethr_time_now(ethr_timeval *time)
{
    int res;
    struct timeval tv;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!time) {
	ASSERT(0);
	return EINVAL;
    }
#endif

    res = gettimeofday(&tv, NULL);
    time->tv_sec = (long) tv.tv_sec;
    time->tv_nsec = ((long) tv.tv_usec)*1000;
    return res;
}

/*
 * Thread specific data
 */

int
ethr_tsd_key_create(ethr_tsd_key *keyp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!keyp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return pthread_key_create((pthread_key_t *) keyp, NULL);
}

int
ethr_tsd_key_delete(ethr_tsd_key key)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return pthread_key_delete((pthread_key_t) key);
}

int
ethr_tsd_set(ethr_tsd_key key, void *value)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return pthread_setspecific((pthread_key_t) key, value);
}

void *
ethr_tsd_get(ethr_tsd_key key)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return NULL;
    }
#endif
    return pthread_getspecific((pthread_key_t) key);
}

/*
 * Signal functions
 */

#if ETHR_HAVE_ETHR_SIG_FUNCS

int ethr_sigmask(int how, const sigset_t *set, sigset_t *oset)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!set && !oset) {
	ASSERT(0);
	return EINVAL;
    }
#endif
  return pthread_sigmask(how, set, oset);
}

int ethr_sigwait(const sigset_t *set, int *sig)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!set || !sig) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (sigwait(set, sig) < 0)
	return errno;
    return 0;
}

#endif /* #if ETHR_HAVE_ETHR_SIG_FUNCS */

#elif defined(ETHR_WIN32_THREADS)
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\
 * Native win32 threads implementation                                       *
\*                                                                           */

#define INVALID_TID -1

/* The spin count values are more or less taken out of the blue */
#define ETHR_MUTEX_SPIN_COUNT	5000
#define ETHR_COND_SPIN_COUNT	1000

ethr_tid serial_shift; /* Bits to shift serial when constructing a tid */
ethr_tid last_serial; /* Last thread table serial used */
ethr_tid last_ix; /* Last thread table index used */
ethr_tid thr_ix_mask; /* Mask used to mask out thread table index from a tid */

/* Event used for conditional variables. On per thread. */
/*typedef struct cnd_wait_event__ cnd_wait_event_;*/
struct cnd_wait_event__ {
    HANDLE handle;
    cnd_wait_event_ *prev;
    cnd_wait_event_ *next;
    int in_queue;
};

/* Thread specific data. Stored in the thread table */
typedef struct {
    ethr_tid thr_id;
    HANDLE thr_handle;
    ethr_tid joiner;
    void *result;
    cnd_wait_event_ wait_event;
} thr_data_;

/* Argument passed to thr_wrapper() */
typedef struct {
    void * (*func)(void *);
    void * arg;
    thr_data_ *ptd;
    thr_data_ *td;
    int res;
    void *prep_func_res;
} thr_wrap_data_;


static CRITICAL_SECTION thr_table_cs; /* Critical section used to protect
					 the thread table from concurrent
					 accesses. */
static CRITICAL_SECTION fake_static_init_cs; /* Critical section used to protect
					initialazition of 'statically
					initialized' mutexes */
static thr_data_ * thr_table[ETHR_MAX_THREADS]; /* The thread table */

static DWORD tls_own_thr_data;

static thr_data_ main_thr_data;

#define THR_IX(TID)	((TID) & thr_ix_mask)
#define OWN_THR_DATA	((thr_data_ *) TlsGetValue(tls_own_thr_data))

/*
 * ----------------------------------------------------------------------------
 * Static functions
 * ----------------------------------------------------------------------------
 */

static int
get_errno(void)
{
    switch (GetLastError()) {
    case ERROR_INVALID_FUNCTION:		return EINVAL;	/* 1	*/
    case ERROR_FILE_NOT_FOUND:			return ENOENT;	/* 2	*/
    case ERROR_PATH_NOT_FOUND:			return ENOENT;	/* 3	*/
    case ERROR_TOO_MANY_OPEN_FILES:		return EMFILE;	/* 4	*/
    case ERROR_ACCESS_DENIED:			return EACCES;	/* 5	*/
    case ERROR_INVALID_HANDLE:			return EBADF;	/* 6	*/
    case ERROR_ARENA_TRASHED:			return ENOMEM;	/* 7	*/
    case ERROR_NOT_ENOUGH_MEMORY:		return ENOMEM;	/* 8	*/
    case ERROR_INVALID_BLOCK:			return ENOMEM;	/* 9	*/
    case ERROR_BAD_ENVIRONMENT:			return E2BIG;	/* 10	*/
    case ERROR_BAD_FORMAT:			return ENOEXEC;	/* 11	*/
    case ERROR_INVALID_ACCESS:			return EINVAL;	/* 12	*/
    case ERROR_INVALID_DATA:			return EINVAL;	/* 13	*/
    case ERROR_OUTOFMEMORY:			return ENOMEM;	/* 14	*/
    case ERROR_INVALID_DRIVE:			return ENOENT;	/* 15	*/
    case ERROR_CURRENT_DIRECTORY:		return EACCES;	/* 16	*/
    case ERROR_NOT_SAME_DEVICE:			return EXDEV;	/* 17	*/
    case ERROR_NO_MORE_FILES:			return ENOENT;	/* 18	*/
    case ERROR_WRITE_PROTECT:			return EACCES;	/* 19	*/
    case ERROR_BAD_UNIT:			return EACCES;	/* 20	*/
    case ERROR_NOT_READY:			return EACCES;	/* 21	*/
    case ERROR_BAD_COMMAND:			return EACCES;	/* 22	*/
    case ERROR_CRC:				return EACCES;	/* 23	*/
    case ERROR_BAD_LENGTH:			return EACCES;	/* 24	*/
    case ERROR_SEEK:				return EACCES;	/* 25	*/
    case ERROR_NOT_DOS_DISK:			return EACCES;	/* 26	*/
    case ERROR_SECTOR_NOT_FOUND:		return EACCES;	/* 27	*/
    case ERROR_OUT_OF_PAPER:			return EACCES;	/* 28	*/
    case ERROR_WRITE_FAULT:			return EACCES;	/* 29	*/
    case ERROR_READ_FAULT:			return EACCES;	/* 30	*/
    case ERROR_GEN_FAILURE:			return EACCES;	/* 31	*/
    case ERROR_SHARING_VIOLATION:		return EACCES;	/* 32	*/
    case ERROR_LOCK_VIOLATION:			return EACCES;	/* 33	*/
    case ERROR_WRONG_DISK:			return EACCES;	/* 34	*/
    case ERROR_SHARING_BUFFER_EXCEEDED:		return EACCES;	/* 36	*/
    case ERROR_BAD_NETPATH:			return ENOENT;	/* 53	*/
    case ERROR_NETWORK_ACCESS_DENIED:		return EACCES;	/* 65	*/
    case ERROR_BAD_NET_NAME:			return ENOENT;	/* 67	*/
    case ERROR_FILE_EXISTS:			return EEXIST;	/* 80	*/
    case ERROR_CANNOT_MAKE:			return EACCES;	/* 82	*/
    case ERROR_FAIL_I24:			return EACCES;	/* 83	*/
    case ERROR_INVALID_PARAMETER:		return EINVAL;	/* 87	*/
    case ERROR_NO_PROC_SLOTS:			return EAGAIN;	/* 89	*/
    case ERROR_DRIVE_LOCKED:			return EACCES;	/* 108	*/
    case ERROR_BROKEN_PIPE:			return EPIPE;	/* 109	*/
    case ERROR_DISK_FULL:			return ENOSPC;	/* 112	*/
    case ERROR_INVALID_TARGET_HANDLE:		return EBADF;	/* 114	*/
    case ERROR_WAIT_NO_CHILDREN:		return ECHILD;	/* 128	*/
    case ERROR_CHILD_NOT_COMPLETE:		return ECHILD;	/* 129	*/
    case ERROR_DIRECT_ACCESS_HANDLE:		return EBADF;	/* 130	*/
    case ERROR_NEGATIVE_SEEK:			return EINVAL;	/* 131	*/
    case ERROR_SEEK_ON_DEVICE:			return EACCES;	/* 132	*/
    case ERROR_DIR_NOT_EMPTY:			return ENOTEMPTY;/* 145	*/
    case ERROR_NOT_LOCKED:			return EACCES;	/* 158	*/
    case ERROR_BAD_PATHNAME:			return ENOENT;	/* 161	*/
    case ERROR_MAX_THRDS_REACHED:		return EAGAIN;	/* 164	*/
    case ERROR_LOCK_FAILED:			return EACCES;	/* 167	*/
    case ERROR_ALREADY_EXISTS:			return EEXIST;	/* 183	*/
    case ERROR_INVALID_STARTING_CODESEG:	return ENOEXEC;	/* 188	*/
    case ERROR_INVALID_STACKSEG:		return ENOEXEC;	/* 189	*/
    case ERROR_INVALID_MODULETYPE:		return ENOEXEC;	/* 190	*/
    case ERROR_INVALID_EXE_SIGNATURE:		return ENOEXEC;	/* 191	*/
    case ERROR_EXE_MARKED_INVALID:		return ENOEXEC;	/* 192	*/
    case ERROR_BAD_EXE_FORMAT:			return ENOEXEC;	/* 193	*/
    case ERROR_ITERATED_DATA_EXCEEDS_64k:	return ENOEXEC;	/* 194	*/
    case ERROR_INVALID_MINALLOCSIZE:		return ENOEXEC;	/* 195	*/
    case ERROR_DYNLINK_FROM_INVALID_RING:	return ENOEXEC;	/* 196	*/
    case ERROR_IOPL_NOT_ENABLED:		return ENOEXEC;	/* 197	*/
    case ERROR_INVALID_SEGDPL:			return ENOEXEC;	/* 198	*/
    case ERROR_AUTODATASEG_EXCEEDS_64k:		return ENOEXEC;	/* 199	*/
    case ERROR_RING2SEG_MUST_BE_MOVABLE:	return ENOEXEC;	/* 200	*/
    case ERROR_RELOC_CHAIN_XEEDS_SEGLIM:	return ENOEXEC;	/* 201	*/
    case ERROR_INFLOOP_IN_RELOC_CHAIN:		return ENOEXEC;	/* 202	*/
    case ERROR_FILENAME_EXCED_RANGE:		return ENOENT;	/* 206	*/
    case ERROR_NESTING_NOT_ALLOWED:		return EAGAIN;	/* 215	*/
    case ERROR_NOT_ENOUGH_QUOTA:		return ENOMEM;	/* 1816	*/
    default:					return EINVAL;
    }
}

static ETHR_INLINE thr_data_ *
tid2thr(ethr_tid tid)
{
    ethr_tid ix;
    thr_data_ *td;
    
    if (tid < 0)
	return NULL;
    ix = THR_IX(tid);
    if (ix >= ETHR_MAX_THREADS)
	return NULL;
    td = thr_table[ix];
    if (!td)
	return NULL;
    if (td->thr_id != tid)
	return NULL;
    return td;
}

static ETHR_INLINE void
new_tid(ethr_tid *new_tid, ethr_tid *new_serial, ethr_tid *new_ix)
{
    ethr_tid tmp_serial = last_serial;
    ethr_tid tmp_ix = last_ix + 1;
    ethr_tid start_ix = tmp_ix;


    do {
	if (tmp_ix >= ETHR_MAX_THREADS) {
	    tmp_serial++;
	    if ((tmp_serial << serial_shift) < 0)
		tmp_serial = 0;
	    tmp_ix = 0;
	}
	if (!thr_table[tmp_ix]) {
	    *new_tid	= (tmp_serial << serial_shift) | tmp_ix;
	    *new_serial	= tmp_serial;
	    *new_ix	= tmp_ix;
	    return;
	}
	tmp_ix++;
    } while (tmp_ix != start_ix);

    *new_tid	= INVALID_TID;
    *new_serial	= INVALID_TID;
    *new_ix	= INVALID_TID;

}


static void thr_exit_cleanup(thr_data_ *td, void *res)
{

    ASSERT(td == OWN_THR_DATA);

    run_exit_handlers();

    EnterCriticalSection(&thr_table_cs);
    CloseHandle(td->wait_event.handle);
    if (td->thr_handle == INVALID_HANDLE_VALUE) {
	/* We are detached; cleanup thread table */
	ASSERT(td->joiner == INVALID_TID);
	ASSERT(td == thr_table[THR_IX(td->thr_id)]);
	thr_table[THR_IX(td->thr_id)] = NULL;
	if (td != &main_thr_data)
	    (*freep)((void *) td);
    }
    else {
	/* Save result and let joining thread cleanup */
	td->result = res;
    }
    LeaveCriticalSection(&thr_table_cs);
}

static unsigned __stdcall thr_wrapper(LPVOID args)
{
    void *(*func)(void*) = ((thr_wrap_data_ *) args)->func;
    void *arg = ((thr_wrap_data_ *) args)->arg;
    thr_data_ *td = ((thr_wrap_data_ *) args)->td;

    td->wait_event.handle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (td->wait_event.handle == INVALID_HANDLE_VALUE
	|| !TlsSetValue(tls_own_thr_data, (LPVOID) td)) {
	((thr_wrap_data_ *) args)->res = get_errno();
	if (td->wait_event.handle != INVALID_HANDLE_VALUE)
	    CloseHandle(td->wait_event.handle);
	SetEvent(((thr_wrap_data_ *) args)->ptd->wait_event.handle);
	_endthreadex((unsigned) 0);
	ASSERT(0);
    }

    td->wait_event.prev = NULL;
    td->wait_event.next = NULL;
    td->wait_event.in_queue = 0;

    if (thread_create_child_func)
	(*thread_create_child_func)(((thr_wrap_data_ *) args)->prep_func_res);

    ASSERT(td == OWN_THR_DATA);

    ((thr_wrap_data_ *) args)->res = 0;
    SetEvent(((thr_wrap_data_ *) args)->ptd->wait_event.handle);

    thr_exit_cleanup(td, (*func)(arg));
    return 0;
}

int
ethr_fake_static_mutex_init(ethr_mutex *mtx)
{
    EnterCriticalSection((CRITICAL_SECTION *) &fake_static_init_cs);
    /* Got here under race conditions; check again... */
    if (!mtx->initialized) {
	if (!InitializeCriticalSectionAndSpinCount(&mtx->cs,
						   ETHR_MUTEX_SPIN_COUNT))
	    return get_errno();
	mtx->initialized = ETHR_MUTEX_INITIALIZED;
    }
    LeaveCriticalSection((CRITICAL_SECTION *) &fake_static_init_cs);
    return 0;
}

static int
fake_static_cond_init(ethr_cond *cnd)
{
    EnterCriticalSection((CRITICAL_SECTION *) &fake_static_init_cs);
    /* Got here under race conditions; check again... */
    if (!cnd->initialized) {
	if (!InitializeCriticalSectionAndSpinCount(&cnd->cs,
						   ETHR_COND_SPIN_COUNT))
	    return get_errno();
	cnd->queue = NULL;
	cnd->queue_end = NULL;
	cnd->initialized = ETHR_COND_INITIALIZED;
    }
    LeaveCriticalSection((CRITICAL_SECTION *) &fake_static_init_cs);
    return 0;
}

#ifdef __GNUC__
#define LL_LITERAL(X) X##LL
#else
#define LL_LITERAL(X) X##i64
#endif

#define EPOCH_JULIAN_DIFF LL_LITERAL(11644473600)

static ETHR_INLINE void
get_curr_time(long *sec, long *nsec)
{
    SYSTEMTIME t;
    FILETIME ft;
    LONGLONG lft;

    GetSystemTime(&t);
    SystemTimeToFileTime(&t, &ft);
    memcpy(&lft, &ft, sizeof(lft));
    *nsec = ((long) (lft % LL_LITERAL(10000000)))*100;
    *sec = (long) ((lft / LL_LITERAL(10000000)) - EPOCH_JULIAN_DIFF);
}

static cnd_wait_event_ *cwe_freelist;
static CRITICAL_SECTION cwe_cs;

static int
alloc_cwe(cnd_wait_event_ **cwe_res)
{
    cnd_wait_event_ *cwe;
    EnterCriticalSection(&cwe_cs);
    cwe = cwe_freelist;
    if (cwe) {
	cwe_freelist = cwe->next;
	LeaveCriticalSection(&cwe_cs);
    }
    else {
	LeaveCriticalSection(&cwe_cs);
	cwe = (*allocp)(sizeof(cnd_wait_event_));
	if (!cwe)
	    return ENOMEM;
	cwe->handle = CreateEvent(NULL, FALSE, FALSE, NULL);
	if (cwe->handle == INVALID_HANDLE_VALUE) {
	    int res = get_errno();
	    (*freep)(cwe);
	    return res;
	}
    }
    *cwe_res = cwe;
    return 0;
}

static
free_cwe(cnd_wait_event_ *cwe)
{
    EnterCriticalSection(&cwe_cs);
    cwe->next = cwe_freelist;
    cwe_freelist = cwe;
    LeaveCriticalSection(&cwe_cs);
}

static ETHR_INLINE int
condwait(ethr_cond *cnd,
	 ethr_mutex *mtx,
	 int with_timeout,
	 ethr_timeval *timeout)
{
    int res;
    thr_data_ *td;
    cnd_wait_event_ *cwe;
    DWORD code;
    long time; /* time until timeout in milli seconds */

#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }

    if (!mtx
	|| mtx->initialized != ETHR_MUTEX_INITIALIZED
	|| !cnd
	|| (cnd->initialized && cnd->initialized != ETHR_COND_INITIALIZED)
	|| (with_timeout && !timeout)) {
	ASSERT(0);
	return EINVAL;
    }
#endif

    td = OWN_THR_DATA;
    if (td)
	cwe = &td->wait_event;
    else { /* A non-ethread thread */
	res = alloc_cwe(&cwe);
	if (res != 0)
	    return res;
    }

    if (!cnd->initialized)
	fake_static_cond_init(cnd);
    EnterCriticalSection(&cnd->cs);

    ASSERT(!cwe->in_queue);
    if (cnd->queue_end) {
	ASSERT(cnd->queue);
	cwe->prev = cnd->queue_end;
	cwe->next = NULL;
	cnd->queue_end->next = cwe;
	cnd->queue_end = cwe;
    }
    else {
	ASSERT(!cnd->queue);
	cwe->prev = NULL;
	cwe->next = NULL;
	cnd->queue = cwe;
	cnd->queue_end = cwe;
    }
    cwe->in_queue = 1;

    LeaveCriticalSection(&cnd->cs);
 
    LeaveCriticalSection(&mtx->cs);

    if (!with_timeout)
	time = INFINITE;
    else {
	long sec, nsec;
	ASSERT(timeout);
	get_curr_time(&sec, &nsec);
	time = (timeout->tv_sec - sec)*1000;
	time += (timeout->tv_nsec - nsec + 500)/1000000;
	if (time < 0)
	    time = 0;
    }

    /* wait for event to signal */
    code = WaitForSingleObject(cwe->handle, time);

    EnterCriticalSection(&mtx->cs);

    if (code == WAIT_OBJECT_0) {
	/* We were woken by a signal or a broadcast ... */
	res = 0;

	/* ... no need to remove event from wait queue since this was
	   taken care of by the signal or broadcast */
#ifdef DEBUG
	EnterCriticalSection(&cnd->cs);
	ASSERT(!cwe->in_queue);
	LeaveCriticalSection(&cnd->cs);
#endif

    }
    else {
	/* We timed out... */
	res = ETIMEDOUT;

	/* ... probably have to remove event from wait queue ... */
	EnterCriticalSection(&cnd->cs);

	if (cwe->in_queue) { /* ... but we must check that we are in queue
				since a signal or broadcast after timeout
				may have removed us from the queue */
	    if (cwe->prev) {
		cwe->prev->next = cwe->next;
	    }
	    else {
		ASSERT(cnd->queue == cwe);
		cnd->queue = cwe->next;
	    }

	    if (cwe->next) {
		cwe->next->prev = cwe->prev;
	    }
	    else {
		ASSERT(cnd->queue_end == cwe);
		cnd->queue_end = cwe->prev;
	    }
	    cwe->in_queue = 0;
	}

	LeaveCriticalSection(&cnd->cs);

    }

    if (!td)
	free_cwe(cwe);

    return res;

}


/*
 * ----------------------------------------------------------------------------
 * Exported functions
 * ----------------------------------------------------------------------------
 */

int
ethr_init(ethr_init_data *id)
{
#ifdef _WIN32_WINNT
    DWORD major = (_WIN32_WINNT >> 8) & 0xff;
    DWORD minor = _WIN32_WINNT & 0xff;
    OSVERSIONINFO os_version;
#endif
    int err = 0;
    thr_data_ *td = &main_thr_data;
    unsigned long i;

    if (!ethr_not_inited)
	return EINVAL;

#ifdef _WIN32_WINNT
    os_version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
    GetVersionEx(&os_version);
    if (os_version.dwPlatformId != VER_PLATFORM_WIN32_NT
	|| os_version.dwMajorVersion < major
	|| (os_version.dwMajorVersion == major
	    && os_version.dwMinorVersion < minor))
	return ENOTSUP;
#endif

    ASSERT(ETHR_MAX_THREADS > 0);
    for (i = ETHR_MAX_THREADS - 1, serial_shift = 0;
	 i;
	 serial_shift++, i >>= 1);
    thr_ix_mask = ~(~((ethr_tid) 0) << serial_shift);

    tls_own_thr_data = TlsAlloc();
    if (tls_own_thr_data == TLS_OUT_OF_INDEXES)
	goto error;

    last_serial = 0;
    last_ix = 0;

    td->thr_id = 0;
    td->thr_handle = GetCurrentThread();
    td->joiner = INVALID_TID;
    td->result = NULL;
    td->wait_event.handle = CreateEvent(NULL, FALSE, FALSE, NULL);
    if (td->wait_event.handle == INVALID_HANDLE_VALUE)
	goto error;
    td->wait_event.prev = NULL;
    td->wait_event.next = NULL;
    td->wait_event.in_queue = 0;
    thr_table[0] = td;

    if (!TlsSetValue(tls_own_thr_data, (LPVOID) td))
	goto error;

    ASSERT(td == OWN_THR_DATA);


    cwe_freelist = NULL;
    if (!InitializeCriticalSectionAndSpinCount(&cwe_cs,
					       ETHR_MUTEX_SPIN_COUNT))
	goto error;

    for (i = 1; i < ETHR_MAX_THREADS; i++)
	thr_table[i] = NULL;

    if (!InitializeCriticalSectionAndSpinCount(&thr_table_cs,
					       ETHR_MUTEX_SPIN_COUNT))
	goto error;
    if (!InitializeCriticalSectionAndSpinCount(&fake_static_init_cs,
					       ETHR_MUTEX_SPIN_COUNT))
	goto error;
    ethr_not_inited = 0;

    err = init_common(id);
    if (err)
	goto error;

    return 0;

 error:
    ethr_not_inited = 1;
    if (err == 0)
	err = get_errno();
    ASSERT(err != 0);
    if (td->thr_handle != INVALID_HANDLE_VALUE)
	CloseHandle(td->thr_handle);
    if (td->wait_event.handle != INVALID_HANDLE_VALUE)
	CloseHandle(td->wait_event.handle);
    return err;
}

/*
 * Thread functions.
 */

int
ethr_thr_create(ethr_tid *tid, void * (*func)(void *), void *arg,
		ethr_thr_opts *opts)
{
    int err = 0;
    thr_wrap_data_ twd;
    thr_data_ *my_td, *child_td = NULL;
    ethr_tid child_tid, child_serial, child_ix;
    DWORD code;
    unsigned ID;
    unsigned stack_size = 0; /* 0 = system default */
    int use_stack_size = (opts && opts->suggested_stack_size >= 0
			  ? opts->suggested_stack_size
			  : -1 /* Use system default */);

#ifdef ETHR_MODIFIED_DEFAULT_STACK_SIZE
    if (use_stack_size < 0)
	use_stack_size = ETHR_MODIFIED_DEFAULT_STACK_SIZE;
#endif

#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!tid || !func) {
	ASSERT(0);
	return EINVAL;
    }
#endif

    my_td = OWN_THR_DATA;
    if (!my_td) {
	/* Only ethreads are allowed to call this function */
	ASSERT(0);
	return EACCES;
    }

    if (use_stack_size >= 0) {
	size_t suggested_stack_size = (size_t) use_stack_size;
#ifdef DEBUG
	suggested_stack_size /= 2; /* Make sure we got margin */
#endif
	if (suggested_stack_size < min_stack_size)
	    stack_size = (unsigned) ETHR_KW2B(min_stack_size);
	else if (suggested_stack_size > max_stack_size)
	    stack_size = (unsigned) ETHR_KW2B(max_stack_size);
	else
	    stack_size =
		(unsigned) ETHR_PAGE_ALIGN(ETHR_KW2B(suggested_stack_size));
    }

    EnterCriticalSection(&thr_table_cs);

    /* Call prepare func if it exist */
    if (thread_create_prepare_func)
	twd.prep_func_res = (*thread_create_prepare_func)();
    else
	twd.prep_func_res = NULL;

    /* Find a new thread id to use */
    new_tid(&child_tid, &child_serial, &child_ix);
    if (child_tid == INVALID_TID) {
	err = EAGAIN;
	goto error;
    }

    ASSERT(child_ix == THR_IX(child_tid));

    *tid = child_tid;

    ASSERT(!thr_table[child_ix]);

    /* Alloc thread data */
    thr_table[child_ix] = child_td = (thr_data_ *) (*allocp)(sizeof(thr_data_));
    if (!child_td) {
	err = ENOMEM;
	goto error;
    }

    /* Init thread data */

    child_td->thr_id		= child_tid;
    child_td->thr_handle	= INVALID_HANDLE_VALUE;
    child_td->joiner		= INVALID_TID;
    child_td->result		= NULL;
    /* 'child_td->wait_event' is initialized by child thread */


    /* Init thread wrapper data */

    twd.func			= func;
    twd.arg			= arg;
    twd.ptd			= my_td;
    twd.td			= child_td;
    twd.res			= 0;

    ASSERT(!my_td->wait_event.in_queue);

    /* spawn the thr_wrapper function */
    child_td->thr_handle = (HANDLE) _beginthreadex(NULL,
						   stack_size,
						   thr_wrapper,
						   (LPVOID) &twd,
						   0,
						   &ID);
    if (child_td->thr_handle == (HANDLE) 0) {
	child_td->thr_handle = INVALID_HANDLE_VALUE;
	goto error;
    }

    ASSERT(child_td->thr_handle != INVALID_HANDLE_VALUE);

    /* Wait for child to finish initialization */
    code = WaitForSingleObject(my_td->wait_event.handle, INFINITE);
    if (twd.res || code != WAIT_OBJECT_0) {
	err = twd.res;
	goto error;
    }

    if (opts && opts->detached) {
	CloseHandle(child_td->thr_handle);
	child_td->thr_handle = INVALID_HANDLE_VALUE;
    }

    last_serial	= child_serial;
    last_ix	= child_ix;

    ASSERT(thr_table[child_ix] == child_td);

    if (thread_create_parent_func)
	(*thread_create_parent_func)(twd.prep_func_res);

    LeaveCriticalSection(&thr_table_cs);

    return 0;

 error:

    if (err == 0)
	err = get_errno();
    ASSERT(err != 0);

    if (thread_create_parent_func)
	(*thread_create_parent_func)(twd.prep_func_res);

    if (child_ix != INVALID_TID) {

	if (child_td) {
	    ASSERT(thr_table[child_ix] == child_td);

	    if (child_td->thr_handle != INVALID_HANDLE_VALUE) {
		WaitForSingleObject(child_td->thr_handle, INFINITE);
		CloseHandle(child_td->thr_handle);
	    }

	    (*freep)((void *) child_td);
	    thr_table[child_ix] = NULL;
	}
    }

    *tid = INVALID_TID;

    LeaveCriticalSection(&thr_table_cs);
    return err;
}

int ethr_thr_join(ethr_tid tid, void **res)
{
    int err = 0;
    DWORD code;
    thr_data_ *td;
    thr_data_ *my_td;

#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif

    my_td = OWN_THR_DATA;

    if (!my_td) {
	/* Only ethreads are allowed to call this function */
	ASSERT(0);
	return EACCES;
    }

    EnterCriticalSection(&thr_table_cs);

    td = tid2thr(tid);
    if (!td)
	err = ESRCH;
    else if (td->thr_handle == INVALID_HANDLE_VALUE /* i.e. detached */
	     || td->joiner != INVALID_TID) /* i.e. someone else is joining */
	err = EINVAL;
    else if (my_td == td)
	err = EDEADLK;
    else
	td->joiner = my_td->thr_id;

    LeaveCriticalSection(&thr_table_cs);

    if (err)
	goto error;

    /* Wait for thread to terminate */
    code = WaitForSingleObject(td->thr_handle, INFINITE);
    if (code != WAIT_OBJECT_0)
	goto error;

    EnterCriticalSection(&thr_table_cs);

    ASSERT(td == tid2thr(tid));
    ASSERT(td->thr_handle != INVALID_HANDLE_VALUE);
    ASSERT(td->joiner == my_td->thr_id);

    if (res)
	*res = td->result;

    CloseHandle(td->thr_handle);
    ASSERT(td == thr_table[THR_IX(td->thr_id)]);
    thr_table[THR_IX(td->thr_id)] = NULL;
    if (td != &main_thr_data)
	(*freep)((void *) td);

    LeaveCriticalSection(&thr_table_cs);

    return 0;

 error:
    if (err == 0)
	err = get_errno();
    ASSERT(err != 0);
    return err;
}


int
ethr_thr_detach(ethr_tid tid)
{
    int res;
    DWORD code;
    thr_data_ *td;

#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif

    if (!OWN_THR_DATA) {
	/* Only ethreads are allowed to call this function */
	ASSERT(0);
	return EACCES;
    }

    EnterCriticalSection(&thr_table_cs);

    td = tid2thr(tid);
    if (!td)
	res = ESRCH;
    if (td->thr_handle == INVALID_HANDLE_VALUE /* i.e. detached */
	|| td->joiner != INVALID_TID) /* i.e. someone is joining */
	res = EINVAL;
    else {
	res = 0;
	CloseHandle(td->thr_handle);
	td->thr_handle = INVALID_HANDLE_VALUE;
    }

    LeaveCriticalSection(&thr_table_cs);

    return res;
}


void
ethr_thr_exit(void *res)
{
    thr_data_ *td;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return;
    }
#endif
    td = OWN_THR_DATA;
    if (!td) {
	/* Only ethreads are allowed to call this function */
	ASSERT(0);
	return;
    }
    thr_exit_cleanup(td, res);
    _endthreadex((unsigned) 0);
}

ethr_tid
ethr_self(void)
{
    thr_data_ *td;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return INVALID_TID;
    }
#endif
    /* It is okay for non-ethreads (i.e. native win32 threads) to call
       ethr_self(). They will however be returned the INVALID_TID. */
    td = OWN_THR_DATA;
    if (!td)
	return INVALID_TID;
    return td->thr_id;
}

int
ethr_equal_tids(ethr_tid tid1, ethr_tid tid2)
{
    /* INVALID_TID does not equal any tid, not even the INVALID_TID */
    return tid1 == tid2 && tid1 != INVALID_TID;
}

/*
 * Mutex functions.
 */

int
ethr_mutex_init(ethr_mutex *mtx)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (!InitializeCriticalSectionAndSpinCount(&mtx->cs, ETHR_MUTEX_SPIN_COUNT))
	return get_errno();
    mtx->initialized = ETHR_MUTEX_INITIALIZED;
#if ETHR_XCHK
    mtx->is_rec_mtx = 0;
#endif
    return 0;
}

int
ethr_rec_mutex_init(ethr_mutex *mtx)
{
    int res;
    res = ethr_mutex_init(mtx);
#if ETHR_XCHK
    mtx->is_rec_mtx = 1;
#endif
    return res;
}

int
ethr_mutex_destroy(ethr_mutex *mtx)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    DeleteCriticalSection(&mtx->cs);
    mtx->initialized = 0;
    return 0;
}

int ethr_mutex_set_forksafe(ethr_mutex *mtx)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return 0; /* No fork() */
}

int ethr_mutex_unset_forksafe(ethr_mutex *mtx)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    return 0; /* No fork() */
}

int
ethr_mutex_trylock(ethr_mutex *mtx)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx
	|| (mtx->initialized && mtx->initialized != ETHR_MUTEX_INITIALIZED)) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (!mtx->initialized) {
	int res = ethr_fake_static_mutex_init(mtx);
	if (res != 0)
	    return res;
    }
    return ethr_mutex_trylock__(mtx);
}

int
ethr_mutex_lock(ethr_mutex *mtx)
{
    int res;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx
	|| (mtx->initialized && mtx->initialized != ETHR_MUTEX_INITIALIZED)) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_mutex_lock__(mtx);
}

int
ethr_mutex_unlock(ethr_mutex *mtx)
{
#if ETHR_XCHK
    int res;
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!mtx || mtx->initialized != ETHR_MUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_mutex_unlock__(mtx);
}

/*
 * Condition variable functions.
 */

int
ethr_cond_init(ethr_cond *cnd)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (!InitializeCriticalSectionAndSpinCount(&cnd->cs, ETHR_COND_SPIN_COUNT))
	return get_errno();
    cnd->queue = NULL;
    cnd->queue_end = NULL;
    cnd->initialized = ETHR_COND_INITIALIZED;
    return 0;
}

int
ethr_cond_destroy(ethr_cond *cnd)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd
	|| (cnd->initialized && cnd->initialized != ETHR_COND_INITIALIZED)
	|| cnd->queue) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    DeleteCriticalSection(&cnd->cs);
    cnd->initialized = 0;
    return 0;
}

int
ethr_cond_signal(ethr_cond *cnd)
{
    cnd_wait_event_ *cwe;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd
	|| (cnd->initialized && cnd->initialized != ETHR_COND_INITIALIZED)) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (!cnd->initialized) {
	int res = fake_static_cond_init(cnd);
	if (res != 0)
	    return res;
    }
    EnterCriticalSection(&cnd->cs);
    cwe = cnd->queue;
    if (cwe) {
	ASSERT(cwe->in_queue);
	SetEvent(cnd->queue->handle);
	if (cwe->next)
	    cwe->next->prev = NULL;
	else {
	    ASSERT(cnd->queue_end == cnd->queue);
	    cnd->queue_end = NULL;
	}
	cnd->queue = cwe->next;
	cwe->in_queue = 0;
    }
    LeaveCriticalSection(&cnd->cs);
    return 0;
}

int
ethr_cond_broadcast(ethr_cond *cnd)
{
    cnd_wait_event_ *cwe;

#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!cnd
	|| (cnd->initialized && cnd->initialized != ETHR_COND_INITIALIZED)) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (!cnd->initialized) {
	int res = fake_static_cond_init(cnd);
	if (res != 0)
	    return res;
    }
    EnterCriticalSection(&cnd->cs);
    for (cwe = cnd->queue; cwe; cwe = cwe->next) {
	ASSERT(cwe->in_queue);
	SetEvent(cwe->handle);
	cwe->in_queue = 0;
    }
    cnd->queue = NULL;
    cnd->queue_end = NULL;
    LeaveCriticalSection(&cnd->cs);
    return 0;

}

int
ethr_cond_wait(ethr_cond *cnd, ethr_mutex *mtx)
{
    return condwait(cnd, mtx, 0, NULL);
}

int
ethr_cond_timedwait(ethr_cond *cnd, ethr_mutex *mtx, ethr_timeval *timeout)
{
    return condwait(cnd, mtx, 1, timeout);
}

int
ethr_time_now(ethr_timeval *time)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!time) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    get_curr_time(&time->tv_sec, &time->tv_nsec);
    return 0;
}

/*
 * Thread specific data
 */

int
ethr_tsd_key_create(ethr_tsd_key *keyp)
{
    DWORD key;
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!keyp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    key = TlsAlloc();
    if (key == TLS_OUT_OF_INDEXES)
	return get_errno();
    *keyp = (ethr_tsd_key) key;
    return 0;
}

int
ethr_tsd_key_delete(ethr_tsd_key key)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    if (!TlsFree((DWORD) key))
	return get_errno();
    return 0;
}

int
ethr_tsd_set(ethr_tsd_key key, void *value)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
#endif
    if (!TlsSetValue((DWORD) key, (LPVOID) value))
	return get_errno();
    return 0;
}

void *
ethr_tsd_get(ethr_tsd_key key)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return NULL;
    }
#endif
    return (void *) TlsGetValue((DWORD) key);
}

/* Misc */

#ifndef ETHR_HAVE_OPTIMIZED_LOCKS

int
ethr_do_spinlock_init(ethr_spinlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    if (InitializeCriticalSectionAndSpinCount(&lock->cs, INT_MAX))
	return 0;
    else
	return get_errno();
}

int
ethr_do_rwlock_init(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    lock->counter = 0;
    if (InitializeCriticalSectionAndSpinCount(&lock->cs, INT_MAX))
	return 0;
    else
	return get_errno();    
}

#endif /* #ifndef ETHR_HAVE_OPTIMIZED_ATOMIC_OPS */

#else
#error "Missing thread implementation"
#endif

/* Atomics */

int
ethr_atomic_init(ethr_atomic_t *var, long i)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
       ASSERT(0);
       return EACCES;
    }  
    if (!var) {
       ASSERT(0);
       return EINVAL;
    }  
#endif
    return ethr_atomic_init__(var, i);
}

int
ethr_atomic_set(ethr_atomic_t *var, long i)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
       ASSERT(0);
       return EACCES;
    }  
    if (!var) {
       ASSERT(0);
       return EINVAL;
    }  
#endif
    return ethr_atomic_set__(var, i);
}

int
ethr_atomic_read(ethr_atomic_t *var, long *i)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
       ASSERT(0);
       return EACCES;
    }  
    if (!var || !i) {
       ASSERT(0);
       return EINVAL;
    }  
#endif
    return ethr_atomic_read__(var, i);
}


int
ethr_atomic_addtest(ethr_atomic_t *var, long incr, long *testp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
       ASSERT(0);
       return EACCES;
    }  
    if (!var || !testp) {
       ASSERT(0);
       return EINVAL;
    }  
#endif
    return ethr_atomic_addtest__(var, incr, testp);
}   
    
int
ethr_atomic_inctest(ethr_atomic_t *incp, long *testp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!incp || !testp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_inctest__(incp, testp);
}

int
ethr_atomic_dectest(ethr_atomic_t *decp, long *testp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!decp || !testp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_dectest__(decp, testp);
}

int
ethr_atomic_add(ethr_atomic_t *var, long incr)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
       ASSERT(0);
       return EACCES;
    }  
    if (!var) {
       ASSERT(0);
       return EINVAL;
    }  
#endif
    return ethr_atomic_add__(var, incr);
}   
    
int 
ethr_atomic_inc(ethr_atomic_t *incp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!incp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_inc__(incp);
}

int
ethr_atomic_dec(ethr_atomic_t *decp)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!decp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_dec__(decp);
}

int
ethr_atomic_and_old(ethr_atomic_t *var, long mask, long *old)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!var || !old) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_and_old__(var, mask, old);
}

int
ethr_atomic_or_old(ethr_atomic_t *var, long mask, long *old)
{
#if ETHR_XCHK
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!var || !old) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_atomic_or_old__(var, mask, old);
}

int
ethr_atomic_xchg(ethr_atomic_t *var, long new, long *old)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }  
    if (!var || !old) {
	ASSERT(0);
	return EINVAL;
    }  
#endif
    return ethr_atomic_xchg__(var, new, old);
}   

int
ethr_atomic_cmpxchg(ethr_atomic_t *var, long new, long expected, long *old)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }  
    if (!var || !old) {
	ASSERT(0);
	return EINVAL;
    }  
#endif
    return ethr_atomic_cmpxchg__(var, new, expected, old);
}

/* Spinlocks and rwspinlocks */

int
ethr_spinlock_init(ethr_spinlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_spinlock_init__(lock);
}

int
ethr_spinlock_destroy(ethr_spinlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_spinlock_destroy__(lock);
}


int
ethr_spin_unlock(ethr_spinlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_spin_unlock__(lock);
}

int
ethr_spin_lock(ethr_spinlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_spin_lock__(lock);
}

int
ethr_rwlock_init(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwlock_init__(lock);
}

int
ethr_rwlock_destroy(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_rwlock_destroy__(lock);
}

int
ethr_read_unlock(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_read_unlock__(lock);
}

int
ethr_read_lock(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_read_lock__(lock);
}

int
ethr_write_unlock(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_write_unlock__(lock);
}

int
ethr_write_lock(ethr_rwlock_t *lock)
{
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!lock) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    return ethr_write_lock__(lock);
}


int
ethr_gate_init(ethr_gate *gp)
{
    int res;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!gp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_init(&gp->mtx);
    if (res != 0)
	return res;
    res = ethr_cond_init(&gp->cnd);
    if (res != 0) {
	ethr_mutex_destroy(&gp->mtx);
	return res;
    }
    gp->open = 0;
    return 0;
}

int
ethr_gate_destroy(ethr_gate *gp)
{
    int res, dres;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!gp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_destroy(&gp->mtx);
    dres = ethr_cond_destroy(&gp->cnd);
    if (res == 0)
	res = dres;
    gp->open = 0;
    return res;
}

int
ethr_gate_close(ethr_gate *gp)
{
    int res;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!gp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_lock__(&gp->mtx);
    if (res != 0)
	return res;
    gp->open = 0;
    res = ethr_mutex_unlock__(&gp->mtx);
    return res;
}

int
ethr_gate_let_through(ethr_gate *gp, unsigned no)
{
    int res, ures;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!gp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_lock__(&gp->mtx);
    if (res != 0)
	return res;
    gp->open += no;
    res = (gp->open == 1
	   ? ethr_cond_signal(&gp->cnd)
	   : ethr_cond_broadcast(&gp->cnd));
    ures = ethr_mutex_unlock__(&gp->mtx);
    if (res != 0)
	res = ures;
    return res;
}

int
ethr_gate_swait(ethr_gate *gp, int spincount)
{
    int res, ures, n;
#if ETHR_XCHK 
    if (ethr_not_inited) {
	ASSERT(0);
	return EACCES;
    }
    if (!gp) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    n = spincount;
    res = ethr_mutex_lock__(&gp->mtx);
    if (res != 0)
	return res;
    while (n >= 0 && !gp->open) {
	res = ethr_mutex_unlock__(&gp->mtx);
	if (res != 0)
	    return res;
	res = ethr_mutex_lock__(&gp->mtx);
	if (res != 0)
	    return res;
	n--;
    }
    while (!gp->open) {
	res = ethr_cond_wait(&gp->cnd, &gp->mtx);
	if (res != 0 && res != EINTR)
	    goto done;
    }
    gp->open--;
 done:
    ures = ethr_mutex_unlock__(&gp->mtx);
    if (res == 0)
	res = ures;
    return res;
}


int
ethr_gate_wait(ethr_gate *gp)
{
    return ethr_gate_swait(gp, 0);
}


/* rwmutex fallback */
#ifdef ETHR_USE_RWMTX_FALLBACK

int
ethr_rwmutex_init(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (!rwmtx) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_init(&rwmtx->mtx);
    if (res != 0)
	return res;
    ethr_cond_init(&rwmtx->rcnd);
    if (res != 0)
	goto error_cleanup1;
    res = ethr_cond_init(&rwmtx->wcnd);
    if (res != 0)
	goto error_cleanup2;
    rwmtx->readers = 0;
    rwmtx->waiting_readers = 0;
    rwmtx->waiting_writers = 0;
#if ETHR_XCHK
    rwmtx->initialized = ETHR_RWMUTEX_INITIALIZED;
#endif
    return 0;
 error_cleanup2:
    ethr_cond_destroy(&rwmtx->rcnd);
 error_cleanup1:
    ethr_mutex_destroy(&rwmtx->mtx);
    return res;
}

int
ethr_rwmutex_destroy(ethr_rwmutex *rwmtx)
{
    int res, pres;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
    rwmtx->initialized = 0;
#endif
    res = ethr_mutex_destroy(&rwmtx->mtx);
    pres = ethr_cond_destroy(&rwmtx->rcnd);
    if (res == 0)
	res = pres;
    pres = ethr_cond_destroy(&rwmtx->wcnd);
    if (res == 0)
	res = pres;
    return res;
}

int
ethr_rwmutex_tryrlock(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_trylock__(&rwmtx->mtx);
    if (res != 0)
	return res;
    if (rwmtx->waiting_writers) {
	res = ethr_mutex_unlock__(&rwmtx->mtx);
	if (res == 0)
	    return EBUSY;
	return res;
    }
    rwmtx->readers++;
    return ethr_mutex_unlock__(&rwmtx->mtx);
}

int
ethr_rwmutex_rlock(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_lock__(&rwmtx->mtx);
    if (res != 0)
	return res;
    while (rwmtx->waiting_writers) {
	rwmtx->waiting_readers++;
	res = ethr_cond_wait(&rwmtx->rcnd, &rwmtx->mtx);
	rwmtx->waiting_readers--;
	if (res != 0 && res != EINTR) {
	    (void) ethr_mutex_unlock__(&rwmtx->mtx);
	    return res;
	}
    }
    rwmtx->readers++;
    return ethr_mutex_unlock__(&rwmtx->mtx);
}

int
ethr_rwmutex_runlock(ethr_rwmutex *rwmtx)
{
    int res, ures;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_lock__(&rwmtx->mtx);
    if (res != 0)
	return res;
    rwmtx->readers--;
    if (!rwmtx->readers && rwmtx->waiting_writers)
	res = ethr_cond_signal(&rwmtx->wcnd);
    ures = ethr_mutex_unlock__(&rwmtx->mtx);
    if (res == 0)
	res = ures;
    return res;
}

int
ethr_rwmutex_tryrwlock(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_trylock__(&rwmtx->mtx);
    if (res != 0)
	return res;
    if (!rwmtx->readers && !rwmtx->waiting_writers)
	return 0;
    else {
	res = ethr_mutex_unlock__(&rwmtx->mtx);
	if (res == 0)
	    return EBUSY;
	return res;
    }
}

int
ethr_rwmutex_rwlock(ethr_rwmutex *rwmtx)
{
    int res;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = ethr_mutex_lock__(&rwmtx->mtx);
    if (res != 0)
	return res;
    if (!rwmtx->readers && !rwmtx->waiting_writers) 
	return 0;
    
    while (rwmtx->readers) {
	rwmtx->waiting_writers++;
	res = ethr_cond_wait(&rwmtx->wcnd, &rwmtx->mtx);
	rwmtx->waiting_writers--;
	if (res != 0 && res != EINTR) {
	    (void) ethr_rwmutex_rwunlock(rwmtx);
	    return res;
	}
    }
    return 0;
}

int
ethr_rwmutex_rwunlock(ethr_rwmutex *rwmtx)
{
    int res, ures;
#if ETHR_XCHK
    if (!rwmtx || rwmtx->initialized != ETHR_RWMUTEX_INITIALIZED) {
	ASSERT(0);
	return EINVAL;
    }
#endif
    res = 0;
    if (rwmtx->waiting_writers)
	res = ethr_cond_signal(&rwmtx->wcnd);
    else if (rwmtx->waiting_readers)
	res = ethr_cond_broadcast(&rwmtx->rcnd);
    ures = ethr_mutex_unlock__(&rwmtx->mtx);
    if (res == 0)
	res = ures;
    return res;
}

#endif /* #ifdef ETHR_USE_RWMTX_FALLBACK */

void
ethr_compiler_barrier(void)
{

}

#ifdef DEBUG

#include <stdio.h>
int ethr_assert_failed(char *f, int l, char *a)
{
    fprintf(stderr, "%s:%d: Assertion failed: %s\n", f, l, a);
    abort();
    return 0;
}

#endif