summaryrefslogtreecommitdiffstats
path: root/nsprpub/pr/src/md/unix/unix.c
blob: 70bb8e8744f9155d1a11d275b14ae142b644ceff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
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
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#include "primpl.h"

#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/utsname.h>

#ifdef _PR_POLL_AVAILABLE
#include <poll.h>
#endif

#if defined(ANDROID)
#include <android/api-level.h>
#endif

/* To get FIONREAD */
#if defined(UNIXWARE)
#include <sys/filio.h>
#endif

#if defined(NTO)
#include <sys/statvfs.h>
#endif

/*
 * Make sure _PRSockLen_t is 32-bit, because we will cast a PRUint32* or
 * PRInt32* pointer to a _PRSockLen_t* pointer.
 */
#if defined(HAVE_SOCKLEN_T) \
    || (defined(__GLIBC__) && __GLIBC__ >= 2)
#define _PRSockLen_t socklen_t
#elif defined(HPUX) || defined(SOLARIS) \
    || defined(AIX4_1) || defined(LINUX) \
    || defined(BSDI) || defined(SCO) \
    || defined(DARWIN) \
    || defined(QNX)
#define _PRSockLen_t int
#elif (defined(AIX) && !defined(AIX4_1)) || defined(FREEBSD) \
    || defined(NETBSD) || defined(OPENBSD) || defined(UNIXWARE) \
    || defined(NTO) || defined(RISCOS)
#define _PRSockLen_t size_t
#else
#error "Cannot determine architecture"
#endif

/*
** Global lock variable used to bracket calls into rusty libraries that
** aren't thread safe (like libc, libX, etc).
*/
static PRLock *_pr_unix_rename_lock = NULL;
static PRMonitor *_pr_Xfe_mon = NULL;

static PRInt64 minus_one;

sigset_t timer_set;

#if !defined(_PR_PTHREADS)

static sigset_t empty_set;

#ifdef SOLARIS
#include <sys/file.h>
#include <sys/filio.h>
#endif

#ifndef PIPE_BUF
#define PIPE_BUF 512
#endif

/*
 * _nspr_noclock - if set clock interrupts are disabled
 */
int _nspr_noclock = 1;

/*
 * There is an assertion in this code that NSPR's definition of PRIOVec
 * is bit compatible with UNIX' definition of a struct iovec. This is
 * applicable to the 'writev()' operations where the types are casually
 * cast to avoid warnings.
 */

int _pr_md_pipefd[2] = { -1, -1 };
static char _pr_md_pipebuf[PIPE_BUF];
static PRInt32 local_io_wait(PRInt32 osfd, PRInt32 wait_flag,
                             PRIntervalTime timeout);

_PRInterruptTable _pr_interruptTable[] = {
    {
        "clock", _PR_MISSED_CLOCK, _PR_ClockInterrupt,
    },
    {
        0
    }
};

void _MD_unix_init_running_cpu(_PRCPU *cpu)
{
    PR_INIT_CLIST(&(cpu->md.md_unix.ioQ));
    cpu->md.md_unix.ioq_max_osfd = -1;
    cpu->md.md_unix.ioq_timeout = PR_INTERVAL_NO_TIMEOUT;
}

PRStatus _MD_open_dir(_MDDir *d, const char *name)
{
    int err;

    d->d = opendir(name);
    if (!d->d) {
        err = _MD_ERRNO();
        _PR_MD_MAP_OPENDIR_ERROR(err);
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

PRInt32 _MD_close_dir(_MDDir *d)
{
    int rv = 0, err;

    if (d->d) {
        rv = closedir(d->d);
        if (rv == -1) {
            err = _MD_ERRNO();
            _PR_MD_MAP_CLOSEDIR_ERROR(err);
        }
    }
    return rv;
}

char * _MD_read_dir(_MDDir *d, PRIntn flags)
{
    struct dirent *de;
    int err;

    for (;;) {
        /*
          * XXX: readdir() is not MT-safe. There is an MT-safe version
          * readdir_r() on some systems.
          */
        _MD_ERRNO() = 0;
        de = readdir(d->d);
        if (!de) {
            err = _MD_ERRNO();
            _PR_MD_MAP_READDIR_ERROR(err);
            return 0;
        }
        if ((flags & PR_SKIP_DOT) &&
            (de->d_name[0] == '.') && (de->d_name[1] == 0)) {
            continue;
        }
        if ((flags & PR_SKIP_DOT_DOT) &&
            (de->d_name[0] == '.') && (de->d_name[1] == '.') &&
            (de->d_name[2] == 0)) {
            continue;
        }
        if ((flags & PR_SKIP_HIDDEN) && (de->d_name[0] == '.')) {
            continue;
        }
        break;
    }
    return de->d_name;
}

PRInt32 _MD_delete(const char *name)
{
    PRInt32 rv, err;
#ifdef UNIXWARE
    sigset_t set, oset;
#endif

#ifdef UNIXWARE
    sigfillset(&set);
    sigprocmask(SIG_SETMASK, &set, &oset);
#endif
    rv = unlink(name);
#ifdef UNIXWARE
    sigprocmask(SIG_SETMASK, &oset, NULL);
#endif
    if (rv == -1) {
        err = _MD_ERRNO();
        _PR_MD_MAP_UNLINK_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_rename(const char *from, const char *to)
{
    PRInt32 rv = -1, err;

    /*
    ** This is trying to enforce the semantics of WINDOZE' rename
    ** operation. That means one is not allowed to rename over top
    ** of an existing file. Holding a lock across these two function
    ** and the open function is known to be a bad idea, but ....
    */
    if (NULL != _pr_unix_rename_lock) {
        PR_Lock(_pr_unix_rename_lock);
    }
    if (0 == access(to, F_OK)) {
        PR_SetError(PR_FILE_EXISTS_ERROR, 0);
    }
    else
    {
        rv = rename(from, to);
        if (rv < 0) {
            err = _MD_ERRNO();
            _PR_MD_MAP_RENAME_ERROR(err);
        }
    }
    if (NULL != _pr_unix_rename_lock) {
        PR_Unlock(_pr_unix_rename_lock);
    }
    return rv;
}

PRInt32 _MD_access(const char *name, PRAccessHow how)
{
    PRInt32 rv, err;
    int amode;

    switch (how) {
        case PR_ACCESS_WRITE_OK:
            amode = W_OK;
            break;
        case PR_ACCESS_READ_OK:
            amode = R_OK;
            break;
        case PR_ACCESS_EXISTS:
            amode = F_OK;
            break;
        default:
            PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
            rv = -1;
            goto done;
    }
    rv = access(name, amode);

    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_ACCESS_ERROR(err);
    }

done:
    return(rv);
}

PRInt32 _MD_mkdir(const char *name, PRIntn mode)
{
    int rv, err;

    /*
    ** This lock is used to enforce rename semantics as described
    ** in PR_Rename. Look there for more fun details.
    */
    if (NULL !=_pr_unix_rename_lock) {
        PR_Lock(_pr_unix_rename_lock);
    }
    rv = mkdir(name, mode);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_MKDIR_ERROR(err);
    }
    if (NULL !=_pr_unix_rename_lock) {
        PR_Unlock(_pr_unix_rename_lock);
    }
    return rv;
}

PRInt32 _MD_rmdir(const char *name)
{
    int rv, err;

    rv = rmdir(name);
    if (rv == -1) {
        err = _MD_ERRNO();
        _PR_MD_MAP_RMDIR_ERROR(err);
    }
    return rv;
}

PRInt32 _MD_read(PRFileDesc *fd, void *buf, PRInt32 amount)
{
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRInt32 rv, err;
#ifndef _PR_USE_POLL
    fd_set rd;
#else
    struct pollfd pfd;
#endif /* _PR_USE_POLL */
    PRInt32 osfd = fd->secret->md.osfd;

#ifndef _PR_USE_POLL
    FD_ZERO(&rd);
    FD_SET(osfd, &rd);
#else
    pfd.fd = osfd;
    pfd.events = POLLIN;
#endif /* _PR_USE_POLL */
    while ((rv = read(osfd,buf,amount)) == -1) {
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ,
                                        PR_INTERVAL_NO_TIMEOUT)) < 0) {
                    goto done;
                }
            } else {
#ifndef _PR_USE_POLL
                while ((rv = _MD_SELECT(osfd + 1, &rd, NULL, NULL, NULL))
                       == -1 && (err = _MD_ERRNO()) == EINTR) {
                    /* retry _MD_SELECT() if it is interrupted */
                }
#else /* _PR_USE_POLL */
                while ((rv = _MD_POLL(&pfd, 1, -1))
                       == -1 && (err = _MD_ERRNO()) == EINTR) {
                    /* retry _MD_POLL() if it is interrupted */
                }
#endif /* _PR_USE_POLL */
                if (rv == -1) {
                    break;
                }
            }
            if (_PR_PENDING_INTERRUPT(me)) {
                break;
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        if (_PR_PENDING_INTERRUPT(me)) {
            me->flags &= ~_PR_INTERRUPT;
            PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        } else {
            _PR_MD_MAP_READ_ERROR(err);
        }
    }
done:
    return(rv);
}

PRInt32 _MD_write(PRFileDesc *fd, const void *buf, PRInt32 amount)
{
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRInt32 rv, err;
#ifndef _PR_USE_POLL
    fd_set wd;
#else
    struct pollfd pfd;
#endif /* _PR_USE_POLL */
    PRInt32 osfd = fd->secret->md.osfd;

#ifndef _PR_USE_POLL
    FD_ZERO(&wd);
    FD_SET(osfd, &wd);
#else
    pfd.fd = osfd;
    pfd.events = POLLOUT;
#endif /* _PR_USE_POLL */
    while ((rv = write(osfd,buf,amount)) == -1) {
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE,
                                        PR_INTERVAL_NO_TIMEOUT)) < 0) {
                    goto done;
                }
            } else {
#ifndef _PR_USE_POLL
                while ((rv = _MD_SELECT(osfd + 1, NULL, &wd, NULL, NULL))
                       == -1 && (err = _MD_ERRNO()) == EINTR) {
                    /* retry _MD_SELECT() if it is interrupted */
                }
#else /* _PR_USE_POLL */
                while ((rv = _MD_POLL(&pfd, 1, -1))
                       == -1 && (err = _MD_ERRNO()) == EINTR) {
                    /* retry _MD_POLL() if it is interrupted */
                }
#endif /* _PR_USE_POLL */
                if (rv == -1) {
                    break;
                }
            }
            if (_PR_PENDING_INTERRUPT(me)) {
                break;
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        if (_PR_PENDING_INTERRUPT(me)) {
            me->flags &= ~_PR_INTERRUPT;
            PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        } else {
            _PR_MD_MAP_WRITE_ERROR(err);
        }
    }
done:
    return(rv);
}

