summaryrefslogblamecommitdiffstats
path: root/private/ntos/afd/tranfile.c
blob: 66ad60616e456a3d6c1756bbdef2e434b948c91d (plain) (tree)
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





























































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                    
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    tranfile.c

Abstract:

    This module contains support for fast kernel-level file transmission
    over a socket handle.

Author:

    David Treadwell (davidtr)    3-Aug-1994

Revision History:

--*/

#include "afdp.h"

//
// Context structure for deferring a MDL read completion.
//

typedef struct _AFD_MDL_COMPLETION_CONTEXT {

    AFD_WORK_ITEM WorkItem;
    PFILE_OBJECT FileObject;
    PMDL MdlChain;
    LONGLONG FileOffset;
    ULONG Length;

} AFD_MDL_COMPLETION_CONTEXT, *PAFD_MDL_COMPLETION_CONTEXT;

//
// A structure for tracking info on checked builds.
//

#if DBG
typedef struct _AFD_TRANSMIT_TRACE_INFO {
    PVOID Caller;
    PVOID CallersCaller;
    ULONG Reason;
    PVOID OtherInfo;
} AFD_TRANSMIT_TRACE_INFO, *PAFD_TRANSMIT_TRACE_INFO;
#endif

NTSTATUS
AfdBuildReadIrp (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    );

ULONG
AfdBuildTransmitSendMdls (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo,
    IN PMDL FileMdlChain,
    IN ULONG FileDataLength,
    IN PAFD_TRANSMIT_IRP_INFO IrpInfo,
    OUT PIRP *DisconnectIrp
    );

BOOLEAN
AfdCancelIrp (
    IN PIRP Irp
    );

VOID
AfdCompleteTransmit (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo,
    IN NTSTATUS Status,
    IN KIRQL OldIrql
    );

VOID
AfdQueueTransmitRead (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    );

NTSTATUS
AfdRestartTransmitRead (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    );

NTSTATUS
AfdRestartTransmitSend (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    );

VOID
AfdStartTransmitIo (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    );

VOID
AfdStartNextQueuedTransmitFile(
    VOID
    );

NTSTATUS
AfdRestartMdlReadComplete (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    );

VOID
AfdDeferredMdlReadComplete(
    IN PVOID Context
    );

#define AfdAllocateMdlCompletionContext()                   \
            AFD_ALLOCATE_POOL(                              \
                NonPagedPool,                               \
                sizeof(AFD_MDL_COMPLETION_CONTEXT),         \
                AFD_MDL_COMPLETION_CONTEXT_POOL_TAG         \
                )

#define AfdFreeMdlCompletionContext(context)                \
            AFD_FREE_POOL(                                  \
                (context),                                  \
                AFD_MDL_COMPLETION_CONTEXT_POOL_TAG         \
                )


//
// Macros to control the status of an IRP.
//

#define SET_IRP_BUSY(_irp) ((_irp)->UserIosb = (PVOID)0xFFFFFFFF)
#define SET_IRP_FREE(_irp) ((_irp)->UserIosb = (PVOID)0)
#define IS_IRP_BUSY(_irp) ((_irp)->UserIosb != 0)

//
// A macro to rebuild a send IRP to contain the appropriate information.
// This is required because the IO system zeros each IRP stack location
// whenever an IRP completes.
//


#define AfdRebuildSend(Irp, FileObj, SendLen)\
    {                                                                        \
        PTDI_REQUEST_KERNEL_SEND p;                                          \
        PIO_STACK_LOCATION _IRPSP;                                           \
        _IRPSP = IoGetNextIrpStackLocation (Irp);                            \
        ASSERT( _IRPSP->MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL );   \
        _IRPSP->MinorFunction = TDI_SEND;                                    \
        _IRPSP->FileObject = FileObj;                                        \
        _IRPSP->Control = SL_INVOKE_ON_SUCCESS |                             \
                          SL_INVOKE_ON_ERROR |                               \
                          SL_INVOKE_ON_CANCEL;                               \
        p = (PTDI_REQUEST_KERNEL_SEND)&_IRPSP->Parameters;                   \
        p->SendLength = SendLen;                                             \
    }

//
// Debugging macros.
//

#if DBG

#define MAX_TRACE 255

#if defined(_X86_)
#define UPDATE_TRANSMIT_DEBUG_INFO( _ti, _reason, _other )                   \
{                                                                            \
    PAFD_TRANSMIT_TRACE_INFO _trace;                                         \
    PULONG _index = (PULONG)(&((_ti)->Debug2));                              \
                                                                             \
    *_index += 1;                                                            \
                                                                             \
    if ( *_index == MAX_TRACE ) {                                            \
        *_index = 0;                                                         \
    }                                                                        \
                                                                             \
    _trace = (PAFD_TRANSMIT_TRACE_INFO)(_ti)->Debug1 + *_index;              \
                                                                             \
    RtlGetCallersAddress( &_trace->Caller, &_trace->CallersCaller );         \
                                                                             \
    _trace->Reason = _reason;                                                \
    _trace->OtherInfo = _other;                                                  \
}
#else
#define UPDATE_TRANSMIT_DEBUG_INFO( _ti, _reason, _other )
#endif                                                                       \

#define SET_READ_PENDING(_ti, _value)                                        \
{                                                                            \
    ASSERT( KeGetCurrentIrql( ) >= DISPATCH_LEVEL );                         \
    if (_value) {                                                            \
        ASSERT( !(_ti)->ReadPending );                                       \
        (_ti)->ReadPendingLastSetTrueLine = __LINE__;                        \
    } else {                                                                 \
        ASSERT( (_ti)->ReadPending );                                        \
        (_ti)->ReadPendingLastSetFalseLine = __LINE__;                       \
    }                                                                        \
    (_ti)->ReadPending = (_value);                                           \
}

#else
#define UPDATE_TRANSMIT_DEBUG_INFO( _ti, _reason, _other )
#define SET_READ_PENDING(_ti,_value) (_ti)->ReadPending = (_value)
#endif

#ifdef ALLOC_PRAGMA
#pragma alloc_text( PAGEAFD, AfdTransmitFile )
#pragma alloc_text( PAGEAFD, AfdStartTransmitIo )
#pragma alloc_text( PAGEAFD, AfdRestartTransmitRead )
#pragma alloc_text( PAGEAFD, AfdRestartTransmitSend )
#pragma alloc_text( PAGEAFD, AfdCompleteTransmit )
#pragma alloc_text( PAGEAFD, AfdBuildReadIrp )
#pragma alloc_text( PAGEAFD, AfdBuildTransmitSendMdls )
#pragma alloc_text( PAGEAFD, AfdCancelIrp )
#pragma alloc_text( PAGEAFD, AfdCancelTransmit )
#pragma alloc_text( PAGEAFD, AfdQueueTransmitRead )
#pragma alloc_text( PAGEAFD, AfdCompleteClosePendedTransmit )
#pragma alloc_text( PAGEAFD, AfdStartNextQueuedTransmitFile )
#pragma alloc_text( PAGEAFD, AfdFastTransmitFile )
#pragma alloc_text( PAGEAFD, AfdMdlReadComplete )
#pragma alloc_text( PAGEAFD, AfdRestartMdlReadComplete )
#pragma alloc_text( PAGEAFD, AfdDeferredMdlReadComplete )
#endif


NTSTATUS
AfdTransmitFile (
    IN PIRP Irp,
    IN PIO_STACK_LOCATION IrpSp
    )

/*++

Routine Description:

    Initial entrypoint for handling transmit file IRPs.  This routine
    verifies parameters, initializes data structures to be used for
    the request, and initiates the I/O.

Arguments:

    Irp - a pointer to a transmit file IRP.

    IrpSp - Our stack location for this IRP.

Return Value:

    STATUS_PENDING if the request was initiated successfully, or a
    failure status code if there was an error.

--*/

{
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    NTSTATUS status;
    PAFD_TRANSMIT_FILE_INFO_INTERNAL transmitInfo = NULL;
    KIRQL oldIrql;
    BOOLEAN lockedHead;
    BOOLEAN lockedTail;
    BOOLEAN clearTransmitIrpOnFailure = FALSE;

    //
    // Initial request validity checks: is the endpoint connected, is
    // the input buffer large enough, etc.
    //

    endpoint = IrpSp->FileObject->FsContext;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );

    if ( endpoint->Type != AfdBlockTypeVcConnecting ||
             endpoint->State != AfdEndpointStateConnected ) {
        status = STATUS_INVALID_CONNECTION;
        goto complete;
    }

    connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );
    ASSERT( connection->Type == AfdBlockTypeConnection );

    if ( IrpSp->Parameters.DeviceIoControl.InputBufferLength <
             sizeof(AFD_TRANSMIT_FILE_INFO) ) {
        status = STATUS_INVALID_PARAMETER;
        goto complete;
    }

    //
    // Ensure there are no other TransmitFile IRPs pending on this
    // endpoint. Only allowing one at a time makes completion and
    // cancellation much simpler.
    //

    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

    if( endpoint->TransmitIrp != NULL ) {

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
        status = STATUS_INVALID_PARAMETER;
        goto complete;

    }

    endpoint->TransmitIrp = Irp;
    clearTransmitIrpOnFailure = TRUE;

    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

    //
    // If this endpoint already has an internal info buffer, use it.
    // Otherwise, allocate a new one from nonpaged pool. We will use
    // this structure to track the request. We'll also store a pointer
    // to the structure in the IRP so we can access it whenever we
    // have a pointer to the IRP.
    //

    transmitInfo = endpoint->TransmitInfo;

    if( transmitInfo == NULL ) {

        transmitInfo = AFD_ALLOCATE_POOL(
                           NonPagedPool,
                           sizeof(*transmitInfo),
                           AFD_TRANSMIT_INFO_POOL_TAG
                           );

        if ( transmitInfo == NULL ) {

            status = STATUS_INSUFFICIENT_RESOURCES;
            goto complete;

        }

        endpoint->TransmitInfo = transmitInfo;

    }

    Irp->AssociatedIrp.SystemBuffer = transmitInfo;

    //
    // NULL the head and tail MDL pointers so that we know whether
    // we need to unlock and free them on exit.
    //

    transmitInfo->HeadMdl = NULL;
    lockedHead = FALSE;
    transmitInfo->TailMdl = NULL;
    lockedTail = FALSE;

    //
    // Set up the rest of the transmit info structure.  input buffer,
    // then set up defaults.
    //

    transmitInfo->FileObject = NULL;
    transmitInfo->TdiFileObject = connection->FileObject;
    transmitInfo->TdiDeviceObject = connection->DeviceObject;
    transmitInfo->BytesRead = 0;
    transmitInfo->BytesSent = 0;

    transmitInfo->TransmitIrp = Irp;
    transmitInfo->Endpoint = endpoint;
    transmitInfo->FileMdl = NULL;
    transmitInfo->ReadPending = TRUE;
    transmitInfo->CompletionPending = FALSE;

    transmitInfo->FirstFileMdlAfterHead = NULL;
    transmitInfo->LastFileMdlBeforeTail = NULL;
    transmitInfo->IrpUsedToSendTail = NULL;

    transmitInfo->Read.Irp = NULL;
    transmitInfo->Read.AfdBuffer = NULL;

    transmitInfo->Send1.Irp = NULL;
    transmitInfo->Send1.AfdBuffer = NULL;

    transmitInfo->Send2.Irp = NULL;
    transmitInfo->Send2.AfdBuffer = NULL;

    transmitInfo->Queued = FALSE;

#if DBG
    transmitInfo->Debug1 = NULL;
