summaryrefslogtreecommitdiffstats
path: root/win/tclWinsockCore.c
blob: 62beaa96be86e347a8e7481e99d6a75c93ab677e (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
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
/*
 * tclWinSockCore.c --
 *
 *	This file contains Windows-specific and protocol agnostic
 *	socket related code.  The default method uses overlapped-I/O
 *	with completion port notification.
 *
 *	No fallback exists, yet, to support non-NT based systems.
 *
 * Copyright (c) 2008 David Gravereaux <davygrvy@pobox.com>
 *
 * See the file "license.terms" for information on usage and redistribution of
 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
 *
 * RCS: @(#) $Id: tclWinsockCore.c,v 1.1.2.14 2009/01/06 22:17:35 davygrvy Exp $
 */

#include "tclWinInt.h"
#include "tclWinsockCore.h"

#ifdef _MSC_VER
#   pragma comment (lib, "ws2_32")
#endif

/* ISO hack for dumb VC++ */
#ifdef _MSC_VER
#define   snprintf	_snprintf
#endif

/*
 * The following variable holds the network name of this host.
 */

static TclInitProcessGlobalValueProc InitializeHostName;
static ProcessGlobalValue hostName = {
    0, 0, NULL, NULL, InitializeHostName, NULL, NULL
};


/*
 * Support for control over sockets' KEEPALIVE and NODELAY behavior is
 * currently disabled.
 */

#undef TCL_FEATURE_KEEPALIVE_NAGLE

/* some globals defined. */
CompletionPortInfo IocpSubSystem;

/* Stats being collected */
LONG StatOpenSockets		= 0;
LONG StatFailedAcceptExCalls	= 0;
LONG StatGeneralBytesInUse	= 0;
LONG StatSpecialBytesInUse	= 0;
LONG StatFailedReplacementAcceptExCalls	= 0;

/* file-scope globals */
GUID AcceptExGuid		= WSAID_ACCEPTEX;
GUID GetAcceptExSockaddrsGuid	= WSAID_GETACCEPTEXSOCKADDRS;
GUID ConnectExGuid		= WSAID_CONNECTEX;
GUID DisconnectExGuid		= WSAID_DISCONNECTEX;
GUID TransmitFileGuid		= WSAID_TRANSMITFILE;
GUID TransmitPacketsGuid	= WSAID_TRANSMITPACKETS;
GUID WSARecvMsgGuid		= WSAID_WSARECVMSG;
static int initialized		= 0;
static DWORD winsockLoadErr	= 0;
Tcl_ThreadDataKey dataKey;
Tcl_HashTable netProtocolTbl;

/* local prototypes */
static int			InitializeIocpSubSystem();
static Tcl_ExitProc		IocpExitHandler;
static Tcl_ExitProc		IocpThreadExitHandler;
static Tcl_EventSetupProc	IocpEventSetupProc;
static Tcl_EventCheckProc	IocpEventCheckProc;
static Tcl_EventProc		IocpEventProc;
static Tcl_EventDeleteProc	IocpRemovePendingEvents;
static Tcl_EventDeleteProc	IocpRemoveAllPendingEvents;

static Tcl_DriverCloseProc	IocpCloseProc;
static Tcl_DriverClose2Proc	IocpClose2Proc;
static Tcl_DriverInputProc	IocpInputProc;
static Tcl_DriverInputProc	IocpInputNotSupProc;
static Tcl_DriverOutputProc	IocpOutputProc;
static Tcl_DriverOutputProc	IocpOutputNotSupProc;
static Tcl_DriverSetOptionProc	IocpSetOptionProc;
static Tcl_DriverGetOptionProc	IocpGetOptionProc;
static Tcl_DriverWatchProc	IocpWatchProc;
static Tcl_DriverGetHandleProc	IocpGetHandleProc;
static Tcl_DriverBlockModeProc	IocpBlockProc;
static Tcl_DriverThreadActionProc IocpThreadActionProc;

static void		AddProtocolData (const char *name,
			    WS2ProtocolData *data);
static int		FindProtocolMatch(LPWSAPROTOCOL_INFO pinfo,
			    WS2ProtocolData **pdata);
static void		IocpZapTclNotifier (SocketInfo *infoPtr);
static void		IocpAlertToTclNewAccept (SocketInfo *infoPtr,
			    SocketInfo *newClient);
static void		IocpAcceptOne (SocketInfo *infoPtr);
static void		IocpPushRecvAlertToTcl(SocketInfo *infoPtr,
			    BufferInfo *bufPtr);
static DWORD		PostOverlappedSend (SocketInfo *infoPtr,
			    BufferInfo *bufPtr);
static DWORD		PostOverlappedDisconnect (SocketInfo *infoPtr,
			    BufferInfo *bufPtr);
static DWORD WINAPI	CompletionThreadProc (LPVOID lpParam);
static void		HandleIo(register SocketInfo *infoPtr,
			    register BufferInfo *bufPtr,
			    HANDLE compPort, DWORD bytes, DWORD error,
			    DWORD flags);
static void		RepostRecvs (SocketInfo *infoPtr,
			    int chanBufSize);
static int		FilterSingleOpRecvBuf (SocketInfo *infoPtr,
			    BufferInfo *bufPtr, int bytesRead);
static int		FilterPartialRecvBufMerge (SocketInfo *infoPtr,
			    BufferInfo *bufPtr, int *bytesRead,
			    int toRead, char *bufPos);
static int		DoRecvBufMerge (SocketInfo *infoPtr,
			    BufferInfo *bufPtr, int *bytesRead,
			    int toRead, char **bufPos, int *gotError);

/* special hack jobs! */
static BOOL PASCAL	OurConnectEx(SOCKET s,
			    const struct sockaddr* name, int namelen,
			    PVOID lpSendBuffer, DWORD dwSendDataLength,
			    LPDWORD lpdwBytesSent,
			    LPOVERLAPPED lpOverlapped);
static BOOL PASCAL	OurDisconnectEx(SOCKET hSocket,
			    LPOVERLAPPED lpOverlapped, DWORD dwFlags,
			    DWORD reserved);

/*
 * This structure describes the channel type structure for TCP socket
 * based I/O using the native overlapped interface along with completion
 * ports for maximum efficiency so that most operation are done entirely
 * in kernel-mode.
 */

Tcl_ChannelType IocpStreamChannelType = {
    "iocp_stream",	    /* Type name. */
    TCL_CHANNEL_VERSION_5,
    IocpCloseProc,	    /* Close proc. */
    IocpInputProc,	    /* Input proc. */
    IocpOutputProc,	    /* Output proc. */
    NULL,		    /* Seek proc. */
    IocpSetOptionProc,	    /* Set option proc. */
    IocpGetOptionProc,	    /* Get option proc. */
    IocpWatchProc,	    /* Set up notifier to watch this channel. */
    IocpGetHandleProc,	    /* Get an OS handle from channel. */
    IocpClose2Proc,	    /* close2proc. */
    IocpBlockProc,	    /* Set socket into (non-)blocking mode. */
    NULL,		    /* flush proc. */
    NULL,		    /* handler proc. */
    NULL,		    /* wide seek */
    IocpThreadActionProc,   /* TIP #218. */
    NULL		    /* truncate */
};

Tcl_ChannelType IocpPacketChannelType = {
    "iocp_packet",	    /* Type name. */
    TCL_CHANNEL_VERSION_5,
    IocpCloseProc,	    /* Close proc. */
    IocpInputNotSupProc,    /* Input proc. */
    IocpOutputNotSupProc,   /* Output proc. */
    NULL,		    /* Seek proc. */
    IocpSetOptionProc,	    /* Set option proc. */
    IocpGetOptionProc,	    /* Get option proc. */
    IocpWatchProc,	    /* Set up notifier to watch this channel. */
    IocpGetHandleProc,	    /* Get an OS handle from channel. */
    NULL,		    /* close2proc. */
    IocpBlockProc,	    /* Set socket into (non-)blocking mode. */
    NULL,		    /* flush proc. */
    NULL,		    /* handler proc. */
    NULL,		    /* wide seek */
    IocpThreadActionProc,   /* TIP #218. */
    NULL		    /* truncate */
};


typedef struct SocketEvent {
    Tcl_Event header;		/* Information that is standard for
				 * all events. */
    SocketInfo *infoPtr;
} SocketEvent;


/* =================================================================== */
/* ============= Initailization and shutdown procedures ============== */


ThreadSpecificData *
InitSockets(void)
{
    WSADATA wsaData;
    OSVERSIONINFO os;
    ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);

    /* global/once init */
    if (!initialized) {
	initialized = 1;

	/*
	 * Initialize the winsock library and check the interface
	 * version number.  We ask for the 2.2 interface, and
	 * don't accept less than 2.2.
	 */

#define WSA_VER_MIN_MAJOR   2
#define WSA_VER_MIN_MINOR   2
#define WSA_VERSION_REQUESTED    MAKEWORD(2,2)

	if ((winsockLoadErr = WSAStartup(WSA_VERSION_REQUESTED,
		&wsaData)) != 0) {
	    goto unloadLibrary;
	}

	/*
	 * Note the byte positions are swapped for the comparison, so
	 * that 0x0002 (2.0, MAKEWORD(2,0)) doesn't look less than 0x0101
	 * (1.1).  We want the comparison to be 0x0200 < 0x0101.
	 */
	if (MAKEWORD(HIBYTE(wsaData.wVersion), LOBYTE(wsaData.wVersion))
		< MAKEWORD(WSA_VER_MIN_MINOR, WSA_VER_MIN_MAJOR)) {
	    SetLastError(WSAVERNOTSUPPORTED);
	    WSACleanup();
	    goto unloadLibrary;
	}

#undef WSA_VERSION_REQUESTED
#undef WSA_VER_MIN_MAJOR
#undef WSA_VER_MIN_MINOR

	os.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
	GetVersionEx(&os);

	// TODO: fallback to WSAAsyncSelect method here, if needed.

	if (InitializeIocpSubSystem() == TCL_ERROR) {
	    goto unloadLibrary;
	}

	Tcl_InitHashTable(&netProtocolTbl, TCL_STRING_KEYS);

	/*
	 * This is the dream list.  Some don't make sense
	 * such as ICMP and ARP, but are listed for completeness.
	 */
	AddProtocolData("tcp",		&tcpAnyProtoData);
	AddProtocolData("tcp4", 	&tcp4ProtoData);
	AddProtocolData("tcp6", 	&tcp6ProtoData);
#if 0
	AddProtocolData("udp",		&udpAnyProtoData);
	AddProtocolData("udp4", 	&udp4ProtoData);
	AddProtocolData("udp6",		&udp6ProtoData);
	AddProtocolData("icmp",		NULL);
	AddProtocolData("icmp6",	NULL);
	AddProtocolData("igmp",		NULL);
	AddProtocolData("igmp6",	NULL);
	AddProtocolData("arp",		NULL);
	AddProtocolData("arp6",		NULL);
	AddProtocolData("pup",		NULL);
	AddProtocolData("ggp",		NULL);
	AddProtocolData("idp",		NULL);
	AddProtocolData("nd",		NULL);
	AddProtocolData("rm",		NULL);
	/*
	 * UNIX domain (machine local) sockets.
	 */
	AddProtocolData("unix",		NULL);
	/*
	 * All four Bluetooth protocols. rfcomm and l2cap only
	 * on win.
	 */
	AddProtocolData("bluetooth_hci",	NULL);
	AddProtocolData("bluetooth_l2cap",	NULL);
	AddProtocolData("bluetooth_rfcomm",	&bthProtoData);
	AddProtocolData("bluetooth_sco",	NULL);
	/*
	 * IrDA has only one type, but name resolution method is
	 * different on windows.
	 */
	AddProtocolData("irda",		&irdaProtoData);
	/*
	 * All AppleTalk protocols, mainly for historical reasons,
	 * as windows doesn't have an LSP for it anymore since XP.
	 */
	AddProtocolData("appletalk_rtm",	NULL);
	AddProtocolData("appletalk_nbp",	NULL);
	AddProtocolData("appletalk_atp",	NULL);
	AddProtocolData("appletalk_aep",	NULL);
	AddProtocolData("appletalk_rtmprq",	NULL);
	AddProtocolData("appletalk_zip",	NULL);
	AddProtocolData("appletalk_adsp",	NULL);
	AddProtocolData("appletalk_asp",	NULL);
	AddProtocolData("appletalk_pap",	NULL);
	/*
	 * DECNet
	 */
	AddProtocolData("decnet",	NULL);
	/*
	 * IPX/SPX (Novell)
	 */
	AddProtocolData("ipx",		NULL);
	AddProtocolData("spx",		NULL);
	AddProtocolData("spx_seq",	NULL);
	AddProtocolData("spx2",		NULL);
	AddProtocolData("spx2_seq",	NULL);
	/*
	 * ISO
	 */
	AddProtocolData("iso_tp0",	NULL);
	AddProtocolData("iso_tp1",	NULL);
	AddProtocolData("iso_tp2",	NULL);
	AddProtocolData("iso_tp3",	NULL);
	AddProtocolData("iso_tp4",	NULL);
	AddProtocolData("iso_cltp",	NULL);
	AddProtocolData("iso_clnp",	NULL);
	AddProtocolData("iso_inactnl",	NULL);
	AddProtocolData("iso_x.25",	NULL);
	AddProtocolData("iso_es-is",	NULL);
	AddProtocolData("iso_is-is",	NULL);
	/*
	 * NetBIOS
	 */
	AddProtocolData("netbios",	NULL);
	/*
	 * Banyan VINES (Virtual Integrated NEtwork Service)
	 */
	AddProtocolData("vines_ipc",	NULL);
	AddProtocolData("vines_ripc",	NULL);
	AddProtocolData("vines_spp",	NULL);
	/*
	 * ATM (Asynchronous Transfer Mode)
	 */
	AddProtocolData("atm_aal1",		NULL);
	AddProtocolData("atm_aal2",		NULL);
	AddProtocolData("atm_aal5",		NULL);
#endif
    }

    /* per thread init */
    if (tsdPtr->threadId == 0) {
	Tcl_CreateEventSource(IocpEventSetupProc, IocpEventCheckProc, NULL);
	tsdPtr->threadId = Tcl_GetCurrentThread();
	tsdPtr->readySockets = IocpLLCreate();
    }

    return tsdPtr;

unloadLibrary:
    initialized = 0;
    return NULL;
}

void
AddProtocolData(const char *name, WS2ProtocolData *data)
{
    int created;
    Tcl_HashEntry *entryPtr;

    entryPtr = Tcl_CreateHashEntry(&netProtocolTbl, name, &created);
    if (created) {
	Tcl_SetHashValue(entryPtr, data);
    }
}

int
TclpHasSockets(Tcl_Interp *interp)
{
    ThreadSpecificData *blob;

    blob = InitSockets();

    if (blob != NULL) {
	return TCL_OK;
    }
    if (interp != NULL) {
	Tcl_AppendResult(interp, "can't start sockets: ",
		Tcl_WinError(interp, GetLastError()), NULL);
    }
    return TCL_ERROR;
}

static int
InitializeIocpSubSystem ()
{
#define IOCP_HEAP_START_SIZE	(si.dwPageSize*64)  /* about 256k */
    DWORD error = NO_ERROR;
    SYSTEM_INFO si;

    GetSystemInfo(&si);

    /* Create the completion port. */
    IocpSubSystem.port = CreateIoCompletionPort(
	    INVALID_HANDLE_VALUE, NULL, (ULONG_PTR)NULL, 0);
    if (IocpSubSystem.port == NULL) {
	goto error;
    }

    /* Create the general private memory heap. */
    IocpSubSystem.heap = HeapCreate(0, IOCP_HEAP_START_SIZE, 0);
    if (IocpSubSystem.heap == NULL) {
	CloseHandle(IocpSubSystem.port);
	goto error;
    }

    /* Create the special private memory heap. */
    IocpSubSystem.NPPheap = HeapCreate(0, IOCP_HEAP_START_SIZE, 0);
    if (IocpSubSystem.NPPheap == NULL) {
	HeapDestroy(IocpSubSystem.heap);
	CloseHandle(IocpSubSystem.port);
	goto error;
    }

    /* Create the thread to service the completion port. */
    IocpSubSystem.thread = CreateThread(NULL, 0, CompletionThreadProc,
	    &IocpSubSystem, 0, NULL);
    if (IocpSubSystem.thread == NULL) {
	HeapDestroy(IocpSubSystem.heap);
	HeapDestroy(IocpSubSystem.NPPheap);
	CloseHandle(IocpSubSystem.port);
	goto error;
    }

    Tcl_CreateExitHandler(IocpExitHandler, NULL);

    return TCL_OK;
error:
    return TCL_ERROR;
#undef IOCP_HEAP_START_SIZE
}