PRInt32 _MD_fsync(PRFileDesc *fd)
{
    PRInt32 rv, err;

    rv = fsync(fd->secret->md.osfd);
    if (rv == -1) {
        err = _MD_ERRNO();
        _PR_MD_MAP_FSYNC_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_close(PRInt32 osfd)
{
    PRInt32 rv, err;

    rv = close(osfd);
    if (rv == -1) {
        err = _MD_ERRNO();
        _PR_MD_MAP_CLOSE_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_socket(PRInt32 domain, PRInt32 type, PRInt32 proto)
{
    PRInt32 osfd, err;

    osfd = socket(domain, type, proto);

    if (osfd == -1) {
        err = _MD_ERRNO();
        _PR_MD_MAP_SOCKET_ERROR(err);
        return(osfd);
    }

    return(osfd);
}

PRInt32 _MD_socketavailable(PRFileDesc *fd)
{
    PRInt32 result;

    if (ioctl(fd->secret->md.osfd, FIONREAD, &result) < 0) {
        _PR_MD_MAP_SOCKETAVAILABLE_ERROR(_MD_ERRNO());
        return -1;
    }
    return result;
}

PRInt64 _MD_socketavailable64(PRFileDesc *fd)
{
    PRInt64 result;
    LL_I2L(result, _MD_socketavailable(fd));
    return result;
}  /* _MD_socketavailable64 */

#define READ_FD        1
#define WRITE_FD    2

/*
 * socket_io_wait --
 *
 * wait for socket i/o, periodically checking for interrupt
 *
 * The first implementation uses select(), for platforms without
 * poll().  The second (preferred) implementation uses poll().
 */

#ifndef _PR_USE_POLL

static PRInt32 socket_io_wait(PRInt32 osfd, PRInt32 fd_type,
                              PRIntervalTime timeout)
{
    PRInt32 rv = -1;
    struct timeval tv;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRIntervalTime epoch, now, elapsed, remaining;
    PRBool wait_for_remaining;
    PRInt32 syserror;
    fd_set rd_wr;

    switch (timeout) {
        case PR_INTERVAL_NO_WAIT:
            PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
            break;
        case PR_INTERVAL_NO_TIMEOUT:
            /*
             * This is a special case of the 'default' case below.
             * Please see the comments there.
             */
            tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
            tv.tv_usec = 0;
            FD_ZERO(&rd_wr);
            do {
                FD_SET(osfd, &rd_wr);
                if (fd_type == READ_FD) {
                    rv = _MD_SELECT(osfd + 1, &rd_wr, NULL, NULL, &tv);
                }
                else {
                    rv = _MD_SELECT(osfd + 1, NULL, &rd_wr, NULL, &tv);
                }
                if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
                    _PR_MD_MAP_SELECT_ERROR(syserror);
                    break;
                }
                if (_PR_PENDING_INTERRUPT(me)) {
                    me->flags &= ~_PR_INTERRUPT;
                    PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
                    rv = -1;
                    break;
                }
            } while (rv == 0 || (rv == -1 && syserror == EINTR));
            break;
        default:
            now = epoch = PR_IntervalNow();
            remaining = timeout;
            FD_ZERO(&rd_wr);
            do {
                /*
                 * We block in _MD_SELECT for at most
                 * _PR_INTERRUPT_CHECK_INTERVAL_SECS seconds,
                 * so that there is an upper limit on the delay
                 * before the interrupt bit is checked.
                 */
                wait_for_remaining = PR_TRUE;
                tv.tv_sec = PR_IntervalToSeconds(remaining);
                if (tv.tv_sec > _PR_INTERRUPT_CHECK_INTERVAL_SECS) {
                    wait_for_remaining = PR_FALSE;
                    tv.tv_sec = _PR_INTERRUPT_CHECK_INTERVAL_SECS;
                    tv.tv_usec = 0;
                } else {
                    tv.tv_usec = PR_IntervalToMicroseconds(
                                     remaining -
                                     PR_SecondsToInterval(tv.tv_sec));
                }
                FD_SET(osfd, &rd_wr);
                if (fd_type == READ_FD) {
                    rv = _MD_SELECT(osfd + 1, &rd_wr, NULL, NULL, &tv);
                }
                else {
                    rv = _MD_SELECT(osfd + 1, NULL, &rd_wr, NULL, &tv);
                }
                /*
                 * we don't consider EINTR a real error
                 */
                if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
                    _PR_MD_MAP_SELECT_ERROR(syserror);
                    break;
                }
                if (_PR_PENDING_INTERRUPT(me)) {
                    me->flags &= ~_PR_INTERRUPT;
                    PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
                    rv = -1;
                    break;
                }
                /*
                 * We loop again if _MD_SELECT timed out or got interrupted
                 * by a signal, and the timeout deadline has not passed yet.
                 */
                if (rv == 0 || (rv == -1 && syserror == EINTR)) {
                    /*
                     * If _MD_SELECT timed out, we know how much time
                     * we spent in blocking, so we can avoid a
                     * PR_IntervalNow() call.
                     */
                    if (rv == 0) {
                        if (wait_for_remaining) {
                            now += remaining;
                        } else {
                            now += PR_SecondsToInterval(tv.tv_sec)
                                   + PR_MicrosecondsToInterval(tv.tv_usec);
                        }
                    } else {
                        now = PR_IntervalNow();
                    }
                    elapsed = (PRIntervalTime) (now - epoch);
                    if (elapsed >= timeout) {
                        PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
                        rv = -1;
                        break;
                    } else {
                        remaining = timeout - elapsed;
                    }
                }
            } while (rv == 0 || (rv == -1 && syserror == EINTR));
            break;
    }
    return(rv);
}

#else /* _PR_USE_POLL */

static PRInt32 socket_io_wait(PRInt32 osfd, PRInt32 fd_type,
                              PRIntervalTime timeout)
{
    PRInt32 rv = -1;
    int msecs;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRIntervalTime epoch, now, elapsed, remaining;
    PRBool wait_for_remaining;
    PRInt32 syserror;
    struct pollfd pfd;

    switch (timeout) {
        case PR_INTERVAL_NO_WAIT:
            PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
            break;
        case PR_INTERVAL_NO_TIMEOUT:
            /*
             * This is a special case of the 'default' case below.
             * Please see the comments there.
             */
            msecs = _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000;
            pfd.fd = osfd;
            if (fd_type == READ_FD) {
                pfd.events = POLLIN;
            } else {
                pfd.events = POLLOUT;
            }
            do {
                rv = _MD_POLL(&pfd, 1, msecs);
                if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
                    _PR_MD_MAP_POLL_ERROR(syserror);
                    break;
                }
                /*
                 * If POLLERR is set, don't process it; retry the operation
                 */
                if ((rv == 1) && (pfd.revents & (POLLHUP | POLLNVAL))) {
                    rv = -1;
                    _PR_MD_MAP_POLL_REVENTS_ERROR(pfd.revents);
                    break;
                }
                if (_PR_PENDING_INTERRUPT(me)) {
                    me->flags &= ~_PR_INTERRUPT;
                    PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
                    rv = -1;
                    break;
                }
            } while (rv == 0 || (rv == -1 && syserror == EINTR));
            break;
        default:
            now = epoch = PR_IntervalNow();
            remaining = timeout;
            pfd.fd = osfd;
            if (fd_type == READ_FD) {
                pfd.events = POLLIN;
            } else {
                pfd.events = POLLOUT;
            }
            do {
                /*
                 * We block in _MD_POLL for at most
                 * _PR_INTERRUPT_CHECK_INTERVAL_SECS seconds,
                 * so that there is an upper limit on the delay
                 * before the interrupt bit is checked.
                 */
                wait_for_remaining = PR_TRUE;
                msecs = PR_IntervalToMilliseconds(remaining);
                if (msecs > _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000) {
                    wait_for_remaining = PR_FALSE;
                    msecs = _PR_INTERRUPT_CHECK_INTERVAL_SECS * 1000;
                }
                rv = _MD_POLL(&pfd, 1, msecs);
                /*
                 * we don't consider EINTR a real error
                 */
                if (rv == -1 && (syserror = _MD_ERRNO()) != EINTR) {
                    _PR_MD_MAP_POLL_ERROR(syserror);
                    break;
                }
                if (_PR_PENDING_INTERRUPT(me)) {
                    me->flags &= ~_PR_INTERRUPT;
                    PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
                    rv = -1;
                    break;
                }
                /*
                 * If POLLERR is set, don't process it; retry the operation
                 */
                if ((rv == 1) && (pfd.revents & (POLLHUP | POLLNVAL))) {
                    rv = -1;
                    _PR_MD_MAP_POLL_REVENTS_ERROR(pfd.revents);
                    break;
                }
                /*
                 * We loop again if _MD_POLL timed out or got interrupted
                 * by a signal, and the timeout deadline has not passed yet.
                 */
                if (rv == 0 || (rv == -1 && syserror == EINTR)) {
                    /*
                     * If _MD_POLL timed out, we know how much time
                     * we spent in blocking, so we can avoid a
                     * PR_IntervalNow() call.
                     */
                    if (rv == 0) {
                        if (wait_for_remaining) {
                            now += remaining;
                        } else {
                            now += PR_MillisecondsToInterval(msecs);
                        }
                    } else {
                        now = PR_IntervalNow();
                    }
                    elapsed = (PRIntervalTime) (now - epoch);
                    if (elapsed >= timeout) {
                        PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
                        rv = -1;
                        break;
                    } else {
                        remaining = timeout - elapsed;
                    }
                }
            } while (rv == 0 || (rv == -1 && syserror == EINTR));
            break;
    }
    return(rv);
}

#endif /* _PR_USE_POLL */

static PRInt32 local_io_wait(
    PRInt32 osfd,
    PRInt32 wait_flag,
    PRIntervalTime timeout)
{
    _PRUnixPollDesc pd;
    PRInt32 rv;

    PR_LOG(_pr_io_lm, PR_LOG_MIN,
           ("waiting to %s on osfd=%d",
            (wait_flag == _PR_UNIX_POLL_READ) ? "read" : "write",
            osfd));

    if (timeout == PR_INTERVAL_NO_WAIT) {
        return 0;
    }

    pd.osfd = osfd;
    pd.in_flags = wait_flag;
    pd.out_flags = 0;

    rv = _PR_WaitForMultipleFDs(&pd, 1, timeout);

    if (rv == 0) {
        PR_SetError(PR_IO_TIMEOUT_ERROR, 0);
        rv = -1;
    }
    return rv;
}


PRInt32 _MD_recv(PRFileDesc *fd, void *buf, PRInt32 amount,
                 PRInt32 flags, PRIntervalTime timeout)
{
    PRInt32 osfd = fd->secret->md.osfd;
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    /*
     * Many OS's (Solaris, Unixware) have a broken recv which won't read
     * from socketpairs.  As long as we don't use flags on socketpairs, this
     * is a decent fix. - mikep
     */
#if defined(UNIXWARE) || defined(SOLARIS)
    while ((rv = read(osfd,buf,amount)) == -1) {
#else
    while ((rv = recv(osfd,buf,amount,flags)) == -1) {
#endif
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd,_PR_UNIX_POLL_READ,timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_RECV_ERROR(err);
    }
done:
    return(rv);
}

PRInt32 _MD_recvfrom(PRFileDesc *fd, void *buf, PRInt32 amount,
                     PRIntn flags, PRNetAddr *addr, PRUint32 *addrlen,
                     PRIntervalTime timeout)
{
    PRInt32 osfd = fd->secret->md.osfd;
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    while ((*addrlen = PR_NETADDR_SIZE(addr)),
           ((rv = recvfrom(osfd, buf, amount, flags,
                           (struct sockaddr *) addr, (_PRSockLen_t *)addrlen)) == -1)) {
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK)) {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ, timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_RECVFROM_ERROR(err);
    }
done:
#ifdef _PR_HAVE_SOCKADDR_LEN
    if (rv != -1) {
        /* ignore the sa_len field of struct sockaddr */
        if (addr) {
            addr->raw.family = ((struct sockaddr *) addr)->sa_family;
        }
    }
#endif /* _PR_HAVE_SOCKADDR_LEN */
    return(rv);
}

PRInt32 _MD_send(PRFileDesc *fd, const void *buf, PRInt32 amount,
                 PRInt32 flags, PRIntervalTime timeout)
{
    PRInt32 osfd = fd->secret->md.osfd;
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();
#if defined(SOLARIS)
    PRInt32 tmp_amount = amount;
#endif

    /*
     * On pre-2.6 Solaris, send() is much slower than write().
     * On 2.6 and beyond, with in-kernel sockets, send() and
     * write() are fairly equivalent in performance.
     */
#if defined(SOLARIS)
    PR_ASSERT(0 == flags);
    while ((rv = write(osfd,buf,tmp_amount)) == -1) {
#else
    while ((rv = send(osfd,buf,amount,flags)) == -1) {
#endif
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK))    {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))< 0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
#if defined(SOLARIS)
            /*
             * The write system call has been reported to return the ERANGE
             * error on occasion. Try to write in smaller chunks to workaround
             * this bug.
             */
            if (err == ERANGE) {
                if (tmp_amount > 1) {
                    tmp_amount = tmp_amount/2;  /* half the bytes */
                    continue;
                }
            }
#endif
            break;
        }
    }
    /*
     * optimization; if bytes sent is less than "amount" call
     * select before returning. This is because it is likely that
     * the next send() call will return EWOULDBLOCK.
     */
    if ((!fd->secret->nonblocking) && (rv > 0) && (rv < amount)
        && (timeout != PR_INTERVAL_NO_WAIT)) {
        if (_PR_IS_NATIVE_THREAD(me)) {
            if (socket_io_wait(osfd, WRITE_FD, timeout)< 0) {
                rv = -1;
                goto done;
            }
        } else {
            if (local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout) < 0) {
                rv = -1;
                goto done;
            }
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_SEND_ERROR(err);
    }
done:
    return(rv);
}

PRInt32 _MD_sendto(
    PRFileDesc *fd, const void *buf, PRInt32 amount, PRIntn flags,
    const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout)
{
    PRInt32 osfd = fd->secret->md.osfd;
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();
#ifdef _PR_HAVE_SOCKADDR_LEN
    PRNetAddr addrCopy;

    addrCopy = *addr;
    ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
    ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;

    while ((rv = sendto(osfd, buf, amount, flags,
                        (struct sockaddr *) &addrCopy, addrlen)) == -1) {
#else
    while ((rv = sendto(osfd, buf, amount, flags,
                        (struct sockaddr *) addr, addrlen)) == -1) {
#endif
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK))    {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))< 0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_SENDTO_ERROR(err);
    }
done:
    return(rv);
}

PRInt32 _MD_writev(
    PRFileDesc *fd, const PRIOVec *iov,
    PRInt32 iov_size, PRIntervalTime timeout)
{
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRInt32 index, amount = 0;
    PRInt32 osfd = fd->secret->md.osfd;

    /*
     * Calculate the total number of bytes to be sent; needed for
     * optimization later.
     * We could avoid this if this number was passed in; but it is
     * probably not a big deal because iov_size is usually small (less than
     * 3)
     */
    if (!fd->secret->nonblocking) {
        for (index=0; index<iov_size; index++) {
            amount += iov[index].iov_len;
        }
    }

    while ((rv = writev(osfd, (const struct iovec*)iov, iov_size)) == -1) {
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK))    {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, WRITE_FD, timeout))<0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    /*
     * optimization; if bytes sent is less than "amount" call
     * select before returning. This is because it is likely that
     * the next writev() call will return EWOULDBLOCK.
     */
    if ((!fd->secret->nonblocking) && (rv > 0) && (rv < amount)
        && (timeout != PR_INTERVAL_NO_WAIT)) {
        if (_PR_IS_NATIVE_THREAD(me)) {
            if (socket_io_wait(osfd, WRITE_FD, timeout) < 0) {
                rv = -1;
                goto done;
            }
        } else {
            if (local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout) < 0) {
                rv = -1;
                goto done;
            }
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_WRITEV_ERROR(err);
    }
done:
    return(rv);
}