#endif

    //
    // Because we're using type 3 (neither) I/O for this IRP, the I/O
    // system does no verification on the user buffer.  Therefore, we
    // must manually check it for validity inside a try-except block.
    // We also leverage the try-except to validate and lock down the
    // head and/or tail buffers specified by the caller.
    //

    try {

        if( Irp->RequestorMode != KernelMode ) {

            //
            // Validate the control buffer.
            //

            ProbeForRead(
                IrpSp->Parameters.DeviceIoControl.Type3InputBuffer,
                IrpSp->Parameters.DeviceIoControl.InputBufferLength,
                sizeof(ULONG)
                );

        }

        //
        // Copy over the user's buffer into our information structure.
        //

        RtlCopyMemory(
            transmitInfo,
            IrpSp->Parameters.DeviceIoControl.Type3InputBuffer,
            sizeof(AFD_TRANSMIT_FILE_INFO)
            );

        //
        // If the caller specified head and/or tail buffers, probe and
        // lock the buffers so that we have MDLs we can use to send the
        // buffers.
        //

        if ( transmitInfo->HeadLength > 0 ) {

            transmitInfo->HeadMdl = IoAllocateMdl(
                                        transmitInfo->Head,
                                        transmitInfo->HeadLength,
                                        FALSE,         // SecondaryBuffer
                                        TRUE,          // ChargeQuota
                                        NULL           // Irp
                                        );
            if ( transmitInfo->HeadMdl == NULL ) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            MmProbeAndLockPages( transmitInfo->HeadMdl, UserMode, IoReadAccess );
            lockedHead = TRUE;

            //
            // Remember that we will need to send this head buffer.
            // This flag will be reset as soon as the head buffer is
            // given to the TDI provider.
            //

            transmitInfo->NeedToSendHead = TRUE;

        } else {

            transmitInfo->NeedToSendHead = FALSE;
        }

        if ( transmitInfo->TailLength > 0 ) {

            transmitInfo->TailMdl = IoAllocateMdl(
                                        transmitInfo->Tail,
                                        transmitInfo->TailLength,
                                        FALSE,         // SecondaryBuffer
                                        TRUE,          // ChargeQuota
                                        NULL           // Irp
                                        );
            if ( transmitInfo->TailMdl == NULL ) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            MmProbeAndLockPages( transmitInfo->TailMdl, UserMode, IoReadAccess );
            lockedTail = TRUE;
        }

    } except( EXCEPTION_EXECUTE_HANDLER ) {

        status = GetExceptionCode();
        goto complete;
    }

    //
    // Set up some tracking information for debugging purposes.
    //

#if DBG
    transmitInfo->Completed = FALSE;

    transmitInfo->ReadPendingLastSetTrueLine = 0xFFFFFFFF;
    transmitInfo->ReadPendingLastSetFalseLine = 0xFFFFFFFF;

    transmitInfo->Debug1 = AFD_ALLOCATE_POOL(
                                    NonPagedPool,
                                    sizeof(AFD_TRANSMIT_TRACE_INFO) * MAX_TRACE,
                                    AFD_TRANSMIT_DEBUG_POOL_TAG
                                    );

    if ( transmitInfo->Debug1 == NULL ) {

        status = STATUS_INSUFFICIENT_RESOURCES;
        goto complete;

    }

    transmitInfo->Debug2 = (PVOID)0;

    RtlZeroMemory(
        transmitInfo->Debug1,
        sizeof(AFD_TRANSMIT_TRACE_INFO) * MAX_TRACE
        );
#endif

    //
    // Validate any flags specified in the request.
    //

    if ( (transmitInfo->Flags &
             ~(AFD_TF_WRITE_BEHIND | AFD_TF_DISCONNECT | AFD_TF_REUSE_SOCKET) )
                 != 0 ) {
        status = STATUS_INVALID_PARAMETER;
        goto complete;
    }

    //
    // Setting AFD_TF_REUSE_SOCKET implies that a disconnect is desired.
    // Also, setting this flag means that no more I/O is legal on the
    // endpoint until the transmit request has been completed, so
    // set up the endpoint's state so that I/O fails.
    //

    if ( (transmitInfo->Flags & AFD_TF_REUSE_SOCKET) != 0 ) {
        transmitInfo->Flags |= AFD_TF_DISCONNECT;
        endpoint->State = AfdEndpointStateTransmitClosing;
    }

    //
    // Get a referenced pointer to the file object for the file that
    // we're going to transmit.  This call will fail if the file handle
    // specified by the caller is invalid.
    //

    status = ObReferenceObjectByHandle(
                 transmitInfo->FileHandle,
                 FILE_READ_DATA,
                 *IoFileObjectType,
                 UserMode,
                 (PVOID *)&transmitInfo->FileObject,
                 NULL
                 );
    if ( !NT_SUCCESS(status) ) {
        goto complete;
    }

    AfdRecordFileRef();

    //
    // Get the device object for the file system that supports this
    // file.  We can't just use the device object stored in the file
    // object because that device object typically refers to the disk
    // driver device and we want the file system device object.
    //

    transmitInfo->DeviceObject =
        IoGetRelatedDeviceObject( transmitInfo->FileObject );

    //
    // If this is a synchronous file object AND the offset specified
    // by the caller is zero, then start the transmission from the
    // current byte offset in the file.
    //

    if ( transmitInfo->FileObject->Flags & FO_SYNCHRONOUS_IO &&
             transmitInfo->Offset == 0 ) {

        transmitInfo->Offset = transmitInfo->FileObject->CurrentByteOffset.QuadPart;
    }

    //
    // If the caller requested that we transmit the entire file,
    // determine current file length so that we know when to quit.
    //

    if ( transmitInfo->FileWriteLength == 0 ) {

        FILE_STANDARD_INFORMATION fileInfo;
        IO_STATUS_BLOCK ioStatusBlock;

        status = ZwQueryInformationFile(
                     transmitInfo->FileHandle,
                     &ioStatusBlock,
                     &fileInfo,
                     sizeof(fileInfo),
                     FileStandardInformation
                     );
        if ( !NT_SUCCESS(status) ) {
            goto complete;
        }

        //
        // Calculate the number of bytes to send from the file.
        // This is the total file length less the specified offset.
        //

        transmitInfo->FileWriteLength =
            fileInfo.EndOfFile.QuadPart - transmitInfo->Offset;
    }

    //
    // Determine the total number of bytes we will send, including head
    // and tail buffers.
    //

    transmitInfo->TotalBytesToSend =
        transmitInfo->FileWriteLength +
            transmitInfo->HeadLength + transmitInfo->TailLength;

    //
    // Allocate and initialize the IRPs we'll give to the TDI provider
    // to actually send data.  We allocate them with a stack size one
    // larger than requested by the TDI provider so that we have a stack
    // location for ourselves.
    //
    // !!! It would be good not to allocate the second send IRP unless
    //     we knew it was really necessary.
    //

    transmitInfo->Send1.Irp =
        IoAllocateIrp( connection->DeviceObject->StackSize, TRUE );

    if ( transmitInfo->Send1.Irp == NULL ) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto complete;
    }

    TdiBuildSend(
        transmitInfo->Send1.Irp,
        connection->DeviceObject,
        connection->FileObject,
        AfdRestartTransmitSend,
        transmitInfo,
        NULL,
        0,
        0,
        );

    transmitInfo->Send2.Irp =
        IoAllocateIrp( connection->DeviceObject->StackSize, TRUE );

    if ( transmitInfo->Send2.Irp == NULL ) {
        status = STATUS_INSUFFICIENT_RESOURCES;
        goto complete;
    }

    TdiBuildSend(
        transmitInfo->Send2.Irp,
        connection->DeviceObject,
        connection->FileObject,
        AfdRestartTransmitSend,
        transmitInfo,
        NULL,
        0,
        0,
        );

    //
    // Determine the maximum read size that we'll use.  If specified by
    // the caller, respect it.  Otherwise, choose an intelligent default
    // based on whether the file system of interest supports the cache
    // manager routines for fast file I/O.  If the file system does not
    // support the cache manager interfaces, we will need to allocate
    // our own buffers so use a smaller, more sensible size.
    //

    if ( transmitInfo->SendPacketLength == 0 ) {
        if ( (transmitInfo->FileObject->Flags & FO_CACHE_SUPPORTED) != 0 ) {
            transmitInfo->SendPacketLength = AfdTransmitIoLength;
        } else {
            transmitInfo->SendPacketLength = AfdLargeBufferSize;
        }
    }

    //
    // Check if the transmit IRP has been cancelled.  If so, quit
    // now.
    //

    IoAcquireCancelSpinLock( &oldIrql );

    if ( Irp->Cancel ) {
        IoReleaseCancelSpinLock( oldIrql );
        status = STATUS_CANCELLED;
        goto complete;
    }

    //
    // Mark the transmit IRP as pending and set up the status field
    // in the IRP.  We leave it as STATUS_SUCCESS until some sort of
    // failure occurs, at which point we modify to the failure
    // code.
    //

    IoMarkIrpPending( Irp );
    Irp->IoStatus.Status = STATUS_SUCCESS;

    //
    // Set up the cancel routine in the IRP. The IRP pointer in the endpoint
    // should already point to the current IRP.
    //

    IoSetCancelRoutine( Irp, AfdCancelTransmit );
    ASSERT( endpoint->TransmitIrp == Irp );

    //
    // Determine if we can really start this file transmit now. If we've
    // exceeded the configured maximum number of active TransmitFile
    // requests, then append this IRP to the TransmitFile queue and set
    // a flag in the transmit info structure to indicate that this IRP
    // is queued.
    //

    if( AfdMaxActiveTransmitFileCount > 0 ) {

        if( AfdActiveTransmitFileCount >= AfdMaxActiveTransmitFileCount ) {

            InsertTailList(
                &AfdQueuedTransmitFileListHead,
                &Irp->Tail.Overlay.ListEntry
                );

            transmitInfo->Queued = TRUE;
            IoReleaseCancelSpinLock( oldIrql );
            return STATUS_PENDING;

        } else {

            AfdActiveTransmitFileCount++;

        }

    }

    IoReleaseCancelSpinLock( oldIrql );

    //
    // Start I/O for the file transmit.
    //

    AfdStartTransmitIo( transmitInfo );

    //
    // Everything looks good so far.  Indicate to the caller that we
    // successfully pended their request.
    //

    return STATUS_PENDING;

complete:

    //
    // There was a failure of some sort.  Clean up and exit.
    //

    if ( transmitInfo != NULL ) {

        if ( transmitInfo->HeadMdl != NULL ) {
            if ( lockedHead ) {
                MmUnlockPages( transmitInfo->HeadMdl );
            }
            IoFreeMdl( transmitInfo->HeadMdl );
        }

        if ( transmitInfo->TailMdl != NULL ) {
            if ( lockedTail ) {
                MmUnlockPages( transmitInfo->TailMdl );
            }
            IoFreeMdl( transmitInfo->TailMdl );
        }

        if ( transmitInfo->FileObject != NULL ) {
            ObDereferenceObject( transmitInfo->FileObject );
            AfdRecordFileDeref();
        }

        if ( transmitInfo->Read.Irp != NULL ) {
            IoFreeIrp( transmitInfo->Read.Irp );
        }

        if ( transmitInfo->Send1.Irp != NULL ) {
            IoFreeIrp( transmitInfo->Send1.Irp );
        }

        if ( transmitInfo->Send2.Irp != NULL ) {
            IoFreeIrp( transmitInfo->Send2.Irp );
        }

#if DBG
        if ( transmitInfo->Debug1 != NULL ) {
            AFD_FREE_POOL(
                transmitInfo->Debug1,
                AFD_TRANSMIT_DEBUG_POOL_TAG
                );
        }
#endif

        //
        // Don't free the transmit info structure here, leave
        // it attached to the endpoint. The structure will get
        // freed when we free the endpoint.
        //

    }

    //
    // Zap the IRP pointer from the endpoint if necessary.
    //

    if( clearTransmitIrpOnFailure ) {
        endpoint->TransmitIrp = NULL;
    }

    //
    // Complete the request.
    //

    Irp->IoStatus.Information = 0;
    Irp->IoStatus.Status = status;
    IoCompleteRequest( Irp, 0 );

    return status;

} // AfdTransmitFile


VOID
AfdStartTransmitIo (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    )

/*++

Routine Description:

    This is the key routine for initiating transmit I/O.  In the high-
    performance case of reading a file from the system cache, this
    routine gets file data MDLs and passes them off to the TDI provider.
    If it cannot get file data inline, it pends a read IRP to get the
    file data.

Arguments:

    TransmitInfo - a pointer to the TransmitInfo structure which
        contains information about the request to process.

Return Value:

    None.

Notes:

    Because it is illegal to call the FsRtl fast read routines at raised
    IRQL or from within a completion routine, this routine must be
    called from a thread whose context we own.  This routine cannot be
    called at distapch level or from a completion routine.

--*/