void
IocpExitHandler (ClientData clientData)
{
    DWORD wait;

    if (initialized) {

	Tcl_DeleteHashTable(&netProtocolTbl);

	Tcl_DeleteEvents(IocpRemoveAllPendingEvents, NULL);

	/* Cause the waiting I/O handler thread(s) to exit. */
	PostQueuedCompletionStatus(IocpSubSystem.port, 0, 0, 0);

	/* Wait for our completion thread to exit. */
	wait = WaitForSingleObject(IocpSubSystem.thread, 400);
	if (wait == WAIT_TIMEOUT) {
	    TerminateThread(IocpSubSystem.thread, 0x666);
	}
	CloseHandle(IocpSubSystem.thread);

	/* Close the completion port object. */
	CloseHandle(IocpSubSystem.port);

	/* Tear down the private memory heaps. */
	HeapDestroy(IocpSubSystem.heap);
	HeapDestroy(IocpSubSystem.NPPheap);

	initialized = 0;
	WSACleanup();
    }
}

/*
 *----------------------------------------------------------------------
 *
 * TclpFinalizeSockets --
 *
 *	This function is called from Tcl_FinalizeThread to finalize the
 *	platform specific socket subsystem. Also, it may be called from within
 *	this module to cleanup the state if unable to initialize the sockets
 *	subsystem.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Deletes the event source and destroys the socket thread.
 *
 *----------------------------------------------------------------------
 */

void
TclpFinalizeSockets (void)
{
    ThreadSpecificData *tsdPtr;

    tsdPtr = (ThreadSpecificData *) TclThreadDataKeyGet(&dataKey);
    Tcl_DeleteEventSource(IocpEventSetupProc, IocpEventCheckProc, NULL);
    if (initialized) {
	IocpLLPopAll(tsdPtr->readySockets, NULL, IOCP_LL_NODESTROY);
	IocpLLDestroy(tsdPtr->readySockets);
	tsdPtr->readySockets = NULL;
    }
}

/* =================================================================== */
/* ===================== Tcl exposed procedures ====================== */