PRInt32 _MD_accept(PRFileDesc *fd, PRNetAddr *addr,
                   PRUint32 *addrlen, PRIntervalTime timeout)
{
    PRInt32 osfd = fd->secret->md.osfd;
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    while ((rv = accept(osfd, (struct sockaddr *) addr,
                        (_PRSockLen_t *)addrlen)) == -1) {
        err = _MD_ERRNO();
        if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == ECONNABORTED)) {
            if (fd->secret->nonblocking) {
                break;
            }
            if (!_PR_IS_NATIVE_THREAD(me)) {
                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_READ, timeout)) < 0) {
                    goto done;
                }
            } else {
                if ((rv = socket_io_wait(osfd, READ_FD, timeout)) < 0) {
                    goto done;
                }
            }
        } else if ((err == EINTR) && (!_PR_PENDING_INTERRUPT(me))) {
            continue;
        } else {
            break;
        }
    }
    if (rv < 0) {
        _PR_MD_MAP_ACCEPT_ERROR(err);
    }
done:
#ifdef _PR_HAVE_SOCKADDR_LEN
    if (rv != -1) {
        /* ignore the sa_len field of struct sockaddr */
        if (addr) {
            addr->raw.family = ((struct sockaddr *) addr)->sa_family;
        }
    }
#endif /* _PR_HAVE_SOCKADDR_LEN */
    return(rv);
}

extern int _connect (int s, const struct sockaddr *name, int namelen);
PRInt32 _MD_connect(
    PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen, PRIntervalTime timeout)
{
    PRInt32 rv, err;
    PRThread *me = _PR_MD_CURRENT_THREAD();
    PRInt32 osfd = fd->secret->md.osfd;
#ifdef _PR_HAVE_SOCKADDR_LEN
    PRNetAddr addrCopy;

    addrCopy = *addr;
    ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
    ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;
#endif

    /*
     * We initiate the connection setup by making a nonblocking connect()
     * call.  If the connect() call fails, there are two cases we handle
     * specially:
     * 1. The connect() call was interrupted by a signal.  In this case
     *    we simply retry connect().
     * 2. The NSPR socket is nonblocking and connect() fails with
     *    EINPROGRESS.  We first wait until the socket becomes writable.
     *    Then we try to find out whether the connection setup succeeded
     *    or failed.
     */

retry:
#ifdef _PR_HAVE_SOCKADDR_LEN
    if ((rv = connect(osfd, (struct sockaddr *)&addrCopy, addrlen)) == -1) {
#else
    if ((rv = connect(osfd, (struct sockaddr *)addr, addrlen)) == -1) {
#endif
        err = _MD_ERRNO();

        if (err == EINTR) {
            if (_PR_PENDING_INTERRUPT(me)) {
                me->flags &= ~_PR_INTERRUPT;
                PR_SetError( PR_PENDING_INTERRUPT_ERROR, 0);
                return -1;
            }
            goto retry;
        }

        if (!fd->secret->nonblocking && (err == EINPROGRESS)) {
            if (!_PR_IS_NATIVE_THREAD(me)) {

                if ((rv = local_io_wait(osfd, _PR_UNIX_POLL_WRITE, timeout)) < 0) {
                    return -1;
                }
            } else {
                /*
                 * socket_io_wait() may return -1 or 1.
                 */

                rv = socket_io_wait(osfd, WRITE_FD, timeout);
                if (rv == -1) {
                    return -1;
                }
            }

            PR_ASSERT(rv == 1);
            if (_PR_PENDING_INTERRUPT(me)) {
                me->flags &= ~_PR_INTERRUPT;
                PR_SetError( PR_PENDING_INTERRUPT_ERROR, 0);
                return -1;
            }
            err = _MD_unix_get_nonblocking_connect_error(osfd);
            if (err != 0) {
                _PR_MD_MAP_CONNECT_ERROR(err);
                return -1;
            }
            return 0;
        }

        _PR_MD_MAP_CONNECT_ERROR(err);
    }

    return rv;
}  /* _MD_connect */

PRInt32 _MD_bind(PRFileDesc *fd, const PRNetAddr *addr, PRUint32 addrlen)
{
    PRInt32 rv, err;
#ifdef _PR_HAVE_SOCKADDR_LEN
    PRNetAddr addrCopy;

    addrCopy = *addr;
    ((struct sockaddr *) &addrCopy)->sa_len = addrlen;
    ((struct sockaddr *) &addrCopy)->sa_family = addr->raw.family;
    rv = bind(fd->secret->md.osfd, (struct sockaddr *) &addrCopy, (int )addrlen);
#else
    rv = bind(fd->secret->md.osfd, (struct sockaddr *) addr, (int )addrlen);
#endif
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_BIND_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_listen(PRFileDesc *fd, PRIntn backlog)
{
    PRInt32 rv, err;

    rv = listen(fd->secret->md.osfd, backlog);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_LISTEN_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_shutdown(PRFileDesc *fd, PRIntn how)
{
    PRInt32 rv, err;

    rv = shutdown(fd->secret->md.osfd, how);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_SHUTDOWN_ERROR(err);
    }
    return(rv);
}

PRInt32 _MD_socketpair(int af, int type, int flags,
                       PRInt32 *osfd)
{
    PRInt32 rv, err;

    rv = socketpair(af, type, flags, osfd);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_SOCKETPAIR_ERROR(err);
    }
    return rv;
}

PRStatus _MD_getsockname(PRFileDesc *fd, PRNetAddr *addr,
                         PRUint32 *addrlen)
{
    PRInt32 rv, err;

    rv = getsockname(fd->secret->md.osfd,
                     (struct sockaddr *) addr, (_PRSockLen_t *)addrlen);
#ifdef _PR_HAVE_SOCKADDR_LEN
    if (rv == 0) {
        /* ignore the sa_len field of struct sockaddr */
        if (addr) {
            addr->raw.family = ((struct sockaddr *) addr)->sa_family;
        }
    }
#endif /* _PR_HAVE_SOCKADDR_LEN */
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_GETSOCKNAME_ERROR(err);
    }
    return rv==0?PR_SUCCESS:PR_FAILURE;
}

PRStatus _MD_getpeername(PRFileDesc *fd, PRNetAddr *addr,
                         PRUint32 *addrlen)
{
    PRInt32 rv, err;

    rv = getpeername(fd->secret->md.osfd,
                     (struct sockaddr *) addr, (_PRSockLen_t *)addrlen);
#ifdef _PR_HAVE_SOCKADDR_LEN
    if (rv == 0) {
        /* ignore the sa_len field of struct sockaddr */
        if (addr) {
            addr->raw.family = ((struct sockaddr *) addr)->sa_family;
        }
    }
#endif /* _PR_HAVE_SOCKADDR_LEN */
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_GETPEERNAME_ERROR(err);
    }
    return rv==0?PR_SUCCESS:PR_FAILURE;
}

PRStatus _MD_getsockopt(PRFileDesc *fd, PRInt32 level,
                        PRInt32 optname, char* optval, PRInt32* optlen)
{
    PRInt32 rv, err;

    rv = getsockopt(fd->secret->md.osfd, level, optname, optval, (_PRSockLen_t *)optlen);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_GETSOCKOPT_ERROR(err);
    }
    return rv==0?PR_SUCCESS:PR_FAILURE;
}

PRStatus _MD_setsockopt(PRFileDesc *fd, PRInt32 level,
                        PRInt32 optname, const char* optval, PRInt32 optlen)
{
    PRInt32 rv, err;

    rv = setsockopt(fd->secret->md.osfd, level, optname, optval, optlen);
    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_SETSOCKOPT_ERROR(err);
    }
    return rv==0?PR_SUCCESS:PR_FAILURE;
}

PRStatus _MD_set_fd_inheritable(PRFileDesc *fd, PRBool inheritable)
{
    int rv;

    rv = fcntl(fd->secret->md.osfd, F_SETFD, inheritable ? 0 : FD_CLOEXEC);
    if (-1 == rv) {
        PR_SetError(PR_UNKNOWN_ERROR, _MD_ERRNO());
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

void _MD_init_fd_inheritable(PRFileDesc *fd, PRBool imported)
{
    if (imported) {
        fd->secret->inheritable = _PR_TRI_UNKNOWN;
    } else {
        /* By default, a Unix fd is not closed on exec. */
#ifdef DEBUG
        {
            int flags = fcntl(fd->secret->md.osfd, F_GETFD, 0);
            PR_ASSERT(0 == flags);
        }
#endif
        fd->secret->inheritable = _PR_TRI_TRUE;
    }
}

/************************************************************************/
#if !defined(_PR_USE_POLL)

/*
** Scan through io queue and find any bad fd's that triggered the error
** from _MD_SELECT
*/
static void FindBadFDs(void)
{
    PRCList *q;
    PRThread *me = _MD_CURRENT_THREAD();

    PR_ASSERT(!_PR_IS_NATIVE_THREAD(me));
    q = (_PR_IOQ(me->cpu)).next;
    _PR_IOQ_MAX_OSFD(me->cpu) = -1;
    _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
    while (q != &_PR_IOQ(me->cpu)) {
        PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
        PRBool notify = PR_FALSE;
        _PRUnixPollDesc *pds = pq->pds;
        _PRUnixPollDesc *epds = pds + pq->npds;
        PRInt32 pq_max_osfd = -1;

        q = q->next;
        for (; pds < epds; pds++) {
            PRInt32 osfd = pds->osfd;
            pds->out_flags = 0;
            PR_ASSERT(osfd >= 0 || pds->in_flags == 0);
            if (pds->in_flags == 0) {
                continue;  /* skip this fd */
            }
            if (fcntl(osfd, F_GETFL, 0) == -1) {
                /* Found a bad descriptor, remove it from the fd_sets. */
                PR_LOG(_pr_io_lm, PR_LOG_MAX,
                       ("file descriptor %d is bad", osfd));
                pds->out_flags = _PR_UNIX_POLL_NVAL;
                notify = PR_TRUE;
            }
            if (osfd > pq_max_osfd) {
                pq_max_osfd = osfd;
            }
        }

        if (notify) {
            PRIntn pri;
            PR_REMOVE_LINK(&pq->links);
            pq->on_ioq = PR_FALSE;

            /*
            * Decrement the count of descriptors for each desciptor/event
            * because this I/O request is being removed from the
            * ioq
            */
            pds = pq->pds;
            for (; pds < epds; pds++) {
                PRInt32 osfd = pds->osfd;
                PRInt16 in_flags = pds->in_flags;
                PR_ASSERT(osfd >= 0 || in_flags == 0);
                if (in_flags & _PR_UNIX_POLL_READ) {
                    if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
                    }
                }
                if (in_flags & _PR_UNIX_POLL_WRITE) {
                    if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
                    }
                }
                if (in_flags & _PR_UNIX_POLL_EXCEPT) {
                    if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
                    }
                }
            }

            _PR_THREAD_LOCK(pq->thr);
            if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
                _PRCPU *cpu = pq->thr->cpu;
                _PR_SLEEPQ_LOCK(pq->thr->cpu);
                _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
                _PR_SLEEPQ_UNLOCK(pq->thr->cpu);

                if (pq->thr->flags & _PR_SUSPENDING) {
                    /*
                     * set thread state to SUSPENDED;
                     * a Resume operation on the thread
                     * will move it to the runQ
                     */
                    pq->thr->state = _PR_SUSPENDED;
                    _PR_MISCQ_LOCK(pq->thr->cpu);
                    _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
                    _PR_MISCQ_UNLOCK(pq->thr->cpu);
                } else {
                    pri = pq->thr->priority;
                    pq->thr->state = _PR_RUNNABLE;

                    _PR_RUNQ_LOCK(cpu);
                    _PR_ADD_RUNQ(pq->thr, cpu, pri);
                    _PR_RUNQ_UNLOCK(cpu);
                }
            }
            _PR_THREAD_UNLOCK(pq->thr);
        } else {
            if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu)) {
                _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
            }
            if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd) {
                _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
            }
        }
    }
    if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
        if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0]) {
            _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
        }
    }
}
#endif  /* !defined(_PR_USE_POLL) */

/************************************************************************/

/*
** Called by the scheduler when there is nothing to do. This means that
** all threads are blocked on some monitor somewhere.
**
** Note: this code doesn't release the scheduler lock.
*/
/*
** Pause the current CPU. longjmp to the cpu's pause stack
**
** This must be called with the scheduler locked
*/
void _MD_PauseCPU(PRIntervalTime ticks)
{
    PRThread *me = _MD_CURRENT_THREAD();
#ifdef _PR_USE_POLL
    int timeout;
    struct pollfd *pollfds;    /* an array of pollfd structures */
    struct pollfd *pollfdPtr;    /* a pointer that steps through the array */
    unsigned long npollfds;     /* number of pollfd structures in array */
    unsigned long pollfds_size;
    int nfd;                    /* to hold the return value of poll() */
#else
    struct timeval timeout, *tvp;
    fd_set r, w, e;
    fd_set *rp, *wp, *ep;
    PRInt32 max_osfd, nfd;
#endif  /* _PR_USE_POLL */
    PRInt32 rv;
    PRCList *q;
    PRUint32 min_timeout;
    sigset_t oldset;

    PR_ASSERT(_PR_MD_GET_INTSOFF() != 0);

    _PR_MD_IOQ_LOCK();

#ifdef _PR_USE_POLL
    /* Build up the pollfd structure array to wait on */

    /* Find out how many pollfd structures are needed */
    npollfds = _PR_IOQ_OSFD_CNT(me->cpu);
    PR_ASSERT(npollfds >= 0);

    /*
     * We use a pipe to wake up a native thread.  An fd is needed
     * for the pipe and we poll it for reading.
     */
    if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
        npollfds++;
    }

    /*
     * if the cpu's pollfd array is not big enough, release it and allocate a new one
     */
    if (npollfds > _PR_IOQ_POLLFDS_SIZE(me->cpu)) {
        if (_PR_IOQ_POLLFDS(me->cpu) != NULL) {
            PR_DELETE(_PR_IOQ_POLLFDS(me->cpu));
        }
        pollfds_size =  PR_MAX(_PR_IOQ_MIN_POLLFDS_SIZE(me->cpu), npollfds);
        pollfds = (struct pollfd *) PR_MALLOC(pollfds_size * sizeof(struct pollfd));
        _PR_IOQ_POLLFDS(me->cpu) = pollfds;
        _PR_IOQ_POLLFDS_SIZE(me->cpu) = pollfds_size;
    } else {
        pollfds = _PR_IOQ_POLLFDS(me->cpu);
    }
    pollfdPtr = pollfds;

    /*
     * If we need to poll the pipe for waking up a native thread,
     * the pipe's fd is the first element in the pollfds array.
     */
    if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
        pollfdPtr->fd = _pr_md_pipefd[0];
        pollfdPtr->events = POLLIN;
        pollfdPtr++;
    }

    min_timeout = PR_INTERVAL_NO_TIMEOUT;
    for (q = _PR_IOQ(me->cpu).next; q != &_PR_IOQ(me->cpu); q = q->next) {
        PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
        _PRUnixPollDesc *pds = pq->pds;
        _PRUnixPollDesc *epds = pds + pq->npds;

        if (pq->timeout < min_timeout) {
            min_timeout = pq->timeout;
        }
        for (; pds < epds; pds++, pollfdPtr++) {
            /*
            * Assert that the pollfdPtr pointer does not go
            * beyond the end of the pollfds array
            */
            PR_ASSERT(pollfdPtr < pollfds + npollfds);
            pollfdPtr->fd = pds->osfd;
            /* direct copy of poll flags */
            pollfdPtr->events = pds->in_flags;
        }
    }
    _PR_IOQ_TIMEOUT(me->cpu) = min_timeout;