{
    IO_STATUS_BLOCK ioStatus;
    BOOLEAN success;
    PMDL fileMdl;
    KIRQL oldIrql;
    KIRQL cancelIrql;
    PAFD_ENDPOINT endpoint;
    PAFD_TRANSMIT_IRP_INFO irpInfo;
    ULONG readLength;
    ULONG sendLength;
    LONGLONG readOffset;
    NTSTATUS status;
    PIRP disconnectIrp;
    PDEVICE_OBJECT tdiDeviceObject;

    //
    // It is illegal to call the fast I/O routines or to submit MDL read
    // IRPs at raised IRQL.
    //

    ASSERT( KeGetCurrentIrql( ) < DISPATCH_LEVEL );

    //
    // Initialize local variables.
    //

    endpoint = TransmitInfo->Endpoint;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );
    ASSERT( endpoint->TransmitInfo == TransmitInfo );

    ASSERT( TransmitInfo->FileMdl == NULL );
    ASSERT( TransmitInfo->ReadPending );
    ASSERT( TransmitInfo->TransmitIrp != NULL );

    //
    // We have to have a special case to handle a file of length 0.
    //

    if ( TransmitInfo->FileWriteLength == 0 ) {

        //
        // Remember that there is not a read pending.
        //

        TransmitInfo->ReadPending = FALSE;

        //
        // If there was neither a head nor tail, just complete the
        // transmit request now.
        //

        if ( TransmitInfo->TotalBytesToSend == 0 ) {

            //
            // If we need to initiate a disconnect on the endpoint, do
            // so.
            //

            if ( (TransmitInfo->Flags & AFD_TF_DISCONNECT) != 0 ) {
                (VOID)AfdBeginDisconnect( endpoint, NULL, NULL );
            }

            //
            // We must hold the cancel spin lock when completing the
            // transmit IRP.
            //

            IoAcquireCancelSpinLock( &oldIrql );
            AfdCompleteTransmit( TransmitInfo, STATUS_SUCCESS, oldIrql );

            return;
        }

        //
        // There is a head and/or a tail buffer to send.  Build an IRP
        // and send the buffer(s).
        //

        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

        sendLength = AfdBuildTransmitSendMdls(
                         TransmitInfo,
                         NULL,
                         0,
                         &TransmitInfo->Send1,
                         &disconnectIrp
                         );

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        //
        // Remember the TDI device object in a local variable.  This is
        // necessary because as soon as we call IoCallDriver for the
        // send, the TransmitInfo structure may be freed up and have
        // been reset.
        //

        tdiDeviceObject = TransmitInfo->TdiDeviceObject;

        //
        // We'll use the first send IRP to send the head/tail buffers.
        //

        SET_IRP_BUSY( TransmitInfo->Send1.Irp );

        AfdRebuildSend(
            TransmitInfo->Send1.Irp,
            TransmitInfo->TdiFileObject,
            sendLength
            );

        //
        // Send the head and/or tail data.
        //

        IoCallDriver( tdiDeviceObject, TransmitInfo->Send1.Irp );

        //
        // If appropriate, submit a graceful disconnect on the endpoint.
        //

        if ( disconnectIrp != NULL ) {
            IoCallDriver( tdiDeviceObject, disconnectIrp );
        }

        return;
    }

    //
    // If the file system supports the fast cache manager interface,
    // attempt to use the fast path to get file data MDLs.
    //

    if ( (TransmitInfo->FileObject->Flags & FO_CACHE_SUPPORTED) != 0 ) {

        while ( TRUE ) {

            //
            // Set fileMdl to NULL because FsRtlMdlRead attempts to
            // chain the MDLs it returns off the input MDL variable.
            //

            fileMdl = NULL;

            //
            // Determine how many bytes we will attempt to read.  This
            // is either the send packet size or the remaining bytes in
            // the file, whichever is less.
            //

            if ( TransmitInfo->FileWriteLength -
                     TransmitInfo->BytesRead >
                     TransmitInfo->SendPacketLength ) {
                readLength = TransmitInfo->SendPacketLength;
            } else {
                readLength = (ULONG)(TransmitInfo->FileWriteLength -
                                     TransmitInfo->BytesRead);
            }

            TransmitInfo->Read.Length = readLength;

            //
            // If we have read everything we needed to read from the file,
            // quit reading.
            //

            if ( readLength == 0 ) {

                //
                // Note that we're no longer in the process of reading
                // file data.
                //

                AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
                SET_READ_PENDING( TransmitInfo, FALSE );

                //
                // If we are attempting to process completion of the
                // transmit IRP, pass control to AfdCompleteTransmit()
                // so that it can continue completion processing with
                // the read pending flag turned off.
                //

                if ( TransmitInfo->CompletionPending ) {

                    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
                    IoAcquireCancelSpinLock( &oldIrql );
                    AfdCompleteTransmit( TransmitInfo, STATUS_SUCCESS, oldIrql );

                } else {

                    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
                }

                return;
            }

            //
            // Determine the offset in the file at which to start
            // reading.  Because all reads are funnelled through this
            // function, and because this function can run in only one
            // thread at a time, there isn't a synchronization issue on
            // these fields of the TransmitInfo structure.
            //

            readOffset =
                TransmitInfo->Offset + TransmitInfo->BytesRead;

            //
            // Attempt to use the fast path to get file data MDLs
            // directly from the cache manager.
            //

            success = FsRtlMdlRead(
                          TransmitInfo->FileObject,
                          (PLARGE_INTEGER)&readOffset,
                          readLength,
                          0,
                          &fileMdl,
                          &ioStatus
                          );

            //
            // If the fast path succeeded and we have a send IRP available,
            // give the send IRP to the TDI provider.
            //

            if ( success ) {

                //
                // If we read less information than was requested, we
                // must have hit the end of the file.  Fail the transmit
                // request, since this can only happen if the caller
                // requested that we send more data than the file
                // currently contains.
                //

                AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

                if ( ioStatus.Information < readLength ) {

                    TransmitInfo->CompletionPending = TRUE;
                    TransmitInfo->TransmitIrp->IoStatus.Status =
                        STATUS_END_OF_FILE;

                    //
                    // If we got some MDLs from the file system, return
                    // them.
                    //

                    if ( fileMdl != NULL ) {
                        status = AfdMdlReadComplete(
                                     TransmitInfo->FileObject,
                                     fileMdl,
                                     readOffset,
                                     readLength
                                     );
                        ASSERT( NT_SUCCESS(status) );

                        fileMdl = NULL;
                    }
                }

                //
                // Update the count of bytes read from the file.
                //

                TransmitInfo->BytesRead =
                    TransmitInfo->BytesRead + ioStatus.Information;

                //
                // If we're in the process of completing the transmit
                // IRP, do not submit a send.  Instead call
                // AfdCompleteTransmit() so that it can continue
                // completing the transmit IRP.
                //

                if ( TransmitInfo->CompletionPending ) {

                    //
                    // Release the endpoint spin lock, grab the cancel
                    // spin lock, then reacquire the endpoint lock.
                    // This is required in order to preserve lock
                    // acquisition ordering.
                    //

                    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
                    IoAcquireCancelSpinLock( &cancelIrql );
                    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

                    //
                    // Remember the file MDL and the fact that a read
                    // is no longer pending.
                    //

                    TransmitInfo->FileMdl = fileMdl;
                    SET_READ_PENDING( TransmitInfo, FALSE );

                    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

                    //
                    // Now continue completing the transmit IRP.
                    //

                    AfdCompleteTransmit(
                        TransmitInfo,
                        STATUS_SUCCESS,
                        cancelIrql
                        );

                    return;
                }

                ASSERT( fileMdl != NULL );
                ASSERT( NT_SUCCESS(ioStatus.Status) );
                ASSERT( ioStatus.Information == readLength );

                //
                // Attempt to find a send IRP which is available to use.
                //

                if ( !IS_IRP_BUSY( TransmitInfo->Send1.Irp ) ) {

                    irpInfo = &TransmitInfo->Send1;
                    SET_IRP_BUSY( TransmitInfo->Send1.Irp );

                } else if ( !IS_IRP_BUSY( TransmitInfo->Send2.Irp ) ) {

                    irpInfo = &TransmitInfo->Send2;
                    SET_IRP_BUSY( TransmitInfo->Send2.Irp );

                } else {

                    //
                    // There are no send IRPs that we can use to send
                    // this file data.  Just hang on to the data until
                    // a send IRP completes.
                    //

                    TransmitInfo->FileMdl = fileMdl;
                    TransmitInfo->FileMdlLength = readLength;
                    SET_READ_PENDING( TransmitInfo, FALSE );

                    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

                    return;
                }

                //
                // Finish building the send IRP and give it to the TDI
                // provider.
                //

                sendLength = AfdBuildTransmitSendMdls(
                                 TransmitInfo,
                                 fileMdl,
                                 readLength,
                                 irpInfo,
                                 &disconnectIrp
                                 );

                AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

                //
                // Remember the TDI device object in a local variable.
                // This is necessary because as soon as we call
                // IoCallDriver for the send, the TransmitInfo structure
                // may be freed up and have been reset.
                //

                tdiDeviceObject = TransmitInfo->TdiDeviceObject;

                AfdRebuildSend(
                    irpInfo->Irp,
                    TransmitInfo->TdiFileObject,
                    sendLength
                    );

                IoCallDriver( tdiDeviceObject, irpInfo->Irp );

                //
                // If appropriate, submit a graceful disconnect on the
                // endpoint.
                //

                if ( disconnectIrp != NULL ) {
                    IoCallDriver( tdiDeviceObject, disconnectIrp );
                }

                //
                // Try to get more file data to send out.
                //

            } else {

                ASSERT( fileMdl == NULL );

                //
                // Drop through to build an IRP to retrieve the file
                // data.
                //

                break;
            }
        }
    }

    //
    // Either the file system does not support the fast cache manager
    // interface or else fast I/O failed.  We'll have to build a read
    // IRP and submit it to the file system
    //

    status = AfdBuildReadIrp( TransmitInfo );
    if ( !NT_SUCCESS(status) ) {

        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
        SET_READ_PENDING( TransmitInfo, FALSE );
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        IoAcquireCancelSpinLock( &TransmitInfo->TransmitIrp->CancelIrql );
        AfdCancelTransmit( NULL, TransmitInfo->TransmitIrp );

        return;
    }

    //
    // If the transmit IRP is in the process of being completed, do not
    // submit the read IRP.  Instead, call AfdCompleteTransmit() after
    // turning off the ReadPending bit so that it can continue
    // completion of the transmit IRP.
    //

    IoAcquireCancelSpinLock( &cancelIrql );
    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

    if ( TransmitInfo->CompletionPending ) {

        ASSERT( !IS_IRP_BUSY( TransmitInfo->Read.Irp ) );
        SET_READ_PENDING( TransmitInfo, FALSE );
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        AfdCompleteTransmit( TransmitInfo, STATUS_SUCCESS, cancelIrql );

        return;
    }

    //
    // We're committed to posting the read IRP.  Remember that it is
    // busy.  Note that there is a small window between setting the IRP
    // busy and the actual submission where we may need to cancel the
    // IRP.  This is handled by the fact that if we attempt to cancel
    // the IRP before the driver gets it, the Cencel flag will be set in
    // the IRP and the driver should fail it immediately.
    //

    SET_IRP_BUSY( TransmitInfo->Read.Irp );
    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
    IoReleaseCancelSpinLock( cancelIrql );

    IoCallDriver( TransmitInfo->DeviceObject, TransmitInfo->Read.Irp );

    //
    // Leave the ReadPending flag set in the TransmitInfo structure
    // until the read IRP completes.
    //

    return;

} // AfdStartTransmitIo