/*
 *----------------------------------------------------------------------
 *
 * Tcl_MakeTcpClientChannel --
 *
 *	Creates a Tcl_Channel from an existing client socket.
 *
 * Results:
 *	The Tcl_Channel wrapped around the preexisting socket
 *	or NULL when an error occurs.  Any errors are left
 *	available through GetLastError().
 *
 * Side effects:
 *	Socket is now owned by Tcl.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_MakeTcpClientChannel (
    ClientData sock)	/* The socket to wrap up into a channel. */
{
    return Tcl_MakeSocketClientChannel(sock);
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_MakeSocketClientChannel --
 *
 *	Creates a Tcl_Channel from an existing client socket.
 *
 * Results:
 *	The Tcl_Channel wrapped around the preexisting socket
 *	or NULL when an error occurs.  Any errors are left
 *	available through GetLastError().
 *
 * Side effects:
 *	Socket is now owned by Tcl.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_MakeSocketClientChannel (
    ClientData data)	/* The socket to wrap up into a channel. */
{
    SocketInfo *infoPtr;
    BufferInfo *bufPtr;
    char channelName[16 + TCL_INTEGER_SPACE];
    SOCKET sock = (SOCKET) data;
    WSAPROTOCOL_INFO protocolInfo;
    int protocolInfoSize = sizeof(WSAPROTOCOL_INFO); 
    WS2ProtocolData *pdata;
    int i;
    ThreadSpecificData *tsdPtr = InitSockets();


    if (getsockopt(sock, SOL_SOCKET, SO_PROTOCOL_INFO,
	    (char *)&protocolInfo, &protocolInfoSize) == SOCKET_ERROR)
    {
	/* Bail if we can't get the LSP data. */
	SetLastError(WSAGetLastError());
	return NULL;
    }

    /* Find proper protocol match. */
    if (FindProtocolMatch(&protocolInfo, &pdata) == TCL_ERROR) {
	SetLastError(WSAEAFNOSUPPORT);
	return NULL;
    }

    IocpInitProtocolData(sock, pdata);
    infoPtr = NewSocketInfo(sock);
    infoPtr->proto = pdata;

    /* Info needed to get back to this thread. */
    infoPtr->tsdHome = tsdPtr;

    /* 
     * Associate the socket and its SocketInfo struct to the
     * completion port.  This implies an automatic set to
     * non-blocking.
     */
    if (CreateIoCompletionPort((HANDLE)sock, IocpSubSystem.port,
	    (ULONG_PTR)infoPtr, 0) == NULL) {
	/* FreeSocketInfo should not close this SOCKET for us. */
	infoPtr->socket = INVALID_SOCKET;
	FreeSocketInfo(infoPtr);
	return NULL;
    }

    /*
     * Start watching for read events on the socket.
     */

    infoPtr->llPendingRecv = IocpLLCreate();

    /* post IOCP_INITIAL_RECV_COUNT recvs. */
    for(i = 0; i < IOCP_INITIAL_RECV_COUNT ;i++) {
	bufPtr = GetBufferObj(infoPtr,
		(infoPtr->recvMode == IOCP_RECVMODE_ZERO_BYTE ? 0 : IOCP_RECV_BUFSIZE));
	if (PostOverlappedRecv(infoPtr, bufPtr, 0, 1)) {
	    FreeBufferObj(bufPtr);
	    break;
	}
    }

    snprintf(channelName, 4 + TCL_INTEGER_SPACE, "sock%lu", infoPtr->socket);
    infoPtr->channel = Tcl_CreateChannel(&IocpStreamChannelType, channelName,
	    (ClientData) infoPtr, (TCL_READABLE | TCL_WRITABLE));
    Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto crlf");
    SetLastError(ERROR_SUCCESS);
    return infoPtr->channel;
}

int
FindProtocolMatch(LPWSAPROTOCOL_INFO pinfo, WS2ProtocolData **pdata)
{
    Tcl_HashSearch HashSrch;
    Tcl_HashEntry *entryPtr;
    WS2ProtocolData *psdata;

    for (
 	entryPtr = Tcl_FirstHashEntry(&netProtocolTbl, &HashSrch);
 	entryPtr != NULL;
 	entryPtr = Tcl_NextHashEntry(&HashSrch)
    ) {
	psdata = Tcl_GetHashValue(entryPtr);
	if (
	    pinfo->iAddressFamily == psdata->af &&
	    pinfo->iSocketType == psdata->type &&
	    pinfo->iProtocol == psdata->protocol
	) {
	    /* found */
	    *pdata = psdata;
	    return TCL_OK;
	}
    }
    return TCL_ERROR;
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenTcpClient --
 *
 *	Opens a TCP client socket and creates a channel around it.
 *	This is the old API maintained for compatability.  Only
 *	IPv4 (AF_INET4) addresses are used.
 *
 * Results:
 *	The channel or NULL if failed.  An error message is returned
 *	in the interpreter on failure.
 *
 * Side effects:
 *	Opens a client socket and creates a new channel for it.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenTcpClient(
    Tcl_Interp *interp,		/* For error reporting; can be NULL. */
    int port,			/* Port number to open. */
    const char *host,		/* Host or IP on which to open port. */
    const char *myaddr,		/* Client-side address */
    int myport,			/* Client-side port (number|service).*/
    int async)			/* If nonzero, should connect
				 * client socket asynchronously. */
{
    char portName[TCL_INTEGER_SPACE];
    char myportName[TCL_INTEGER_SPACE];

    TclFormatInt(portName, port);
    TclFormatInt(myportName, myport);
    return Tcl_OpenClientChannel(interp, portName, host, myaddr,
	    myportName, "tcp4", async);
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenClientChannel --
 *
 *	Opens a client socket and creates a channel around it.
 *
 * Results:
 *	The channel or NULL if failed.  An error message is returned
 *	in the interpreter on failure.
 *
 * Side effects:
 *	Opens a client socket and creates a new channel for it.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenClientChannel(
    Tcl_Interp *interp,		/* For error reporting; can be NULL. */
    const char *port,		/* Port (number|service) to open. */
    const char *host,		/* Host on which to open port. */
    const char *myaddr,		/* Client-side address. */
    const char *myport,		/* Client-side port (number|service).*/
    const char *type,		/* the protocol to use. */
    int async)			/* If nonzero, should connect
				 * client socket asynchronously. */
{
    Tcl_HashEntry *entryPtr;
    WS2ProtocolData *pdata;

    entryPtr = Tcl_FindHashEntry(&netProtocolTbl, type);
    if (entryPtr) pdata = Tcl_GetHashValue(entryPtr);
    if (entryPtr == NULL || pdata == NULL) {
	TclWinConvertWSAError(WSAEAFNOSUPPORT);
	if (interp != NULL) {
	    // TODO: better reporting here
	    Tcl_AppendResult(interp, "-type must be one of ...\n",
		    Tcl_PosixError(interp), NULL);
	}
	return NULL;
    }
    return (pdata->CreateClient)(interp, port, host, myaddr,
	    myport, async, pdata->afhint);
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenTcpServer --
 *
 *	Opens a TCP server socket and creates a channel around it.
 *
 * Results:
 *	The channel or NULL if failed.  An error message is returned
 *	in the interpreter on failure.
 *
 * Side effects:
 *	Opens a server socket and creates a new channel.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenTcpServer(
    Tcl_Interp *interp,		/* For error reporting, may be NULL. */
    int port,			/* Port number to open. */
    const char *host,		/* Name of host for binding. */
    Tcl_TcpAcceptProc *acceptProc,
				/* Callback for accepting connections
				 * from new clients. */
    ClientData acceptProcData)	/* Data for the callback. */
{
    /*char portName[TCL_INTEGER_SPACE];

    TclFormatInt(portName, port);
    return Tcl_OpenServerChannel(interp, portName, host, "tcp4",
	    acceptProc, acceptProcData);*/
    return NULL;
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_OpenTcpServer --
 *
 *	Opens a TCP server socket and creates a channel around it.
 *
 * Results:
 *	The channel or NULL if failed.  An error message is returned
 *	in the interpreter on failure.
 *
 * Side effects:
 *	Opens a server socket and creates a new channel.
 *
 *----------------------------------------------------------------------
 */

Tcl_Channel
Tcl_OpenServerChannel(
    Tcl_Interp *interp,		/* For error reporting, may be NULL. */
    const char *port,		/* Port (number|service) to open. */
    const char *host,		/* Name of host for binding. */
    const char *type,
    Tcl_SocketAcceptProc *acceptProc,
				/* Callback for accepting connections
				 * from new clients. */
    ClientData acceptProcData)	/* Data for the callback. */
{
    Tcl_HashEntry *entryPtr;
    WS2ProtocolData *pdata;

    entryPtr = Tcl_FindHashEntry(&netProtocolTbl, type);
    if (entryPtr) pdata = Tcl_GetHashValue(entryPtr);
    if (entryPtr == NULL || pdata == NULL) {
	TclWinConvertWSAError(WSAEAFNOSUPPORT);
	if (interp != NULL) {
	    // TODO: better reporting here
	    Tcl_AppendResult(interp, "-type must be one of ...\n",
		    Tcl_PosixError(interp), NULL);
	}
	return NULL;
    }
    return (pdata->CreateServer)(interp, port, host, acceptProc,
	    acceptProcData, pdata->afhint);
}


/* =================================================================== */
/* ==================== Tcl_Event*Proc procedures ==================== */


/*
 *-----------------------------------------------------------------------
 * IocpEventSetupProc --
 *
 *  Happens before the event loop is to wait in the notifier.
 *
 *-----------------------------------------------------------------------
 */
static void
IocpEventSetupProc (
    ClientData clientData,
    int flags)
{
    ThreadSpecificData *tsdPtr = InitSockets();
    Tcl_Time blockTime = {0, 0};

    if (!(flags & TCL_FILE_EVENTS)) {
	return;
    }

    /*
     * If any ready events exist now, don't let the notifier go into it's
     * wait state.  This function call is very inexpensive.
     */

    if (IocpLLIsNotEmpty(tsdPtr->readySockets) ||
		0 /*TODO: IocpLLIsNotEmpty(tsdPtr->deadSockets)*/) {
	Tcl_SetMaxBlockTime(&blockTime);
    }
}

/*
 *-----------------------------------------------------------------------
 * IocpEventCheckProc --
 *
 *  Happens after the notifier has waited.
 *
 *-----------------------------------------------------------------------
 */
static void
IocpEventCheckProc (
    ClientData clientData,
    int flags)
{
    ThreadSpecificData *tsdPtr = InitSockets();
    SocketInfo *infoPtr;
    SocketEvent *evPtr;
    int evCount;

    if (!(flags & TCL_FILE_EVENTS)) {
	/* Don't be greedy. */
	return;
    }

    /*
     * Sockets that are EOF, but not yet closed, are considered readable.
     * Because Tcl historically requires that EOF channels shall still
     * fire readable and writable events until closed and our alert
     * semantics are such that we'll never get repeat notifications after
     * EOF, we place this poll condition here.
     */

    /* TODO: evCount = IocpLLGetCount(tsdPtr->deadSockets); */

    /*
     * Do we have any jobs to queue?  Take a snapshot of the count as
     * of now.
     */

    evCount = IocpLLGetCount(tsdPtr->readySockets);

    while (evCount--) {
	EnterCriticalSection(&tsdPtr->readySockets->lock);
	infoPtr = IocpLLPopFront(tsdPtr->readySockets,
		IOCP_LL_NOLOCK | IOCP_LL_NODESTROY, 0);
	/*
	 * Flop the markedReady toggle.  This is used to improve event
	 * loop efficiency to avoid unneccesary events being queued into
	 * the readySockets list.
	 */
	if (infoPtr) InterlockedExchange(&infoPtr->markedReady, 0);
	LeaveCriticalSection(&tsdPtr->readySockets->lock);

	/*
	 * Safety check. Somehow the count of what is and what actually
	 * is, is less (!?)..  whatever...  
	 */
	if (!infoPtr) continue;

	/*
	 * The socket isn't ready to be serviced.  accept() in the Tcl
	 * layer hasn't happened yet while reads on the new socket are
	 * coming in or the socket is in the middle of doing an async
	 * close.
	 */
	if (infoPtr->channel == NULL) {
	    continue;
	}

	evPtr = (SocketEvent *) ckalloc(sizeof(SocketEvent));
	evPtr->header.proc = IocpEventProc;
	evPtr->infoPtr = infoPtr;
	Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
    }
}

/*
 *-----------------------------------------------------------------------
 * IocpEventProc --
 *
 *  Tcl's event loop is now servicing this.
 *
 *-----------------------------------------------------------------------
 */
static int
IocpEventProc (
    Tcl_Event *evPtr,		/* Event to service. */
    int flags)			/* Flags that indicate what events to
				 * handle, such as TCL_FILE_EVENTS. */
{
    SocketInfo *infoPtr = ((SocketEvent *)evPtr)->infoPtr;
    int readyMask = 0;

    if (!(flags & TCL_FILE_EVENTS)) {
	/* Don't be greedy. */
	return 0;
    }

    /*
     * If an accept is ready, pop one only.  There might be more,
     * but this would be greedy with regards to the event loop.
     */
    if (infoPtr->readyAccepts != NULL) {
	IocpAcceptOne(infoPtr);
	return 1;
    }

    /*
     * If there is at least one entry on the infoPtr->llPendingRecv list,
     * and the watch mask is set to notify for readable events, the channel
     * is readable.
     */
    if (infoPtr->watchMask & TCL_READABLE &&
	    IocpLLIsNotEmpty(infoPtr->llPendingRecv)) {
	readyMask |= TCL_READABLE;
    }

    /*
     * If the watch mask is set to notify for writable events, and
     * outstanding sends are less than the resource cap allowed for
     * this socket, the channel is writable.
     */
    if (infoPtr->watchMask & TCL_WRITABLE && infoPtr->llPendingRecv
	    && infoPtr->outstandingSends < infoPtr->outstandingSendCap) {
	readyMask |= TCL_WRITABLE;
    }

    if (readyMask) {
	Tcl_NotifyChannel(infoPtr->channel, readyMask);
    } else {
	/* This was a useless queue.  I want to know why! */
	__asm nop;
    }
    return 1;
}

/*
 *-----------------------------------------------------------------------
 * IocpAcceptOne --
 *
 *  Accept one connection from the listening socket.  Repost to the
 *  readySockets list if more are available.  By doing it this way,
 *  incoming connections aren't greedy.
 *
 *-----------------------------------------------------------------------
 */
static void
IocpAcceptOne (SocketInfo *infoPtr)
{
    char channelName[4 + TCL_INTEGER_SPACE];
    AcceptInfo *acptInfo;
    int objc;
    Tcl_Obj **objv, *AddrInfo;

    acptInfo = IocpLLPopFront(infoPtr->readyAccepts, IOCP_LL_NODESTROY, 0);

    if (acptInfo == NULL) {
	/* Don't barf if the counts don't match. */
	return;
    }

    snprintf(channelName, 4 + TCL_INTEGER_SPACE, "sock%lu", acptInfo->clientInfo->socket);
    acptInfo->clientInfo->channel = Tcl_CreateChannel(&IocpStreamChannelType, channelName,
	    (ClientData) acptInfo->clientInfo, (TCL_READABLE | TCL_WRITABLE));
    if (Tcl_SetChannelOption(NULL, acptInfo->clientInfo->channel, "-translation",
	    "auto crlf") == TCL_ERROR) {
	Tcl_Close((Tcl_Interp *) NULL, acptInfo->clientInfo->channel);
	goto error;
    }
    if (Tcl_SetChannelOption(NULL, acptInfo->clientInfo->channel, "-eofchar", "")
	    == TCL_ERROR) {
	Tcl_Close((Tcl_Interp *) NULL, acptInfo->clientInfo->channel);
	goto error;
    }

    /*
     * Invoke the accept callback procedure.
     */

    AddrInfo = acptInfo->clientInfo->proto->DecodeSockAddr(
	    acptInfo->clientInfo, acptInfo->clientInfo->remoteAddr,
	    1 /* noLookup */);
    Tcl_ListObjGetElements(NULL, AddrInfo, &objc, &objv);

    if (infoPtr->acceptProc != NULL) {
	(infoPtr->acceptProc) (infoPtr->acceptProcData,
		acptInfo->clientInfo->channel,
		Tcl_GetString(objv[0]) /* address string */,
		Tcl_GetString(objv[2]) /* port string */);
    }

    Tcl_DecrRefCount(AddrInfo);

error:
    /* TODO: return error info to a trace routine. */

    IocpFree(acptInfo);

    /* Requeue another for the next checkProc iteration if another
     * readyAccepts exists. */
    EnterCriticalSection(&infoPtr->tsdHome->readySockets->lock);
    if (IocpLLIsNotEmpty(infoPtr->readyAccepts)) {
	/*
	 * Flop the markedReady toggle.  This is used to improve event
	 * loop efficiency to avoid unneccesary events being queued into
	 * the readySockets list.
	 */
	if (!InterlockedExchange(&infoPtr->markedReady, 1)) {
	    /* No entry on the ready list.  Insert one. */
	    IocpLLPushBack(infoPtr->tsdHome->readySockets, infoPtr,
		    &infoPtr->node, IOCP_LL_NOLOCK);
	}
    }
    LeaveCriticalSection(&infoPtr->tsdHome->readySockets->lock);
    return;
}

static int
IocpRemovePendingEvents (Tcl_Event *ev, ClientData cData)
{
    SocketInfo *infoPtr = (SocketInfo *) cData;
    SocketEvent *sev = (SocketEvent *) ev;

    if (ev->proc == IocpEventProc && sev->infoPtr == infoPtr) {
	return 1;
    } else {
	return 0;
    }
}

static int
IocpRemoveAllPendingEvents (Tcl_Event *ev, ClientData cData)
{
    if (ev->proc == IocpEventProc) {
	return 1;
    } else {
	return 0;
    }
}

/* =================================================================== */
/* ==================== Tcl_Driver*Proc procedures =================== */

static int
IocpCloseProc (
    ClientData instanceData,	/* The socket to close. */
    Tcl_Interp *interp)		/* Unused. */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;
    int errorCode = 0;
    BufferInfo *bufPtr;

    /* TODO: Tcl convention says a blocking device should wait for
    all data and return an error code (if any). A non-blocking
    device should hard-close.. what to do here? */

    /*
     * The core wants to close channels after the exit handler(!?)
     * Our heap is gone!
     */
    if (initialized) {

	/* Artificially increment the count. */
	InterlockedIncrement(&infoPtr->outstandingOps);

	/* Flip the bit so no new stuff can ever come in again. */
	InterlockedExchange(&infoPtr->markedReady, 1);

	/* Setting this means all returning operations will get
	 * trashed and no new operations are allowed. */
	infoPtr->flags |= IOCP_CLOSING;

	/* Tcl now doesn't recognize us anymore, so don't let this
	 * dangle. */
	infoPtr->channel = NULL;

	/* Remove ourselves from the readySockets list. */
	IocpLLPop(&infoPtr->node, IOCP_LL_NODESTROY);

	/* Remove all events queued in the event loop for this socket. */
	Tcl_DeleteEvents(IocpRemovePendingEvents, infoPtr);

	if (!infoPtr->acceptProc) {
	    /* Queue this client socket up for auto-destroy. */
	    bufPtr = GetBufferObj(infoPtr, 0);
	    PostOverlappedDisconnect(infoPtr, bufPtr);
	} else {
	    SOCKET temp;
	    /* Close this listening socket directly. */
	    infoPtr->flags |= IOCP_CLOSABLE;
	    InterlockedDecrement(&infoPtr->outstandingOps);
	    temp = infoPtr->socket;
	    infoPtr->socket = INVALID_SOCKET;
	    /* Cause all pending AcceptEx calls to return with WSA_OPERATION_ABORTED */
	    closesocket(temp);
	}
    }

    return errorCode;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpClose2Proc --
 *
 *	This function is called by the generic IO level to perform the channel
 *	type specific part of a half-close: namely, a shutdown() on a socket.
 *
 * Results:
 *	0 if successful, the value of errno if failed.
 *
 * Side effects:
 *	Shuts down one side of the socket.
 *
 *----------------------------------------------------------------------
 */

static int
IocpClose2Proc(
    ClientData instanceData,	/* The socket to close. */
    Tcl_Interp *interp,		/* For error reporting. */
    int flags)			/* Flags that indicate which side to close. */
{
    /*
     * Shutdown the OS socket handle.
     */
    switch(flags) {
	case TCL_CLOSE_READ:
	    sd=SD_RECEIVE;
	    break;
	case TCL_CLOSE_WRITE:
	    if (!infoPtr->acceptProc) {
		bufPtr = GetBufferObj(infoPtr, 0);
		PostOverlappedDisconnect(infoPtr, bufPtr);
	    }
	    break;
	default:
	    if (interp) {
		Tcl_AppendResult(interp, "Socket close2proc called bidirectionally", NULL);
	    }
	    return TCL_ERROR;
	}

	if (!infoPtr->acceptProc) {
	    bufPtr = GetBufferObj(infoPtr, 0);
	    PostOverlappedDisconnect(infoPtr, bufPtr);
	} else {
	    SOCKET temp;
	    /* Close this listening socket directly. */
	    infoPtr->flags |= IOCP_CLOSABLE;
	    InterlockedDecrement(&infoPtr->outstandingOps);
	    temp = infoPtr->socket;
	    infoPtr->socket = INVALID_SOCKET;
	    /* Cause all pending AcceptEx calls to return with WSA_OPERATION_ABORTED */
	    closesocket(temp);
	}

    return errorCode;
}

static int
IocpInputProc (
    ClientData instanceData,	/* The socket state. */
    char *buf,			/* Where to store data. */
    int toRead,			/* Maximum number of bytes to read. */
    int *errorCodePtr)		/* Where to store error codes. */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;
    char *bufPos = buf;
    int bytesRead = 0;
    DWORD timeout;
    BufferInfo *bufPtr;
    int done, gotError = 0;
    Tcl_Obj *errorObj;

    *errorCodePtr = 0;

    /* If we are async, don't block on the queue. */
    timeout = (infoPtr->flags & IOCP_ASYNC ? 0 : INFINITE);

    /* Merge in as much as toRead will allow. */

    if ((!(infoPtr->flags & IOCP_ASYNC))
	    || IocpLLIsNotEmpty(infoPtr->llPendingRecv)) {

	while ((bufPtr = IocpLLPopFront(infoPtr->llPendingRecv,
		IOCP_LL_NODESTROY, timeout)) != NULL) {

	    if (FilterSingleOpRecvBuf(infoPtr, bufPtr, bytesRead)) {
		break;
	    }
	    if (FilterPartialRecvBufMerge(infoPtr, bufPtr, &bytesRead,
		    toRead, bufPos)) {
		break;
	    }
	    done = DoRecvBufMerge(infoPtr, bufPtr, &bytesRead,
		    toRead, &bufPos, &gotError);
	    if (gotError) goto error;
	    if (done) break;
	    FreeBufferObj(bufPtr);
	    /* When blocking, only read one. */
	    if (!(infoPtr->flags & IOCP_ASYNC)) break;
	}
	RepostRecvs(infoPtr, toRead);

    } else {
	/* If there's nothing to get, return EWOULDBLOCK. */
	*errorCodePtr = EWOULDBLOCK;
	bytesRead = -1;
    }

    return bytesRead;

error:
    errorObj = Tcl_NewStringObj(Tcl_WinErrMsg(WSAGetLastError()),-1);
    Tcl_SetChannelError(infoPtr->channel, errorObj);
    return -1;
}

static int
IocpInputNotSupProc (
    ClientData instanceData,	/* The socket state. */
    char *buf,			/* Where to store data. */
    int toRead,			/* Maximum number of bytes to read. */
    int *errorCodePtr)		/* Where to store error codes. */
{
    Tcl_SetErrno(EOPNOTSUPP);
    *errorCodePtr = Tcl_GetErrno();
    return -1;
}

static int
FilterPartialRecvBufMerge (
    SocketInfo *infoPtr,
    BufferInfo *bufPtr,
    int *bytesRead,
    int toRead,
    char *bufPos)
{
    BYTE *buffer;
    SIZE_T howMuch = toRead - *bytesRead;

    if ((*bytesRead + (int) bufPtr->used) > toRead) {

	/*
	 * Socket WSABUF is larger than the channel buffer space.  We need
	 * to do a partial copy to the channel buffer and repost the
	 * BufferInfo* back onto the linkedlist for the next read()
	 * operation.
	 */
	if (bufPtr->last) {
	    buffer = bufPtr->last;
	} else {
	    buffer = bufPtr->buf;
	}
	memcpy(bufPos, buffer, howMuch);
	bufPtr->used -= howMuch;
	bufPtr->last = buffer + howMuch;
	*bytesRead += howMuch;
	IocpLLPushFront(infoPtr->llPendingRecv, bufPtr,
		&bufPtr->node, 0);
	return 1;
    }
    return 0;
}

static int
FilterSingleOpRecvBuf (SocketInfo *infoPtr, BufferInfo *bufPtr, int bytesRead)
{
    if (bufPtr->used == 0 && bufPtr->buflen != 0 && bytesRead) {
	
	/*
	 * We have a new EOF or error, yet some bytes have already been
	 * written to the channel buffer within this read() operation.
	 * Push the bufPtr back onto the linkedlist for later. We need
	 * the EOF (or error) as a single operation.
	 */
	IocpLLPushFront(infoPtr->llPendingRecv, bufPtr,
		&bufPtr->node, 0);
	return 1;
    }
    return 0;
}

static int
DoRecvBufMerge (
    SocketInfo *infoPtr,
    BufferInfo *bufPtr,
    int *bytesRead,
    int toRead,
    char **bufPos,
    int *gotError)
{
    *gotError = 0;

    if (bufPtr->WSAerr != NO_ERROR) {
	WSASetLastError(bufPtr->WSAerr);
	FreeBufferObj(bufPtr);
	*gotError = 1;
	return 1;
    } else {
	if (bufPtr->used == 0) {
	    if (bufPtr->buflen != 0) {
		/* got official EOF */
		infoPtr->flags |= IOCP_EOF;
		/* A read value of zero indicates EOF to the generic layer. */
		*bytesRead = 0;
		FreeBufferObj(bufPtr);
		return 1;
	    } else {
		WSABUF buffer;
		DWORD NumberOfBytesRecvd, Flags;

		/*
		 * Got the zero-byte recv alert. Do a non-blocking
		 * and non-posting WSARecv using the channel buffer
		 * directly.
		 */

		if (infoPtr->lastError != NO_ERROR) {

		    /*
		     * A write-side error occured.  Just return EOF,
		     * ignore this bufPtr error and don't call WSARecv.
		     */
		    *bytesRead = 0;
		    infoPtr->flags |= IOCP_EOF;
		    FreeBufferObj(bufPtr);
		    return 1;

		} else {
		    buffer.len = toRead;
		    buffer.buf = *bufPos;
		    Flags = 0;

		    if (WSARecv(infoPtr->socket, &buffer, 1,
			    &NumberOfBytesRecvd, &Flags, 0L, 0L)) {
			*gotError = 1;
			FreeBufferObj(bufPtr);
			return 1;
		    }
		    *bytesRead = NumberOfBytesRecvd;
		    if (NumberOfBytesRecvd == 0) {
			/* got official EOF */
			infoPtr->flags |= IOCP_EOF;
			FreeBufferObj(bufPtr);
			return 1;
		    }
		}
	    }
	} else {
	    BYTE *buffer;
	    if (bufPtr->last) {
		buffer = bufPtr->last;
	    } else {
		buffer = bufPtr->buf;
	    }
	    memcpy(*bufPos, buffer, bufPtr->used);
	    bytesRead += bufPtr->used;
	    *bufPos += bufPtr->used;
	}
    }
    return 0;
}

static void
RepostRecvs (SocketInfo *infoPtr, int chanBufSize)
{
    BufferInfo *newBufPtr;

    /* No more overlapped WSARecv calls needed? */
    if (infoPtr->flags & IOCP_EOF) return;

    if (infoPtr->recvMode == IOCP_RECVMODE_ZERO_BYTE
	    || infoPtr->recvMode == IOCP_RECVMODE_FLOW_CTRL) {
	newBufPtr = GetBufferObj(infoPtr,
		(infoPtr->recvMode == IOCP_RECVMODE_ZERO_BYTE ? 0 : chanBufSize));

	/*
	 * If an immediate error occurs, we can not return it to Tcl now
	 * as this is essentially the "next" packet of delivery. We have
	 * to force post it to the completion port to "read" it later.
	 */
	if (PostOverlappedRecv(infoPtr, newBufPtr, 0 /*useBurst*/,
		1 /*forcepost*/) != NO_ERROR) {
	    FreeBufferObj(newBufPtr);
	}
    } else if (infoPtr->recvMode == IOCP_RECVMODE_BURST_DETECT && infoPtr->needRecvRestart
	    && IocpLLGetCount(infoPtr->llPendingRecv) < infoPtr->outstandingRecvBufferCap) {
	newBufPtr = GetBufferObj(infoPtr, IOCP_RECV_BUFSIZE);

	/*
	 * If an immediate error occurs, we can not return it to Tcl now
	 * as this is essentially the "next" packet of delivery. We have
	 * to force post it to the completion port to "read" it later.
	 */
	if (PostOverlappedRecv(infoPtr, newBufPtr, 1 /*useBurst*/,
		1 /*forcepost*/) != NO_ERROR) {
	    FreeBufferObj(newBufPtr);
	}
	infoPtr->needRecvRestart = 0;
    }
}

static int
IocpOutputProc (
    ClientData instanceData,	/* The socket state. */
    CONST char *buf,		/* Where to get data. */
    int toWrite,		/* Maximum number of bytes to write. */
    int *errorCodePtr)		/* Where to store error codes. */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;
    BufferInfo *bufPtr;
    DWORD result;
    Tcl_Obj *errorObj;

    *errorCodePtr = 0;


    if (TclInExit() || infoPtr->flags & IOCP_CLOSING) {
	*errorCodePtr = ENOTCONN;
	return -1;
    }

    bufPtr = GetBufferObj(infoPtr, toWrite);
    memcpy(bufPtr->buf, buf, toWrite);
    result = PostOverlappedSend(infoPtr, bufPtr);
    if (result == WSAENOBUFS) {
	/* Would have been over the sendcap restriction. */
	FreeBufferObj(bufPtr);
	*errorCodePtr = EWOULDBLOCK;
	return -1;
    } else if (result != NO_ERROR) {
	/* Don't FreeBufferObj(), as it is already queued to the cp, too */
	WSASetLastError(result);
	goto error;
    }

    return toWrite;

error:
    errorObj = Tcl_NewStringObj(Tcl_WinErrMsg(WSAGetLastError()),-1);
    Tcl_SetChannelError(infoPtr->channel, errorObj);
    return -1;
}

static int
IocpOutputNotSupProc (
    ClientData instanceData,	/* The socket state. */
    CONST char *buf,		/* Where to get data. */
    int toWrite,		/* Maximum number of bytes to write. */
    int *errorCodePtr)		/* Where to store error codes. */
{
    Tcl_SetErrno(EOPNOTSUPP);
    *errorCodePtr = Tcl_GetErrno();
    return -1;
}

static int
IocpSetOptionProc (
    ClientData instanceData,	/* Socket state. */
    Tcl_Interp *interp,		/* For error reporting - can be NULL. */
    CONST char *optionName,	/* Name of the option to set. */
    CONST char *value)		/* New value for option. */
{
    SocketInfo *infoPtr;
    SOCKET sock;
    BOOL val = FALSE;
    int Integer, rtn;

    infoPtr = (SocketInfo *) instanceData;
    sock = infoPtr->socket;

    if (!stricmp(optionName, "-keepalive")) {
	if (Tcl_GetBoolean(interp, value, &Integer) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (Integer) val = TRUE;
	rtn = setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE,
		(const char *) &val, sizeof(BOOL));
	if (rtn != 0) {
	    if (interp) {
		Tcl_AppendResult(interp, "couldn't set keepalive socket option: ",
			Tcl_WinError(interp, WSAGetLastError()), NULL);
	    }
	    return TCL_ERROR;
	}
	return TCL_OK;

    } else if (!stricmp(optionName, "-nagle")) {
	if (Tcl_GetBoolean(interp, value, &Integer) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (!Integer) val = TRUE;
	rtn = setsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
		(const char *) &val, sizeof(BOOL));
	if (rtn != 0) {
	    if (interp) {
		Tcl_AppendResult(interp, "couldn't set nagle socket option: ",
			Tcl_WinError(interp, WSAGetLastError()), NULL);
	    }
	    return TCL_ERROR;
	}
	return TCL_OK;

    } else if (strcmp(optionName, "-backlog") == 0 && infoPtr->acceptProc) {
	int i, error = TCL_OK;
	if (Tcl_GetInt(interp, value, &Integer) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (Integer < IOCP_ACCEPT_CAP) {
	    if (interp) {
		char buf[TCL_INTEGER_SPACE];
		TclFormatInt(buf, IOCP_ACCEPT_CAP);
		Tcl_AppendResult(interp,
			"only a positive integer not less than ", buf,
			" is recommended", NULL);
	    }
	    error = TCL_ERROR;
	    if (Integer < 1) {
		return TCL_ERROR;
	    }
	    /* Let an unacceptably low -backlog get set anyways */
	}
	infoPtr->outstandingAcceptCap = Integer;
	/* Now post them in, if outstandingAcceptCap is now larger. */
        for (
	    i = infoPtr->outstandingAccepts;
	    i < infoPtr->outstandingAcceptCap;
	    i++
	) {
	    BufferInfo *bufPtr;
	    bufPtr = GetBufferObj(infoPtr, 0);
	    if (PostOverlappedAccept(infoPtr, bufPtr, 0) != NO_ERROR) {
		/* Oh no, the AcceptEx failed. */
		FreeBufferObj(bufPtr); break;
		/* TODO: add error reporting */
	    }
        }
	return error;

    } else if (strcmp(optionName, "-sendcap") == 0) {
	if (Tcl_GetInt(interp, value, &Integer) != TCL_OK) {
	    return TCL_ERROR;
	}
	if (Integer < 1) {
	    if (interp) {
		Tcl_AppendResult(interp,
			"only a positive integer greater than zero is allowed",
			NULL);
	    }
	    return TCL_ERROR;
	}
	InterlockedExchange(&infoPtr->outstandingSendCap, Integer);
	return TCL_OK;

    } else if (strcmp(optionName, "-recvmode") == 0) {
	CONST char **argv;
	int argc, recvCap, bufferCap;

        if (Tcl_SplitList(interp, value, &argc, &argv) == TCL_ERROR) {
            return TCL_ERROR;
        }

	if (strcmp(argv[0], "zero-byte") == 0) {
	    infoPtr->recvMode = IOCP_RECVMODE_ZERO_BYTE;
	    InterlockedExchange(&infoPtr->outstandingRecvCap, 1);
	    InterlockedExchange(&infoPtr->outstandingRecvBufferCap, 1);
	} else if (strcmp(argv[0], "flow-controlled") == 0) {
	    infoPtr->recvMode = IOCP_RECVMODE_FLOW_CTRL;
	    InterlockedExchange(&infoPtr->outstandingRecvCap, 1);
	    InterlockedExchange(&infoPtr->outstandingRecvBufferCap, 1);
	} else if (strcmp(argv[0], "burst-detection") == 0) {
	    if (argc == 3) {
		if (Tcl_GetInt(interp, argv[1], &recvCap) != TCL_OK) {
		    return TCL_ERROR;
		}
		if (Tcl_GetInt(interp, argv[2], &bufferCap) != TCL_OK) {
		    return TCL_ERROR;
		}
		if (recvCap < 1) {
		    if (interp) {
			Tcl_AppendResult(interp,
			    "only a positive integer greater than zero is "
			    "allowed", NULL);
		    }
		    return TCL_ERROR;
		}
		infoPtr->recvMode = IOCP_RECVMODE_BURST_DETECT;
		InterlockedExchange(&infoPtr->outstandingRecvCap, recvCap);
		InterlockedExchange(&infoPtr->outstandingRecvBufferCap, bufferCap);
	    } else {
		if (interp) {
		    Tcl_AppendResult(interp,
			"burst-detection must be followed by an integer for "
			"the concurrency limit and another integer for the "
			"buffer limit count as a list.", NULL);
		}
		return TCL_ERROR;
	    }
	} else {
	    if (interp) {
		Tcl_AppendResult(interp,
		    "unknown option for -recvmode: must be one of "
		    "zero-byte, flow-controlled or {burst-detection "
		    "<WSARecv_limit> <buffer_limit>}.", NULL);
	    }
	    return TCL_ERROR;
	}

	return TCL_OK;
    }

/* TODO: pass this also to a protocol specific option routine. */

    if (infoPtr->acceptProc) {
	return Tcl_BadChannelOption(interp, optionName,
		"keepalive nagle backlog sendcap recvmode");
    } else {
	return Tcl_BadChannelOption(interp, optionName,
		"keepalive nagle sendcap recvmode");
    }
}

static int
IocpGetOptionProc (
    ClientData instanceData,	/* Socket state. */
    Tcl_Interp *interp,		/* For error reporting - can be NULL */
    CONST char *optionName,	/* Name of the option to
				 * retrieve the value for, or
				 * NULL to get all options and
				 * their values. */
    Tcl_DString *dsPtr)		/* Where to store the computed
				 * value; initialized by caller. */
{
    SocketInfo *infoPtr;
    SOCKET sock;
    int size;
    size_t len = 0;
    char buf[TCL_INTEGER_SPACE];
    Tcl_Obj *AddrInfo;
    int objc, i;
    Tcl_Obj **objv;

    
    infoPtr = (SocketInfo *) instanceData;
    sock = infoPtr->socket;
    if (optionName != (char *) NULL) {
        len = strlen(optionName);
    }

    if (len > 1) {
	if ((optionName[1] == 'e') &&
	    (strncmp(optionName, "-error", len) == 0)) {
	    if (infoPtr->lastError != NO_ERROR) {
		Tcl_DStringAppend(dsPtr, Tcl_WinErrMsg(infoPtr->lastError), -1);
	    }
	    return TCL_OK;
#if _DEBUG   /* for debugging only */
	} else if (strncmp(optionName, "-ops", len) == 0) {
	    TclFormatInt(buf, infoPtr->outstandingOps);
	    Tcl_DStringAppendElement(dsPtr, buf);
	    return TCL_OK;
	} else if (strncmp(optionName, "-ready", len) == 0) {
	    EnterCriticalSection(&infoPtr->tsdHome->readySockets->lock);
	    TclFormatInt(buf, infoPtr->markedReady);
	    LeaveCriticalSection(&infoPtr->tsdHome->readySockets->lock);
	    Tcl_DStringAppendElement(dsPtr, buf);
	    return TCL_OK;
	} else if (strncmp(optionName, "-readable", len) == 0) {
	    if (infoPtr->llPendingRecv != NULL) {
		EnterCriticalSection(&infoPtr->llPendingRecv->lock);
		TclFormatInt(buf, infoPtr->llPendingRecv->lCount);
		LeaveCriticalSection(&infoPtr->llPendingRecv->lock);
		Tcl_DStringAppendElement(dsPtr, buf);
		return TCL_OK;
	    } else {
		if (interp) {
		    Tcl_AppendResult(interp,
			"A listening socket is not readable, ever.", NULL);
		}
		return TCL_ERROR;
	    }
	} else if (strncmp(optionName, "-readyaccepts", len) == 0) {
	    if (infoPtr->readyAccepts != NULL) {
		EnterCriticalSection(&infoPtr->readyAccepts->lock);
		TclFormatInt(buf, infoPtr->readyAccepts->lCount);
		LeaveCriticalSection(&infoPtr->readyAccepts->lock);
		Tcl_DStringAppendElement(dsPtr, buf);
		return TCL_OK;
	    } else {
		if (interp) {
		    Tcl_AppendResult(interp, "Not a listening socket.",
			    NULL);
		}
		return TCL_ERROR;
	    }
#endif
	}
    }

    if ((infoPtr->readyAccepts == NULL) /* not a listening socket */
	    && ((len == 0) || ((len > 1) && (optionName[1] == 'p') &&
            (strncmp(optionName, "-peername", len) == 0))))
    {
        if (infoPtr->remoteAddr == NULL) {
	    size = infoPtr->proto->addrLen;
	    infoPtr->remoteAddr = IocpAlloc(size);
	    if (getpeername(sock, infoPtr->remoteAddr, &size)
		    == SOCKET_ERROR) {
		/*
		 * getpeername failed - but if we were asked for all the
		 * options (len==0), don't flag an error at that point
		 * because it could be an fconfigure request on a server
		 * socket. (which have no peer). {copied from
		 * unix/tclUnixChan.c}
		 */
		if (len) {
		    if (interp) {
			Tcl_AppendResult(interp, "getpeername() failed: ",
				Tcl_WinError(interp, WSAGetLastError()), NULL);
		    }
		    return TCL_ERROR;
		}
	    }
	}
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-peername");
            Tcl_DStringStartSublist(dsPtr);
        }

	AddrInfo = infoPtr->proto->DecodeSockAddr(infoPtr, infoPtr->remoteAddr, 0);
	Tcl_ListObjGetElements(NULL, AddrInfo, &objc, &objv);

	/* Append data as per the protocol type. */
	for (i = 0; i < objc; i++) {
	    Tcl_DStringAppendElement(dsPtr, Tcl_GetString(objv[i]));
	}
	Tcl_DecrRefCount(AddrInfo);

        if (len == 0) {
            Tcl_DStringEndSublist(dsPtr);
        } else {
            return TCL_OK;
        }
    }

    if ((len == 0) ||
            ((len > 1) && (optionName[1] == 's') &&
                    (strncmp(optionName, "-sockname", len) == 0))) {
        if (infoPtr->localAddr == NULL) {
	    size = infoPtr->proto->addrLen;
	    infoPtr->localAddr = IocpAlloc(size);
	    if (getsockname(sock, infoPtr->localAddr, &size)
		    == SOCKET_ERROR) {
		if (interp) {
		    Tcl_AppendResult(interp, "getsockname() failed: ",
			    Tcl_WinError(interp, WSAGetLastError()), NULL);
		}
		return TCL_ERROR;
	    }
	}
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-sockname");
            Tcl_DStringStartSublist(dsPtr);
        }

	AddrInfo = infoPtr->proto->DecodeSockAddr(infoPtr, infoPtr->localAddr, 0);
	Tcl_ListObjGetElements(NULL, AddrInfo, &objc, &objv);

	/* Append data as per the protocol type. */
	for (i = 0; i < objc; i++) {
	    Tcl_DStringAppendElement(dsPtr, Tcl_GetString(objv[i]));
	}
	Tcl_DecrRefCount(AddrInfo);

        if (len == 0) {
            Tcl_DStringEndSublist(dsPtr);
        } else {
            return TCL_OK;
        }
    }

    if (len == 0 || !strncmp(optionName, "-keepalive", len)) {
	int optlen;
	BOOL opt = FALSE;
    
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-keepalive");
        }
	optlen = sizeof(BOOL);
	getsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (char *)&opt,
		&optlen);
	if (opt) {
	    Tcl_DStringAppendElement(dsPtr, "1");
	} else {
	    Tcl_DStringAppendElement(dsPtr, "0");
	}
	if (len > 0) return TCL_OK;
    }

    if (len == 0 || !strncmp(optionName, "-nagle", len)) {
	int optlen;
	BOOL opt = FALSE;
    
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-nagle");
        }
	optlen = sizeof(BOOL);
	getsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char *)&opt,
		&optlen);
	if (opt) {
	    Tcl_DStringAppendElement(dsPtr, "0");
	} else {
	    Tcl_DStringAppendElement(dsPtr, "1");
	}
	if (len > 0) return TCL_OK;
    }

    if (infoPtr->acceptProc) {
	if (len == 0 || !strncmp(optionName, "-backlog", len)) {
	    if (len == 0) {
		Tcl_DStringAppendElement(dsPtr, "-backlog");
		Tcl_DStringStartSublist(dsPtr);
	    }
	    TclFormatInt(buf, infoPtr->outstandingAcceptCap);
	    Tcl_DStringAppendElement(dsPtr, buf);
	    TclFormatInt(buf, infoPtr->outstandingAccepts);
	    Tcl_DStringAppendElement(dsPtr, buf);
	    if (len == 0) {
		Tcl_DStringEndSublist(dsPtr);
	    } else {
		return TCL_OK;
	    }
	}
    }

    if (len == 0 || !strncmp(optionName, "-sendcap", len)) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-sendcap");
            Tcl_DStringStartSublist(dsPtr);
        }
	TclFormatInt(buf, infoPtr->outstandingSendCap);
	Tcl_DStringAppendElement(dsPtr, buf);
	TclFormatInt(buf, infoPtr->outstandingSends);
	Tcl_DStringAppendElement(dsPtr, buf);
        if (len == 0) {
            Tcl_DStringEndSublist(dsPtr);
        } else {
            return TCL_OK;
        }
    }

    if (len == 0 || !strncmp(optionName, "-recvmode", len)) {
        if (len == 0) {
            Tcl_DStringAppendElement(dsPtr, "-recvmode");
        }
	switch (infoPtr->recvMode) {
	    case IOCP_RECVMODE_ZERO_BYTE:
		Tcl_DStringAppendElement(dsPtr, "zero-byte");
		break;
	    case IOCP_RECVMODE_FLOW_CTRL:
		Tcl_DStringAppendElement(dsPtr, "flow-controlled");
		break;
	    case IOCP_RECVMODE_BURST_DETECT:
		if (len == 0) {
		    Tcl_DStringStartSublist(dsPtr);
		}
		Tcl_DStringAppendElement(dsPtr, "burst-detection");
		TclFormatInt(buf, infoPtr->outstandingRecvCap);
		Tcl_DStringAppendElement(dsPtr, buf);
		TclFormatInt(buf, infoPtr->outstandingRecvs);
		Tcl_DStringAppendElement(dsPtr, buf);
		if (len == 0) {
		    Tcl_DStringEndSublist(dsPtr);
		}
		break;
	    default:
		Tcl_Panic("improper enumerator in IocpGetOptionProc");
	}
        if (len != 0) {
            return TCL_OK;
        }
    }

    if (len > 0) {
	if (infoPtr->acceptProc) {
	    return Tcl_BadChannelOption(interp, optionName,
		"peername sockname keepalive nagle backlog sendcap recvmode");
	} else {
	    return Tcl_BadChannelOption(interp, optionName,
		"peername sockname keepalive nagle sendcap recvmode");
	}
    }

    return TCL_OK;
}