#else
    /*
     * assigment of fd_sets
     */
    r = _PR_FD_READ_SET(me->cpu);
    w = _PR_FD_WRITE_SET(me->cpu);
    e = _PR_FD_EXCEPTION_SET(me->cpu);

    rp = &r;
    wp = &w;
    ep = &e;

    max_osfd = _PR_IOQ_MAX_OSFD(me->cpu) + 1;
    min_timeout = _PR_IOQ_TIMEOUT(me->cpu);
#endif  /* _PR_USE_POLL */
    /*
    ** Compute the minimum timeout value: make it the smaller of the
    ** timeouts specified by the i/o pollers or the timeout of the first
    ** sleeping thread.
    */
    q = _PR_SLEEPQ(me->cpu).next;

    if (q != &_PR_SLEEPQ(me->cpu)) {
        PRThread *t = _PR_THREAD_PTR(q);

        if (t->sleep < min_timeout) {
            min_timeout = t->sleep;
        }
    }
    if (min_timeout > ticks) {
        min_timeout = ticks;
    }

#ifdef _PR_USE_POLL
    if (min_timeout == PR_INTERVAL_NO_TIMEOUT) {
        timeout = -1;
    }
    else {
        timeout = PR_IntervalToMilliseconds(min_timeout);
    }
#else
    if (min_timeout == PR_INTERVAL_NO_TIMEOUT) {
        tvp = NULL;
    } else {
        timeout.tv_sec = PR_IntervalToSeconds(min_timeout);
        timeout.tv_usec = PR_IntervalToMicroseconds(min_timeout)
                          % PR_USEC_PER_SEC;
        tvp = &timeout;
    }
#endif  /* _PR_USE_POLL */

    _PR_MD_IOQ_UNLOCK();
    _MD_CHECK_FOR_EXIT();
    /*
     * check for i/o operations
     */
#ifndef _PR_NO_CLOCK_TIMER
    /*
     * Disable the clock interrupts while we are in select, if clock interrupts
     * are enabled. Otherwise, when the select/poll calls are interrupted, the
     * timer value starts ticking from zero again when the system call is restarted.
     */
    if (!_nspr_noclock) {
        PR_ASSERT(sigismember(&timer_set, SIGALRM));
    }
    sigprocmask(SIG_BLOCK, &timer_set, &oldset);
#endif  /* !_PR_NO_CLOCK_TIMER */

#ifndef _PR_USE_POLL
    PR_ASSERT(FD_ISSET(_pr_md_pipefd[0],rp));
    nfd = _MD_SELECT(max_osfd, rp, wp, ep, tvp);
#else
    nfd = _MD_POLL(pollfds, npollfds, timeout);
#endif  /* !_PR_USE_POLL */

#ifndef _PR_NO_CLOCK_TIMER
    if (!_nspr_noclock) {
        sigprocmask(SIG_SETMASK, &oldset, 0);
    }
#endif  /* !_PR_NO_CLOCK_TIMER */

    _MD_CHECK_FOR_EXIT();

    _PR_MD_primordial_cpu();

    _PR_MD_IOQ_LOCK();
    /*
    ** Notify monitors that are associated with the selected descriptors.
    */
#ifdef _PR_USE_POLL
    if (nfd > 0) {
        pollfdPtr = pollfds;
        if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
            /*
             * Assert that the pipe is the first element in the
             * pollfds array.
             */
            PR_ASSERT(pollfds[0].fd == _pr_md_pipefd[0]);
            if ((pollfds[0].revents & POLLIN) && (nfd == 1)) {
                /*
                 * woken up by another thread; read all the data
                 * in the pipe to empty the pipe
                 */
                while ((rv = read(_pr_md_pipefd[0], _pr_md_pipebuf,
                                  PIPE_BUF)) == PIPE_BUF) {
                }
                PR_ASSERT((rv > 0) || ((rv == -1) && (errno == EAGAIN)));
            }
            pollfdPtr++;
        }
        for (q = _PR_IOQ(me->cpu).next; q != &_PR_IOQ(me->cpu); q = q->next) {
            PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
            PRBool notify = PR_FALSE;
            _PRUnixPollDesc *pds = pq->pds;
            _PRUnixPollDesc *epds = pds + pq->npds;

            for (; pds < epds; pds++, pollfdPtr++) {
                /*
                  * Assert that the pollfdPtr pointer does not go beyond
                  * the end of the pollfds array.
                  */
                PR_ASSERT(pollfdPtr < pollfds + npollfds);
                /*
                 * Assert that the fd's in the pollfds array (stepped
                 * through by pollfdPtr) are in the same order as
                 * the fd's in _PR_IOQ() (stepped through by q and pds).
                 * This is how the pollfds array was created earlier.
                 */
                PR_ASSERT(pollfdPtr->fd == pds->osfd);
                pds->out_flags = pollfdPtr->revents;
                /* Negative fd's are ignored by poll() */
                if (pds->osfd >= 0 && pds->out_flags) {
                    notify = PR_TRUE;
                }
            }
            if (notify) {
                PRIntn pri;
                PRThread *thred;

                PR_REMOVE_LINK(&pq->links);
                pq->on_ioq = PR_FALSE;

                thred = pq->thr;
                _PR_THREAD_LOCK(thred);
                if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
                    _PRCPU *cpu = pq->thr->cpu;
                    _PR_SLEEPQ_LOCK(pq->thr->cpu);
                    _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
                    _PR_SLEEPQ_UNLOCK(pq->thr->cpu);

                    if (pq->thr->flags & _PR_SUSPENDING) {
                        /*
                         * set thread state to SUSPENDED;
                         * a Resume operation on the thread
                         * will move it to the runQ
                         */
                        pq->thr->state = _PR_SUSPENDED;
                        _PR_MISCQ_LOCK(pq->thr->cpu);
                        _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
                        _PR_MISCQ_UNLOCK(pq->thr->cpu);
                    } else {
                        pri = pq->thr->priority;
                        pq->thr->state = _PR_RUNNABLE;

                        _PR_RUNQ_LOCK(cpu);
                        _PR_ADD_RUNQ(pq->thr, cpu, pri);
                        _PR_RUNQ_UNLOCK(cpu);
                        if (_pr_md_idle_cpus > 1) {
                            _PR_MD_WAKEUP_WAITER(thred);
                        }
                    }
                }
                _PR_THREAD_UNLOCK(thred);
                _PR_IOQ_OSFD_CNT(me->cpu) -= pq->npds;
                PR_ASSERT(_PR_IOQ_OSFD_CNT(me->cpu) >= 0);
            }
        }
    } else if (nfd == -1) {
        PR_LOG(_pr_io_lm, PR_LOG_MAX, ("poll() failed with errno %d", errno));
    }

#else
    if (nfd > 0) {
        q = _PR_IOQ(me->cpu).next;
        _PR_IOQ_MAX_OSFD(me->cpu) = -1;
        _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
        while (q != &_PR_IOQ(me->cpu)) {
            PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
            PRBool notify = PR_FALSE;
            _PRUnixPollDesc *pds = pq->pds;
            _PRUnixPollDesc *epds = pds + pq->npds;
            PRInt32 pq_max_osfd = -1;

            q = q->next;
            for (; pds < epds; pds++) {
                PRInt32 osfd = pds->osfd;
                PRInt16 in_flags = pds->in_flags;
                PRInt16 out_flags = 0;
                PR_ASSERT(osfd >= 0 || in_flags == 0);
                if ((in_flags & _PR_UNIX_POLL_READ) && FD_ISSET(osfd, rp)) {
                    out_flags |= _PR_UNIX_POLL_READ;
                }
                if ((in_flags & _PR_UNIX_POLL_WRITE) && FD_ISSET(osfd, wp)) {
                    out_flags |= _PR_UNIX_POLL_WRITE;
                }
                if ((in_flags & _PR_UNIX_POLL_EXCEPT) && FD_ISSET(osfd, ep)) {
                    out_flags |= _PR_UNIX_POLL_EXCEPT;
                }
                pds->out_flags = out_flags;
                if (out_flags) {
                    notify = PR_TRUE;
                }
                if (osfd > pq_max_osfd) {
                    pq_max_osfd = osfd;
                }
            }
            if (notify == PR_TRUE) {
                PRIntn pri;
                PRThread *thred;

                PR_REMOVE_LINK(&pq->links);
                pq->on_ioq = PR_FALSE;

                /*
                 * Decrement the count of descriptors for each desciptor/event
                 * because this I/O request is being removed from the
                 * ioq
                 */
                pds = pq->pds;
                for (; pds < epds; pds++) {
                    PRInt32 osfd = pds->osfd;
                    PRInt16 in_flags = pds->in_flags;
                    PR_ASSERT(osfd >= 0 || in_flags == 0);
                    if (in_flags & _PR_UNIX_POLL_READ) {
                        if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0) {
                            FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
                        }
                    }
                    if (in_flags & _PR_UNIX_POLL_WRITE) {
                        if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0) {
                            FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
                        }
                    }
                    if (in_flags & _PR_UNIX_POLL_EXCEPT) {
                        if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0) {
                            FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
                        }
                    }
                }

                /*
                 * Because this thread can run on a different cpu right
                 * after being added to the run queue, do not dereference
                 * pq
                 */
                thred = pq->thr;
                _PR_THREAD_LOCK(thred);
                if (pq->thr->flags & (_PR_ON_PAUSEQ|_PR_ON_SLEEPQ)) {
                    _PRCPU *cpu = thred->cpu;
                    _PR_SLEEPQ_LOCK(pq->thr->cpu);
                    _PR_DEL_SLEEPQ(pq->thr, PR_TRUE);
                    _PR_SLEEPQ_UNLOCK(pq->thr->cpu);

                    if (pq->thr->flags & _PR_SUSPENDING) {
                        /*
                         * set thread state to SUSPENDED;
                         * a Resume operation on the thread
                         * will move it to the runQ
                         */
                        pq->thr->state = _PR_SUSPENDED;
                        _PR_MISCQ_LOCK(pq->thr->cpu);
                        _PR_ADD_SUSPENDQ(pq->thr, pq->thr->cpu);
                        _PR_MISCQ_UNLOCK(pq->thr->cpu);
                    } else {
                        pri = pq->thr->priority;
                        pq->thr->state = _PR_RUNNABLE;

                        pq->thr->cpu = cpu;
                        _PR_RUNQ_LOCK(cpu);
                        _PR_ADD_RUNQ(pq->thr, cpu, pri);
                        _PR_RUNQ_UNLOCK(cpu);
                        if (_pr_md_idle_cpus > 1) {
                            _PR_MD_WAKEUP_WAITER(thred);
                        }
                    }
                }
                _PR_THREAD_UNLOCK(thred);
            } else {
                if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu)) {
                    _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
                }
                if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd) {
                    _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
                }
            }
        }
        if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
            if ((FD_ISSET(_pr_md_pipefd[0], rp)) && (nfd == 1)) {
                /*
                * woken up by another thread; read all the data
                * in the pipe to empty the pipe
                */
                while ((rv =
                            read(_pr_md_pipefd[0], _pr_md_pipebuf, PIPE_BUF))
                       == PIPE_BUF) {
                }
                PR_ASSERT((rv > 0) ||
                          ((rv == -1) && (errno == EAGAIN)));
            }
            if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0]) {
                _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
            }
        }
    } else if (nfd < 0) {
        if (errno == EBADF) {
            FindBadFDs();
        } else {
            PR_LOG(_pr_io_lm, PR_LOG_MAX, ("select() failed with errno %d",
                                           errno));
        }
    } else {
        PR_ASSERT(nfd == 0);
        /*
         * compute the new value of _PR_IOQ_TIMEOUT
         */
        q = _PR_IOQ(me->cpu).next;
        _PR_IOQ_MAX_OSFD(me->cpu) = -1;
        _PR_IOQ_TIMEOUT(me->cpu) = PR_INTERVAL_NO_TIMEOUT;
        while (q != &_PR_IOQ(me->cpu)) {
            PRPollQueue *pq = _PR_POLLQUEUE_PTR(q);
            _PRUnixPollDesc *pds = pq->pds;
            _PRUnixPollDesc *epds = pds + pq->npds;
            PRInt32 pq_max_osfd = -1;

            q = q->next;
            for (; pds < epds; pds++) {
                if (pds->osfd > pq_max_osfd) {
                    pq_max_osfd = pds->osfd;
                }
            }
            if (pq->timeout < _PR_IOQ_TIMEOUT(me->cpu)) {
                _PR_IOQ_TIMEOUT(me->cpu) = pq->timeout;
            }
            if (_PR_IOQ_MAX_OSFD(me->cpu) < pq_max_osfd) {
                _PR_IOQ_MAX_OSFD(me->cpu) = pq_max_osfd;
            }
        }
        if (_PR_IS_NATIVE_THREAD_SUPPORTED()) {
            if (_PR_IOQ_MAX_OSFD(me->cpu) < _pr_md_pipefd[0]) {
                _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
            }
        }
    }