NTSTATUS
AfdRestartTransmitRead (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

  This is the completion routine for transmit read IRPs.  It updates the
  context based on the result of the read operation and attempts to find
  a send IRP to use to give the read data to the TDI provider.  If no
  send IRP is available, it just holds on to the read data until a send
  IRP completes.

Arguments:

    DeviceObject - ignored.

    Irp - the read IRP that is completing.

    Context - a pointer to the TransmitInfo structure that describes
        the transmit file request corresponding to the IRP that is
        completing.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED which indicates to the I/O system
    that it should stop completion processing of this IRP.  We handle
    all completion from this point forward.

--*/

{
    PAFD_TRANSMIT_FILE_INFO_INTERNAL transmitInfo;
    PAFD_TRANSMIT_IRP_INFO irpInfo;
    KIRQL oldIrql;
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    BOOLEAN readMore;
    ULONG sendLength;
    PIRP disconnectIrp;
    PDEVICE_OBJECT tdiDeviceObject;

    //
    // Initialize local variables.
    //

    transmitInfo = Context;
    ASSERT( transmitInfo->Read.Irp == Irp );

    endpoint = transmitInfo->Endpoint;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );
    ASSERT( endpoint->TransmitInfo == transmitInfo );

    connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );
    ASSERT( connection->Type == AfdBlockTypeConnection );

    ASSERT( IS_IRP_BUSY( Irp ) );
    ASSERT( transmitInfo->ReadPending );

    //
    // If the read failed or we're in the process of completing the
    // transmit IRP, start/continue the process of completing the
    // transmit IRP.
    //

    if ( !NT_SUCCESS(Irp->IoStatus.Status) || transmitInfo->CompletionPending ) {

        KIRQL cancelIrql;

        IoAcquireCancelSpinLock( &cancelIrql );

        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
        SET_IRP_FREE( Irp );
        SET_READ_PENDING( transmitInfo, FALSE );
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        KdPrint(( "AfdRestartTransmitRead: failed, status == %lx\n",
                      Irp->IoStatus.Status ));

        AfdCompleteTransmit( transmitInfo, Irp->IoStatus.Status, cancelIrql );
        return STATUS_MORE_PROCESSING_REQUIRED;
    }

    //
    // Update the count of bytes we have read from the file so far.
    //

    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

    transmitInfo->BytesRead =
        transmitInfo->BytesRead + Irp->IoStatus.Information;

    //
    // If this is a non-cached read, update the MDL byte count in the
    // AFD buffer to reflect the count of bytes actually read.
    //

    if ( transmitInfo->Read.AfdBuffer != NULL ) {
        transmitInfo->Read.AfdBuffer->Mdl->ByteCount = Irp->IoStatus.Information;
    }

    //
    // Remember that the read IRP is no longer in use.
    //

    SET_IRP_FREE( Irp );

    //
    // Check whether one of the send IRPs is waiting for data.
    //

    irpInfo = NULL;

    if ( !IS_IRP_BUSY( transmitInfo->Send1.Irp ) ) {
        irpInfo = &transmitInfo->Send1;
    } else if ( !IS_IRP_BUSY( transmitInfo->Send2.Irp ) ) {
        irpInfo = &transmitInfo->Send2;
    }

    //
    // If both send IRPs are in the TDI provider, reset the read IRP to
    // "free", remember that there is read data available, and wait for
    // a send to complete.
    //

    if ( irpInfo == NULL ) {

        ASSERT( transmitInfo->FileMdl == NULL );

        transmitInfo->FileMdl = Irp->MdlAddress;
        Irp->MdlAddress = NULL;
        transmitInfo->FileMdlLength = Irp->IoStatus.Information;
        SET_IRP_FREE( Irp );
        SET_READ_PENDING( transmitInfo, FALSE );

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
        return STATUS_MORE_PROCESSING_REQUIRED;
    }

    //
    // There is a send IRP that we'll give to the TDI provider.  Move
    // the buffers from the read IRP to the send IRP.  If we need to
    // send the head buffer, do so.
    //

    sendLength = AfdBuildTransmitSendMdls(
                     transmitInfo,
                     Irp->MdlAddress,
                     Irp->IoStatus.Information,
                     irpInfo,
                     &disconnectIrp
                     );

    //
    // If we have read all of the file data we were requested to read,
    // there is no need to submit another read IRP.  Check for this
    // condition before releasing the lock in order to synchronize with
    // send completion.
    //

    if ( transmitInfo->BytesRead == transmitInfo->FileWriteLength ) {

        readMore = FALSE;

        //
        // Note that there is no longer a read pending for this transmit
        // IRP.
        //

        SET_READ_PENDING( transmitInfo, FALSE );

    } else {

        //
        // Leave the ReadPending flag set so that completion does not
        // occur between our releasing the spin lock and attempting to
        // queue another read.
        //

        readMore = TRUE;
    }

    //
    // Remember that this send IRP is in use and release the lock.
    //

    SET_IRP_BUSY( irpInfo->Irp );

    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

    //
    // Remember the TDI device object in a local variable.  This is
    // necessary because as soon as we call IoCallDriver for the send,
    // the TransmitInfo structure may be freed up and have been reset.
    //

    tdiDeviceObject = transmitInfo->TdiDeviceObject;

    //
    // Finish setting up the send IRP and hand it off to the TDI
    // provider.
    //

    AfdRebuildSend( irpInfo->Irp, transmitInfo->TdiFileObject, sendLength );

    IoCallDriver( tdiDeviceObject, irpInfo->Irp );

    //
    // If appropriate, submit a graceful disconnect on the endpoint.
    //

    if ( disconnectIrp != NULL ) {
        IoCallDriver( tdiDeviceObject, disconnectIrp );
    }

    //
    // If there's more file data to read, queue work to a thread so that
    // we can perform another read on the file.  It is illegal to do a
    // cache read in a completion routine because completion routines
    // may be called at raised IRQL.
    //

    if ( readMore ) {
        AfdQueueTransmitRead( transmitInfo );
    }

    return STATUS_MORE_PROCESSING_REQUIRED;

} // AfdRestartTransmitRead


NTSTATUS
AfdRestartTransmitSend (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

    This is the completion routine for TDI send IRPs used for transmit
    file requests.  This routine updates information based on the
    results of the send and checks whether there is more file data
    available to be sent.  If there is more data, it is placed into the
    send IRP and the IRP is resubmitted to the TDI provider.  If no data
    is available, the send IRP is simply held until file data becomes
    available.

Arguments:

    DeviceObject - ignored.

    Irp - the send IRP that is completing.

    Context - a pointer to the TransmitInfo structure that describes
        the transmit file request corresponding to the IRP that is
        completing.

Return Value:

    STATUS_MORE_PROCESSING_REQUIRED which indicates to the I/O system
    that it should stop completion processing of this IRP.  We handle
    all completion from this point forward.

--*/

{
    PAFD_TRANSMIT_FILE_INFO_INTERNAL transmitInfo;
    PAFD_TRANSMIT_IRP_INFO irpInfo;
    KIRQL oldIrql;
    KIRQL cancelIrql;
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    ULONG sendLength;
    BOOLEAN readMore;
    BOOLEAN sendAgain;
    PIRP disconnectIrp;
    PDEVICE_OBJECT tdiDeviceObject;
    NTSTATUS status;

    //
    // Initialize local variables.
    //

    transmitInfo = Context;

    endpoint = transmitInfo->Endpoint;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );
    ASSERT( endpoint->TransmitInfo == transmitInfo );

    connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );
    ASSERT( connection->Type == AfdBlockTypeConnection );

    ASSERT( IS_IRP_BUSY( Irp ) );
    ASSERT( transmitInfo->Send1.Irp == Irp || transmitInfo->Send2.Irp == Irp );
    ASSERT( !transmitInfo->NeedToSendHead );

    //
    // Determine which of the two send IRPs completed.  This completion
    // routine is used for both of the TDI send IRPs.  We use two send
    // IRPs in order to ensure that the TDI provider always has enough
    // data to send at any given time.  This prevents Nagling delays and
    // sub-MTU packets.
    //

    if ( transmitInfo->Send1.Irp == Irp ) {
        irpInfo = &transmitInfo->Send1;
    } else {
        irpInfo = &transmitInfo->Send2;
    }

    //
    // If we didn't send any file data, there is no need to return file
    // MDLs or AFD buffers.  The FileWriteLength will be nonzero if we
    // sent file data.
    //

    if ( transmitInfo->FileWriteLength != 0 ) {

        //
        // Free the AFD buffer if we allocated one for this request, or
        // else release the MDLs to the file system.
        //

        if ( irpInfo->AfdBuffer != NULL ) {

            //
            // If this send IRP was used to send the tail buffer, reset
            // the Next pointer of the last file MDL to NULL.
            //

            if ( transmitInfo->IrpUsedToSendTail == Irp ) {
                transmitInfo->LastFileMdlBeforeTail->Next = NULL;
            }

            //
            // Free the AFD buffer used for the request.
            //

            irpInfo->AfdBuffer->Mdl->ByteCount = irpInfo->AfdBuffer->BufferLength;
            AfdReturnBuffer( irpInfo->AfdBuffer );
            irpInfo->AfdBuffer = NULL;

        } else {

            //
            // We need to be careful to return only file system MDLs to
            // the file system.  We cannot give head or tail buffer MDLs
            // to the file system.  If the head buffer MDL was at the
            // front of this IRP's MDL chain, use the first actual file
            // MDL.
            //

            if ( Irp->MdlAddress == transmitInfo->HeadMdl ) {
                Irp->MdlAddress = transmitInfo->FirstFileMdlAfterHead;
            }

            //
            // If this send IRP was used to send the tail buffer, reset
            // the Next pointer of the last file MDL to NULL.
            //

            if ( transmitInfo->IrpUsedToSendTail == Irp ) {
                transmitInfo->LastFileMdlBeforeTail->Next = NULL;
            }

            //
            // Now we can return the file data MDLs to the file system.
            //

            status = AfdMdlReadComplete(
                         transmitInfo->FileObject,
                         Irp->MdlAddress,
                         transmitInfo->Offset + transmitInfo->BytesRead,
                         irpInfo->Length
                         );
            ASSERT( NT_SUCCESS(status) );
        }
    }

    //
    // If the send failed or we're in the process of completing the
    // transmit IRP, start/continue the process of completing the
    // transmit IRP.
    //

    if ( !NT_SUCCESS(Irp->IoStatus.Status) || transmitInfo->CompletionPending ) {

        KIRQL cancelIrql;

        IoAcquireCancelSpinLock( &cancelIrql );

        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
        SET_IRP_FREE( Irp );
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        KdPrint(( "AfdRestartTransmitSend: failed, status == %lx\n",
                      Irp->IoStatus.Status ));

        AfdCompleteTransmit( transmitInfo, Irp->IoStatus.Status, cancelIrql );
        return STATUS_MORE_PROCESSING_REQUIRED;
    }

    //
    // Update the count of file data bytes we've sent so far.
    //

    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

    transmitInfo->BytesSent =
        transmitInfo->BytesSent + Irp->IoStatus.Information;

    ASSERT( transmitInfo->BytesSent <= transmitInfo->TotalBytesToSend );

    //
    // If we have sent all of the file data, then we've done all the
    // necessary work for the transmit file IRP.  Complete the IRP.
    //

    if ( transmitInfo->BytesSent == transmitInfo->TotalBytesToSend ) {

        ASSERT( transmitInfo->BytesSent ==
                    transmitInfo->BytesRead + transmitInfo->HeadLength +
                        transmitInfo->TailLength );

        //
        // Release the endpoint lock, then reacquire both the cancel
        // lock and the endpoint lock in the correct lock acquisition
        // order.  We must hold the cancel spin lock when calling
        // AfdCompleteTransmit() and we must hold the endpoint lock to
        // set the send IRP as free.
        //

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        IoAcquireCancelSpinLock( &cancelIrql );
        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
        SET_IRP_FREE( Irp );
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        AfdCompleteTransmit( transmitInfo, STATUS_SUCCESS, cancelIrql );

        return STATUS_MORE_PROCESSING_REQUIRED;
    }

    //
    // Check whether there is more file data waiting to be sent.  If
    // there is more data we can send it immediately.
    //

    if ( transmitInfo->FileMdl != NULL ) {

        //
        // There is data available in the read IRP.  Move the buffers
        // to this send IRP.
        //

        sendLength = AfdBuildTransmitSendMdls(
                         transmitInfo,
                         transmitInfo->FileMdl,
                         transmitInfo->FileMdlLength,
                         irpInfo,
                         &disconnectIrp
                         );

        transmitInfo->FileMdl = NULL;
        sendAgain = TRUE;

        //
        // If we have read all of the file data we were requested to
        // read, there is no need to submit another read IRP.  Check for
        // this condition before releasing the lock in order to
        // synchronize with send completion.  Note that we will not
        // attempt to submit another read if a read is already pending.
        //

        if ( transmitInfo->BytesRead == transmitInfo->FileWriteLength ||
                 transmitInfo->ReadPending ) {
            readMore = FALSE;
        } else {
            readMore = TRUE;
            SET_READ_PENDING( transmitInfo, TRUE );
        }

    } else {

        //
        // There is no read data available now, so there must already be
        // a read pending or else we've sent all the file data.
        //

        readMore = FALSE;
        ASSERT( transmitInfo->BytesRead == transmitInfo->FileWriteLength ||
                    transmitInfo->ReadPending );

        //
        // This send IRP is now available for use as soon as a read
        // completes.
        //

        sendAgain = FALSE;
        SET_IRP_FREE( Irp );
    }

    //
    // Release the lock.  We cannot submit IRPs while holding a lock.
    //

    AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

    //
    // If there was file data immediately available to be sent, finish
    // setting up the send IRP and hand it off to the TDI provider.
    //

    if ( sendAgain ) {

        //
        // Remember the TDI device object in a local variable.  This is
        // necessary because as soon as we call IoCallDriver for the
        // send, the TransmitInfo structure may be freed up and have
        // been reset.
        //

        tdiDeviceObject = transmitInfo->TdiDeviceObject;

        AfdRebuildSend( irpInfo->Irp, transmitInfo->TdiFileObject, sendLength );
        IoCallDriver( tdiDeviceObject, irpInfo->Irp );

        //
        // If appropriate, submit a graceful disconnect on the endpoint.
        //

        if ( disconnectIrp != NULL ) {
            IoCallDriver( tdiDeviceObject, disconnectIrp );
        }
    }

    //
    // If there is more file data to read, queue work to a thread so
    // that we can perform another read on the file.  It is illegal to
    // do a cache read in a completion routine.
    //

    if ( readMore ) {
        AfdQueueTransmitRead( transmitInfo );
    }

    return STATUS_MORE_PROCESSING_REQUIRED;

} // AfdRestartTransmitSend