static void
IocpWatchProc (
    ClientData instanceData,	/* The socket state. */
    int mask)			/* Events of interest; an OR-ed
				 * combination of TCL_READABLE,
				 * TCL_WRITABLE and TCL_EXCEPTION. */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;

    if (!infoPtr->acceptProc) {
        infoPtr->watchMask = mask;
	if (!mask) {
	    return;
	}
	if (mask & TCL_READABLE
		&& IocpLLIsNotEmpty(infoPtr->llPendingRecv)) {
	    /* Instance is readable, validate the instance is on the
	     * ready list. */
	    IocpZapTclNotifier(infoPtr);
	} else if (mask & TCL_WRITABLE && infoPtr->llPendingRecv
		&& infoPtr->outstandingSends < infoPtr->outstandingSendCap) {
	    /* Instance is writable, validate the instance is on the
	     * ready list. */
	    IocpZapTclNotifier(infoPtr);
	}
    }
}

static int
IocpBlockProc (
    ClientData instanceData,	/* The socket state. */
    int mode)			/* TCL_MODE_BLOCKING or
                                 * TCL_MODE_NONBLOCKING. */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;

    if (!initialized) return 0;

    if (mode == TCL_MODE_NONBLOCKING) {
	infoPtr->flags |= IOCP_ASYNC;
    } else {
	infoPtr->flags &= ~(IOCP_ASYNC);
    }
    return 0;
}