#endif  /* _PR_USE_POLL */
    _PR_MD_IOQ_UNLOCK();
}

void _MD_Wakeup_CPUs()
{
    PRInt32 rv, data;

    data = 0;
    rv = write(_pr_md_pipefd[1], &data, 1);

    while ((rv < 0) && (errno == EAGAIN)) {
        /*
         * pipe full, read all data in pipe to empty it
         */
        while ((rv =
                    read(_pr_md_pipefd[0], _pr_md_pipebuf, PIPE_BUF))
               == PIPE_BUF) {
        }
        PR_ASSERT((rv > 0) ||
                  ((rv == -1) && (errno == EAGAIN)));
        rv = write(_pr_md_pipefd[1], &data, 1);
    }
}


void _MD_InitCPUS()
{
    PRInt32 rv, flags;
    PRThread *me = _MD_CURRENT_THREAD();

    rv = pipe(_pr_md_pipefd);
    PR_ASSERT(rv == 0);
    _PR_IOQ_MAX_OSFD(me->cpu) = _pr_md_pipefd[0];
#ifndef _PR_USE_POLL
    FD_SET(_pr_md_pipefd[0], &_PR_FD_READ_SET(me->cpu));
#endif

    flags = fcntl(_pr_md_pipefd[0], F_GETFL, 0);
    fcntl(_pr_md_pipefd[0], F_SETFL, flags | O_NONBLOCK);
    flags = fcntl(_pr_md_pipefd[1], F_GETFL, 0);
    fcntl(_pr_md_pipefd[1], F_SETFL, flags | O_NONBLOCK);
}

/*
** Unix SIGALRM (clock) signal handler
*/
static void ClockInterruptHandler()
{
    int olderrno;
    PRUintn pri;
    _PRCPU *cpu = _PR_MD_CURRENT_CPU();
    PRThread *me = _MD_CURRENT_THREAD();

#ifdef SOLARIS
    if (!me || _PR_IS_NATIVE_THREAD(me)) {
        _pr_primordialCPU->u.missed[_pr_primordialCPU->where] |= _PR_MISSED_CLOCK;
        return;
    }
#endif

    if (_PR_MD_GET_INTSOFF() != 0) {
        cpu->u.missed[cpu->where] |= _PR_MISSED_CLOCK;
        return;
    }
    _PR_MD_SET_INTSOFF(1);

    olderrno = errno;
    _PR_ClockInterrupt();
    errno = olderrno;

    /*
    ** If the interrupt wants a resched or if some other thread at
    ** the same priority needs the cpu, reschedule.
    */
    pri = me->priority;
    if ((cpu->u.missed[3] || (_PR_RUNQREADYMASK(me->cpu) >> pri))) {
#ifdef _PR_NO_PREEMPT
        cpu->resched = PR_TRUE;
        if (pr_interruptSwitchHook) {
            (*pr_interruptSwitchHook)(pr_interruptSwitchHookArg);
        }
#else /* _PR_NO_PREEMPT */
        /*
        ** Re-enable unix interrupts (so that we can use
        ** setjmp/longjmp for context switching without having to
        ** worry about the signal state)
        */
        sigprocmask(SIG_SETMASK, &empty_set, 0);
        PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("clock caused context switch"));

        if(!(me->flags & _PR_IDLE_THREAD)) {
            _PR_THREAD_LOCK(me);
            me->state = _PR_RUNNABLE;
            me->cpu = cpu;
            _PR_RUNQ_LOCK(cpu);
            _PR_ADD_RUNQ(me, cpu, pri);
            _PR_RUNQ_UNLOCK(cpu);
            _PR_THREAD_UNLOCK(me);
        } else {
            me->state = _PR_RUNNABLE;
        }
        _MD_SWITCH_CONTEXT(me);
        PR_LOG(_pr_sched_lm, PR_LOG_MIN, ("clock back from context switch"));
#endif /* _PR_NO_PREEMPT */
    }
    /*
     * Because this thread could be running on a different cpu after
     * a context switch the current cpu should be accessed and the
     * value of the 'cpu' variable should not be used.
     */
    _PR_MD_SET_INTSOFF(0);
}

/*
 * On HP-UX 9, we have to use the sigvector() interface to restart
 * interrupted system calls, because sigaction() does not have the
 * SA_RESTART flag.
 */

#ifdef HPUX9
static void HPUX9_ClockInterruptHandler(
    int sig,
    int code,
    struct sigcontext *scp)
{
    ClockInterruptHandler();
    scp->sc_syscall_action = SIG_RESTART;
}
#endif /* HPUX9 */

/* # of milliseconds per clock tick that we will use */
#define MSEC_PER_TICK    50


void _MD_StartInterrupts()
{
    char *eval;

    if ((eval = getenv("NSPR_NOCLOCK")) != NULL) {
        if (atoi(eval) == 0) {
            _nspr_noclock = 0;
        }
        else {
            _nspr_noclock = 1;
        }
    }

#ifndef _PR_NO_CLOCK_TIMER
    if (!_nspr_noclock) {
        _MD_EnableClockInterrupts();
    }
#endif
}

void _MD_StopInterrupts()
{
    sigprocmask(SIG_BLOCK, &timer_set, 0);
}

void _MD_EnableClockInterrupts()
{
    struct itimerval itval;
    extern PRUintn _pr_numCPU;
#ifdef HPUX9
    struct sigvec vec;

    vec.sv_handler = (void (*)()) HPUX9_ClockInterruptHandler;
    vec.sv_mask = 0;
    vec.sv_flags = 0;
    sigvector(SIGALRM, &vec, 0);
#else
    struct sigaction vtact;

    vtact.sa_handler = (void (*)()) ClockInterruptHandler;
    sigemptyset(&vtact.sa_mask);
    vtact.sa_flags = SA_RESTART;
    sigaction(SIGALRM, &vtact, 0);
#endif /* HPUX9 */

    PR_ASSERT(_pr_numCPU == 1);
    itval.it_interval.tv_sec = 0;
    itval.it_interval.tv_usec = MSEC_PER_TICK * PR_USEC_PER_MSEC;
    itval.it_value = itval.it_interval;
    setitimer(ITIMER_REAL, &itval, 0);
}

void _MD_DisableClockInterrupts()
{
    struct itimerval itval;
    extern PRUintn _pr_numCPU;

    PR_ASSERT(_pr_numCPU == 1);
    itval.it_interval.tv_sec = 0;
    itval.it_interval.tv_usec = 0;
    itval.it_value = itval.it_interval;
    setitimer(ITIMER_REAL, &itval, 0);
}

void _MD_BlockClockInterrupts()
{
    sigprocmask(SIG_BLOCK, &timer_set, 0);
}

void _MD_UnblockClockInterrupts()
{
    sigprocmask(SIG_UNBLOCK, &timer_set, 0);
}

void _MD_MakeNonblock(PRFileDesc *fd)
{
    PRInt32 osfd = fd->secret->md.osfd;
    int flags;

    if (osfd <= 2) {
        /* Don't mess around with stdin, stdout or stderr */
        return;
    }
    flags = fcntl(osfd, F_GETFL, 0);

    /*
     * Use O_NONBLOCK (POSIX-style non-blocking I/O) whenever possible.
     * On SunOS 4, we must use FNDELAY (BSD-style non-blocking I/O),
     * otherwise connect() still blocks and can be interrupted by SIGALRM.
     */

    fcntl(osfd, F_SETFL, flags | O_NONBLOCK);
}

PRInt32 _MD_open(const char *name, PRIntn flags, PRIntn mode)
{
    PRInt32 osflags;
    PRInt32 rv, err;

    if (flags & PR_RDWR) {
        osflags = O_RDWR;
    } else if (flags & PR_WRONLY) {
        osflags = O_WRONLY;
    } else {
        osflags = O_RDONLY;
    }

    if (flags & PR_EXCL) {
        osflags |= O_EXCL;
    }
    if (flags & PR_APPEND) {
        osflags |= O_APPEND;
    }
    if (flags & PR_TRUNCATE) {
        osflags |= O_TRUNC;
    }
    if (flags & PR_SYNC) {
#if defined(O_SYNC)
        osflags |= O_SYNC;
#elif defined(O_FSYNC)
        osflags |= O_FSYNC;
#else
#error "Neither O_SYNC nor O_FSYNC is defined on this platform"
#endif
    }

    /*
    ** On creations we hold the 'create' lock in order to enforce
    ** the semantics of PR_Rename. (see the latter for more details)
    */
    if (flags & PR_CREATE_FILE)
    {
        osflags |= O_CREAT;
        if (NULL !=_pr_unix_rename_lock) {
            PR_Lock(_pr_unix_rename_lock);
        }
    }

#if defined(ANDROID)
    osflags |= O_LARGEFILE;
#endif

    rv = _md_iovector._open64(name, osflags, mode);

    if (rv < 0) {
        err = _MD_ERRNO();
        _PR_MD_MAP_OPEN_ERROR(err);
    }

    if ((flags & PR_CREATE_FILE) && (NULL !=_pr_unix_rename_lock)) {
        PR_Unlock(_pr_unix_rename_lock);
    }
    return rv;
}

PRIntervalTime intr_timeout_ticks;

#if defined(SOLARIS)
static void sigsegvhandler() {
    fprintf(stderr,"Received SIGSEGV\n");
    fflush(stderr);
    pause();
}

static void sigaborthandler() {
    fprintf(stderr,"Received SIGABRT\n");
    fflush(stderr);
    pause();
}

static void sigbushandler() {
    fprintf(stderr,"Received SIGBUS\n");
    fflush(stderr);
    pause();
}
#endif /* SOLARIS */

#endif  /* !defined(_PR_PTHREADS) */

void _MD_query_fd_inheritable(PRFileDesc *fd)
{
    int flags;

    PR_ASSERT(_PR_TRI_UNKNOWN == fd->secret->inheritable);
    flags = fcntl(fd->secret->md.osfd, F_GETFD, 0);
    PR_ASSERT(-1 != flags);
    fd->secret->inheritable = (flags & FD_CLOEXEC) ?
                              _PR_TRI_FALSE : _PR_TRI_TRUE;
}

PROffset32 _MD_lseek(PRFileDesc *fd, PROffset32 offset, PRSeekWhence whence)
{
    PROffset32 rv, where;

    switch (whence) {
        case PR_SEEK_SET:
            where = SEEK_SET;
            break;
        case PR_SEEK_CUR:
            where = SEEK_CUR;
            break;
        case PR_SEEK_END:
            where = SEEK_END;
            break;
        default:
            PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
            rv = -1;
            goto done;
    }
    rv = lseek(fd->secret->md.osfd,offset,where);
    if (rv == -1)
    {
        PRInt32 syserr = _MD_ERRNO();
        _PR_MD_MAP_LSEEK_ERROR(syserr);
    }
done:
    return(rv);
}

PROffset64 _MD_lseek64(PRFileDesc *fd, PROffset64 offset, PRSeekWhence whence)
{
    PRInt32 where;
    PROffset64 rv;

    switch (whence)
    {
        case PR_SEEK_SET:
            where = SEEK_SET;
            break;
        case PR_SEEK_CUR:
            where = SEEK_CUR;
            break;
        case PR_SEEK_END:
            where = SEEK_END;
            break;
        default:
            PR_SetError(PR_INVALID_ARGUMENT_ERROR, 0);
            rv = minus_one;
            goto done;
    }
    rv = _md_iovector._lseek64(fd->secret->md.osfd, offset, where);
    if (LL_EQ(rv, minus_one))
    {
        PRInt32 syserr = _MD_ERRNO();
        _PR_MD_MAP_LSEEK_ERROR(syserr);
    }
done:
    return rv;
}  /* _MD_lseek64 */

/*
** _MD_set_fileinfo_times --
**     Set the modifyTime and creationTime of the PRFileInfo
**     structure using the values in struct stat.
**
** _MD_set_fileinfo64_times --
**     Set the modifyTime and creationTime of the PRFileInfo64
**     structure using the values in _MDStat64.
*/

#if defined(_PR_STAT_HAS_ST_ATIM)
/*
** struct stat has st_atim, st_mtim, and st_ctim fields of
** type timestruc_t.
*/
static void _MD_set_fileinfo_times(
    const struct stat *sb,
    PRFileInfo *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtim.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtim.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctim.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctim.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}

static void _MD_set_fileinfo64_times(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtim.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtim.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctim.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctim.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}
#elif defined(_PR_STAT_HAS_ST_ATIM_UNION)
/*
** The st_atim, st_mtim, and st_ctim fields in struct stat are
** unions with a st__tim union member of type timestruc_t.
*/
static void _MD_set_fileinfo_times(
    const struct stat *sb,
    PRFileInfo *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtim.st__tim.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtim.st__tim.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctim.st__tim.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctim.st__tim.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}