VOID
AfdCompleteTransmit (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo,
    IN NTSTATUS Status,
    IN KIRQL OldIrql
    )

/*++

Routine Description:

    This routine is responsible for handling all aspects of completing a
    transmit file request.  First it checks to make sure that all
    aspects of the request (read IRPs, send IRPs, queued reads to
    threads, etc.) have completed.  If any are still pending, they
    are cancelled and this routine exits until they complete.

    When everything has finished, this routine cleans up the resources
    allocated for the request and completed the transmit file IRP.

Arguments:

    TransmitInfo - a pointer to the TransmitInfo structure which
        contains information about the request to process.

Return Value:

    None.

--*/

{
    KIRQL endpointOldIrql;
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    NTSTATUS status;
    BOOLEAN reuseSocket;
    PMDL fileMdl;
    PIRP transmitIrp;

    endpoint = TransmitInfo->Endpoint;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );
    ASSERT( endpoint->TransmitInfo == TransmitInfo );

    connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );
    ASSERT( connection != NULL );
    ASSERT( connection->Type == AfdBlockTypeConnection );

    //
    // Make sure that we hold the cancel spin lock for the followiung
    // tests.  Then acquire the endpoint spin lock for proper
    // synchronization.
    //

    ASSERT( KeGetCurrentIrql( ) == DISPATCH_LEVEL );

    AfdAcquireSpinLock( &endpoint->SpinLock, &endpointOldIrql );

    transmitIrp = TransmitInfo->TransmitIrp;

    ASSERT( endpoint->TransmitIrp == NULL || endpoint->TransmitIrp == transmitIrp );

    //
    // If this transmit IRP is on the TransmitFile queue, remove it.
    //

    if( TransmitInfo->Queued ) {

        RemoveEntryList(
            &transmitIrp->Tail.Overlay.ListEntry
            );

        TransmitInfo->Queued = FALSE;

    }

    //
    // Remember the completion status in the transmit IRP.  Note that we
    // use the first failure status code as the completion status code.
    // Subsequent failures (for example STATUS_CANCELLED) are ignored.
    //

    if ( NT_SUCCESS(transmitIrp->IoStatus.Status) ) {
        transmitIrp->IoStatus.Status = Status;
    }

    //
    // Note that we only attempt to do the disconnect and socket reuse
    // if the transmit request was successful.  If it fails for any
    // reason, we do not begin disconnecting the connection.
    //

    if ( !NT_SUCCESS(transmitIrp->IoStatus.Status) ||
             (TransmitInfo->Flags & AFD_TF_REUSE_SOCKET) == 0 ) {

        endpoint->TransmitIrp = NULL;
        reuseSocket = FALSE;

        //
        // We're doing our best to complete the transmit IRP, so remove
        // the cancel routine from the transmit IRP.  Also remove the
        // transmit IRP pointer from the endpoint structure in order to
        // synchronize with cleanup IRPs.
        //

        IoSetCancelRoutine( transmitIrp, NULL );

    } else {

        PIO_STACK_LOCATION irpSp;

        reuseSocket = TRUE;

        //
        // Reset the control code in our stack location in the IRP
        // so that the cancel routine knows about the special state
        // of this IRP and cancels it appropriately.
        //

        irpSp = IoGetCurrentIrpStackLocation( transmitIrp );
        irpSp->Parameters.DeviceIoControl.IoControlCode = 0;
    }

    //
    // Remember that we are in the process of completing this IRP.
    // Other steps in transmit IRP processing use this flag to know
    // whether to bail out immediately instead of continuing to attempt
    // transmit processing.
    //

    TransmitInfo->CompletionPending = TRUE;

    //
    // Determine whether any of the child IRPs are still outstanding.
    // If any are, cancel them.  Note that if any of these IRPs was not
    // in a cancellable state (IoCancelIrp() returns FALSE) there's
    // nothing we can do, so just plow on and wait for the IRPs to
    // complete.
    //
    // As soon as we hit an active IRP quit processing.  We must quit
    // because the cancel spin lock gets released by IoCancelIrp() and
    // the IRP of interest could get completed immediately and reenter
    // AfdCompleteTransmit(), which could complete the transmit IRP
    // before we continue executing.
    //

    if ( TransmitInfo->Read.Irp != NULL && IS_IRP_BUSY(TransmitInfo->Read.Irp) ) {

        TransmitInfo->Read.Irp->CancelIrql = OldIrql;
        UPDATE_TRANSMIT_DEBUG_INFO( TransmitInfo, 1, 0 );
        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );

        AfdCancelIrp( TransmitInfo->Read.Irp );

        return;
    }

    if ( IS_IRP_BUSY(TransmitInfo->Send1.Irp) ) {

        TransmitInfo->Send1.Irp->CancelIrql = OldIrql;
        UPDATE_TRANSMIT_DEBUG_INFO( TransmitInfo, 2, 0 );
        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );

        AfdCancelIrp( TransmitInfo->Send1.Irp );

        return;
    }

    if ( IS_IRP_BUSY(TransmitInfo->Send2.Irp) ) {

        TransmitInfo->Send2.Irp->CancelIrql = OldIrql;
        UPDATE_TRANSMIT_DEBUG_INFO( TransmitInfo, 3, 0 );
        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );

        AfdCancelIrp( TransmitInfo->Send2.Irp );

        return;
    }

    //
    // If there is a read about to happen, bail.  When the read
    // completes the appropriate routine will check the
    // CompletionPending flag and call this routine again.
    //

    if ( TransmitInfo->ReadPending ) {

        UPDATE_TRANSMIT_DEBUG_INFO( TransmitInfo, 4, 0 );

        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );
        IoReleaseCancelSpinLock( OldIrql );

        return;
    }

#if DBG
    TransmitInfo->Completed = TRUE;
#endif

    //
    // Everything is on track to complete the transmit IRP, so we're
    // full steam ahead.  Free the resources allocated to service this
    // request.
    //

    if ( TransmitInfo->Read.Irp != NULL ) {
        IoFreeIrp( TransmitInfo->Read.Irp );
    }

    IoFreeIrp( TransmitInfo->Send1.Irp );
    IoFreeIrp( TransmitInfo->Send2.Irp );

    //
    // If there was an AFD buffer with read data, free it.  If there was
    // no AFD buffer but FileMdl is non-NULL, then we have some file
    // system MDLs which we need to free.
    //

    if ( TransmitInfo->Read.AfdBuffer != NULL ) {

        TransmitInfo->Read.AfdBuffer->Mdl->ByteCount =
            TransmitInfo->Read.AfdBuffer->BufferLength;
        AfdReturnBuffer( TransmitInfo->Read.AfdBuffer );

        TransmitInfo->Read.AfdBuffer = NULL;

        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );
        IoReleaseCancelSpinLock( OldIrql );

    } else if ( TransmitInfo->FileMdl != NULL ) {

        fileMdl = TransmitInfo->FileMdl;
        TransmitInfo->FileMdl = NULL;

        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );
        IoReleaseCancelSpinLock( OldIrql );

        status = AfdMdlReadComplete(
                     TransmitInfo->FileObject,
                     fileMdl,
                     TransmitInfo->Offset + TransmitInfo->BytesRead,
                     TransmitInfo->Read.Length
                     );
        ASSERT( NT_SUCCESS(status) );

    } else {

        AfdReleaseSpinLock( &endpoint->SpinLock, endpointOldIrql );
        IoReleaseCancelSpinLock( OldIrql );
    }

    if ( TransmitInfo->Send1.AfdBuffer != NULL ) {
        TransmitInfo->Send1.AfdBuffer->Mdl->ByteCount =
            TransmitInfo->Send1.AfdBuffer->BufferLength;
        AfdReturnBuffer( TransmitInfo->Send1.AfdBuffer );
    }

    if ( TransmitInfo->Send2.AfdBuffer != NULL ) {
        TransmitInfo->Send2.AfdBuffer->Mdl->ByteCount =
            TransmitInfo->Send2.AfdBuffer->BufferLength;
        AfdReturnBuffer( TransmitInfo->Send2.AfdBuffer );
    }

    if ( TransmitInfo->HeadMdl != NULL ) {
        MmUnlockPages( TransmitInfo->HeadMdl );
        IoFreeMdl( TransmitInfo->HeadMdl );
    }

    if ( TransmitInfo->TailMdl != NULL ) {
        MmUnlockPages( TransmitInfo->TailMdl );
        IoFreeMdl( TransmitInfo->TailMdl );
    }

#if DBG
    if ( TransmitInfo->Debug1 != NULL ) {
        AFD_FREE_POOL(
            TransmitInfo->Debug1,
            AFD_TRANSMIT_DEBUG_POOL_TAG
            );
        TransmitInfo->Debug1 = NULL;
    }
#endif

    //
    // Update the file position and clean up the reference count.
    //

    TransmitInfo->FileObject->CurrentByteOffset.QuadPart += TransmitInfo->BytesRead;

    ObDereferenceObject( TransmitInfo->FileObject );
    AfdRecordFileDeref();

    //
    // Remember how many bytes we sent with this request.
    //

    transmitIrp->IoStatus.Information = (ULONG)TransmitInfo->BytesSent;

    //
    // Begin socket reuse if so requested.  This causes the transmit
    // not to complete until the connection is fully disconnected
    // and the endpoint is ready for reuse, i.e.  it is in the same
    // state as if it had just been opened.
    //

    if ( reuseSocket ) {

        //
        // Remember that there is a transmit IRP pended on the endpoint,
        // so that when we're freeing up the connection we also complete
        // the transmit IRP.
        //

        connection->ClosePendedTransmit = TRUE;

        //
        // Since we are going to effectively close this connection,
        // remember that we have started cleanup on this connection.
        // This allows AfdDeleteConnectedReference to remove the
        // connected reference when appropriate.
        //

        connection->CleanupBegun = TRUE;

        //
        // Attempt to remove the connected reference.
        //

        AfdDeleteConnectedReference( connection, FALSE );

        //
        // Delete the endpoint's reference to the connection in
        // preparation for reusing this endpoint.
        //

        endpoint->Common.VcConnecting.Connection = NULL;
        DEREFERENCE_CONNECTION( connection );

        //
        // DO NOT access the IRP after this point, since it may have
        // been completed inside AfdDereferenceConnection!
        //
    }

    //
    // Complete the actual transmit file IRP, unless we need to pend it
    // until the connection is fully disconnected as requested by the
    // AFD_TF_REUSE_SOCKET flag.
    //
    // If we are going to wait on completion until the connection object
    // is disconnected, note that we do not have a cancellation routine
    // in the transmit IRP any more.  This generally shouldn't cause a
    // problem because the time for a cancellation is bounded.
    //

    if ( !reuseSocket ) {

        IoCompleteRequest( transmitIrp, AfdPriorityBoost );

        //
        // If we're enforcing a maximum active TransmitFile count, then
        // check the list of queued TransmitFile requests and start the
        // next one.
        //

        if( AfdMaxActiveTransmitFileCount > 0 ) {

            AfdStartNextQueuedTransmitFile();

        }

    }

    //
    // Don't free the transmit info structure here, leave
    // it attached to the endpoint. The structure will get
    // freed when we free the endpoint.
    //

} // AfdCompleteTransmit