static int
IocpGetHandleProc (
    ClientData instanceData,	/* The socket state. */
    int direction,		/* TCL_READABLE or TCL_WRITABLE */
    ClientData *handlePtr)	/* Where to store the handle.  */
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;

    *handlePtr = (ClientData) infoPtr->socket;
    return TCL_OK;
}

static void
IocpThreadActionProc (ClientData instanceData, int action)
{
    SocketInfo *infoPtr = (SocketInfo *) instanceData;

    if (initialized) {
	/* This lock is to prevent IocpZapTclNotifier() from accessing
	 * infoPtr->tsdHome */
	EnterCriticalSection(&infoPtr->tsdLock);
	switch (action) {
	case TCL_CHANNEL_THREAD_INSERT:
	    infoPtr->tsdHome = InitSockets();
	    break;
	case TCL_CHANNEL_THREAD_REMOVE:
	    /* Unable to turn off reading, therefore don't notify
	     * anyone during the move. */
	    infoPtr->tsdHome = NULL;
	    break;
	}
	LeaveCriticalSection(&infoPtr->tsdLock);
    }
}

/* =================================================================== */
/* ============== Lo-level buffer and state manipulation ============= */

SocketInfo *
NewSocketInfo (SOCKET socket)
{
    SocketInfo *infoPtr;

    /* collect stats */
    InterlockedIncrement(&StatOpenSockets);

    infoPtr = IocpAlloc(sizeof(SocketInfo));
    infoPtr->channel = NULL;
    infoPtr->socket = socket;
    infoPtr->flags = 0;		    /* assume initial blocking state */
    infoPtr->markedReady = 0;
    infoPtr->outstandingOps = 0;	/* Total operations pending */
    infoPtr->outstandingSends = 0;
    infoPtr->outstandingSendCap = IOCP_SEND_CAP;
    infoPtr->outstandingAccepts = 0;
    infoPtr->outstandingAcceptCap = IOCP_ACCEPT_CAP;
    infoPtr->outstandingRecvs = 0;
    infoPtr->outstandingRecvCap = IOCP_RECV_CAP;
    infoPtr->needRecvRestart = 0;
    InitializeCriticalSectionAndSpinCount(&infoPtr->tsdLock, 400);
    infoPtr->recvMode = IOCP_RECVMODE_FLOW_CTRL;
    infoPtr->watchMask = 0;
    infoPtr->readyAccepts = NULL;
    infoPtr->acceptProc = NULL;
    infoPtr->localAddr = NULL;	    /* Local sockaddr. */
    infoPtr->remoteAddr = NULL;	    /* Remote sockaddr. */
    infoPtr->lastError = NO_ERROR;
    infoPtr->node.ll = NULL;
    return infoPtr;
}

void
FreeSocketInfo (SocketInfo *infoPtr)
{
    BufferInfo *bufPtr;

    if (!infoPtr) return;

    /* Remove us from the readySockets list, if on it. */
    IocpLLPop(&infoPtr->node, IOCP_LL_NODESTROY);

    /* Just in case... */
    if (infoPtr->socket != INVALID_SOCKET) {
	closesocket(infoPtr->socket);
    }

    /* collect stats */
    InterlockedDecrement(&StatOpenSockets);

    DeleteCriticalSection(&infoPtr->tsdLock);

    if (infoPtr->localAddr) {
	IocpFree(infoPtr->localAddr);
    }
    if (infoPtr->remoteAddr) {
	IocpFree(infoPtr->remoteAddr);
    }

    if (infoPtr->readyAccepts) {
	AcceptInfo *acptInfo;
	while ((acptInfo = IocpLLPopFront(infoPtr->readyAccepts,
		IOCP_LL_NODESTROY, 0)) != NULL) {
	    /* Recursion, but can't be a server socket.. So this is safe. */
	    FreeSocketInfo(acptInfo->clientInfo);
	    IocpFree(acptInfo);
	}
	IocpLLDestroy(infoPtr->readyAccepts);
    }
    if (infoPtr->llPendingRecv) {
	while ((bufPtr = IocpLLPopFront(infoPtr->llPendingRecv,
		IOCP_LL_NODESTROY, 0)) != NULL) {
	    FreeBufferObj(bufPtr);
	}
	IocpLLDestroy(infoPtr->llPendingRecv);
    }
    IocpFree(infoPtr);
}

BufferInfo *
GetBufferObj (SocketInfo *infoPtr, SIZE_T buflen)
{
    BufferInfo *bufPtr;

    /* Allocate the object. */
    bufPtr = IocpNPPAlloc(sizeof(BufferInfo));
    if (bufPtr == NULL) {
	return NULL;
    }
    /* Allocate the buffer. */
    bufPtr->buf = IocpNPPAlloc(sizeof(BYTE)*buflen);
    if (bufPtr->buf == NULL) {
	IocpNPPFree(bufPtr);
	return NULL;
    }
    bufPtr->socket = INVALID_SOCKET;
    bufPtr->last = NULL;
    bufPtr->buflen = buflen;
    bufPtr->WSAerr = NO_ERROR;
    bufPtr->parent = infoPtr;
    bufPtr->node.ll = NULL;
    return bufPtr;
}

void
FreeBufferObj (BufferInfo *bufPtr)
{
    /* Pop itself off any linked-list it may be on. */
    IocpLLPop(&bufPtr->node, IOCP_LL_NODESTROY);
    /* If we have a socket for AcceptEx(), close it. */
    if (bufPtr->socket != INVALID_SOCKET) {
	closesocket(bufPtr->socket);
    }
    IocpNPPFree(bufPtr->buf);
    IocpNPPFree(bufPtr);
}

SocketInfo *
NewAcceptSockInfo (SOCKET socket, SocketInfo *infoPtr)
{
    SocketInfo *newInfoPtr;

    newInfoPtr = NewSocketInfo(socket);
    if (newInfoPtr == NULL) {
	return NULL;
    }

    /* Initialize some members (partial cloning of the parent). */
    newInfoPtr->proto = infoPtr->proto;
    newInfoPtr->tsdHome = infoPtr->tsdHome;
    newInfoPtr->llPendingRecv = IocpLLCreate();
    InterlockedExchange(&newInfoPtr->outstandingSendCap,
	    infoPtr->outstandingSendCap);
    InterlockedExchange(&newInfoPtr->outstandingRecvCap,
	    infoPtr->outstandingRecvCap);
    newInfoPtr->recvMode = infoPtr->recvMode;

    return newInfoPtr;
}

/*
 *----------------------------------------------------------------------
 * IocpZapTclNotifier --
 *
 *	Wake the notifier.  Only zap the notifier when the notifier is
 *	waiting and this request has not already been made previously.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None known.
 *
 *----------------------------------------------------------------------
 */

static void
IocpZapTclNotifier (SocketInfo *infoPtr)
{
    EnterCriticalSection(&infoPtr->tsdLock);
    /*
     * If we are in the middle of a thread transfer on the channel,
     * infoPtr->tsdHome will be NULL.
     */
    if (infoPtr->tsdHome) {
	EnterCriticalSection(&infoPtr->tsdHome->readySockets->lock);
	if (!InterlockedExchange(&infoPtr->markedReady, 1)) {
	    /* No entry on the ready list.  Insert one. */
	    IocpLLPushBack(infoPtr->tsdHome->readySockets, infoPtr,
		    &infoPtr->node, IOCP_LL_NOLOCK);
	}
	LeaveCriticalSection(&infoPtr->tsdHome->readySockets->lock);
	/* This is safe to call from any thread. */
	Tcl_ThreadAlert(infoPtr->tsdHome->threadId);
    }
    LeaveCriticalSection(&infoPtr->tsdLock);
}

/* takes buffer ownership */

static void
IocpAlertToTclNewAccept (
    SocketInfo *infoPtr,
    SocketInfo *newClient)
{
    AcceptInfo *acptInfo;

    acptInfo = IocpAlloc(sizeof(AcceptInfo));
    if (acptInfo == NULL) {
	return;
    }

    memcpy(&acptInfo->local, newClient->localAddr,
	    newClient->proto->addrLen);
    acptInfo->localLen = newClient->proto->addrLen;
    memcpy(&acptInfo->remote, newClient->remoteAddr,
	    newClient->proto->addrLen);
    acptInfo->remoteLen = newClient->proto->addrLen;
    acptInfo->clientInfo = newClient;

    /*
     * Queue this accept's data into the listening channel's info block.
     */

    IocpLLPushBack(infoPtr->readyAccepts, acptInfo, &acptInfo->node, 0);

    /*
     * Let IocpCheckProc() know this channel has an accept ready
     * that needs servicing.
     */
    IocpZapTclNotifier(infoPtr);
}

static void
IocpPushRecvAlertToTcl(SocketInfo *infoPtr, BufferInfo *bufPtr)
{
    /* (takes buffer ownership) */
    IocpLLPushBack(infoPtr->llPendingRecv, bufPtr,
	    &bufPtr->node, 0);

    /*
     * Let IocpCheckProc() know this new channel has a ready
     * event (a recv) that needs servicing.  That is, if Tcl
     * is interested in knowing about it.
     */
    if (infoPtr->watchMask & TCL_READABLE) {
	IocpZapTclNotifier(infoPtr);
    }
}

DWORD
PostOverlappedAccept (
    SocketInfo *infoPtr,
    BufferInfo *bufPtr,
    int useBurst)
{
    DWORD bytes, WSAerr;
    int rc;
    SIZE_T buflen, addr_storage;

    if (infoPtr->flags & IOCP_CLOSING) return WSAENOTCONN;

    /* Recursion limit */
    if (InterlockedIncrement(&infoPtr->outstandingAccepts)
	    > infoPtr->outstandingAcceptCap) {
	InterlockedDecrement(&infoPtr->outstandingAccepts);
	/* Best choice I could think of for an error value. */
	return WSAENOBUFS;
    }

    bufPtr->operation = OP_ACCEPT;
    buflen = bufPtr->buflen;
    addr_storage = infoPtr->proto->addrLen + 16;

    /*
     * Create a ready client socket of the same type for a future
     * incoming connection.
     */

    bufPtr->socket = WSASocket(infoPtr->proto->af,
	    infoPtr->proto->type, infoPtr->proto->protocol, NULL, 0,
	    WSA_FLAG_OVERLAPPED);

    if (bufPtr->socket == INVALID_SOCKET) {
	return WSAENOTSOCK;
    }

    /*
     * Realloc for the extra needed addr storage space.
     */
    bufPtr->buf = IocpNPPReAlloc(bufPtr->buf, bufPtr->buflen +
	    (addr_storage * 2));
    bufPtr->buflen += (addr_storage * 2);

    /*
     * Increment the outstanding overlapped count for this socket and put
     * the buffer on the pending accepts list.  We need to do this before
     * the operation because it might complete instead of posting.
     */
    
    InterlockedIncrement(&infoPtr->outstandingOps);

    /*
     * Use the special function for overlapped accept() that is provided
     * by the LSP of this socket type.
     */

    rc = infoPtr->proto->_AcceptEx(infoPtr->socket, bufPtr->socket,
	    bufPtr->buf, bufPtr->buflen - (addr_storage * 2),
	    addr_storage, addr_storage, &bytes, &bufPtr->ol);

    if (rc == FALSE) {
	if ((WSAerr = WSAGetLastError()) != WSA_IO_PENDING) {
	    InterlockedDecrement(&infoPtr->outstandingOps);
	    InterlockedDecrement(&infoPtr->outstandingAccepts);
	    bufPtr->WSAerr = WSAerr;
	    return WSAerr;
	}
    } else if (useBurst) {
	/*
	 * Tested under extreme listening socket abuse it was found that
	 * this logic condition is never met.  AcceptEx _never_ completes
	 * immediately.  It always returns WSA_IO_PENDING.  Too bad,
	 * as this was looking like a good way to detect and handle burst
	 * conditions.
	 */

	BufferInfo *newBufPtr;

	/*
	 * The AcceptEx() has completed now, and was posted to the port.
	 * Keep giving more AcceptEx() calls to drain the internal
	 * backlog.  Why should we wait for the time when the completion
	 * routine is run if we know the listening socket can take another
	 * right now?  IOW, keep recursing until the WSA_IO_PENDING 
	 * condition is achieved.
	 */

	newBufPtr = GetBufferObj(infoPtr, buflen);
	if (PostOverlappedAccept(infoPtr, newBufPtr, 1) != NO_ERROR) {
	    FreeBufferObj(newBufPtr);
	}
    }

    return NO_ERROR;
}

/*
 * A NO_ERROR return indicates the WSARecv operation is pending, or 
 * if an error occurs that the bufPtr was posted to the port.
 */

DWORD
PostOverlappedRecv (
    SocketInfo *infoPtr,
    BufferInfo *bufPtr,
    int useBurst,
    int ForcePostOnError)
{
    WSABUF wbuf;
    DWORD bytes = 0, flags, WSAerr;
    int rc;

    bufPtr->WSAerr = NO_ERROR;

    if (infoPtr->flags & IOCP_EOF || infoPtr->flags & IOCP_CLOSING)
	    return WSAENOTCONN;

    /* Recursion limit */
    if (InterlockedIncrement(&infoPtr->outstandingRecvs)
	    > infoPtr->outstandingRecvCap) {
	InterlockedDecrement(&infoPtr->outstandingRecvs);
	/* Best choice I could think of for an error value. */
	return WSAENOBUFS;
    }

    bufPtr->operation = OP_READ;
    wbuf.buf = bufPtr->buf;
    wbuf.len = bufPtr->buflen;
    flags = 0;

    /*
     * Increment the outstanding overlapped count for this socket.
     */

    InterlockedIncrement(&infoPtr->outstandingOps);

    if (infoPtr->proto->type == SOCK_STREAM) {
	rc = WSARecv(infoPtr->socket, &wbuf, 1, &bytes, &flags,
		&bufPtr->ol, NULL);
    } else {
	rc = WSARecvFrom(infoPtr->socket, &wbuf, 1, &bytes,
		&flags, (LPSOCKADDR)&bufPtr->addr, &infoPtr->proto->addrLen,
		&bufPtr->ol, NULL);
    }

    /*
     * There are three states that can happen here:
     *
     * 1) WSARecv returns zero when the operation has completed
     *	  immediately and the completion is queued to the port (behind
     *	  us now).
     * 2) WSARecv returns SOCKET_ERROR with WSAGetLastError() returning
     *	  WSA_IO_PENDING to indicate the operation was succesfully
     *	  initiated and will complete at a later time (and possibly
     *	  complete with an error or not).
     * 3) WSARecv returns SOCKET_ERROR with WSAGetLastError() returning
     *	  any other WSAGetLastError() code to indicate the operation was
     *	  NOT succesfully initiated and completion will NOT occur.
     */

    if (rc == SOCKET_ERROR) {
	if ((WSAerr = WSAGetLastError()) != WSA_IO_PENDING) {
	    bufPtr->WSAerr = WSAerr;
	    if (ForcePostOnError) {
		PostQueuedCompletionStatus(IocpSubSystem.port, 0,
			(ULONG_PTR) infoPtr, &bufPtr->ol);
		/* We can not process the error now, but is posted, so don't return an error. */
		return NO_ERROR;
	    } else {
		InterlockedDecrement(&infoPtr->outstandingOps);
		InterlockedDecrement(&infoPtr->outstandingRecvs);
		/* return the error. */
		return WSAerr;
	    }
	}
    } else if (bytes > 0 && useBurst) {
	BufferInfo *newBufPtr;

	/*
	 * The WSARecv(From) has completed now, *AND* is posted to the
	 * port.  Keep giving more WSARecv(From) calls to drain the
	 * internal buffer (AFD.sys).  Why should we wait for the time
	 * when the completion routine is run if we know the connected
	 * socket can take another right now?  IOW, keep recursing until
	 * the WSA_IO_PENDING condition is achieved.
	 * 
	 * The only drawback to this is the amount of outstanding calls
	 * will increase.  There is no method for coming out of a burst
	 * condition to return the count to normal.  This shouldn't be
	 * an issue with short lived sockets -- only ones with a long
	 * lifetime.
	 */

	newBufPtr = GetBufferObj(infoPtr, wbuf.len);
	if (PostOverlappedRecv(infoPtr, newBufPtr, 1 /*useBurst */, 1 /*forcepost*/)) {
	    /*
	     * simple states for burstCap and !connected shall be
	     * ignored and the buffer recycled.
	     */
	    FreeBufferObj(newBufPtr);
	}
    }

    return NO_ERROR;
}