static void _MD_set_fileinfo64_times(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtim.st__tim.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtim.st__tim.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctim.st__tim.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctim.st__tim.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}
#elif defined(_PR_STAT_HAS_ST_ATIMESPEC)
/*
** struct stat has st_atimespec, st_mtimespec, and st_ctimespec
** fields of type struct timespec.
*/
#if defined(_PR_TIMESPEC_HAS_TS_SEC)
static void _MD_set_fileinfo_times(
    const struct stat *sb,
    PRFileInfo *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtimespec.ts_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtimespec.ts_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctimespec.ts_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctimespec.ts_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}

static void _MD_set_fileinfo64_times(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtimespec.ts_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtimespec.ts_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctimespec.ts_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctimespec.ts_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}
#else /* _PR_TIMESPEC_HAS_TS_SEC */
/*
** The POSIX timespec structure has tv_sec and tv_nsec.
*/
static void _MD_set_fileinfo_times(
    const struct stat *sb,
    PRFileInfo *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtimespec.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtimespec.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctimespec.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctimespec.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}

static void _MD_set_fileinfo64_times(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    PRInt64 us, s2us;

    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(info->modifyTime, sb->st_mtimespec.tv_sec);
    LL_MUL(info->modifyTime, info->modifyTime, s2us);
    LL_I2L(us, sb->st_mtimespec.tv_nsec / 1000);
    LL_ADD(info->modifyTime, info->modifyTime, us);
    LL_I2L(info->creationTime, sb->st_ctimespec.tv_sec);
    LL_MUL(info->creationTime, info->creationTime, s2us);
    LL_I2L(us, sb->st_ctimespec.tv_nsec / 1000);
    LL_ADD(info->creationTime, info->creationTime, us);
}
#endif /* _PR_TIMESPEC_HAS_TS_SEC */
#elif defined(_PR_STAT_HAS_ONLY_ST_ATIME)
/*
** struct stat only has st_atime, st_mtime, and st_ctime fields
** of type time_t.
*/
static void _MD_set_fileinfo_times(
    const struct stat *sb,
    PRFileInfo *info)
{
    PRInt64 s, s2us;
    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(s, sb->st_mtime);
    LL_MUL(s, s, s2us);
    info->modifyTime = s;
    LL_I2L(s, sb->st_ctime);
    LL_MUL(s, s, s2us);
    info->creationTime = s;
}

static void _MD_set_fileinfo64_times(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    PRInt64 s, s2us;
    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(s, sb->st_mtime);
    LL_MUL(s, s, s2us);
    info->modifyTime = s;
    LL_I2L(s, sb->st_ctime);
    LL_MUL(s, s, s2us);
    info->creationTime = s;
}
#else
#error "I don't know yet"
#endif

static int _MD_convert_stat_to_fileinfo(
    const struct stat *sb,
    PRFileInfo *info)
{
    if (S_IFREG & sb->st_mode) {
        info->type = PR_FILE_FILE;
    }
    else if (S_IFDIR & sb->st_mode) {
        info->type = PR_FILE_DIRECTORY;
    }
    else {
        info->type = PR_FILE_OTHER;
    }

#if defined(_PR_HAVE_LARGE_OFF_T)
    if (0x7fffffffL < sb->st_size)
    {
        PR_SetError(PR_FILE_TOO_BIG_ERROR, 0);
        return -1;
    }
#endif /* defined(_PR_HAVE_LARGE_OFF_T) */
    info->size = sb->st_size;

    _MD_set_fileinfo_times(sb, info);
    return 0;
}  /* _MD_convert_stat_to_fileinfo */

static int _MD_convert_stat64_to_fileinfo64(
    const _MDStat64 *sb,
    PRFileInfo64 *info)
{
    if (S_IFREG & sb->st_mode) {
        info->type = PR_FILE_FILE;
    }
    else if (S_IFDIR & sb->st_mode) {
        info->type = PR_FILE_DIRECTORY;
    }
    else {
        info->type = PR_FILE_OTHER;
    }

    LL_I2L(info->size, sb->st_size);

    _MD_set_fileinfo64_times(sb, info);
    return 0;
}  /* _MD_convert_stat64_to_fileinfo64 */

PRInt32 _MD_getfileinfo(const char *fn, PRFileInfo *info)
{
    PRInt32 rv;
    struct stat sb;

    rv = stat(fn, &sb);
    if (rv < 0) {
        _PR_MD_MAP_STAT_ERROR(_MD_ERRNO());
    }
    else if (NULL != info) {
        rv = _MD_convert_stat_to_fileinfo(&sb, info);
    }
    return rv;
}

PRInt32 _MD_getfileinfo64(const char *fn, PRFileInfo64 *info)
{
    _MDStat64 sb;
    PRInt32 rv = _md_iovector._stat64(fn, &sb);
    if (rv < 0) {
        _PR_MD_MAP_STAT_ERROR(_MD_ERRNO());
    }
    else if (NULL != info) {
        rv = _MD_convert_stat64_to_fileinfo64(&sb, info);
    }
    return rv;
}

PRInt32 _MD_getopenfileinfo(const PRFileDesc *fd, PRFileInfo *info)
{
    struct stat sb;
    PRInt32 rv = fstat(fd->secret->md.osfd, &sb);
    if (rv < 0) {
        _PR_MD_MAP_FSTAT_ERROR(_MD_ERRNO());
    }
    else if (NULL != info) {
        rv = _MD_convert_stat_to_fileinfo(&sb, info);
    }
    return rv;
}

PRInt32 _MD_getopenfileinfo64(const PRFileDesc *fd, PRFileInfo64 *info)
{
    _MDStat64 sb;
    PRInt32 rv = _md_iovector._fstat64(fd->secret->md.osfd, &sb);
    if (rv < 0) {
        _PR_MD_MAP_FSTAT_ERROR(_MD_ERRNO());
    }
    else if (NULL != info) {
        rv = _MD_convert_stat64_to_fileinfo64(&sb, info);
    }
    return rv;
}

/*
 * _md_iovector._open64 must be initialized to 'open' so that _PR_InitLog can
 * open the log file during NSPR initialization, before _md_iovector is
 * initialized by _PR_MD_FINAL_INIT.  This means the log file cannot be a
 * large file on some platforms.
 */
struct _MD_IOVector _md_iovector = { open };

/*
** These implementations are to emulate large file routines on systems that
** don't have them. Their goal is to check in case overflow occurs. Otherwise
** they will just operate as normal using 32-bit file routines.
**
** The checking might be pre- or post-op, depending on the semantics.
*/

#if defined(SOLARIS2_5)

static PRIntn _MD_solaris25_fstat64(PRIntn osfd, _MDStat64 *buf)
{
    PRInt32 rv;
    struct stat sb;

    rv = fstat(osfd, &sb);
    if (rv >= 0)
    {
        /*
        ** I'm only copying the fields that are immediately needed.
        ** If somebody else calls this function, some of the fields
        ** may not be defined.
        */
        (void)memset(buf, 0, sizeof(_MDStat64));
        buf->st_mode = sb.st_mode;
        buf->st_ctim = sb.st_ctim;
        buf->st_mtim = sb.st_mtim;
        buf->st_size = sb.st_size;
    }
    return rv;
}  /* _MD_solaris25_fstat64 */

static PRIntn _MD_solaris25_stat64(const char *fn, _MDStat64 *buf)
{
    PRInt32 rv;
    struct stat sb;

    rv = stat(fn, &sb);
    if (rv >= 0)
    {
        /*
        ** I'm only copying the fields that are immediately needed.
        ** If somebody else calls this function, some of the fields
        ** may not be defined.
        */
        (void)memset(buf, 0, sizeof(_MDStat64));
        buf->st_mode = sb.st_mode;
        buf->st_ctim = sb.st_ctim;
        buf->st_mtim = sb.st_mtim;
        buf->st_size = sb.st_size;
    }
    return rv;
}  /* _MD_solaris25_stat64 */
#endif /* defined(SOLARIS2_5) */

#if defined(_PR_NO_LARGE_FILES) || defined(SOLARIS2_5)

static PROffset64 _MD_Unix_lseek64(PRIntn osfd, PROffset64 offset, PRIntn whence)
{
    PRUint64 maxoff;
    PROffset64 rv = minus_one;
    LL_I2L(maxoff, 0x7fffffff);
    if (LL_CMP(offset, <=, maxoff))
    {
        off_t off;
        LL_L2I(off, offset);
        LL_I2L(rv, lseek(osfd, off, whence));
    }
    else {
        errno = EFBIG;    /* we can't go there */
    }
    return rv;
}  /* _MD_Unix_lseek64 */

static void* _MD_Unix_mmap64(
    void *addr, PRSize len, PRIntn prot, PRIntn flags,
    PRIntn fildes, PRInt64 offset)
{
    PR_SetError(PR_FILE_TOO_BIG_ERROR, 0);
    return NULL;
}  /* _MD_Unix_mmap64 */
#endif /* defined(_PR_NO_LARGE_FILES) || defined(SOLARIS2_5) */

/* NDK non-unified headers for API < 21 don't have mmap64. However,
 * NDK unified headers do provide mmap64 for all API versions when building
 * with clang. Therefore, we should provide mmap64 here for API < 21 if we're
 * not using clang or if we're using non-unified headers. We check for
 * non-unified headers by the lack of __ANDROID_API_L__ macro. */
#if defined(ANDROID) && __ANDROID_API__ < 21 && \
    (!defined(__clang__) || !defined(__ANDROID_API_L__))
PR_IMPORT(void) *__mmap2(void *, size_t, int, int, int, size_t);

#define ANDROID_PAGE_SIZE 4096

static void *
mmap64(void *addr, size_t len, int prot, int flags, int fd, loff_t offset)
{
    if (offset & (ANDROID_PAGE_SIZE - 1)) {
        errno = EINVAL;
        return MAP_FAILED;
    }
    return __mmap2(addr, len, prot, flags, fd, offset / ANDROID_PAGE_SIZE);
}
#endif

static void _PR_InitIOV(void)
{
#if defined(SOLARIS2_5)
    PRLibrary *lib;
    void *open64_func;

    open64_func = PR_FindSymbolAndLibrary("open64", &lib);
    if (NULL != open64_func)
    {
        PR_ASSERT(NULL != lib);
        _md_iovector._open64 = (_MD_Open64)open64_func;
        _md_iovector._mmap64 = (_MD_Mmap64)PR_FindSymbol(lib, "mmap64");
        _md_iovector._fstat64 = (_MD_Fstat64)PR_FindSymbol(lib, "fstat64");
        _md_iovector._stat64 = (_MD_Stat64)PR_FindSymbol(lib, "stat64");
        _md_iovector._lseek64 = (_MD_Lseek64)PR_FindSymbol(lib, "lseek64");
        (void)PR_UnloadLibrary(lib);
    }
    else
    {
        _md_iovector._open64 = open;
        _md_iovector._mmap64 = _MD_Unix_mmap64;
        _md_iovector._fstat64 = _MD_solaris25_fstat64;
        _md_iovector._stat64 = _MD_solaris25_stat64;
        _md_iovector._lseek64 = _MD_Unix_lseek64;
    }
#elif defined(_PR_NO_LARGE_FILES)
    _md_iovector._open64 = open;
    _md_iovector._mmap64 = _MD_Unix_mmap64;
    _md_iovector._fstat64 = fstat;
    _md_iovector._stat64 = stat;
    _md_iovector._lseek64 = _MD_Unix_lseek64;
#elif defined(_PR_HAVE_OFF64_T)
#if (defined(ANDROID) && __ANDROID_API__ < 21)
    /*
     * Android < 21 doesn't have open64.  We pass the O_LARGEFILE flag to open
     * in _MD_open.
     */
    _md_iovector._open64 = open;
#else
    _md_iovector._open64 = open64;
#endif
    _md_iovector._mmap64 = mmap64;
#if (defined(ANDROID) && __ANDROID_API__ < 21)
    /* Same as the open64 case for Android. */
    _md_iovector._fstat64 = (_MD_Fstat64)fstat;
    _md_iovector._stat64 = (_MD_Stat64)stat;
#else
    _md_iovector._fstat64 = fstat64;
    _md_iovector._stat64 = stat64;
#endif
    _md_iovector._lseek64 = lseek64;
#elif defined(_PR_HAVE_LARGE_OFF_T)
    _md_iovector._open64 = open;
    _md_iovector._mmap64 = mmap;
    _md_iovector._fstat64 = fstat;
    _md_iovector._stat64 = stat;
    _md_iovector._lseek64 = lseek;
#else
#error "I don't know yet"
#endif
    LL_I2L(minus_one, -1);
}  /* _PR_InitIOV */