NTSTATUS
AfdBuildReadIrp (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    )

/*++

Routine Description:

    This routine builds a read file data IRP for a transmit file
    request.  It determines how much data needs to be read and builds an
    IRP appropriate to the functionality supported by the file system.

Arguments:

    TransmitInfo - a pointer to the TransmitInfo structure which
        contains information about the request to process.

Return Value:

    NTSTATUS - indicates whether the IRP was built successfully.

--*/

{
    ULONG readLength;
    PIO_STACK_LOCATION readIrpSp;

    ASSERT( TransmitInfo->Endpoint->TransmitInfo == TransmitInfo );

    //
    // If we haven't already done so, allocate and initialize the IRP
    // that we'll use to read file data.
    //

    if ( TransmitInfo->Read.Irp == NULL ) {

        TransmitInfo->Read.Irp =
            IoAllocateIrp( TransmitInfo->DeviceObject->StackSize, TRUE );
        if ( TransmitInfo->Read.Irp == NULL ) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        readIrpSp = IoGetNextIrpStackLocation( TransmitInfo->Read.Irp );
        readIrpSp->MajorFunction = IRP_MJ_READ;
    }

    //
    // We have to rebuild parts of the stack location because
    // the IO system zeros them out on every I/O completion.
    //

    readIrpSp = IoGetNextIrpStackLocation( TransmitInfo->Read.Irp );
    readIrpSp->FileObject = TransmitInfo->FileObject;

    IoSetCompletionRoutine(
        TransmitInfo->Read.Irp,
        AfdRestartTransmitRead,
        TransmitInfo,
        TRUE,
        TRUE,
        TRUE
        );

    ASSERT( readIrpSp->MajorFunction == IRP_MJ_READ );
    ASSERT( readIrpSp->Parameters.Read.Key == 0 );
    ASSERT( !IS_IRP_BUSY(TransmitInfo->Read.Irp) );

    //
    // Determine how many bytes we will attempt to read.  This is
    // either the send packet size or the remaining bytes in the file.
    //

    if ( TransmitInfo->FileWriteLength - TransmitInfo->BytesRead >
             TransmitInfo->SendPacketLength ) {
        readLength = TransmitInfo->SendPacketLength;
    } else {
        readLength =
            (ULONG)(TransmitInfo->FileWriteLength - TransmitInfo->BytesRead);
    }

    TransmitInfo->Read.Length = readLength;

    readIrpSp = IoGetNextIrpStackLocation(TransmitInfo->Read.Irp );

    //
    // If supported by the file system, try to perform MDL I/O to get
    // MDLs that we can pass to the TDI provider.  This is by far the
    // fastest way to get the file data because it avoids all file
    // copies.
    //

    if ( (TransmitInfo->FileObject->Flags & FO_CACHE_SUPPORTED) != 0 ) {

        readIrpSp->MinorFunction = IRP_MN_MDL;
        TransmitInfo->Read.Irp->MdlAddress = NULL;

        //
        // Set the synchronous flag in the IRP to tell the file system
        // that we are aware of the fact that this IRP will be completed
        // synchronously.  This means that we must supply our own thread
        // for the operation and that the disk read will occur
        // synchronously in this thread if the data is not cached.
        //

        TransmitInfo->Read.Irp->Flags |= IRP_SYNCHRONOUS_API;

    } else {

        //
        // The file system does not support the special cache manager
        // routines.  Allocate an AFD buffer for the request.
        //

        TransmitInfo->Read.AfdBuffer = AfdGetBuffer( readLength, 0 );
        if ( TransmitInfo->Read.AfdBuffer == NULL ) {
            return STATUS_INSUFFICIENT_RESOURCES;
        }

        readIrpSp->MinorFunction = IRP_MN_NORMAL;

        TransmitInfo->Read.Irp->MdlAddress = TransmitInfo->Read.AfdBuffer->Mdl;
        TransmitInfo->Read.Irp->AssociatedIrp.SystemBuffer =
            TransmitInfo->Read.AfdBuffer->Buffer;
        TransmitInfo->Read.Irp->UserBuffer =
            TransmitInfo->Read.AfdBuffer->Buffer;
    }

    //
    // Finish building the read IRP.
    //

    readIrpSp->Parameters.Read.Length = readLength;
    readIrpSp->Parameters.Read.ByteOffset.QuadPart =
            TransmitInfo->Offset + TransmitInfo->BytesRead;

    return STATUS_SUCCESS;

} // AfdBuildReadIrp


ULONG
AfdBuildTransmitSendMdls (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo,
    IN PMDL FileMdlChain,
    IN ULONG FileDataLength,
    IN PAFD_TRANSMIT_IRP_INFO IrpInfo,
    OUT PIRP *DisconnectIrp
    )

/*++

Routine Description:

    This routine sets up the MDL chain in a send IRP.  Typically this
    just means moving file data MDLs to the send IRP, but it may also
    involve chaining a head buffer MDL at the beginning of the chain
    and/or putting a tail buffer MDL at the end of the chain.

Arguments:

    TransmitInfo - a pointer to the TransmitInfo structure which
        contains information about the request to process.

    FileMdlChain - a pointer to the first MDL in a chain of file data
        MDLs.

    FileDataLength - the number of bytes in the file data MDL chain.

    IrpInfo - a pointer to the IrpInfo structure which contains the
        send IRP of interest.

    DisconnectIrp - set on output to indicate that this is the final
        send of the TransmitFile request, and that the caller should
        submit the disconnect IRP after submitting the send IRP.

Return Value:

    The total number of bytes represented by the MDLs in the send IRP.

Notes:

    In order for this routine to synchronize properly its access to the
    TransmitInfo structure is MUST be called with the endpoint spin lock
    held.

--*/

{
    ULONG sendLength;
    PMDL lastMdl;

    ASSERT( TransmitInfo->Endpoint->TransmitInfo == TransmitInfo );

    //
    // This routine MUST be called with the endpoint spin lock held.
    //

    ASSERT( KeGetCurrentIrql( ) >= DISPATCH_LEVEL );

    //
    // If we need to send the head buffer, chain file data MDLs after
    // the head buffer MDLs.
    //

    if ( TransmitInfo->NeedToSendHead ) {

        ASSERT( TransmitInfo->HeadMdl != NULL );

        //
        // Now that we're about to send the head buffer, there is no
        // need to send it again.
        //

        TransmitInfo->NeedToSendHead = FALSE;

        //
        // Find the last MDL in the chain of head buffer MDLs.
        //

        for ( lastMdl = TransmitInfo->HeadMdl;
              lastMdl->Next != NULL;
              lastMdl = lastMdl->Next );

        //
        // Chain the file MDLs after the last head MDL.
        //

        lastMdl->Next = FileMdlChain;

        //
        // Put the head buffer MDL into the send IRP.
        //

        IrpInfo->Irp->MdlAddress = TransmitInfo->HeadMdl;
        IrpInfo->AfdBuffer = TransmitInfo->Read.AfdBuffer;
        IrpInfo->Length = TransmitInfo->Read.Length;
        TransmitInfo->Read.AfdBuffer = NULL;

        //
        // Remember a pointer to the first actual file MDL so that we
        // can quickly jump to it when the send completes and we need
        // to return the file MDLs to the file system.
        //

        TransmitInfo->FirstFileMdlAfterHead = FileMdlChain;

        //
        // Calculate the number of bytes in the MDLs so far.
        //

        sendLength = FileDataLength + TransmitInfo->HeadLength;

    } else {

        IrpInfo->Irp->MdlAddress = FileMdlChain;
        IrpInfo->AfdBuffer = TransmitInfo->Read.AfdBuffer;
        IrpInfo->Length = TransmitInfo->Read.Length;
        TransmitInfo->Read.AfdBuffer = NULL;

        sendLength = FileDataLength;
    }

    //
    // If we have read all the file data, put any tail buffer MDLs at
    // the end of the MDL chain.
    //

    if ( TransmitInfo->BytesRead == TransmitInfo->FileWriteLength ) {

        //
        // If the caller needs to do a disconnect after the send, get a
        // disconnect IRP.
        //

        if ( (TransmitInfo->Flags & AFD_TF_DISCONNECT) != 0 ) {
            (VOID)AfdBeginDisconnect(
                      TransmitInfo->Endpoint,
                      NULL,
                      DisconnectIrp
                      );
        } else {
            *DisconnectIrp = NULL;
        }

        if ( TransmitInfo->TailMdl != NULL ) {

            //
            // Find the last MDL in the chain.  If the FileMdlChain is
            // NULL, then we're not sending any file data, so use the
            // head MDL chain (if present) or just tag it on to the IRP
            // if all we're sending is the tail.
            //

            if ( FileMdlChain != NULL ) {

                for ( lastMdl = FileMdlChain;
                      lastMdl->Next != NULL;
                      lastMdl = lastMdl->Next );

                //
                // Chain the tail MDLs after the last file MDL.
                //

                lastMdl->Next = TransmitInfo->TailMdl;

                //
                // Remember a pointer to the last file MDL before the
                // tail MDLs so that we can quickly jump to it when the
                // send completes and we need to return the file MDLs to
                // the system.  Note that we must reset the Next pointer
                // on this MDL to NULL before returning it to the file
                // system.
                //

                TransmitInfo->LastFileMdlBeforeTail = lastMdl;

            } else if ( IrpInfo->Irp->MdlAddress !=NULL ) {

                for ( lastMdl = IrpInfo->Irp->MdlAddress;
                      lastMdl->Next != NULL;
                      lastMdl = lastMdl->Next );

                //
                // Chain the tail MDLs after the last head buffer MDL.
                //

                lastMdl->Next = TransmitInfo->TailMdl;

            } else {

                //
                // We're only sending a tail buffer here.
                //

                IrpInfo->Irp->MdlAddress = TransmitInfo->TailMdl;
            }

            //
            // Remember the IRP we used to send the tail so that the
            // send completion routine knows whether it needs to read
            // just the file MDLs.
            //

            TransmitInfo->IrpUsedToSendTail = IrpInfo->Irp;

            //
            // Calculate the number of bytes in the MDLs so far.
            //

            sendLength += TransmitInfo->TailLength;
        }

    } else {

        *DisconnectIrp = NULL;
    }

    //
    // Return the total number of bytes in the MDLs we chained off the
    // send IRP.
    //

    return sendLength;

} // AfdBuildTransmitSendMdls


VOID
AfdCancelTransmit (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp
    )

/*++

Routine Description:

    The cancel routine for transmit requests.  This routine simply
    calls AfdCompleteTransmit which performs the actual work of
    killing the transmit request.

Arguments:

    DeviceObject - ignored.

    Irp - a pointer to the transmit file IRP to cancel.

Return Value:

    None.

--*/

{
    KIRQL oldIrql;
    PIO_STACK_LOCATION irpSp;
    PAFD_ENDPOINT endpoint;

    //
    // Initialize some locals and grab the endpoint spin lock.
    //

    irpSp = IoGetCurrentIrpStackLocation( Irp );

    endpoint = irpSp->FileObject->FsContext;
    ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );

    AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );

    //
    // Test whether the transmit request is normally cancellable or if
    // it is in the process of closing the connection, in which case we
    // will complete it directly.
    //

    if ( irpSp->Parameters.DeviceIoControl.IoControlCode != 0 ) {

        ASSERT( irpSp->Parameters.DeviceIoControl.IoControlCode ==
                    IOCTL_AFD_TRANSMIT_FILE );

        ASSERT( endpoint->TransmitInfo ==
            (PAFD_TRANSMIT_FILE_INFO_INTERNAL)Irp->AssociatedIrp.SystemBuffer );

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );

        //
        // The transmit request is in the normal cancellation state.
        // Just call the completion routine to handle the cancellation.
        //

        AfdCompleteTransmit(
            (PAFD_TRANSMIT_FILE_INFO_INTERNAL)(Irp->AssociatedIrp.SystemBuffer),
            STATUS_CANCELLED,
            Irp->CancelIrql
            );

    } else {

        //
        // The transmit request is in the process of closing the
        // connection.  Just complete the transmit IRP and let the
        // connection closure proceed as normal.
        //

        endpoint->TransmitIrp = NULL;
        Irp->IoStatus.Status = STATUS_CANCELLED;
        IoSetCancelRoutine( Irp, NULL );

        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
        IoReleaseCancelSpinLock( Irp->CancelIrql );

        IoCompleteRequest( Irp, AfdPriorityBoost );
    }

    return;

} // AfdCancelTransmit