DWORD
PostOverlappedSend (SocketInfo *infoPtr, BufferInfo *bufPtr)
{
    WSABUF wbuf;
    DWORD bytes = 0, WSAerr;
    int rc;

    if (infoPtr->flags & IOCP_EOF || infoPtr->flags & IOCP_CLOSING)
	    return WSAENOTCONN;

    bufPtr->operation = OP_WRITE;
    wbuf.buf = bufPtr->buf;
    wbuf.len = bufPtr->buflen;

    /* Recursion limit */
    if (InterlockedIncrement(&infoPtr->outstandingSends)
	    > infoPtr->outstandingSendCap) {
	InterlockedDecrement(&infoPtr->outstandingSends);
	/* Best choice I could think of for an error value. */
	return WSAENOBUFS;
    }

    /*
     * Increment the outstanding overlapped counts for this socket.
     */

    InterlockedIncrement(&infoPtr->outstandingOps);

    if (infoPtr->proto->type == SOCK_STREAM) {
	rc = WSASend(infoPtr->socket, &wbuf, 1, &bytes, 0,
		&bufPtr->ol, NULL);
    } else {
	rc = WSASendTo(infoPtr->socket, &wbuf, 1, &bytes, 0,
                (LPSOCKADDR)&bufPtr->addr, infoPtr->proto->addrLen,
		&bufPtr->ol, NULL);
    }

    if (rc == SOCKET_ERROR) {
	if ((WSAerr = WSAGetLastError()) != WSA_IO_PENDING) {
	    bufPtr->WSAerr = WSAerr;

	    /*
	     * Eventhough we know about the error now, post this to the
	     * port manually, too.  We need to force EOF on the read side
	     * as the generic layer needs a little help to know that both
	     * sides of our bidirectional channel are now dead because of
	     * this write side error.
	     */

	    PostQueuedCompletionStatus(IocpSubSystem.port, 0,
		(ULONG_PTR) infoPtr, &bufPtr->ol);
	    return WSAerr;
	}
    } else {
	/*
	 * The WSASend/To completed now and is queued to the port.
	 */
	__asm nop;
    }

    return NO_ERROR;
}

static DWORD
PostOverlappedDisconnect (SocketInfo *infoPtr, BufferInfo *bufPtr)
{
    BOOL rc;
    DWORD WSAerr;

    /*
     * Increment the outstanding overlapped count for this socket.
     */
    InterlockedIncrement(&infoPtr->outstandingOps);

    bufPtr->operation = OP_DISCONNECT;

    rc = infoPtr->proto->_DisconnectEx(infoPtr->socket, &bufPtr->ol,
	    0 /*TF_REUSE_SOCKET*/, 0);

    if (rc == FALSE) {
	if ((WSAerr = WSAGetLastError()) != WSA_IO_PENDING) {
	    bufPtr->WSAerr = WSAerr;

	    /*
	     * Eventhough we know about the error now, post this to the
	     * port manually, anyways.
	     */

	    PostQueuedCompletionStatus(IocpSubSystem.port, 0,
		(ULONG_PTR) infoPtr, &bufPtr->ol);
	    return NO_ERROR;
	}
    } else {
	/*
	 * The DisconnectEx completed now and is queued to the port.
	 */
	__asm nop;
    }

    return NO_ERROR;
}

DWORD
PostOverlappedQOS (SocketInfo *infoPtr, BufferInfo *bufPtr)
{
    int rc;
    DWORD bytes = 0, WSAerr;

    /*
     * Increment the outstanding overlapped count for this socket.
     */
    InterlockedIncrement(&infoPtr->outstandingOps);
    bufPtr->operation = OP_QOS;

    rc = WSAIoctl(infoPtr->socket, SIO_GET_QOS, NULL, 0,
	    bufPtr->buf, bufPtr->buflen, &bytes, &bufPtr->ol, NULL);

    if (rc == SOCKET_ERROR) {
	if ((WSAerr = WSAGetLastError()) != WSA_IO_PENDING) {
	    /*
	     * Eventhough we know about the error now, post this to the
	     * port manually, anyways.
	     */

	    bufPtr->WSAerr = WSAerr;
	    PostQueuedCompletionStatus(IocpSubSystem.port, 0,
		(ULONG_PTR) infoPtr, &bufPtr->ol);
	}
    } else {
	/*
	 * The WSAIoctl completed now and is queued to the port.
	 */
	__asm nop;
    }

    return NO_ERROR;
}


/* =================================================================== */
/* ================== Lo-level Completion handler ==================== */


/*
 *----------------------------------------------------------------------
 * CompletionThread --
 *
 *	The "main" for the I/O handling thread.  Only one thread is used.
 *
 * Results:
 *
 *	None.  Returns when the completion port is sent a completion
 *	notification with a NULL key by the exit handler
 *	(IocpExitHandler).
 *
 * Side effects:
 *
 *	Without direct interaction from Tcl, incoming accepts will be
 *	accepted and receives, received.  The results of the operations
 *	are posted and tcl will service them when the event loop is
 *	ready to.  Winsock is never left "dangling" on operations.
 *
 *----------------------------------------------------------------------
 */

static DWORD WINAPI
CompletionThreadProc (LPVOID lpParam)
{
    CompletionPortInfo *cpinfo = (CompletionPortInfo *)lpParam;
    SocketInfo *infoPtr;
    BufferInfo *bufPtr;
    OVERLAPPED *ol;
    DWORD bytes, flags, WSAerr, error = NO_ERROR;
    BOOL ok;

#ifdef _DEBUG
#else
    __try {
#endif
again:
	WSAerr = NO_ERROR;
	flags = 0;

	ok = GetQueuedCompletionStatus(cpinfo->port, &bytes,
		(PULONG_PTR) &infoPtr, &ol, INFINITE);

	if (ok && !infoPtr) {
	    /* A NULL key indicates closure time for this thread. */
#ifdef _DEBUG
	    return error;
#else
	    __leave;
#endif
	}

	/*
	 * Use the pointer to the overlapped structure and derive from it
	 * the top of the parent BufferInfo structure it sits in.  If the
	 * position of the overlapped structure moves around within the
	 * BufferInfo structure declaration, this logic does _not_ need
	 * to be modified.
	 */

	bufPtr = CONTAINING_RECORD(ol, BufferInfo, ol);

	if (!ok) {
	    /*
	     * If GetQueuedCompletionStatus() returned a failure on
	     * the operation, call WSAGetOverlappedResult() to
	     * translate the error into a Winsock error code.
	     */

	    ok = WSAGetOverlappedResult(infoPtr->socket,
		    ol, &bytes, FALSE, &flags);

	    if (!ok) {
		WSAerr = WSAGetLastError();
	    }
	}

	/* Go handle the IO operation. */
	HandleIo(infoPtr, bufPtr, cpinfo->port, bytes, WSAerr, flags);
	goto again;
#ifdef _DEBUG
#else
    }
    __except (error = GetExceptionCode(), EXCEPTION_EXECUTE_HANDLER) {
	Tcl_Panic("Big ERROR!  IOCP Completion thread died with exception"
		" code: %#x\n", error);
    }

    return error;
#endif
}

/*
 *----------------------------------------------------------------------
 * HandleIo --
 *
 *	Has all the logic for what to do with a socket "event".
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Either deletes the buffer handed to it, or processes it.
 *
 *----------------------------------------------------------------------
 */

static void
HandleIo (
    register SocketInfo *infoPtr,
    register BufferInfo *bufPtr,
    HANDLE CompPort,
    DWORD bytes,
    DWORD WSAerr,
    DWORD flags)
{
    register SocketInfo *newInfoPtr;
    register BufferInfo *newBufPtr;
    register int i;
    SOCKADDR *local, *remote;
    SIZE_T addr_storage;
    int localLen, remoteLen;


    if (WSAerr == WSA_OPERATION_ABORTED) {
	/* Reclaim cancelled overlapped buffer objects. */
        FreeBufferObj(bufPtr);
	goto done;
    }

    bufPtr->used = bytes;
    /* An error stored in the buffer object takes precedence. */
    if (bufPtr->WSAerr == NO_ERROR) {
	bufPtr->WSAerr = WSAerr;
    }

    switch (bufPtr->operation) {
    case OP_ACCEPT:

	/*
	 * Decrement the count of pending accepts from the total.
	 */

	InterlockedDecrement(&infoPtr->outstandingAccepts);

	if (bufPtr->WSAerr == NO_ERROR) {
	    addr_storage = infoPtr->proto->addrLen + 16;

	    /*
	     * Get the address information from the decoder routine
	     * specific to this socket's Layered Service Provider.
	     */

	    infoPtr->proto->_GetAcceptExSockaddrs(bufPtr->buf,
		    bufPtr->buflen - (addr_storage * 2), addr_storage,
		    addr_storage, &local, &localLen, &remote,
		    &remoteLen);

	    setsockopt(bufPtr->socket, SOL_SOCKET,
		    SO_UPDATE_ACCEPT_CONTEXT, (char *)&infoPtr->socket,
		    sizeof(SOCKET));

	    /*
	     * Get a new SocketInfo for the new client connection.
	     */

	    newInfoPtr = NewAcceptSockInfo(bufPtr->socket, infoPtr);

	    /*
	     * Set the socket to invalid in the buffer so it won't be
	     * closed when the buffer is reclaimed.
	     */

	    bufPtr->socket = INVALID_SOCKET;

	    /*
	     * Save the remote and local SOCKADDRs to its SocketInfo
	     * struct.
	     */

	    newInfoPtr->localAddr = IocpAlloc(localLen);
	    memcpy(newInfoPtr->localAddr, local, localLen);
	    newInfoPtr->remoteAddr = IocpAlloc(remoteLen);
	    memcpy(newInfoPtr->remoteAddr, remote, remoteLen);

	    /* Associate the new socket to our completion port. */
	    CreateIoCompletionPort((HANDLE) newInfoPtr->socket, CompPort,
		    (ULONG_PTR) newInfoPtr, 0);

	    /* post IOCP_INITIAL_RECV_COUNT recvs. */
	    for(i=0; i < IOCP_INITIAL_RECV_COUNT ;i++) {
		newBufPtr = GetBufferObj(newInfoPtr,
			(infoPtr->recvMode == IOCP_RECVMODE_ZERO_BYTE ? 0
			: IOCP_RECV_BUFSIZE));
		if ((WSAerr = PostOverlappedRecv(newInfoPtr, newBufPtr,
			0 /*useburst*/, 0 /*forcepost*/)) != NO_ERROR) {
		    /*
		     * The new connection is not valid.  Do not alert
		     * Tcl about this new dud connection.  Clean it
		     * up ourselves.
		     */
		    newInfoPtr->flags |= IOCP_CLOSING;
		    PostOverlappedDisconnect(newInfoPtr, newBufPtr);
		    goto replace;
		}
	    }

	    /* Alert Tcl to this new connection. */
	    IocpAlertToTclNewAccept(infoPtr, newInfoPtr);

	    if (bytes > 0) {
		/* Only if we asked for AcceptEx to give us an initial
		 * recv with the accept. */
		IocpPushRecvAlertToTcl(newInfoPtr, bufPtr);
	    } else {
		/* No data received from AcceptEx(). */
		FreeBufferObj(bufPtr);
	    }

	} else if (bufPtr->WSAerr == WSA_OPERATION_ABORTED ||
		bufPtr->WSAerr == WSAENOTSOCK) {
	    /* The operation was cancelled.  The listening socket must
	     * be closing.  Do NOT replace this returning AcceptEx. */
	    FreeBufferObj(bufPtr);
	    break;

	} else if (bufPtr->WSAerr == WSAENOBUFS) {
	    /*
	     * No more space! The pending limit has been reached.
	     * Decrement the asking cap by one.
	     */

	    InterlockedDecrement(&infoPtr->outstandingAcceptCap);
	    FreeBufferObj(bufPtr);
	    break;

	} else {
	    /*
	     * Possible spoofed SYN flood in progress. We WANT this
	     * returning AcceptEx that had an error to be replaced.
	     * An AcceptEx can fail with the same errors as ConnectEx,
	     * believe it or not!  Some of the errors sampled are:
	     *
	     * WSAEHOSTUNREACH, WSAETIMEDOUT, WSAENETUNREACH
	     */
	    InterlockedIncrement(&StatFailedAcceptExCalls);
	    FreeBufferObj(bufPtr);
	}

replace:
	/*
	 * Post another new AcceptEx() to replace this one that just
	 * completed.
	 */

	newBufPtr = GetBufferObj(infoPtr, 0);
	if (PostOverlappedAccept(infoPtr, newBufPtr, 0) != NO_ERROR) {

	    /*
	     * Oh no, the AcceptEx failed.  There is no way to return an
	     * error for this condition.  Tcl has no failure aspect for
	     * listening sockets.  This Just shouldn't have happened.
	     */
	    FreeBufferObj(newBufPtr);
	    InterlockedIncrement(&StatFailedReplacementAcceptExCalls);
	}
	break;

    case OP_READ:

	/* Decrement the count of pending recvs from the total. */
	InterlockedDecrement(&infoPtr->outstandingRecvs);

	if (bytes > 0) {
	    /*
	     * Don't replace this buffer if we hit the cap.  Not until the
	     * buffers get consumed will the receiving be restarted.
	     */

	    if (infoPtr->recvMode == IOCP_RECVMODE_BURST_DETECT) {
		if (IocpLLGetCount(infoPtr->llPendingRecv)
			< infoPtr->outstandingRecvBufferCap) {

		    /*
		     * Create a new buffer object to replace the one that
		     * just came in, but use the hard-coded size of
		     * IOCP_RECV_BUFSIZE.
		     */

		    newBufPtr = GetBufferObj(infoPtr, IOCP_RECV_BUFSIZE);
		    if (PostOverlappedRecv(infoPtr, newBufPtr,
			    1 /*useburst*/, 1 /*forcepost*/) != NO_ERROR) {
			FreeBufferObj(newBufPtr);
		    }
		} else {
		    infoPtr->needRecvRestart = 1;
		}
	    }

	} else if (infoPtr->flags & IOCP_CLOSING) {
	    infoPtr->flags |= IOCP_CLOSABLE;
	    FreeBufferObj(bufPtr);
	    break;

	} else if (bufPtr->WSAerr == WSAENOBUFS) {
	    /*
	     * No more space! The pending limit has been reached.
	     * Decrement the asking cap by one.
	     */

	    InterlockedDecrement(&infoPtr->outstandingRecvCap);
	    FreeBufferObj(bufPtr);
	    break;
	}

	/* Takes buffer ownership. */
	IocpPushRecvAlertToTcl(infoPtr, bufPtr);

	break;

    case OP_WRITE:

	/*
	 * Decrement the count of pending sends from the total.
	 */

	InterlockedDecrement(&infoPtr->outstandingSends);

	if (infoPtr->flags & IOCP_CLOSING) {
	    FreeBufferObj(bufPtr);
	    break;
	}

	if (bufPtr->WSAerr != NO_ERROR && bufPtr->WSAerr != WSAENOBUFS
		&& infoPtr->llPendingRecv) {

	    infoPtr->lastError = bufPtr->WSAerr;

	    /* Errors are writable events too. */
	    IocpZapTclNotifier(infoPtr);


	} else if (infoPtr->watchMask & TCL_WRITABLE &&
		infoPtr->outstandingSends < infoPtr->outstandingSendCap) {

	    if (bufPtr->WSAerr == WSAENOBUFS) {
		/*
		 * No more space! The pending limit has been reached.
		 * Decrement the asking cap by one.
		 */

		InterlockedDecrement(&infoPtr->outstandingSendCap);
	    } else {
		/* can write more. */
		IocpZapTclNotifier(infoPtr);
	    }
	}
	FreeBufferObj(bufPtr);
	break;

    case OP_CONNECT:

	infoPtr->llPendingRecv = IocpLLCreate();

	if (bufPtr->WSAerr != NO_ERROR) {
	    infoPtr->lastError = bufPtr->WSAerr;
	    newBufPtr = GetBufferObj(infoPtr, 1);
	    newBufPtr->WSAerr = bufPtr->WSAerr;
	    /* Force EOF. */
	    IocpPushRecvAlertToTcl(infoPtr, newBufPtr);
	} else {
	    setsockopt(infoPtr->socket, SOL_SOCKET,
		    SO_UPDATE_CONNECT_CONTEXT, NULL, 0);

	    /* post IOCP_INITIAL_RECV_COUNT recvs. */
	    for(i=0; i < IOCP_INITIAL_RECV_COUNT ;i++) {
		newBufPtr = GetBufferObj(infoPtr,
			(infoPtr->recvMode == IOCP_RECVMODE_ZERO_BYTE ? 0
			: IOCP_RECV_BUFSIZE));
		if (PostOverlappedRecv(infoPtr, newBufPtr, 0 /*useburst*/,
			1 /*forcepost*/) != NO_ERROR) {
		    FreeBufferObj(newBufPtr);
		    break;
		}
	    }
	    IocpZapTclNotifier(infoPtr);
	}
	FreeBufferObj(bufPtr);
	break;

    case OP_DISCONNECT:
	/* remove the extra ref count. */
	InterlockedDecrement(&infoPtr->outstandingOps);
	infoPtr->flags |= IOCP_CLOSABLE;
	FreeBufferObj(bufPtr);
	break;

    case OP_QOS: {
	/* TODO: make this do something useful. */
	QOS *stuff = (QOS *) bufPtr->buf;
	FreeBufferObj(bufPtr);
	break;
	}

    case OP_TRANSMIT:
    case OP_LOOKUP:
    case OP_IOCTL:
	/* For future use. */
	break;
    }

done:
    if (InterlockedDecrement(&infoPtr->outstandingOps) <= 0
	    && infoPtr->flags & IOCP_CLOSABLE) {
	/* This is the last operation. */
	FreeSocketInfo(infoPtr);
    }
}