void _PR_UnixInit(void)
{
    struct sigaction sigact;
    int rv;

    sigemptyset(&timer_set);

#if !defined(_PR_PTHREADS)

    sigaddset(&timer_set, SIGALRM);
    sigemptyset(&empty_set);
    intr_timeout_ticks =
        PR_SecondsToInterval(_PR_INTERRUPT_CHECK_INTERVAL_SECS);

#if defined(SOLARIS)

    if (getenv("NSPR_SIGSEGV_HANDLE")) {
        sigact.sa_handler = sigsegvhandler;
        sigact.sa_flags = 0;
        sigact.sa_mask = timer_set;
        sigaction(SIGSEGV, &sigact, 0);
    }

    if (getenv("NSPR_SIGABRT_HANDLE")) {
        sigact.sa_handler = sigaborthandler;
        sigact.sa_flags = 0;
        sigact.sa_mask = timer_set;
        sigaction(SIGABRT, &sigact, 0);
    }

    if (getenv("NSPR_SIGBUS_HANDLE")) {
        sigact.sa_handler = sigbushandler;
        sigact.sa_flags = 0;
        sigact.sa_mask = timer_set;
        sigaction(SIGBUS, &sigact, 0);
    }

#endif
#endif  /* !defined(_PR_PTHREADS) */

    sigact.sa_handler = SIG_IGN;
    sigemptyset(&sigact.sa_mask);
    sigact.sa_flags = 0;
    rv = sigaction(SIGPIPE, &sigact, 0);
    PR_ASSERT(0 == rv);

    _pr_unix_rename_lock = PR_NewLock();
    PR_ASSERT(NULL != _pr_unix_rename_lock);
    _pr_Xfe_mon = PR_NewMonitor();
    PR_ASSERT(NULL != _pr_Xfe_mon);

    _PR_InitIOV();  /* one last hack */
}

void _PR_UnixCleanup(void)
{
    if (_pr_unix_rename_lock) {
        PR_DestroyLock(_pr_unix_rename_lock);
        _pr_unix_rename_lock = NULL;
    }
    if (_pr_Xfe_mon) {
        PR_DestroyMonitor(_pr_Xfe_mon);
        _pr_Xfe_mon = NULL;
    }
}

#if !defined(_PR_PTHREADS)

/*
 * Variables used by the GC code, initialized in _MD_InitSegs().
 */
static PRInt32 _pr_zero_fd = -1;
static PRLock *_pr_md_lock = NULL;

/*
 * _MD_InitSegs --
 *
 * This is Unix's version of _PR_MD_INIT_SEGS(), which is
 * called by _PR_InitSegs(), which in turn is called by
 * PR_Init().
 */
void _MD_InitSegs(void)
{
#ifdef DEBUG
    /*
    ** Disable using mmap(2) if NSPR_NO_MMAP is set
    */
    if (getenv("NSPR_NO_MMAP")) {
        _pr_zero_fd = -2;
        return;
    }
#endif
    _pr_zero_fd = open("/dev/zero",O_RDWR, 0);
    /* Prevent the fd from being inherited by child processes */
    fcntl(_pr_zero_fd, F_SETFD, FD_CLOEXEC);
    _pr_md_lock = PR_NewLock();
}

PRStatus _MD_AllocSegment(PRSegment *seg, PRUint32 size, void *vaddr)
{
    static char *lastaddr = (char*) _PR_STACK_VMBASE;
    PRStatus retval = PR_SUCCESS;
    int prot;
    void *rv;

    PR_ASSERT(seg != 0);
    PR_ASSERT(size != 0);

    PR_Lock(_pr_md_lock);
    if (_pr_zero_fd < 0) {
from_heap:
        seg->vaddr = PR_MALLOC(size);
        if (!seg->vaddr) {
            retval = PR_FAILURE;
        }
        else {
            seg->size = size;
        }
        goto exit;
    }

    prot = PROT_READ|PROT_WRITE;
    /*
     * On Alpha Linux, the user-level thread stack needs
     * to be made executable because longjmp/signal seem
     * to put machine instructions on the stack.
     */
#if defined(LINUX) && defined(__alpha)
    prot |= PROT_EXEC;
#endif
    rv = mmap((vaddr != 0) ? vaddr : lastaddr, size, prot,
              _MD_MMAP_FLAGS,
              _pr_zero_fd, 0);
    if (rv == (void*)-1) {
        goto from_heap;
    }
    lastaddr += size;
    seg->vaddr = rv;
    seg->size = size;
    seg->flags = _PR_SEG_VM;

exit:
    PR_Unlock(_pr_md_lock);
    return retval;
}

void _MD_FreeSegment(PRSegment *seg)
{
    if (seg->flags & _PR_SEG_VM) {
        (void) munmap(seg->vaddr, seg->size);
    }
    else {
        PR_DELETE(seg->vaddr);
    }
}

#endif /* _PR_PTHREADS */

/*
 *-----------------------------------------------------------------------
 *
 * PR_Now --
 *
 *     Returns the current time in microseconds since the epoch.
 *     The epoch is midnight January 1, 1970 GMT.
 *     The implementation is machine dependent.  This is the Unix
 *     implementation.
 *     Cf. time_t time(time_t *tp)
 *
 *-----------------------------------------------------------------------
 */

PR_IMPLEMENT(PRTime)
PR_Now(void)
{
    struct timeval tv;
    PRInt64 s, us, s2us;

    GETTIMEOFDAY(&tv);
    LL_I2L(s2us, PR_USEC_PER_SEC);
    LL_I2L(s, tv.tv_sec);
    LL_I2L(us, tv.tv_usec);
    LL_MUL(s, s, s2us);
    LL_ADD(s, s, us);
    return s;
}

#if defined(_MD_INTERVAL_USE_GTOD)
/*
 * This version of interval times is based on the time of day
 * capability offered by the system. This isn't valid for two reasons:
 * 1) The time of day is neither linear nor montonically increasing
 * 2) The units here are milliseconds. That's not appropriate for our use.
 */
PRIntervalTime _PR_UNIX_GetInterval()
{
    struct timeval time;
    PRIntervalTime ticks;

    (void)GETTIMEOFDAY(&time);  /* fallicy of course */
    ticks = (PRUint32)time.tv_sec * PR_MSEC_PER_SEC;  /* that's in milliseconds */
    ticks += (PRUint32)time.tv_usec / PR_USEC_PER_MSEC;  /* so's that */
    return ticks;
}  /* _PR_UNIX_GetInterval */

PRIntervalTime _PR_UNIX_TicksPerSecond()
{
    return 1000;  /* this needs some work :) */
}
#endif

#if defined(_PR_HAVE_CLOCK_MONOTONIC)
PRIntervalTime _PR_UNIX_GetInterval2()
{
    struct timespec time;
    PRIntervalTime ticks;

    if (clock_gettime(CLOCK_MONOTONIC, &time) != 0) {
        fprintf(stderr, "clock_gettime failed: %d\n", errno);
        abort();
    }

    ticks = (PRUint32)time.tv_sec * PR_MSEC_PER_SEC;
    ticks += (PRUint32)time.tv_nsec / PR_NSEC_PER_MSEC;
    return ticks;
}

PRIntervalTime _PR_UNIX_TicksPerSecond2()
{
    return 1000;
}
#endif

#if !defined(_PR_PTHREADS)
/*
 * Wait for I/O on multiple descriptors.
 *
 * Return 0 if timed out, return -1 if interrupted,
 * else return the number of ready descriptors.
 */
PRInt32 _PR_WaitForMultipleFDs(
    _PRUnixPollDesc *unixpds,
    PRInt32 pdcnt,
    PRIntervalTime timeout)
{
    PRPollQueue pq;
    PRIntn is;
    PRInt32 rv;
    _PRCPU *io_cpu;
    _PRUnixPollDesc *unixpd, *eunixpd;
    PRThread *me = _PR_MD_CURRENT_THREAD();

    PR_ASSERT(!(me->flags & _PR_IDLE_THREAD));

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }

    pq.pds = unixpds;
    pq.npds = pdcnt;

    _PR_INTSOFF(is);
    _PR_MD_IOQ_LOCK();
    _PR_THREAD_LOCK(me);

    pq.thr = me;
    io_cpu = me->cpu;
    pq.on_ioq = PR_TRUE;
    pq.timeout = timeout;
    _PR_ADD_TO_IOQ(pq, me->cpu);

#if !defined(_PR_USE_POLL)
    eunixpd = unixpds + pdcnt;
    for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
        PRInt32 osfd = unixpd->osfd;
        if (unixpd->in_flags & _PR_UNIX_POLL_READ) {
            FD_SET(osfd, &_PR_FD_READ_SET(me->cpu));
            _PR_FD_READ_CNT(me->cpu)[osfd]++;
        }
        if (unixpd->in_flags & _PR_UNIX_POLL_WRITE) {
            FD_SET(osfd, &_PR_FD_WRITE_SET(me->cpu));
            (_PR_FD_WRITE_CNT(me->cpu))[osfd]++;
        }
        if (unixpd->in_flags & _PR_UNIX_POLL_EXCEPT) {
            FD_SET(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
            (_PR_FD_EXCEPTION_CNT(me->cpu))[osfd]++;
        }
        if (osfd > _PR_IOQ_MAX_OSFD(me->cpu)) {
            _PR_IOQ_MAX_OSFD(me->cpu) = osfd;
        }
    }
#endif  /* !defined(_PR_USE_POLL) */

    if (_PR_IOQ_TIMEOUT(me->cpu) > timeout) {
        _PR_IOQ_TIMEOUT(me->cpu) = timeout;
    }

    _PR_IOQ_OSFD_CNT(me->cpu) += pdcnt;

    _PR_SLEEPQ_LOCK(me->cpu);
    _PR_ADD_SLEEPQ(me, timeout);
    me->state = _PR_IO_WAIT;
    me->io_pending = PR_TRUE;
    me->io_suspended = PR_FALSE;
    _PR_SLEEPQ_UNLOCK(me->cpu);
    _PR_THREAD_UNLOCK(me);
    _PR_MD_IOQ_UNLOCK();

    _PR_MD_WAIT(me, timeout);

    me->io_pending = PR_FALSE;
    me->io_suspended = PR_FALSE;

    /*
     * This thread should run on the same cpu on which it was blocked; when
     * the IO request times out the fd sets and fd counts for the
     * cpu are updated below.
     */
    PR_ASSERT(me->cpu == io_cpu);

    /*
    ** If we timed out the pollq might still be on the ioq. Remove it
    ** before continuing.
    */
    if (pq.on_ioq) {
        _PR_MD_IOQ_LOCK();
        /*
         * Need to check pq.on_ioq again
         */
        if (pq.on_ioq) {
            PR_REMOVE_LINK(&pq.links);
#ifndef _PR_USE_POLL
            eunixpd = unixpds + pdcnt;
            for (unixpd = unixpds; unixpd < eunixpd; unixpd++) {
                PRInt32 osfd = unixpd->osfd;
                PRInt16 in_flags = unixpd->in_flags;

                if (in_flags & _PR_UNIX_POLL_READ) {
                    if (--(_PR_FD_READ_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_READ_SET(me->cpu));
                    }
                }
                if (in_flags & _PR_UNIX_POLL_WRITE) {
                    if (--(_PR_FD_WRITE_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_WRITE_SET(me->cpu));
                    }
                }
                if (in_flags & _PR_UNIX_POLL_EXCEPT) {
                    if (--(_PR_FD_EXCEPTION_CNT(me->cpu))[osfd] == 0) {
                        FD_CLR(osfd, &_PR_FD_EXCEPTION_SET(me->cpu));
                    }
                }
            }
#endif  /* _PR_USE_POLL */
            PR_ASSERT(pq.npds == pdcnt);
            _PR_IOQ_OSFD_CNT(me->cpu) -= pdcnt;
            PR_ASSERT(_PR_IOQ_OSFD_CNT(me->cpu) >= 0);
        }
        _PR_MD_IOQ_UNLOCK();
    }
    /* XXX Should we use _PR_FAST_INTSON or _PR_INTSON? */
    if (1 == pdcnt) {
        _PR_FAST_INTSON(is);
    } else {
        _PR_INTSON(is);
    }

    if (_PR_PENDING_INTERRUPT(me)) {
        me->flags &= ~_PR_INTERRUPT;
        PR_SetError(PR_PENDING_INTERRUPT_ERROR, 0);
        return -1;
    }

    rv = 0;
    if (pq.on_ioq == PR_FALSE) {
        /* Count the number of ready descriptors */
        while (--pdcnt >= 0) {
            if (unixpds->out_flags != 0) {
                rv++;
            }
            unixpds++;
        }
    }

    return rv;
}

/*
 * Unblock threads waiting for I/O
 *    used when interrupting threads
 *
 * NOTE: The thread lock should held when this function is called.
 * On return, the thread lock is released.
 */
void _PR_Unblock_IO_Wait(PRThread *thr)
{
    int pri = thr->priority;
    _PRCPU *cpu = thr->cpu;

    /*
     * GLOBAL threads wakeup periodically to check for interrupt
     */
    if (_PR_IS_NATIVE_THREAD(thr)) {
        _PR_THREAD_UNLOCK(thr);
        return;
    }

    PR_ASSERT(thr->flags & (_PR_ON_SLEEPQ | _PR_ON_PAUSEQ));
    _PR_SLEEPQ_LOCK(cpu);
    _PR_DEL_SLEEPQ(thr, PR_TRUE);
    _PR_SLEEPQ_UNLOCK(cpu);

    PR_ASSERT(!(thr->flags & _PR_IDLE_THREAD));
    thr->state = _PR_RUNNABLE;
    _PR_RUNQ_LOCK(cpu);
    _PR_ADD_RUNQ(thr, cpu, pri);
    _PR_RUNQ_UNLOCK(cpu);
    _PR_THREAD_UNLOCK(thr);
    _PR_MD_WAKEUP_WAITER(thr);
}
#endif  /* !defined(_PR_PTHREADS) */

/*
 * When a nonblocking connect has completed, determine whether it
 * succeeded or failed, and if it failed, what the error code is.
 *
 * The function returns the error code.  An error code of 0 means
 * that the nonblocking connect succeeded.
 */