BOOLEAN
AfdCancelIrp (
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine is invoked to cancel an individual I/O Request Packet.
    It is similiar to IoCancelIrp() except that it *must* be called with
    the cancel spin lock held.  This routine exists because of the
    synchronization requirements of the cancellation/completion of
    transmit IRPs.

Arguments:

    Irp - Supplies a pointer to the IRP to be cancelled.  The CancelIrql
        field of the IRP must have been correctly initialized with the
        IRQL from the cancel spin lock acquisition.


Return Value:

    The function value is TRUE if the IRP was in a cancellable state (it
    had a cancel routine), else FALSE is returned.

Notes:

    It is assumed that the caller has taken the necessary action to ensure
    that the packet cannot be fully completed before invoking this routine.

--*/

{
    PDRIVER_CANCEL cancelRoutine;

    //
    // Make sure that the cancel spin lock is held.
    //

    ASSERT( KeGetCurrentIrql( ) == DISPATCH_LEVEL );

    //
    // Set the cancel flag in the IRP.
    //

    Irp->Cancel = TRUE;

    //
    // Obtain the address of the cancel routine, and if one was specified,
    // invoke it.
    //

    cancelRoutine = Irp->CancelRoutine;
    if (cancelRoutine) {
        if (Irp->CurrentLocation > (CCHAR) (Irp->StackCount + 1)) {
            KeBugCheckEx( CANCEL_STATE_IN_COMPLETED_IRP, (ULONG) Irp, 0, 0, 0 );
        }
        Irp->CancelRoutine = (PDRIVER_CANCEL) NULL;
        cancelRoutine( Irp->Tail.Overlay.CurrentStackLocation->DeviceObject,
                       Irp );
        //
        // The cancel spinlock should have been released by the cancel routine.
        //

        return(TRUE);

    } else {

        //
        // There was no cancel routine, so release the cancel spinlock and
        // return indicating the Irp was not currently cancelable.
        //

        IoReleaseCancelSpinLock( Irp->CancelIrql );

        return(FALSE);
    }

} // AfdCancelIrp


VOID
AfdQueueTransmitRead (
    IN PAFD_TRANSMIT_FILE_INFO_INTERNAL TransmitInfo
    )

/*++

Routine Description:

    Because FsRtl fast reads must be performed in thread context,
    this routine is used to queue reads to a separate thread.

Arguments:

    TransmitInfo - a pointer to the TransmitInfo structure which
        contains information about the request to process.

Return Value:

    None.

--*/

{
    ASSERT( !TransmitInfo->Completed );
    ASSERT( TransmitInfo->ReadPending );
    ASSERT( TransmitInfo->Endpoint->TransmitInfo == TransmitInfo );

    //
    // Initialize an executive work quete item and hand it off to an
    // executive worker thread.
    //

    ExInitializeWorkItem(
        &TransmitInfo->WorkQueueItem,
        AfdStartTransmitIo,
        TransmitInfo
        );
    ExQueueWorkItem( &TransmitInfo->WorkQueueItem, DelayedWorkQueue );

    //
    // All done.
    //

    return;

} // AfdQueueTransmitRead


VOID
AfdCompleteClosePendedTransmit (
    IN PAFD_ENDPOINT Endpoint
    )

/*++

Routine Description:

    Completes a transmit IRP that was waiting for the connection to be
    completely disconnected.

Arguments:

    Endpoint - the endpoint on which the transmit request is pending.

Return Value:

    None.

--*/

{
    PIRP irp;
    KIRQL cancelIrql;
    KIRQL oldIrql;
    PIRP transmitIrp;

    IoAcquireCancelSpinLock( &cancelIrql );
    AfdAcquireSpinLock( &Endpoint->SpinLock, &oldIrql );

    //
    // First make sure that thre is really a transmit request pended on
    // this endpoint.  We do this while holding the appropriate locks
    // to close the timing window that would exist otherwise, since
    // the caller may not have had the locks when making the test.
    //

    if ( Endpoint->TransmitIrp == NULL ) {
        AfdReleaseSpinLock( &Endpoint->SpinLock, oldIrql );
        IoReleaseCancelSpinLock( cancelIrql );
        return;
    }

    //
    // Grab the IRP from the endpoint and reset the endpoint's pointer
    // to it while still holding the locks so that nobody else accesses
    // the IRP.
    //

    transmitIrp = Endpoint->TransmitIrp;
    Endpoint->TransmitIrp = NULL;

    //
    // Reset the cancel routine in the IRP before attempting to complete
    // it.
    //

    IoSetCancelRoutine( transmitIrp, NULL );

    //
    // Release the lock before completing the transmit IRP--it is
    // illegal to call IoCompleteRequest while holding a spin lock.
    //

    AfdReleaseSpinLock( &Endpoint->SpinLock, oldIrql );
    IoReleaseCancelSpinLock( cancelIrql );

    //
    // Make sure to refresh the endpoint BEFORE completing the transmit
    // IRP.  This is because the user-mode caller may reuse the endpoint
    // as soon as the IRP completes, and there would be a timing window
    // between reuse of the endpoint and the refresh otherwise.
    //
    // Also, AfdRefreshEndpoint must be called at low IRQL since it must
    // do a KeAttachProcess to free some resources.
    //

    AfdRefreshEndpoint( Endpoint );

    //
    // Finally, we can complete the transmit request.
    //

    IoCompleteRequest( transmitIrp, AfdPriorityBoost );

    //
    // If we're enforcing a maximum active TransmitFile count, then
    // check the list of queued TransmitFile requests and start the
    // next one.
    //

    if( AfdMaxActiveTransmitFileCount > 0 ) {

        AfdStartNextQueuedTransmitFile();

    }

} // AfdCompleteClosePendedTransmit


VOID
AfdStartNextQueuedTransmitFile(
    VOID
    )
{

    KIRQL oldIrql;
    PLIST_ENTRY listEntry;
    PIRP irp;
    PAFD_TRANSMIT_FILE_INFO_INTERNAL transmitInfo;

    //
    // This should only be called if we're actually enforcing a maximum
    // TransmitFile count.
    //

    ASSERT( AfdMaxActiveTransmitFileCount > 0 );

    //
    // The TransmitFile request queue is protected by the I/O cancel
    // spinlock, so grab that lock before examining the queue.
    //

    IoAcquireCancelSpinLock( &oldIrql );

    //
    // This routine is only called after a pended TransmitFile IRP
    // completes, so account for that completion here.
    //

    ASSERT( AfdActiveTransmitFileCount > 0 );
    AfdActiveTransmitFileCount--;

    if( !IsListEmpty( &AfdQueuedTransmitFileListHead ) ) {

        //
        // Dequeue exactly one IRP from the list, then start the
        // TransmitFile.
        //

        listEntry = RemoveHeadList(
                        &AfdQueuedTransmitFileListHead
                        );

        irp = CONTAINING_RECORD(
                  listEntry,
                  IRP,
                  Tail.Overlay.ListEntry
                  );

        transmitInfo = irp->AssociatedIrp.SystemBuffer;

        ASSERT( transmitInfo != NULL );
        ASSERT( transmitInfo->Endpoint->TransmitInfo == transmitInfo );

        //
        // Mark this TransmitFile request as no longer queued.
        //

        ASSERT( transmitInfo->Queued );
        transmitInfo->Queued = FALSE;

        //
        // Adjust the count, release the I/O cancel spinlock, then queue
        // the TransmitFile.
        //

        AfdActiveTransmitFileCount++;
        ASSERT( AfdActiveTransmitFileCount <= AfdMaxActiveTransmitFileCount );

        IoReleaseCancelSpinLock( oldIrql );

        AfdQueueTransmitRead(
            transmitInfo
            );

    } else {

        //
        // Release the I/O cancel spinlock before returning.
        //

        IoReleaseCancelSpinLock( oldIrql );

    }

}   // AfdStartNextQueuedTransmitFile


BOOLEAN
AfdFastTransmitFile (
    IN struct _FILE_OBJECT *FileObject,
    IN PVOID InputBuffer OPTIONAL,
    IN ULONG InputBufferLength,
    OUT PIO_STATUS_BLOCK IoStatus
    )

/*++

Routine Description:

    Attempts to perform a fast TransmitFile call.  This will succeed
    only if the caller requests write behind, the file data to be sent
    is small, and the data is in the file system cache.

Arguments:

    FileObject - the endpoint file object of interest.

    InputBuffer - a buffer from the caller containing the
        AFD_TRANSMIT_FILE_INFO structure.

    InputBufferLength - the length of the above buffer.

    IoStatus - points to the IO status block that will be set on successful
        return from this function.

Return Value:

    TRUE if the fast path was successful; FALSE if we need to do through
    the normal path.

--*/

{
    PAFD_ENDPOINT endpoint;
    PAFD_CONNECTION connection;
    PAFD_TRANSMIT_FILE_INFO userTransmitInfo;
    PAFD_BUFFER afdBuffer;
    ULONG sendLength;
    PFILE_OBJECT fileObject;
    BOOLEAN success;
    BOOLEAN sendCountersUpdated;
    KIRQL oldIrql;
    ULONG fileWriteLength;
    NTSTATUS status;
    LARGE_INTEGER fileOffset;
    PMDL fileMdl;

    //
    // Initialize locals so that cleanup is easier.
    //

    fileObject = NULL;
    afdBuffer = NULL;
    sendCountersUpdated = FALSE;
    fileMdl = NULL;

    //
    // Any access to the user-specified input buffer must be done inside
    // a try-except block.
    //

    try {

        //
        // Make sure that the flags are specified such that a fast-path
        // TransmitFile is reasonable.  The caller must have specified
        // the write-behind flag, but not the disconnect or reuse
        // socket flags.
        //

        userTransmitInfo = InputBuffer;

        if ( userTransmitInfo->Flags != AFD_TF_WRITE_BEHIND ) {
            return FALSE;
        }

        //
        // Calculate the length the entire send.
        //

        fileWriteLength = userTransmitInfo->WriteLength.LowPart;

        sendLength = userTransmitInfo->HeadLength +
                         fileWriteLength +
                         userTransmitInfo->TailLength;

        //
        // Require the following for the fast path:
        //
        //    - The caller must specify the write length.
        //    - The write length must be less than the configured maximum.
        //    - If the entire send is larger than an AFD buffer page,
        //      we're going to use FsRtlMdlRead, so for purposes of
        //      simplicity there must be:
        //        - a head buffer, and
        //        - no tail buffer
        //    - The configured maximum will always be less than 4GB.
        //    - There be no limitation on the count of simultaneous
        //      TransmitFile calls.  The fast path would work around
        //      this limit, if it exists.
        //    - The head buffer, if any, fits on a single page.
        //

        if ( userTransmitInfo->WriteLength.LowPart == 0

                 ||

             sendLength > AfdMaxFastTransmit

                 ||

             ( sendLength > AfdMaxFastCopyTransmit &&
                   (userTransmitInfo->HeadLength == 0 ||
                    userTransmitInfo->TailLength != 0 ) )

                 ||

             userTransmitInfo->WriteLength.HighPart != 0

                 ||

             AfdMaxActiveTransmitFileCount != 0

                 ||

             userTransmitInfo->HeadLength > AfdBufferLengthForOnePage ) {

            return FALSE;
        }

        //
        // Initial request validity checks: is the endpoint connected, is
        // the input buffer large enough, etc.
        //

        endpoint = FileObject->FsContext;
        ASSERT( IS_AFD_ENDPOINT_TYPE( endpoint ) );

        if ( endpoint->Type != AfdBlockTypeVcConnecting ||
                 endpoint->State != AfdEndpointStateConnected ) {
            return FALSE;
        }

        connection = AFD_CONNECTION_FROM_ENDPOINT( endpoint );
        ASSERT( connection->Type == AfdBlockTypeConnection );

        if ( InputBufferLength < sizeof(AFD_TRANSMIT_FILE_INFO) ) {
            return FALSE;
        }

        //
        // Determine whether there is already too much send data
        // pending on the connection.  If there is too much send
        // data, don't do the fast path.
        //

        if ( AfdShouldSendBlock( endpoint, connection, sendLength ) ) {
            goto complete;
        }

        //
        // AfdShouldSendBlock() updates the send counters in the AFD
        // connection object.  Remember this fact so that we can clean
        // them up if the fast path fails after this point.
        //

        sendCountersUpdated = TRUE;

        //
        // Grab an AFD buffer large enough to hold the entire send.
        //

        afdBuffer = AfdGetBuffer( sendLength, 0 );
        if ( afdBuffer == NULL ) {
            goto complete;
        }

        //
        // Get a referenced pointer to the file object for the file that
        // we're going to transmit.  This call will fail if the file
        // handle specified by the caller is invalid.
        //

        status = ObReferenceObjectByHandle(
                     userTransmitInfo->FileHandle,
                     FILE_READ_DATA,
                     *IoFileObjectType,
                     UserMode,
                     (PVOID *)&fileObject,
                     NULL
                     );
        if ( !NT_SUCCESS(status) ) {
            goto complete;
        }

        //
        // If the file system doesn't support the fast cache manager
        // interface, bail and go through the IRP path.
        //

        if( ( fileObject->Flags & FO_CACHE_SUPPORTED ) == 0 ) {
            goto complete;
        }

        //
        // Grab the file offset into a local so that we know that the
        // offset pointer we pass to FsRtlCopyRead is valid.
        //

        fileOffset = userTransmitInfo->Offset;

        //
        // Get the file data.  If the amount of file data is small, copy
        // it directly into the AFD buffer.  If it is large, get an MDL
        // chain for the data and chain it on to the AFD buffer chain.
        //

        if ( sendLength < AfdMaxFastCopyTransmit ) {

            success = FsRtlCopyRead(
                          fileObject,
                          &fileOffset,
                          fileWriteLength,
                          FALSE,
                          0,
                          (PCHAR)afdBuffer->Buffer + userTransmitInfo->HeadLength,
                          IoStatus,
                          IoGetRelatedDeviceObject( fileObject )
                          );

            //
            // We're done with the file object, so deference it now.
            //

            ObDereferenceObject( fileObject );
            fileObject = NULL;

        } else {

            success = FsRtlMdlRead(
                          fileObject,
                          &fileOffset,
                          fileWriteLength,
                          0,
                          &fileMdl,
                          IoStatus
                          );

            //
            // Save the file object in the AFD buffer.  The send restart
            // routine will handle dereferencing the file object and
            // returning the file MDLs to the system.
            //

            afdBuffer->FileObject = fileObject;
            afdBuffer->FileOffset = fileOffset.QuadPart;
            afdBuffer->ReadLength = fileWriteLength;
        }

        if ( !success ) {
            goto complete;
        }

        //
        // If we read less information than was requested, we must have
        // hit the end of the file.  Fail the transmit request, since
        // this can only happen if the caller requested that we send
        // more data than the file currently contains.
        //

        if ( IoStatus->Information < fileWriteLength ) {
            goto complete;
        }

        //
        // We got all the file data, so things are looking good.  Copy
        // in the head and tail buffers, if necessary.  Note that if we
        // used MDL read, then there cannot be a tail buffer because of
        // the check at the beginning of this function.
        //

        if ( userTransmitInfo->HeadLength > 0 ) {
            RtlCopyMemory(
                afdBuffer->Buffer,
                userTransmitInfo->Head,
                userTransmitInfo->HeadLength
                );
        }

        if ( userTransmitInfo->TailLength > 0 ) {
            RtlCopyMemory(
                (PCHAR)afdBuffer->Buffer + userTransmitInfo->HeadLength +
                    fileWriteLength,
                userTransmitInfo->Tail,
                userTransmitInfo->TailLength
                );
        }

        //
        // We have to rebuild the MDL in the AFD buffer structure to
        // represent exactly the number of bytes we're going to be
        // sending.  If the AFD buffer has all the send data, indicate
        // that.  If we did MDL file I/O, then chain the file data on
        // to the head MDL.
        //

        if ( fileMdl == NULL ) {
            afdBuffer->Mdl->ByteCount = sendLength;
        } else {
            afdBuffer->Mdl->ByteCount = userTransmitInfo->HeadLength;
            afdBuffer->Mdl->Next = fileMdl;
        }

        SET_CHAIN_LENGTH( afdBuffer, sendLength );

        //
        // Remember the endpoint in the AFD buffer structure.  We need
        // this in order to access the endpoint in the restart routine.
        //

        afdBuffer->Context = endpoint;

        //
        // Use the IRP in the AFD buffer structure to give to the TDI
        // provider.  Build the TDI send request.
        //

        TdiBuildSend(
            afdBuffer->Irp,
            connection->DeviceObject,
            connection->FileObject,
            AfdRestartBufferSend,
            afdBuffer,
            afdBuffer->Mdl,
            0,
            sendLength
            );

        //
        // Add a reference to the connection object since the send
        // request will complete asynchronously.
        //

        REFERENCE_CONNECTION( connection );

        //
        // Call the transport to actually perform the send.
        //

        status = IoCallDriver( connection->DeviceObject, afdBuffer->Irp );

        //
        // Reset all the local variables that control cleanup.  This is
        // necessary because the send restart routine will handle all
        // cleanup at this point, and we cannot duplicate cleanup in the
        // case of a failure or exception below.
        //

        fileObject = NULL;
        afdBuffer = NULL;
        sendCountersUpdated = FALSE;
        fileMdl = NULL;

        //
        // The fast path succeeded--complete the call.  Note that we
        // change the status code from what was returned by the TDI
        // provider into STATUS_SUCCESS.  This is because we don't want
        // to complete the IRP with STATUS_PENDING etc.
        //

        if ( NT_SUCCESS(status) ) {
            IoStatus->Information = sendLength;
            IoStatus->Status = STATUS_SUCCESS;

            return TRUE;
        }

        //
        // The call failed for some reason.  Fail fast IO.
        //

        goto complete;

    } except( EXCEPTION_EXECUTE_HANDLER ) {

        goto complete;
    }

complete:

    if ( afdBuffer != NULL ) {
        afdBuffer->FileObject = NULL;
        afdBuffer->Mdl->Next = NULL;
        afdBuffer->Mdl->ByteCount = afdBuffer->BufferLength;
        AfdReturnBuffer( afdBuffer );
    }

    if ( fileMdl != NULL ) {
        FsRtlMdlReadComplete( fileObject, fileMdl );
    }
    if ( fileObject != NULL ) {
        ObDereferenceObject( fileObject );
    }

    if ( sendCountersUpdated ) {
        AfdAcquireSpinLock( &endpoint->SpinLock, &oldIrql );
        connection->VcBufferredSendBytes -= sendLength;
        connection->VcBufferredSendCount -= 1;
        AfdReleaseSpinLock( &endpoint->SpinLock, oldIrql );
    }

    return FALSE;

} // AfdFastTransmitFile


NTSTATUS
AfdMdlReadComplete(
    IN PFILE_OBJECT FileObject,
    IN PMDL MdlChain,
    IN LONGLONG FileOffset,
    IN ULONG Length
    )

/*++

Routine Description:

    Completes a MDL read operation by calling FsRtlMdlReadComplete().
    If this returns TRUE, cool. Otherwise (it returns FALSE) and this
    routine will allocate a new IRP and submit it to the filesystem.

Arguments:

    FileObject - Pointer to the file object being read.

    MdlChain - Supplies a pointer to an MDL chain returned from CcMdlRead.

    FileOffset - Byte offset in file for desired data.

    Length - Length of desired data in bytes.

Return Value:

    NTSTATUS - Completion status.

--*/

{

    PIRP irp;
    PIO_STACK_LOCATION irpSp;
    PAFD_MDL_COMPLETION_CONTEXT context;

    //
    // If we're being called at low IRQL, we can handle the
    // request immediately "in-line".
    //

    if( KeGetCurrentIrql() == LOW_LEVEL ) {

        //
        // First, try the fast path. If that succeeds, we're done.
        //

        if( FsRtlMdlReadComplete( FileObject, MdlChain ) ) {

            return STATUS_SUCCESS;

        }

        //
        // Fast past failed, so create a new IRP.
        //

        irp = IoAllocateIrp(
                  FileObject->DeviceObject->StackSize,
                  FALSE
                  );

        if( irp == NULL ) {

            return STATUS_INSUFFICIENT_RESOURCES;

        }

        //
        // Setup the IRP.
        //

        irpSp = IoGetNextIrpStackLocation( irp );

        irp->MdlAddress = MdlChain;

        irpSp->MajorFunction = IRP_MJ_READ;
        irpSp->MinorFunction = IRP_MN_MDL | IRP_MN_COMPLETE;

        irpSp->Parameters.Read.Length = Length;
        irpSp->Parameters.Read.ByteOffset = *(PLARGE_INTEGER)&FileOffset;
        irpSp->Parameters.Read.Key = 0;

        irpSp->FileObject = FileObject;
        irpSp->DeviceObject = IoGetRelatedDeviceObject( FileObject );

        //
        // Submit the IRP.
        //

        IoSetCompletionRoutine(
            irp,
            AfdRestartMdlReadComplete,
            NULL,
            TRUE,
            TRUE,
            TRUE
            );

        return IoCallDriver( irpSp->DeviceObject, irp );

    }

    //
    // We're being called at raised IRQL (probably in a TDI completion
    // routine) so we cannot touch the filesystem. We'll fire off a
    // worker thread to do the actual completion.
    //
    // Allocate a deferred completion context.
    //

    context = AfdAllocateMdlCompletionContext();

    if( context == NULL ) {

        return STATUS_INSUFFICIENT_RESOURCES;

    }

    //
    // Initialize the context and queue it to the worker thread.
    //

    context->FileObject = FileObject;
    context->MdlChain = MdlChain;
    context->FileOffset = FileOffset;
    context->Length = Length;

    //
    // Add a reference to the FileObject so it doesn't go away
    // before our completion routine gets called
    //

    ObReferenceObject( FileObject );

    AfdQueueWorkItem(
        AfdDeferredMdlReadComplete,
        &context->WorkItem
        );

    return STATUS_SUCCESS;

} // AfdMdlReadComplete


NTSTATUS
AfdRestartMdlReadComplete (
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Context
    )

/*++

Routine Description:

    Completion routine for IRPs issued by AfdMdlReadComplete. The only
    purpose of this completion routine is to free the IRPs created by
    AfdMdlReadComplete().

Arguments:

    DeviceObject - Unused.

    Irp - The completed IRP.

    Context - Unused.

Return Value:

    NTSTATUS - Completion status.

--*/

{
    //
    // Free the IRP since it's no longer needed.
    //

    IoFreeIrp( Irp );

    //
    // Return STATUS_MORE_PROCESSING_REQUIRED so that IoCompleteRequest
    // will stop working on the IRP.
    //

    return STATUS_MORE_PROCESSING_REQUIRED;

} // AfdRestartMdlReadComplete


VOID
AfdDeferredMdlReadComplete(
    IN PVOID Context
    )

/*++

Routine Description:

    Delayed worker thread routine for completing MDL reads. This routine
    is queued if we call AfdMdlReadComplete() at raised IRQL. Since it
    is invalid to call file systems at raised IRQL, this routine is
    scheduled to do the dirty work.

Arguments:

    Context - Points to the AFD_WORK_ITEM structure embedded within the
        AFD_MDL_COMPLETION_CONTEXT structure defining the MDL to complete.

Return Value:

    None.

--*/

{

    PAFD_MDL_COMPLETION_CONTEXT mdlComplete;

    //
    // Sanity check.
    //

    ASSERT( KeGetCurrentIrql() == LOW_LEVEL );
    ASSERT( Context != NULL );

    //
    // Get the completion context pointer.
    //

    mdlComplete = CONTAINING_RECORD(
                      Context,
                      AFD_MDL_COMPLETION_CONTEXT,
                      WorkItem
                      );

    //
    // Let AfdMdlReadComplete do the dirty work.
    //

    AfdMdlReadComplete(
        mdlComplete->FileObject,
        mdlComplete->MdlChain,
        mdlComplete->FileOffset,
        mdlComplete->Length
        );

    //
    // Remove the reference we added in AfdMdlReadComplete
    //

    ObDereferenceObject( mdlComplete->FileObject );

    //
    // Free the context.
    //

    AfdFreeMdlCompletionContext( mdlComplete );

} // AfdDeferredMdlReadComplete