/* =================================================================== */
/* ====================== Private memory heap ======================== */

/* general pool */


__inline LPVOID
IocpAlloc (SIZE_T size)
{
    LPVOID p;
    p = HeapAlloc(IocpSubSystem.heap, HEAP_ZERO_MEMORY, size);
    if (p) InterlockedExchangeAdd(&StatGeneralBytesInUse, size);
    return p;
}

__inline LPVOID
IocpReAlloc (LPVOID block, SIZE_T size)
{
    LPVOID p;
    SIZE_T oldSize;
    oldSize = HeapSize(IocpSubSystem.heap, 0, block);
    p = HeapReAlloc(IocpSubSystem.heap, HEAP_ZERO_MEMORY, block, size);
    if (p) InterlockedExchangeAdd(&StatGeneralBytesInUse, ((LONG)size - oldSize));
    return p;
}

__inline BOOL
IocpFree (LPVOID block)
{
    BOOL code;
    SIZE_T oldSize;
    oldSize = HeapSize(IocpSubSystem.heap, 0, block);
    code = HeapFree(IocpSubSystem.heap, 0, block);
    if (code) InterlockedExchangeAdd(&StatGeneralBytesInUse, -((LONG)oldSize));
    return code;
}

/* special pool */

__inline LPVOID
IocpNPPAlloc (SIZE_T size)
{
    LPVOID p;
    p = HeapAlloc(IocpSubSystem.NPPheap, HEAP_ZERO_MEMORY, size);
    if (p) InterlockedExchangeAdd(&StatSpecialBytesInUse, size);
    return p;
}

__inline LPVOID
IocpNPPReAlloc (LPVOID block, SIZE_T size)
{
    LPVOID p;
    SIZE_T oldSize;
    oldSize = HeapSize(IocpSubSystem.NPPheap, 0, block);
    p = HeapReAlloc(IocpSubSystem.NPPheap, HEAP_ZERO_MEMORY, block, size);
    if (p) InterlockedExchangeAdd(&StatSpecialBytesInUse, ((LONG)size - oldSize));
    return p;
}

__inline BOOL
IocpNPPFree (LPVOID block)
{
    BOOL code;
    SIZE_T oldSize;
    oldSize = HeapSize(IocpSubSystem.NPPheap, 0, block);
    code = HeapFree(IocpSubSystem.NPPheap, 0, block);
    if (code) InterlockedExchangeAdd(&StatSpecialBytesInUse, -((LONG)oldSize));
    return code;
}


/* =================================================================== */
/* =================== Protocol neutral procedures =================== */


/*
 *-----------------------------------------------------------------------
 *
 * IocpInitProtocolData --
 *
 *	This function initializes the WS2ProtocolData struct.
 *
 * Results:
 *	nothing.
 *
 * Side effects:
 *	Fills in the WS2ProtocolData structure, if uninitialized.
 *
 *-----------------------------------------------------------------------
 */

void
IocpInitProtocolData (SOCKET sock, WS2ProtocolData *pdata)
{
    DWORD bytes;

    /* is it already cached? */
    if (pdata->_AcceptEx == NULL) {
	/* Get the LSP specific functions. */
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&AcceptExGuid, sizeof(GUID),
		&pdata->_AcceptEx,
		sizeof(pdata->_AcceptEx),
		&bytes, NULL, NULL);
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&GetAcceptExSockaddrsGuid, sizeof(GUID),
		&pdata->_GetAcceptExSockaddrs,
		sizeof(pdata->_GetAcceptExSockaddrs),
		&bytes, NULL, NULL);
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&ConnectExGuid, sizeof(GUID),
		&pdata->_ConnectEx,
		sizeof(pdata->_ConnectEx),
		&bytes, NULL, NULL);
	if (pdata->_ConnectEx == NULL) {
	    /* Use our lame Win2K/NT4 emulation for this. */
	    pdata->_ConnectEx = OurConnectEx;
	}
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&DisconnectExGuid, sizeof(GUID),
		&pdata->_DisconnectEx,
		sizeof(pdata->_DisconnectEx),
		&bytes, NULL, NULL);
	if (pdata->_DisconnectEx == NULL) {
	    /* Use our lame Win2K/NT4 emulation for this. */
	    pdata->_DisconnectEx = OurDisconnectEx;
	}
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&TransmitFileGuid, sizeof(GUID),
		&pdata->_TransmitFile,
		sizeof(pdata->_TransmitFile),
		&bytes, NULL, NULL);
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&TransmitPacketsGuid, sizeof(GUID),
		&pdata->_TransmitPackets,
		sizeof(pdata->_TransmitPackets),
		&bytes, NULL, NULL);
	if (pdata->_TransmitPackets == NULL) {
	    /* There is no Win2K/NT4 emulation for this. */
	    pdata->_TransmitPackets = NULL;
	}
        WSAIoctl(sock, SIO_GET_EXTENSION_FUNCTION_POINTER,
		&WSARecvMsgGuid, sizeof(GUID),
		&pdata->_WSARecvMsg,
		sizeof(pdata->_WSARecvMsg),
		&bytes, NULL, NULL);
	if (pdata->_WSARecvMsg == NULL) {
	    /* There is no Win2K/NT4 emulation for this. */
	    pdata->_WSARecvMsg = NULL;
	}
    }
}

/*
 *-----------------------------------------------------------------------
 *
 * CreateSocketAddress --
 *
 *	This function initializes a ADDRINFO structure for a host and
 *	port.
 *
 * Results:
 *	1 if the host was valid, 0 if the host could not be converted to
 *	an IP address.
 *
 * Side effects:
 *	Fills in the *ADDRINFO structure.
 *
 *-----------------------------------------------------------------------
 */

int
CreateSocketAddress (
     const char *addr,
     const char *port,
     LPADDRINFO inhints,
     LPADDRINFO *paddrinfo)
{
    ADDRINFO hints;
    LPADDRINFO phints;
    int result;

    if (inhints != NULL) {
	ZeroMemory(&hints, sizeof(hints));
	hints.ai_flags  = ((addr) ? 0 : AI_PASSIVE);
	hints.ai_family = inhints->ai_family;
	hints.ai_socktype = inhints->ai_socktype;
	hints.ai_protocol = inhints->ai_protocol;
	phints = &hints;
    } else {
	phints = NULL;
    }

    result = getaddrinfo(addr, port, phints, paddrinfo);

    if (result != 0) {
	/* an older platSDK needed this; the current doesn't.
	WSASetLastError(result); */
	return 0;
    }
    return 1;
}

void
FreeSocketAddress (LPADDRINFO addrinfo)
{
    freeaddrinfo(addrinfo);
}

/*
 *----------------------------------------------------------------------
 *
 * FindProtocolInfo --
 *
 *	This function searches the Winsock catalog for a provider of the
 *	given address family, socket type, protocol and flags. The flags
 *	field is a bitwise OR of all the attributes that you request
 *	such as multipoint or QOS support.
 *
 * Results:
 *	TRUE if pinfo was set or FALSE for an error.
 *
 * Side effects:
 *	None known.
 *
 *----------------------------------------------------------------------
 */

BOOL FindProtocolInfo(int af, int type, 
    int protocol, DWORD flags, WSAPROTOCOL_INFO *pinfo)
{
    DWORD protosz = 0, nprotos, i;
    WSAPROTOCOL_INFO *buf = NULL;
    int ret;

    /*
     * Find out the size of the buffer needed to enumerate
     * all entries.
     */
    ret = WSAEnumProtocols(NULL, NULL, &protosz);
    if (ret != SOCKET_ERROR) {
        return FALSE;  
    }
    /* Allocate the necessary buffer */
    buf = (WSAPROTOCOL_INFO *) IocpAlloc(protosz);
    if (!buf) {
        return FALSE;
    }
    nprotos = protosz / sizeof(WSAPROTOCOL_INFO);
    /* Make the real call */
    ret = WSAEnumProtocols(NULL, buf, &protosz);
    if (ret == SOCKET_ERROR) {
        IocpFree(buf);
        return FALSE;
    }
    /*
     * Search throught the catalog entries returned for the 
     * requested attributes.
     */
    for(i=0; i < nprotos ;i++) {
        if ((buf[i].iAddressFamily == af) &&
		(buf[i].iSocketType == type) &&
		(buf[i].iProtocol == protocol)) {
            if ((buf[i].dwServiceFlags1 & flags) == flags) {
                memcpy(pinfo, &buf[i], sizeof(WSAPROTOCOL_INFO));
                IocpFree(buf);
                return TRUE;
            }
        }
    }
    /* LSP with flag combination not found.. */
    WSASetLastError(WSAEOPNOTSUPP);
    IocpFree(buf);
    return FALSE;
}

/* =================================================================== */
/* ========================= Bad hack jobs! ========================== */


typedef struct {
    SOCKET s;
    LPSOCKADDR name;
    int namelen;
    PVOID lpSendBuffer;
    LPOVERLAPPED lpOverlapped;
} ConnectJob;

DWORD WINAPI
ConnectThread (LPVOID lpParam)
{
    int code;
    ConnectJob *job = lpParam;
    BufferInfo *bufPtr;

    bufPtr = CONTAINING_RECORD(job->lpOverlapped, BufferInfo, ol);
    code = connect(job->s, job->name, job->namelen);
    if (code == SOCKET_ERROR) {
	bufPtr->WSAerr = WSAGetLastError();
    }
    PostQueuedCompletionStatus(IocpSubSystem.port, 0,
	    (ULONG_PTR) bufPtr->parent, job->lpOverlapped);
    IocpFree(job->name);
    IocpFree(job);
    return 0;
}

BOOL PASCAL
OurConnectEx (
    SOCKET s,
    const struct sockaddr* name,
    int namelen,
    PVOID lpSendBuffer,
    DWORD dwSendDataLength,
    LPDWORD lpdwBytesSent,
    LPOVERLAPPED lpOverlapped)
{
    ConnectJob *job;
    HANDLE thread;
    DWORD dummy;

    // 1) Create a thread and have the thread do the work.
    //    Return thread start status.
    // 2) thread will do a blocking connect() and possible send()
    //    should lpSendBuffer not be NULL and dwSendDataLength greater
    //    than zero.
    // 3) Notify the completion port with PostQueuedCompletionStatus().
    //    We don't exactly know the port associated to us, so assume the
    //    one we ALWAYS use (insider knowledge of ourselves).
    // 4) exit thread.

    job = IocpAlloc(sizeof(ConnectJob));
    job->s = s;
    job->name = IocpAlloc(namelen);
    memcpy(job->name, name, namelen);
    job->namelen = namelen;
//    job->lpSendBuffer = lpSendBuffer;    Not supported here.
    job->lpOverlapped = lpOverlapped;

    thread = CreateThread(NULL, 256, ConnectThread, job, 0, &dummy);

    if (thread) {
	/* remove local reference so the thread cleans up after it exits. */
	CloseHandle(thread);
	WSASetLastError(WSA_IO_PENDING);
    } else {
	WSASetLastError(GetLastError());
    }
    return FALSE;
}

BOOL PASCAL
OurDisconnectEx (
    SOCKET hSocket,
    LPOVERLAPPED lpOverlapped,
    DWORD dwFlags,
    DWORD reserved)
{
    BufferInfo *bufPtr;
    bufPtr = CONTAINING_RECORD(lpOverlapped, BufferInfo, ol);
    WSASendDisconnect(hSocket, NULL);
    PostQueuedCompletionStatus(IocpSubSystem.port, 0,
	    (ULONG_PTR) bufPtr->parent, lpOverlapped);
    WSASetLastError(WSA_IO_PENDING);
    return FALSE;
}

/*
 * compare and swap functions
 */

#if !defined(_MSC_VER)
static inline char CAS (volatile void * addr, volatile void * value, void * newvalue) 
{
    register char ret;
    __asm__ __volatile__ (
	"# CAS \n\t"
	"lock ; cmpxchg %2, (%1) \n\t"
	"sete %0                 \n\t"
	:"=a" (ret)
	:"c" (addr), "d" (newvalue), "a" (value)
    );
    return ret;
}

static inline char CAS2 (volatile void * addr, volatile void * v1, volatile long v2, void * n1, long n2) 
{
    register char ret;
    __asm__ __volatile__ (
	"# CAS2 \n\t"
	"lock ;  cmpxchg8b (%1) \n\t"
	"sete %0                \n\t"
	:"=a" (ret)
	:"D" (addr), "d" (v2), "a" (v1), "b" (n1), "c" (n2)
    );
    return ret;
}
#else
static __inline char CAS (volatile void * addr, volatile void * value, void * newvalue) 
{
    register char c;
    __asm {
	push	ebx
	push	esi
	mov	esi, addr
	mov	eax, value
	mov	ebx, newvalue
	lock	cmpxchg dword ptr [esi], ebx
	sete	c
	pop	esi
	pop	ebx
    }
    return c;
}

static __inline char CAS2 (volatile void * addr, volatile void * v1, volatile long v2, void * n1, long n2) 
{
    register char c;
    __asm {
	push	ebx
	push	ecx
	push	edx
	push	esi
	mov	esi, addr
	mov	eax, v1
	mov	ebx, n1
	mov	ecx, n2
	mov	edx, v2
	lock    cmpxchg8b qword ptr [esi]
	sete	c
	pop	esi
	pop	edx
	pop	ecx
	pop	ebx
    }
    return c;
}
#endif


/* Bitmask macros. */
#define mask_a( mask, val ) if ( ( mask & val ) != val ) { mask |= val; }
#define mask_d( mask, val ) if ( ( mask & val ) == val ) { mask &= ~(val); }
#define mask_y( mask, val ) ( mask & val ) == val
#define mask_n( mask, val ) ( mask & val ) != val


/*
 *----------------------------------------------------------------------
 *
 * IocpLLCreate --
 *
 *	Creates a linked list.
 *
 * Results:
 *	pointer to the new one or NULL for error.
 *
 * Side effects:
 *	None known.
 *
 *----------------------------------------------------------------------
 */