int _MD_unix_get_nonblocking_connect_error(int osfd)
{
#if defined(NTO)
    /* Neutrino does not support the SO_ERROR socket option */
    PRInt32      rv;
    PRNetAddr    addr;
    _PRSockLen_t addrlen = sizeof(addr);

    /* Test to see if we are using the Tiny TCP/IP Stack or the Full one. */
    struct statvfs superblock;
    rv = fstatvfs(osfd, &superblock);
    if (rv == 0) {
        if (strcmp(superblock.f_basetype, "ttcpip") == 0) {
            /* Using the Tiny Stack! */
            rv = getpeername(osfd, (struct sockaddr *) &addr,
                             (_PRSockLen_t *) &addrlen);
            if (rv == -1) {
                int errno_copy = errno;    /* make a copy so I don't
                                            * accidentally reset */

                if (errno_copy == ENOTCONN) {
                    struct stat StatInfo;
                    rv = fstat(osfd, &StatInfo);
                    if (rv == 0) {
                        time_t current_time = time(NULL);

                        /*
                         * this is a real hack, can't explain why it
                         * works it just does
                         */
                        if (abs(current_time - StatInfo.st_atime) < 5) {
                            return ECONNREFUSED;
                        } else {
                            return ETIMEDOUT;
                        }
                    } else {
                        return ECONNREFUSED;
                    }
                } else {
                    return errno_copy;
                }
            } else {
                /* No Error */
                return 0;
            }
        } else {
            /* Have the FULL Stack which supports SO_ERROR */
            /* Hasn't been written yet, never been tested! */
            /* Jerry.Kirk@Nexwarecorp.com */

            int err;
            _PRSockLen_t optlen = sizeof(err);

            if (getsockopt(osfd, SOL_SOCKET, SO_ERROR,
                           (char *) &err, &optlen) == -1) {
                return errno;
            } else {
                return err;
            }
        }
    } else {
        return ECONNREFUSED;
    }
#elif defined(UNIXWARE)
    /*
     * getsockopt() fails with EPIPE, so use getmsg() instead.
     */

    int rv;
    int flags = 0;
    rv = getmsg(osfd, NULL, NULL, &flags);
    PR_ASSERT(-1 == rv || 0 == rv);
    if (-1 == rv && errno != EAGAIN && errno != EWOULDBLOCK) {
        return errno;
    }
    return 0; /* no error */
#else
    int err;
    _PRSockLen_t optlen = sizeof(err);
    if (getsockopt(osfd, SOL_SOCKET, SO_ERROR, (char*)&err, &optlen) == -1) {
        return errno;
    }
    return err;

#endif
}

/************************************************************************/

/*
** Special hacks for xlib. Xlib/Xt/Xm is not re-entrant nor is it thread
** safe.  Unfortunately, neither is mozilla. To make these programs work
** in a pre-emptive threaded environment, we need to use a lock.
*/

void _PR_XLock(void)
{
    PR_EnterMonitor(_pr_Xfe_mon);
}

void _PR_XUnlock(void)
{
    PR_ExitMonitor(_pr_Xfe_mon);
}

PRBool _PR_XIsLocked(void)
{
    return (PR_InMonitor(_pr_Xfe_mon)) ? PR_TRUE : PR_FALSE;
}

#if defined(HAVE_FCNTL_FILE_LOCKING)

PRStatus
_MD_LockFile(PRInt32 f)
{
    PRInt32 rv;
    struct flock arg;

    arg.l_type = F_WRLCK;
    arg.l_whence = SEEK_SET;
    arg.l_start = 0;
    arg.l_len = 0;  /* until EOF */
    rv = fcntl(f, F_SETLKW, &arg);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_TLockFile(PRInt32 f)
{
    PRInt32 rv;
    struct flock arg;

    arg.l_type = F_WRLCK;
    arg.l_whence = SEEK_SET;
    arg.l_start = 0;
    arg.l_len = 0;  /* until EOF */
    rv = fcntl(f, F_SETLK, &arg);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_UnlockFile(PRInt32 f)
{
    PRInt32 rv;
    struct flock arg;

    arg.l_type = F_UNLCK;
    arg.l_whence = SEEK_SET;
    arg.l_start = 0;
    arg.l_len = 0;  /* until EOF */
    rv = fcntl(f, F_SETLK, &arg);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

#elif defined(HAVE_BSD_FLOCK)

#include <sys/file.h>

PRStatus
_MD_LockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = flock(f, LOCK_EX);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_TLockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = flock(f, LOCK_EX|LOCK_NB);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_UnlockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = flock(f, LOCK_UN);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_FLOCK_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}
#else

PRStatus
_MD_LockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = lockf(f, F_LOCK, 0);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_TLockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = lockf(f, F_TLOCK, 0);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus
_MD_UnlockFile(PRInt32 f)
{
    PRInt32 rv;
    rv = lockf(f, F_ULOCK, 0);
    if (rv == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_LOCKF_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}
#endif

PRStatus _MD_gethostname(char *name, PRUint32 namelen)
{
    PRIntn rv;

    rv = gethostname(name, namelen);
    if (0 == rv) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_GETHOSTNAME_ERROR(_MD_ERRNO());
    return PR_FAILURE;
}

PRStatus _MD_getsysinfo(PRSysInfo cmd, char *name, PRUint32 namelen)
{
    struct utsname info;

    PR_ASSERT((cmd == PR_SI_SYSNAME) || (cmd == PR_SI_RELEASE) ||
              (cmd == PR_SI_RELEASE_BUILD));

    if (uname(&info) == -1) {
        _PR_MD_MAP_DEFAULT_ERROR(errno);
        return PR_FAILURE;
    }
    if (PR_SI_SYSNAME == cmd) {
        (void)PR_snprintf(name, namelen, info.sysname);
    }
    else if (PR_SI_RELEASE == cmd) {
        (void)PR_snprintf(name, namelen, info.release);
    }
    else if (PR_SI_RELEASE_BUILD == cmd) {
        (void)PR_snprintf(name, namelen, info.version);
    }
    else {
        return PR_FAILURE;
    }
    return PR_SUCCESS;
}

/*
 *******************************************************************
 *
 * Memory-mapped files
 *
 *******************************************************************
 */

PRStatus _MD_CreateFileMap(PRFileMap *fmap, PRInt64 size)
{
    PRFileInfo info;
    PRUint32 sz;

    LL_L2UI(sz, size);
    if (sz) {
        if (PR_GetOpenFileInfo(fmap->fd, &info) == PR_FAILURE) {
            return PR_FAILURE;
        }
        if (sz > info.size) {
            /*
             * Need to extend the file
             */
            if (fmap->prot != PR_PROT_READWRITE) {
                PR_SetError(PR_NO_ACCESS_RIGHTS_ERROR, 0);
                return PR_FAILURE;
            }
            if (PR_Seek(fmap->fd, sz - 1, PR_SEEK_SET) == -1) {
                return PR_FAILURE;
            }
            if (PR_Write(fmap->fd, "", 1) != 1) {
                return PR_FAILURE;
            }
        }
    }
    if (fmap->prot == PR_PROT_READONLY) {
        fmap->md.prot = PROT_READ;
#if defined(DARWIN) || defined(ANDROID)
        /*
         * This is needed on OS X because its implementation of
         * POSIX shared memory returns an error for MAP_PRIVATE, even
         * when the mapping is read-only.
         *
         * And this is needed on Android, because mapping ashmem with
         * MAP_PRIVATE creates a mapping of zeroed memory instead of
         * the shm contents.
         */
        fmap->md.flags = MAP_SHARED;
#else
        fmap->md.flags = MAP_PRIVATE;
#endif
    } else if (fmap->prot == PR_PROT_READWRITE) {
        fmap->md.prot = PROT_READ | PROT_WRITE;
        fmap->md.flags = MAP_SHARED;
    } else {
        PR_ASSERT(fmap->prot == PR_PROT_WRITECOPY);
        fmap->md.prot = PROT_READ | PROT_WRITE;
        fmap->md.flags = MAP_PRIVATE;
    }
    return PR_SUCCESS;
}

void * _MD_MemMap(
    PRFileMap *fmap,
    PRInt64 offset,
    PRUint32 len)
{
    PRInt32 off;
    void *addr;

    LL_L2I(off, offset);
    if ((addr = mmap(0, len, fmap->md.prot, fmap->md.flags,
                     fmap->fd->secret->md.osfd, off)) == (void *) -1) {
        _PR_MD_MAP_MMAP_ERROR(_MD_ERRNO());
        addr = NULL;
    }
    return addr;
}

PRStatus _MD_MemUnmap(void *addr, PRUint32 len)
{
    if (munmap(addr, len) == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_DEFAULT_ERROR(errno);
    return PR_FAILURE;
}

PRStatus _MD_CloseFileMap(PRFileMap *fmap)
{
    if ( PR_TRUE == fmap->md.isAnonFM ) {
        PRStatus rc = PR_Close( fmap->fd );
        if ( PR_FAILURE == rc ) {
            PR_LOG( _pr_io_lm, PR_LOG_DEBUG,
                    ("_MD_CloseFileMap(): error closing anonymnous file map osfd"));
            return PR_FAILURE;
        }
    }
    PR_DELETE(fmap);
    return PR_SUCCESS;
}

PRStatus _MD_SyncMemMap(
    PRFileDesc *fd,
    void *addr,
    PRUint32 len)
{
    /* msync(..., MS_SYNC) alone is sufficient to flush modified data to disk
     * synchronously. It is not necessary to call fsync. */
    if (msync(addr, len, MS_SYNC) == 0) {
        return PR_SUCCESS;
    }
    _PR_MD_MAP_DEFAULT_ERROR(errno);
    return PR_FAILURE;
}

#if defined(_PR_NEED_FAKE_POLL)

/*
 * Some platforms don't have poll().  For easier porting of code
 * that calls poll(), we emulate poll() using select().
 */

int poll(struct pollfd *filedes, unsigned long nfds, int timeout)
{
    int i;
    int rv;
    int maxfd;
    fd_set rd, wr, ex;
    struct timeval tv, *tvp;

    if (timeout < 0 && timeout != -1) {
        errno = EINVAL;
        return -1;
    }

    if (timeout == -1) {
        tvp = NULL;
    } else {
        tv.tv_sec = timeout / 1000;
        tv.tv_usec = (timeout % 1000) * 1000;
        tvp = &tv;
    }

    maxfd = -1;
    FD_ZERO(&rd);
    FD_ZERO(&wr);
    FD_ZERO(&ex);

    for (i = 0; i < nfds; i++) {
        int osfd = filedes[i].fd;
        int events = filedes[i].events;
        PRBool fdHasEvent = PR_FALSE;

        PR_ASSERT(osfd < FD_SETSIZE);
        if (osfd < 0 || osfd >= FD_SETSIZE) {
            continue;  /* Skip this osfd. */
        }

        /*
         * Map the poll events to the select fd_sets.
         *     POLLIN, POLLRDNORM  ===> readable
         *     POLLOUT, POLLWRNORM ===> writable
         *     POLLPRI, POLLRDBAND ===> exception
         *     POLLNORM, POLLWRBAND (and POLLMSG on some platforms)
         *     are ignored.
         *
         * The output events POLLERR and POLLHUP are never turned on.
         * POLLNVAL may be turned on.
         */

        if (events & (POLLIN | POLLRDNORM)) {
            FD_SET(osfd, &rd);
            fdHasEvent = PR_TRUE;
        }
        if (events & (POLLOUT | POLLWRNORM)) {
            FD_SET(osfd, &wr);
            fdHasEvent = PR_TRUE;
        }
        if (events & (POLLPRI | POLLRDBAND)) {
            FD_SET(osfd, &ex);
            fdHasEvent = PR_TRUE;
        }
        if (fdHasEvent && osfd > maxfd) {
            maxfd = osfd;
        }
    }

    rv = select(maxfd + 1, &rd, &wr, &ex, tvp);

    /* Compute poll results */
    if (rv > 0) {
        rv = 0;
        for (i = 0; i < nfds; i++) {
            PRBool fdHasEvent = PR_FALSE;

            filedes[i].revents = 0;
            if (filedes[i].fd < 0) {
                continue;
            }
            if (filedes[i].fd >= FD_SETSIZE) {
                filedes[i].revents |= POLLNVAL;
                continue;
            }
            if (FD_ISSET(filedes[i].fd, &rd)) {
                if (filedes[i].events & POLLIN) {
                    filedes[i].revents |= POLLIN;
                }
                if (filedes[i].events & POLLRDNORM) {
                    filedes[i].revents |= POLLRDNORM;
                }
                fdHasEvent = PR_TRUE;
            }
            if (FD_ISSET(filedes[i].fd, &wr)) {
                if (filedes[i].events & POLLOUT) {
                    filedes[i].revents |= POLLOUT;
                }
                if (filedes[i].events & POLLWRNORM) {
                    filedes[i].revents |= POLLWRNORM;
                }
                fdHasEvent = PR_TRUE;
            }
            if (FD_ISSET(filedes[i].fd, &ex)) {
                if (filedes[i].events & POLLPRI) {
                    filedes[i].revents |= POLLPRI;
                }
                if (filedes[i].events & POLLRDBAND) {
                    filedes[i].revents |= POLLRDBAND;
                }
                fdHasEvent = PR_TRUE;
            }
            if (fdHasEvent) {
                rv++;
            }
        }
        PR_ASSERT(rv > 0);
    } else if (rv == -1 && errno == EBADF) {
        rv = 0;
        for (i = 0; i < nfds; i++) {
            filedes[i].revents = 0;
            if (filedes[i].fd < 0) {
                continue;
            }
            if (fcntl(filedes[i].fd, F_GETFL, 0) == -1) {
                filedes[i].revents = POLLNVAL;
                rv++;
            }
        }
        PR_ASSERT(rv > 0);
    }
    PR_ASSERT(-1 != timeout || rv != 0);

    return rv;
}
#endif /* _PR_NEED_FAKE_POLL */