LPLLIST
IocpLLCreate (void)
{   
    LPLLIST ll;
    
    /* Alloc a linked list. */
    if (!(ll = IocpAlloc(sizeof(LLIST)))) {
	return NULL;
    }
    if (!InitializeCriticalSectionAndSpinCount(&ll->lock, 4000)) {
	IocpFree(ll);
	return NULL;
    }
    ll->haveData = CreateEvent(NULL, TRUE, FALSE, NULL);  /* manual reset */
    if (ll->haveData == INVALID_HANDLE_VALUE) {
	DeleteCriticalSection(&ll->lock);
	IocpFree(ll);
	return NULL;
    }
    ll->back = ll->front = 0L;
    ll->lCount = 0;
    return ll;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLDestroy --
 *
 *	Destroys a linked list.
 *
 * Results:
 *	Same as HeapFree.
 *
 * Side effects:
 *	Nodes aren't destroyed.
 *
 *----------------------------------------------------------------------
 */

BOOL 
IocpLLDestroy (
    LPLLIST ll)
{
    if (!ll) {
	return FALSE;
    }
    DeleteCriticalSection(&ll->lock);
    CloseHandle(ll->haveData);
    return IocpFree(ll);
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPushFront --
 *
 *	Adds an item to the end of the list.
 *
 * Results:
 *	The node.
 *
 * Side effects:
 *	Will create a new node, if not given one.
 *
 *----------------------------------------------------------------------
 */

LPLLNODE 
IocpLLPushBack(
    LPLLIST ll,
    LPVOID lpItem,
    LPLLNODE pnode,
    DWORD dwState)
{
    LPLLNODE tmp;

    if (!ll) {
	return NULL;
    }
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	EnterCriticalSection(&ll->lock);
    }
    if (!pnode) {
	pnode = IocpAlloc(sizeof(LLNODE));
    }
    if (!pnode) {
	if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	    LeaveCriticalSection(&ll->lock);
	}
	return NULL;
    }
    pnode->lpItem = lpItem;
    if (!ll->front && !ll->back) {
	ll->front = pnode;
	ll->back = pnode;
    } else {
	ll->back->next = pnode;
	tmp = ll->back;
	ll->back = pnode;
	ll->back->prev = tmp;
    }
    ll->lCount++;
    pnode->ll = ll;
    SetEvent(ll->haveData);
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	LeaveCriticalSection(&ll->lock);
    }
    return pnode;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPushFront --
 *
 *	Adds an item to the front of the list.
 *
 * Results:
 *	The node.
 *
 * Side effects:
 *	Will create a new node, if not given one.
 *
 *----------------------------------------------------------------------
 */

LPLLNODE 
IocpLLPushFront(
    LPLLIST ll,
    LPVOID lpItem,
    LPLLNODE pnode,
    DWORD dwState)
{
    LPLLNODE tmp;

    if (!ll) {
	return NULL;
    }
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	EnterCriticalSection(&ll->lock);
    }
    if (!pnode) {
	pnode = IocpAlloc(sizeof(LLNODE));
    }
    if (!pnode) {
	if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	    LeaveCriticalSection(&ll->lock);
	}
	return NULL;
    }
    pnode->lpItem = lpItem;
    if (!ll->front && !ll->back) {
	ll->front = pnode;
	ll->back = pnode;
    } else {
	ll->front->prev = pnode;
	tmp = ll->front;
	ll->front = pnode;
	ll->front->next = tmp;
    }
    ll->lCount++;
    pnode->ll = ll;
    SetEvent(ll->haveData);
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	LeaveCriticalSection(&ll->lock);
    }
    return pnode;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPopAll --
 *
 *	Removes all items from the list.
 *
 * Results:
 *	TRUE if something was popped or FALSE if nothing was poppable.
 *
 * Side effects:
 *	Won't free the node(s) with IOCP_LL_NODESTROY in the state arg.
 *
 *----------------------------------------------------------------------
 */

BOOL 
IocpLLPopAll(
    LPLLIST ll,
    LPLLNODE snode,
    DWORD dwState)
{
    LPLLNODE tmp1, tmp2;

    if (!ll) {
	return FALSE;
    }
    if (snode && snode->ll) {
	ll = snode->ll;
    }
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	EnterCriticalSection(&ll->lock);
    }
    if (!ll->front && ! ll->back || ll->lCount <= 0) {
	if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	    LeaveCriticalSection(&ll->lock);
	}
	return FALSE;
    }
    tmp1 = ll->front;
    if (snode) {
	tmp1 = snode;
    }
    while(tmp1) {
	tmp2 = tmp1->next;
	/* Delete (or blank) the node and decrement the counter. */
        if (mask_n(dwState, IOCP_LL_NODESTROY)) {
	    IocpLLNodeDestroy(tmp1);
	} else {
	    tmp1->ll = NULL;
	    tmp1->next = NULL; 
            tmp1->prev = NULL;
	}
        ll->lCount--;
	tmp1 = tmp2;
    }

    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	LeaveCriticalSection(&ll->lock);
    }
    
    return TRUE;
}


BOOL 
IocpLLPopAllCompare(
    LPLLIST ll,
    LPVOID lpItem,
    DWORD dwState)
{
    LPLLNODE tmp1, tmp2;

    if (!ll) {
	return FALSE;
    }
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	EnterCriticalSection(&ll->lock);
    }
    if (!ll->front && !ll->back || ll->lCount <= 0) {
	if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	    LeaveCriticalSection(&ll->lock);
	}
	return FALSE;
    }
    tmp1 = ll->front;
    while(tmp1) {
	tmp2 = tmp1->next;
	if (tmp1->lpItem == lpItem) {
	    IocpLLPop(tmp1, IOCP_LL_NOLOCK | dwState);
	}
	tmp1 = tmp2;
    }
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	LeaveCriticalSection(&ll->lock);
    }
    
    return TRUE;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPop --
 *
 *	Removes an item from the list.
 *
 * Results:
 *	TRUE if something was popped or FALSE if nothing was poppable.
 *
 * Side effects:
 *	Won't free the node with IOCP_LL_NODESTROY in the state arg.
 *
 *----------------------------------------------------------------------
 */

BOOL 
IocpLLPop(
    LPLLNODE node,
    DWORD dwState)
{
    LPLLIST ll;
    LPLLNODE prev, next;

    //Ready the node
    if (!node || !node->ll) {
	return FALSE;
    }
    ll = node->ll;
    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	EnterCriticalSection(&ll->lock);
    }
    if (!ll->front && !ll->back || ll->lCount <= 0) {
	if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	    LeaveCriticalSection(&ll->lock);
	}
	return FALSE;
    }
    prev = node->prev;
    next = node->next;

    /* Check for only item. */
    if (!prev & !next) {
	ll->front = NULL;
	ll->back = NULL;
    /* Check for front of list. */
    } else if (!prev && next) {
	next->prev = NULL;
	ll->front = next;
    /* Check for back of list. */
    } else if (prev && !next) {
	prev->next = NULL;
	ll->back = prev;
    /* Check for middle of list. */
    } else if (prev && next) {
	next->prev = prev;
	prev->next = next;
    }

    /* Delete the node when IOCP_LL_NODESTROY is not specified. */
    if (mask_n(dwState, IOCP_LL_NODESTROY)) {
	IocpLLNodeDestroy(node);
    } else {
	node->ll = NULL;
	node->next = NULL; 
        node->prev = NULL;
    }
    ll->lCount--;
    if (ll->lCount <= 0) {
	ll->front = NULL;
	ll->back = NULL;
    }

    if (mask_n(dwState, IOCP_LL_NOLOCK)) {
	LeaveCriticalSection(&ll->lock);
    }
    return TRUE;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLNodeDestroy --
 *
 *	Destroys a node.
 *
 * Results:
 *	Same as HeapFree.
 *
 * Side effects:
 *	memory returns to the system.
 *
 *----------------------------------------------------------------------
 */

BOOL
IocpLLNodeDestroy (LPLLNODE node)
{
    return IocpFree(node);
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPopBack --
 *
 *	Removes the item at the back of the list.
 *
 * Results:
 *	The item stored in the node at the front or NULL for none.
 *
 * Side effects:
 *	Won't free the node with IOCP_LL_NODESTROY in the state arg.
 *
 *----------------------------------------------------------------------
 */

LPVOID
IocpLLPopBack(
    LPLLIST ll,
    DWORD dwState,
    DWORD timeout)
{
    LPLLNODE tmp;
    LPVOID data;

    if (!ll) {
	return NULL;
    }
    EnterCriticalSection(&ll->lock);
    if (!ll->lCount) {
	if (timeout) {
	    DWORD dwWait;
	    ResetEvent(ll->haveData);
	    LeaveCriticalSection(&ll->lock);
	    dwWait = WaitForSingleObject(ll->haveData, timeout);
	    if (dwWait == WAIT_OBJECT_0) {
		/* wait succedded, fall through and remove one. */
		EnterCriticalSection(&ll->lock);
	    } else {
		/* wait failed */
		return NULL;
	    }
	} else {
	    LeaveCriticalSection(&ll->lock);
	    return NULL;
	}
    }
    tmp = ll->back;
    data = tmp->lpItem;
    IocpLLPop(tmp, IOCP_LL_NOLOCK | dwState);
    LeaveCriticalSection(&ll->lock);
    return data;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLPopFront --
 *
 *	Removes the item at the front of the list.
 *
 * Results:
 *	The item stored in the node at the front or NULL for none.
 *
 * Side effects:
 *	Won't free the node with IOCP_LL_NODESTROY in the state arg.
 *
 *----------------------------------------------------------------------
 */

LPVOID
IocpLLPopFront(
    LPLLIST ll,
    DWORD dwState,
    DWORD timeout)
{
    LPLLNODE tmp;
    LPVOID data;

    if (!ll) {
	return NULL;
    }
    EnterCriticalSection(&ll->lock);
    if (!ll->lCount) {
	if (timeout) {
	    DWORD dwWait;
	    ResetEvent(ll->haveData);
	    LeaveCriticalSection(&ll->lock);
	    dwWait = WaitForSingleObject(ll->haveData, timeout);
	    if (dwWait == WAIT_OBJECT_0) {
		/* wait succedded, fall through and remove one. */
		EnterCriticalSection(&ll->lock);
	    } else {
		/* wait failed */
		return NULL;
	    }
	} else {
	    LeaveCriticalSection(&ll->lock);
	    return NULL;
	}
    }
    tmp = ll->front;
    data = tmp->lpItem;
    IocpLLPop(tmp, IOCP_LL_NOLOCK | dwState);
    LeaveCriticalSection(&ll->lock);
    return data;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLIsNotEmpty --
 *
 *	self explanatory.
 *
 * Results:
 *	Boolean for if the linked-list has entries.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

BOOL
IocpLLIsNotEmpty (LPLLIST ll)
{
    BOOL b;
    if (!ll) {
	return FALSE;
    }
    EnterCriticalSection(&ll->lock);
    b = (ll->lCount != 0);
    LeaveCriticalSection(&ll->lock);
    return b;
}

/*
 *----------------------------------------------------------------------
 *
 * IocpLLGetCount --
 *
 *	How many nodes are on the list?
 *
 * Results:
 *	Count of entries.
 *
 * Side effects:
 *	None.
 *
 *----------------------------------------------------------------------
 */

SIZE_T
IocpLLGetCount (LPLLIST ll)
{
    SIZE_T c;
    if (!ll) {
	return 0;
    }
    EnterCriticalSection(&ll->lock);
    c = ll->lCount;
    LeaveCriticalSection(&ll->lock);
    return c;
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_GetHostName --
 *
 *	Returns the name of the local host.
 *
 * Results:
 *	A string containing the network name for this machine. The caller must
 *	not modify or free this string.
 *
 * Side effects:
 *	Caches the name to return for future calls.
 *
 *----------------------------------------------------------------------
 */

const char *
Tcl_GetHostName(void)
{
    return Tcl_GetString(TclGetProcessGlobalValue(&hostName));
}

/*
 *----------------------------------------------------------------------
 *
 * InitializeHostName --
 *
 *	This routine sets the process global value of the name of the local
 *	host on which the process is running.
 *
 * Results:
 *	None.
 *
 *----------------------------------------------------------------------
 */

void
InitializeHostName(
    char **valuePtr,
    int *lengthPtr,
    Tcl_Encoding *encodingPtr)
{
    WCHAR wbuf[MAX_COMPUTERNAME_LENGTH + 1];
    DWORD length = sizeof(wbuf) / sizeof(WCHAR);
    Tcl_DString ds;

    if (tclWinProcs->getComputerNameProc(wbuf, &length) != 0) {
	/*
	 * Convert string from native to UTF then change to lowercase.
	 */

	Tcl_UtfToLower(Tcl_WinTCharToUtf((TCHAR *) wbuf, -1, &ds));

    } else {
	Tcl_DStringInit(&ds);
	if (TclpHasSockets(NULL) == TCL_OK) {
	    /*
	     * Buffer length of 255 copied slavishly from previous version of
	     * this routine. Presumably there's a more "correct" macro value
	     * for a properly sized buffer for a gethostname() call.
	     * Maintainers are welcome to supply it.
	     */

	    Tcl_DString inDs;

	    Tcl_DStringInit(&inDs);
	    Tcl_DStringSetLength(&inDs, 255);
	    if (gethostname(Tcl_DStringValue(&inDs),
			    Tcl_DStringLength(&inDs)) == 0) {
		Tcl_DStringSetLength(&ds, 0);
	    } else {
		Tcl_ExternalToUtfDString(NULL,
			Tcl_DStringValue(&inDs), -1, &ds);
	    }
	    Tcl_DStringFree(&inDs);
	}
    }

    *encodingPtr = Tcl_GetEncoding(NULL, "utf-8");
    *lengthPtr = Tcl_DStringLength(&ds);
    *valuePtr = ckalloc((unsigned int) (*lengthPtr)+1);
    memcpy(*valuePtr, Tcl_DStringValue(&ds), (size_t)(*lengthPtr)+1);
    Tcl_DStringFree(&ds);
}

/*
 *----------------------------------------------------------------------
 *
 * TclWinGetSockOpt, et al. --
 *
 *	These functions are wrappers that let us bind the WinSock API
 *	dynamically so we can run on systems that don't have the wsock32.dll.
 *	We need wrappers for these interfaces because they are called from the
 *	generic Tcl code.
 *
 * Results:
 *	As defined for each function.
 *
 * Side effects:
 *	As defined for each function.
 *
 *----------------------------------------------------------------------
 */

int
TclWinGetSockOpt(
    int s,
    int level,
    int optname,
    char * optval,
    int FAR *optlen)
{
    /*
     * Check that WinSock is initialized; do not call it if not, to prevent
     * system crashes. This can happen at exit time if the exit handler for
     * WinSock ran before other exit handlers that want to use sockets.
     */

    if (!InitSockets()) {
	return SOCKET_ERROR;
    }

    return getsockopt((SOCKET)s, level, optname, optval, optlen);
}

int
TclWinSetSockOpt(
    int s,
    int level,
    int optname,
    const char * optval,
    int optlen)
{
    /*
     * Check that WinSock is initialized; do not call it if not, to prevent
     * system crashes. This can happen at exit time if the exit handler for
     * WinSock ran before other exit handlers that want to use sockets.
     */

    if (!InitSockets()) {
	return SOCKET_ERROR;
    }

    /*
     * The changing of the internal buffers is inappropriate with overlapped
     * sockets as the per-io buffer will equal the channel buffer size after
     * the first and all following read() operations.
     */
    return SOCKET_ERROR;
}

u_short
TclWinNToHS(
    u_short netshort)
{
    /*
     * Check that WinSock is initialized; do not call it if not, to prevent
     * system crashes. This can happen at exit time if the exit handler for
     * WinSock ran before other exit handlers that want to use sockets.
     */

    if (!InitSockets()) {
	return (u_short) -1;
    }

    return ntohs(netshort);
}

struct servent *
TclWinGetServByName(
    const char *name,
    const char *proto)
{
    /*
     * Check that WinSock is initialized; do not call it if not, to prevent
     * system crashes. This can happen at exit time if the exit handler for
     * WinSock ran before other exit handlers that want to use sockets.
     */

    if (!InitSockets()) {
	return NULL;
    }

    return getservbyname(name, proto);
}

/*
 * Local Variables:
 * mode: c
 * c-basic-offset: 4
 * fill-column: 78
 * End:
 */