summaryrefslogtreecommitdiff
path: root/filesys/fastfat/write.c
blob: 9a5c594baafe986e3290bc1b359c7d36597b83b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
/*++

Copyright (c) 1989-2000 Microsoft Corporation

Module Name:

    Write.c

Abstract:

    This module implements the File Write routine for Write called by the
    dispatch driver.


--*/

#include "FatProcs.h"

//
//  The Bug check file id for this module
//

#define BugCheckFileId                   (FAT_BUG_CHECK_WRITE)

//
//  The local debug trace level
//

#define Dbg                              (DEBUG_TRACE_WRITE)

//
//  Macros to increment the appropriate performance counters.
//

#define CollectWriteStats(VCB,OPEN_TYPE,BYTE_COUNT) {                                        \
    PFILESYSTEM_STATISTICS Stats = &(VCB)->Statistics[KeGetCurrentProcessorNumber() % FatData.NumberProcessors].Common; \
    if (((OPEN_TYPE) == UserFileOpen)) {                                                     \
        Stats->UserFileWrites += 1;                                                          \
        Stats->UserFileWriteBytes += (ULONG)(BYTE_COUNT);                                    \
    } else if (((OPEN_TYPE) == VirtualVolumeFile || ((OPEN_TYPE) == DirectoryFile))) {       \
        Stats->MetaDataWrites += 1;                                                          \
        Stats->MetaDataWriteBytes += (ULONG)(BYTE_COUNT);                                    \
    }                                                                                        \
}

BOOLEAN FatNoAsync = FALSE;

//
//  Local support routines
//

KDEFERRED_ROUTINE FatDeferredFlushDpc;

VOID
FatDeferredFlushDpc (
    _In_ PKDPC Dpc,
    _In_opt_ PVOID DeferredContext,
    _In_opt_ PVOID SystemArgument1,
    _In_opt_ PVOID SystemArgument2
    );

WORKER_THREAD_ROUTINE FatDeferredFlush;

VOID
FatDeferredFlush (
    _In_ PVOID Parameter
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FatDeferredFlush)
#pragma alloc_text(PAGE, FatCommonWrite)
#endif


_Function_class_(IRP_MJ_WRITE)
_Function_class_(DRIVER_DISPATCH)
NTSTATUS
FatFsdWrite (
    _In_ PVOLUME_DEVICE_OBJECT VolumeDeviceObject,
    _Inout_ PIRP Irp
    )

/*++

Routine Description:

    This routine implements the FSD part of the NtWriteFile API call

Arguments:

    VolumeDeviceObject - Supplies the volume device object where the
        file being Write exists

    Irp - Supplies the Irp being processed

Return Value:

    NTSTATUS - The FSD status for the IRP

--*/

{
    PFCB Fcb;
    NTSTATUS Status;
    PIRP_CONTEXT IrpContext = NULL;

    BOOLEAN ModWriter = FALSE;
    BOOLEAN TopLevel = FALSE;

    DebugTrace(+1, Dbg, "FatFsdWrite\n", 0);

    //
    //  Call the common Write routine, with blocking allowed if synchronous
    //

    FsRtlEnterFileSystem();

    //
    //  We are first going to do a quick check for paging file IO.  Since this
    //  is a fast path, we must replicate the check for the fsdo.
    //

    if (!FatDeviceIsFatFsdo( IoGetCurrentIrpStackLocation(Irp)->DeviceObject))  {

        Fcb = (PFCB)(IoGetCurrentIrpStackLocation(Irp)->FileObject->FsContext);

        if ((NodeType(Fcb) == FAT_NTC_FCB) &&
            FlagOn(Fcb->FcbState, FCB_STATE_PAGING_FILE)) {

            //
            //  Do the usual STATUS_PENDING things.
            //

            IoMarkIrpPending( Irp );

            //
            //  Perform the actual IO, it will be completed when the io finishes.
            //

            FatPagingFileIo( Irp, Fcb );

            FsRtlExitFileSystem();

            return STATUS_PENDING;
        }
    }

    try {

        TopLevel = FatIsIrpTopLevel( Irp );

        IrpContext = FatCreateIrpContext( Irp, CanFsdWait( Irp ) );

        //
        //  This is a kludge for the mod writer case.  The correct state
        //  of recursion is set in IrpContext, however, we much with the
        //  actual top level Irp field to get the correct WriteThrough
        //  behaviour.
        //

        if (IoGetTopLevelIrp() == (PIRP)FSRTL_MOD_WRITE_TOP_LEVEL_IRP) {

            ModWriter = TRUE;

            IoSetTopLevelIrp( Irp );
        }

        //
        //  If this is an Mdl complete request, don't go through
        //  common write.
        //

        if (FlagOn( IrpContext->MinorFunction, IRP_MN_COMPLETE )) {

            DebugTrace(0, Dbg, "Calling FatCompleteMdl\n", 0 );
            Status = FatCompleteMdl( IrpContext, Irp );

        } else {

            Status = FatCommonWrite( IrpContext, Irp );
        }

    } except(FatExceptionFilter( IrpContext, GetExceptionInformation() )) {

        //
        //  We had some trouble trying to perform the requested
        //  operation, so we'll abort the I/O request with
        //  the error status that we get back from the
        //  execption code
        //

        Status = FatProcessException( IrpContext, Irp, GetExceptionCode() );
    }

//  NT_ASSERT( !(ModWriter && (Status == STATUS_CANT_WAIT)) );

    NT_ASSERT( !(ModWriter && TopLevel) );

    if (ModWriter) { IoSetTopLevelIrp((PIRP)FSRTL_MOD_WRITE_TOP_LEVEL_IRP); }

    if (TopLevel) { IoSetTopLevelIrp( NULL ); }

    FsRtlExitFileSystem();

    //
    //  And return to our caller
    //

    DebugTrace(-1, Dbg, "FatFsdWrite -> %08lx\n", Status);

    UNREFERENCED_PARAMETER( VolumeDeviceObject );

    return Status;
}


_Requires_lock_held_(_Global_critical_region_)    
NTSTATUS
FatCommonWrite (
    IN PIRP_CONTEXT IrpContext,
    IN PIRP Irp
    )

/*++

Routine Description:

    This is the common write routine for NtWriteFile, called from both
    the Fsd, or from the Fsp if a request could not be completed without
    blocking in the Fsd.  This routine's actions are
    conditionalized by the Wait input parameter, which determines whether
    it is allowed to block or not.  If a blocking condition is encountered
    with Wait == FALSE, however, the request is posted to the Fsp, who
    always calls with WAIT == TRUE.

Arguments:

    Irp - Supplies the Irp to process

Return Value:

    NTSTATUS - The return status for the operation

--*/

{
    PVCB Vcb;
    PFCB FcbOrDcb;
    PCCB Ccb;

    VBO StartingVbo;
    ULONG ByteCount;
    ULONG FileSize = 0;
    ULONG InitialFileSize = 0;
    ULONG InitialValidDataLength = 0;

    PIO_STACK_LOCATION IrpSp;
    PFILE_OBJECT FileObject;
    TYPE_OF_OPEN TypeOfOpen;

    BOOLEAN PostIrp = FALSE;
    BOOLEAN OplockPostIrp = FALSE;
    BOOLEAN ExtendingFile = FALSE;
    BOOLEAN FcbOrDcbAcquired = FALSE;
    BOOLEAN SwitchBackToAsync = FALSE;
    BOOLEAN CalledByLazyWriter = FALSE;
    BOOLEAN ExtendingValidData = FALSE;
    BOOLEAN FcbAcquiredExclusive = FALSE;
    BOOLEAN FcbCanDemoteToShared = FALSE;
    BOOLEAN WriteFileSizeToDirent = FALSE;
    BOOLEAN RecursiveWriteThrough = FALSE;
    BOOLEAN UnwindOutstandingAsync = FALSE;
    BOOLEAN PagingIoResourceAcquired = FALSE;
    BOOLEAN SuccessfulPurge = FALSE;

    BOOLEAN SynchronousIo;
    BOOLEAN WriteToEof;
    BOOLEAN PagingIo;
    BOOLEAN NonCachedIo;
    BOOLEAN Wait;
    NTSTATUS Status = STATUS_SUCCESS;

    FAT_IO_CONTEXT StackFatIoContext;

    //
    // A system buffer is only used if we have to access the buffer directly
    // from the Fsp to clear a portion or to do a synchronous I/O, or a
    // cached transfer.  It is possible that our caller may have already
    // mapped a system buffer, in which case we must remember this so
    // we do not unmap it on the way out.
    //

    PVOID SystemBuffer = (PVOID) NULL;

    LARGE_INTEGER StartingByte;

    PAGED_CODE();

    //
    // Get current Irp stack location and file object
    //

    IrpSp = IoGetCurrentIrpStackLocation( Irp );
    FileObject = IrpSp->FileObject;


    DebugTrace(+1, Dbg, "FatCommonWrite\n", 0);
    DebugTrace( 0, Dbg, "Irp                 = %p\n", Irp);
    DebugTrace( 0, Dbg, "ByteCount           = %8lx\n", IrpSp->Parameters.Write.Length);
    DebugTrace( 0, Dbg, "ByteOffset.LowPart  = %8lx\n", IrpSp->Parameters.Write.ByteOffset.LowPart);
    DebugTrace( 0, Dbg, "ByteOffset.HighPart = %8lx\n", IrpSp->Parameters.Write.ByteOffset.HighPart);

    //
    // Initialize the appropriate local variables.
    //

    Wait          = BooleanFlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT);
    PagingIo      = BooleanFlagOn(Irp->Flags, IRP_PAGING_IO);
    NonCachedIo   = BooleanFlagOn(Irp->Flags,IRP_NOCACHE);
    SynchronousIo = BooleanFlagOn(FileObject->Flags, FO_SYNCHRONOUS_IO);

    //NT_ASSERT( PagingIo || FileObject->WriteAccess );

    //
    //  Extract the bytecount and do our noop/throttle checking.
    //

    ByteCount = IrpSp->Parameters.Write.Length;

    //
    //  If there is nothing to write, return immediately.
    //

    if (ByteCount == 0) {

        Irp->IoStatus.Information = 0;
        FatCompleteRequest( IrpContext, Irp, STATUS_SUCCESS );
        return STATUS_SUCCESS;
    }

    //
    //  See if we have to defer the write.
    //

    if (!NonCachedIo &&
        !CcCanIWrite(FileObject,
                     ByteCount,
                     (BOOLEAN)(Wait && !BooleanFlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_IN_FSP)),
                     BooleanFlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_DEFERRED_WRITE))) {

        BOOLEAN Retrying = BooleanFlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_DEFERRED_WRITE);

        FatPrePostIrp( IrpContext, Irp );

        SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_DEFERRED_WRITE );

        CcDeferWrite( FileObject,
                      (PCC_POST_DEFERRED_WRITE)FatAddToWorkque,
                      IrpContext,
                      Irp,
                      ByteCount,
                      Retrying );

        return STATUS_PENDING;
    }

    //
    //  Determine our starting position and type.  If we are writing
    //  at EOF, then we will need additional synchronization before
    //  the IO is issued to determine where the data will go.
    //

    StartingByte = IrpSp->Parameters.Write.ByteOffset;
    StartingVbo = StartingByte.LowPart;

    WriteToEof = ( (StartingByte.LowPart == FILE_WRITE_TO_END_OF_FILE) &&
                   (StartingByte.HighPart == -1) );

    //
    //  Extract the nature of the write from the file object, and case on it
    //

    TypeOfOpen = FatDecodeFileObject(FileObject, &Vcb, &FcbOrDcb, &Ccb);

    NT_ASSERT( Vcb != NULL );

    //
    //  Save callers who try to do cached IO to the raw volume from themselves.
    //

    if (TypeOfOpen == UserVolumeOpen) {

        NonCachedIo = TRUE;
    }

    NT_ASSERT(!(NonCachedIo == FALSE && TypeOfOpen == VirtualVolumeFile));

    //
    //  Collect interesting statistics.  The FLAG_USER_IO bit will indicate
    //  what type of io we're doing in the FatNonCachedIo function.
    //

    if (PagingIo) {
        CollectWriteStats(Vcb, TypeOfOpen, ByteCount);

        if (TypeOfOpen == UserFileOpen) {
            SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_USER_IO);
        } else {
            ClearFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_USER_IO);
        }
    }

    //
    //  We must disallow writes to regular objects that would require us
    //  to maintain an AllocationSize of greater than 32 significant bits.
    //
    //  If this is paging IO, this is simply a case where we need to trim.
    //  This will occur in due course.
    //

    if (!PagingIo && !WriteToEof && (TypeOfOpen != UserVolumeOpen)) {


        if (!FatIsIoRangeValid( Vcb, StartingByte, ByteCount)) {


            Irp->IoStatus.Information = 0;
            FatCompleteRequest( IrpContext, Irp, STATUS_DISK_FULL );

            return STATUS_DISK_FULL;
        }
    }

    //
    //  Allocate if necessary and initialize a FAT_IO_CONTEXT block for
    //  all non cached Io.  For synchronous Io
    //  we use stack storage, otherwise we allocate pool.
    //

    if (NonCachedIo) {

        if (IrpContext->FatIoContext == NULL) {

            if (!Wait) {

                IrpContext->FatIoContext =
                    FsRtlAllocatePoolWithTag( NonPagedPoolNx,
                                              sizeof(FAT_IO_CONTEXT),
                                              TAG_FAT_IO_CONTEXT );

            } else {

                IrpContext->FatIoContext = &StackFatIoContext;

                SetFlag( IrpContext->Flags, IRP_CONTEXT_STACK_IO_CONTEXT );
            }
        }

        RtlZeroMemory( IrpContext->FatIoContext, sizeof(FAT_IO_CONTEXT) );

        if (Wait) {

            KeInitializeEvent( &IrpContext->FatIoContext->Wait.SyncEvent,
                               NotificationEvent,
                               FALSE );

        } else {

            if (PagingIo) {

                IrpContext->FatIoContext->Wait.Async.ResourceThreadId =
                    ExGetCurrentResourceThread();

            } else {

                IrpContext->FatIoContext->Wait.Async.ResourceThreadId =
                    ((ULONG_PTR)IrpContext->FatIoContext) | 3;
            }

            IrpContext->FatIoContext->Wait.Async.RequestedByteCount =
                ByteCount;

            IrpContext->FatIoContext->Wait.Async.FileObject = FileObject;
        }
        
    }

    //
    //  Check if this volume has already been shut down.  If it has, fail
    //  this write request.
    //

    if ( FlagOn(Vcb->VcbState, VCB_STATE_FLAG_SHUTDOWN) ) {

        Irp->IoStatus.Information = 0;
        FatCompleteRequest( IrpContext, Irp, STATUS_TOO_LATE );
        return STATUS_TOO_LATE;
    }

    //
    //  This case corresponds to a write of the volume file (only the first
    //  fat allowed, the other fats are written automatically in parallel).
    //
    //  We use an Mcb keep track of dirty sectors.  Actual entries are Vbos
    //  and Lbos (ie. bytes), though they are all added in sector chunks.
    //  Since Vbo == Lbo for the volume file, the Mcb entries
    //  alternate between runs of Vbo == Lbo, and holes (Lbo == 0).  We use
    //  the prior to represent runs of dirty fat sectors, and the latter
    //  for runs of clean fat.  Note that since the first part of the volume
    //  file (boot sector) is always clean (a hole), and an Mcb never ends in
    //  a hole, there must always be an even number of runs(entries) in the Mcb.
    //
    //  The strategy is to find the first and last dirty run in the desired
    //  write range (which will always be a set of pages), and write from the
    //  former to the later.  The may result in writing some clean data, but
    //  will generally be more efficient than writing each runs seperately.
    //

    if (TypeOfOpen == VirtualVolumeFile) {

        LBO DirtyLbo;
        LBO CleanLbo;

        VBO DirtyVbo;
        VBO StartingDirtyVbo;

        ULONG DirtyByteCount;
        ULONG CleanByteCount;

        ULONG WriteLength;

        BOOLEAN MoreDirtyRuns = TRUE;

        IO_STATUS_BLOCK RaiseIosb;

        DebugTrace(0, Dbg, "Type of write is Virtual Volume File\n", 0);

        //
        //  If we can't wait we have to post this.
        //

        if (!Wait) {

            DebugTrace( 0, Dbg, "Passing request to Fsp\n", 0 );

            Status = FatFsdPostRequest(IrpContext, Irp);

            return Status;
        }

        //
        //  If we weren't called by the Lazy Writer, then this write
        //  must be the result of a write-through or flush operation.
        //  Setting the IrpContext flag, will cause DevIoSup.c to
        //  write-through the data to the disk.
        //

        if (!FlagOn((ULONG_PTR)IoGetTopLevelIrp(), FSRTL_CACHE_TOP_LEVEL_IRP)) {

            SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WRITE_THROUGH );
        }

        //
        //  Assert an even number of entries in the Mcb, an odd number would
        //  mean that the Mcb is corrupt.
        //

        NT_ASSERT( (FsRtlNumberOfRunsInLargeMcb( &Vcb->DirtyFatMcb ) & 1) == 0);

        //
        //  We need to skip over any clean sectors at the start of the write.
        //
        //  Also check the two cases where there are no dirty fats in the
        //  desired write range, and complete them with success.
        //
        //      1) There is no Mcb entry corresponding to StartingVbo, meaning
        //         we are beyond the end of the Mcb, and thus dirty fats.
        //
        //      2) The run at StartingVbo is clean and continues beyond the
        //         desired write range.
        //

        if (!FatLookupMcbEntry( Vcb, &Vcb->DirtyFatMcb,
                                StartingVbo,
                                &DirtyLbo,
                                &DirtyByteCount,
                                NULL )

          || ( (DirtyLbo == 0) && (DirtyByteCount >= ByteCount) ) ) {

            DebugTrace(0, DEBUG_TRACE_DEBUG_HOOKS,
                       "No dirty fat sectors in the write range.\n", 0);

            FatCompleteRequest( IrpContext, Irp, STATUS_SUCCESS );
            return STATUS_SUCCESS;
        }

        DirtyVbo = (VBO)DirtyLbo;

        //
        //  If the last run was a hole (clean), up DirtyVbo to the next
        //  run, which must be dirty.
        //

        if (DirtyVbo == 0) {

            DirtyVbo = StartingVbo + DirtyByteCount;
        }

        //
        //  This is where the write will start.
        //

        StartingDirtyVbo = DirtyVbo;

        //
        //
        //  Now start enumerating the dirty fat sectors spanning the desired
        //  write range, this first one of which is now DirtyVbo.
        //

        while ( MoreDirtyRuns ) {

            //
            //  Find the next dirty run, if it is not there, the Mcb ended
            //  in a hole, or there is some other corruption of the Mcb.
            //

            if (!FatLookupMcbEntry( Vcb, &Vcb->DirtyFatMcb,
                                    DirtyVbo,
                                    &DirtyLbo,
                                    &DirtyByteCount,
                                    NULL )) {

#pragma prefast( suppress:28931, "needed for debug build" )
                DirtyVbo = (VBO)DirtyLbo;

                DebugTrace(0, Dbg, "Last dirty fat Mcb entry was a hole: corrupt.\n", 0);
                
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )                
                FatBugCheck( 0, 0, 0 );

            } else {

                DirtyVbo = (VBO)DirtyLbo;

                //
                //  This has to correspond to a dirty run, and must start
                //  within the write range since we check it at entry to,
                //  and at the bottom of this loop.
                //

                NT_ASSERT((DirtyVbo != 0) && (DirtyVbo < StartingVbo + ByteCount));

                //
                //  There are three ways we can know that this was the
                //  last dirty run we want to write.
                //
                //      1)  The current dirty run extends beyond or to the
                //          desired write range.
                //
                //      2)  On trying to find the following clean run, we
                //          discover that this is the last run in the Mcb.
                //
                //      3)  The following clean run extend beyond the
                //          desired write range.
                //
                //  In any of these cases we set MoreDirtyRuns = FALSE.
                //

                //
                //  If the run is larger than we are writing, we also
                //  must truncate the WriteLength.  This is benign in
                //  the equals case.
                //

                if (DirtyVbo + DirtyByteCount >= StartingVbo + ByteCount) {

                    DirtyByteCount = StartingVbo + ByteCount - DirtyVbo;

                    MoreDirtyRuns = FALSE;

                } else {

                    //
                    //  Scan the clean hole after this dirty run.  If this
                    //  run was the last, prepare to exit the loop
                    //

                    if (!FatLookupMcbEntry( Vcb, &Vcb->DirtyFatMcb,
                                            DirtyVbo + DirtyByteCount,
                                            &CleanLbo,
                                            &CleanByteCount,
                                            NULL )) {

                        MoreDirtyRuns = FALSE;

                    } else {

                        //
                        //  Assert that we actually found a clean run.
                        //  and compute the start of the next dirty run.
                        //

                        NT_ASSERT (CleanLbo == 0);

                        //
                        //  If the next dirty run starts beyond the desired
                        //  write, we have found all the runs we need, so
                        //  prepare to exit.
                        //

                        if (DirtyVbo + DirtyByteCount + CleanByteCount >=
                                                    StartingVbo + ByteCount) {

                            MoreDirtyRuns = FALSE;

                        } else {

                            //
                            //  Compute the start of the next dirty run.
                            //

                            DirtyVbo += DirtyByteCount + CleanByteCount;
                        }
                    }
                }
            }
        } // while ( MoreDirtyRuns )

        //
        //  At this point DirtyVbo and DirtyByteCount correctly reflect the
        //  final dirty run, constrained to the desired write range.
        //
        //  Now compute the length we finally must write.
        //

        WriteLength = (DirtyVbo + DirtyByteCount) - StartingDirtyVbo;

        //
        // We must now assume that the write will complete with success,
        // and initialize our expected status in RaiseIosb.  It will be
        // modified below if an error occurs.
        //

        RaiseIosb.Status = STATUS_SUCCESS;
        RaiseIosb.Information = ByteCount;

        //
        //  Loop through all the fats, setting up a multiple async to
        //  write them all.  If there are more than FAT_MAX_PARALLEL_IOS
        //  then we do several muilple asyncs.
        //

        {
            ULONG Fat;
            ULONG BytesPerFat;
            IO_RUN StackIoRuns[2];
            PIO_RUN IoRuns;

            BytesPerFat = FatBytesPerFat( &Vcb->Bpb );

            if ((ULONG)Vcb->Bpb.Fats > 2) {

                IoRuns = FsRtlAllocatePoolWithTag( PagedPool,
                                                   (ULONG)(Vcb->Bpb.Fats*sizeof(IO_RUN)),
                                                   TAG_IO_RUNS );

            } else {

                IoRuns = StackIoRuns;
            }

            for (Fat = 0; Fat < (ULONG)Vcb->Bpb.Fats; Fat++) {

                IoRuns[Fat].Vbo = StartingDirtyVbo;
                IoRuns[Fat].Lbo = Fat * BytesPerFat + StartingDirtyVbo;
                IoRuns[Fat].Offset = StartingDirtyVbo - StartingVbo;
                IoRuns[Fat].ByteCount = WriteLength;
            }

            //
            //  Keep track of meta-data disk ios.
            //

            Vcb->Statistics[KeGetCurrentProcessorNumber() % FatData.NumberProcessors].Common.MetaDataDiskWrites += Vcb->Bpb.Fats;

            try {

                FatMultipleAsync( IrpContext,
                                  Vcb,
                                  Irp,
                                  (ULONG)Vcb->Bpb.Fats,
                                  IoRuns );

            } finally {

                if (IoRuns != StackIoRuns) {

                    ExFreePool( IoRuns );
                }
            }

#if (NTDDI_VERSION >= NTDDI_WIN8)

            //
            //  Account for DASD Ios
            //

            if (FatDiskAccountingEnabled) {

                PETHREAD ThreadIssuingIo = PsGetCurrentThread();

                PsUpdateDiskCounters( PsGetThreadProcess( ThreadIssuingIo ),
                                      0,
                                      WriteLength,
                                      0,
                                      1,
                                      0 );
            }

#endif
            //
            //  Wait for all the writes to finish
            //

            FatWaitSync( IrpContext );

            //
            //  If we got an error, or verify required, remember it.
            //

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

                DebugTrace( 0,
                            Dbg,
                            "Error %X while writing volume file.\n",
                            Irp->IoStatus.Status );

                RaiseIosb = Irp->IoStatus;
            }
        }

        //
        //  If the writes were a success, set the sectors clean, else
        //  raise the error status and mark the volume as needing
        //  verification.  This will automatically reset the volume
        //  structures.
        //
        //  If not, then mark this volume as needing verification to
        //  automatically cause everything to get cleaned up.
        //

        Irp->IoStatus = RaiseIosb;

        if ( NT_SUCCESS( Status = Irp->IoStatus.Status )) {

            FatRemoveMcbEntry( Vcb, &Vcb->DirtyFatMcb,
                               StartingDirtyVbo,
                               WriteLength );

        } else {

            FatNormalizeAndRaiseStatus( IrpContext, Status );
        }

        DebugTrace(-1, Dbg, "CommonWrite -> %08lx\n", Status );

        FatCompleteRequest( IrpContext, Irp, Status );
        return Status;
    }

    //
    //  This case corresponds to a general opened volume (DASD), ie.
    //  open ("a:").
    //

    if (TypeOfOpen == UserVolumeOpen) {

        LBO StartingLbo;
        LBO VolumeSize;

        //
        //  Precalculate the volume size since we're nearly always going
        //  to be wanting to use it.
        //

        VolumeSize = (LBO) Int32x32To64( Vcb->Bpb.BytesPerSector,
                                         (Vcb->Bpb.Sectors != 0 ? Vcb->Bpb.Sectors :
                                                                  Vcb->Bpb.LargeSectors));

        StartingLbo = StartingByte.QuadPart;

        DebugTrace(0, Dbg, "Type of write is User Volume.\n", 0);

        //
        //  If this is a write on a disk-based volume that is not locked, we need to limit
        //  the sectors we allow to be written within the volume.  Specifically, we only
        //  allow writes to the reserved area.  Note that extended DASD can still be used
        //  to write past the end of the volume.  We also allow kernel mode callers to force
        //  access via a flag in the IRP.  A handle that issued a dismount can write anywhere
        //  as well.
        //

        if ((Vcb->TargetDeviceObject->DeviceType == FILE_DEVICE_DISK) &&
            !FlagOn( Vcb->VcbState, VCB_STATE_FLAG_LOCKED ) &&
            !FlagOn( IrpSp->Flags, SL_FORCE_DIRECT_WRITE ) &&
            !FlagOn( Ccb->Flags, CCB_FLAG_COMPLETE_DISMOUNT )) {

            //
            //  First check for a write beyond the end of the volume.
            //

            if (!WriteToEof && (StartingLbo < VolumeSize)) {

                //
                //  This write is within the volume.  Make sure it is not beyond the reserved section.
                //

                if ((StartingLbo >= FatReservedBytes( &(Vcb->Bpb) )) ||
                    (ByteCount > (FatReservedBytes( &(Vcb->Bpb) ) - StartingLbo))) {

                    FatCompleteRequest( IrpContext, Irp, STATUS_ACCESS_DENIED );
                    return STATUS_ACCESS_DENIED;
                }
            }
        }

        //
        //  Verify that the volume for this handle is still valid, permitting
        //  operations to proceed on dismounted volumes via the handle which
        //  performed the dismount or sent a format unit command.
        //

        if (!FlagOn( Ccb->Flags, CCB_FLAG_COMPLETE_DISMOUNT | CCB_FLAG_SENT_FORMAT_UNIT )) {

            FatQuickVerifyVcb( IrpContext, Vcb );
        }

        //
        //  If the caller previously sent a format unit command, then we will allow
        //  their read/write requests to ignore the verify flag on the device, since some
        //  devices send a media change event after format unit, but we don't want to 
        //  process it yet since we're probably in the process of formatting the
        //  media.
        //
        
        if (FlagOn( Ccb->Flags, CCB_FLAG_SENT_FORMAT_UNIT )) {
        
            SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_OVERRIDE_VERIFY );
        }

        if (!FlagOn( Ccb->Flags, CCB_FLAG_DASD_PURGE_DONE )) {

            BOOLEAN PreviousWait = BooleanFlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );

            //
            //  Grab the entire volume so that even the normally unsafe action
            //  of writing to an unlocked volume won't open us to a race between
            //  the flush and purge of the FAT below.
            //
            //  I really don't think this is particularly important to worry about,
            //  but a repro case for another bug happens to dance into this race
            //  condition pretty easily. Eh.
            //
            
            SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );
            FatAcquireExclusiveVolume( IrpContext, Vcb );

            try {

                //
                //  If the volume isn't locked, flush and purge it.
                //

                if (!FlagOn(Vcb->VcbState, VCB_STATE_FLAG_LOCKED)) {

                    FatFlushFat( IrpContext, Vcb );
                    CcPurgeCacheSection( &Vcb->SectionObjectPointers,
                                         NULL,
                                         0,
                                         FALSE );

                    FatPurgeReferencedFileObjects( IrpContext, Vcb->RootDcb, Flush );
                }

            } finally {

                FatReleaseVolume( IrpContext, Vcb );
                if (!PreviousWait) {
                    ClearFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );
                }
            }

            SetFlag( Ccb->Flags, CCB_FLAG_DASD_PURGE_DONE |
                                 CCB_FLAG_DASD_FLUSH_DONE );
        }

        if (!FlagOn( Ccb->Flags, CCB_FLAG_ALLOW_EXTENDED_DASD_IO )) {

            //
            //  Make sure we don't try to write past end of volume,
            //  reducing the requested byte count if necessary.
            //

            if (WriteToEof || StartingLbo >= VolumeSize) {
                FatCompleteRequest( IrpContext, Irp, STATUS_SUCCESS );
                return STATUS_SUCCESS;
            }

            if (ByteCount > VolumeSize - StartingLbo) {

                ByteCount = (ULONG) (VolumeSize - StartingLbo);

                //
                //  For async writes we had set the byte count in the FatIoContext
                //  above, so fix that here.
                //

                if (!Wait) {

                    IrpContext->FatIoContext->Wait.Async.RequestedByteCount =
                        ByteCount;
                }
            }
        } else {

            //
            //  This has a peculiar interpretation, but just adjust the starting
            //  byte to the end of the visible volume.
            //

            if (WriteToEof) {

                StartingLbo = VolumeSize;
            }
        }

        //
        // For DASD we have to probe and lock the user's buffer
        //

        FatLockUserBuffer( IrpContext, Irp, IoReadAccess, ByteCount );

        //
        //  Set the FO_MODIFIED flag here to trigger a verify when this
        //  handle is closed.  Note that we can err on the conservative
        //  side with no problem, i.e. if we accidently do an extra
        //  verify there is no problem.
        //

        SetFlag( FileObject->Flags, FO_FILE_MODIFIED );

        //
        //  Write the data and wait for the results
        //

        FatSingleAsync( IrpContext,
                        Vcb,
                        StartingLbo,
                        ByteCount,
                        Irp );

#if (NTDDI_VERSION >= NTDDI_WIN8)

        //
        //  Account for DASD Ios
        //

        if (FatDiskAccountingEnabled) {

            PETHREAD ThreadIssuingIo = PsGetCurrentThread();

            PsUpdateDiskCounters( PsGetThreadProcess( ThreadIssuingIo ),
                                  0,
                                  ByteCount,
                                  0,
                                  1,
                                  0 );
        }

#endif

        if (!Wait) {

            //
            //  We, nor anybody else, need the IrpContext any more.
            //

            IrpContext->FatIoContext = NULL;

            FatDeleteIrpContext( IrpContext );

            DebugTrace(-1, Dbg, "FatNonCachedIo -> STATUS_PENDING\n", 0);

            return STATUS_PENDING;
        }

        FatWaitSync( IrpContext );

        //
        //  If the call didn't succeed, raise the error status
        //
        //  Also mark this volume as needing verification to automatically
        //  cause everything to get cleaned up.
        //

        if (!NT_SUCCESS( Status = Irp->IoStatus.Status )) {

            FatNormalizeAndRaiseStatus( IrpContext, Status );
        }

        //
        //  Update the current file position.  We assume that
        //  open/create zeros out the CurrentByteOffset field.
        //

        if (SynchronousIo && !PagingIo) {
            FileObject->CurrentByteOffset.QuadPart =
                StartingLbo + Irp->IoStatus.Information;
        }

        DebugTrace(-1, Dbg, "FatCommonWrite -> %08lx\n", Status );

        FatCompleteRequest( IrpContext, Irp, Status );
        return Status;
    }

    //
    //  At this point we know there is an Fcb/Dcb.
    //

    NT_ASSERT( FcbOrDcb != NULL );

    //
    //  Use a try-finally to free Fcb/Dcb and buffers on the way out.
    //

    try {

        //
        // This case corresponds to a normal user write file.
        //

        if ( TypeOfOpen == UserFileOpen
            ) {

            ULONG ValidDataLength;
            ULONG ValidDataToDisk;
            ULONG ValidDataToCheck;

            DebugTrace(0, Dbg, "Type of write is user file open\n", 0);

            //
            //  If this is a noncached transfer and is not a paging I/O, and
            //  the file has been opened cached, then we will do a flush here
            //  to avoid stale data problems.  Note that we must flush before
            //  acquiring the Fcb shared since the write may try to acquire
            //  it exclusive.
            //
            //  The Purge following the flush will guarentee cache coherency.
            //

            if (NonCachedIo && !PagingIo &&
                (FileObject->SectionObjectPointer->DataSectionObject != NULL)) {

                IO_STATUS_BLOCK IoStatus = {0};

                //
                //  We need the Fcb exclsuive to do the CcPurgeCache
                //

                if (!FatAcquireExclusiveFcb( IrpContext, FcbOrDcb )) {

                    DebugTrace( 0, Dbg, "Cannot acquire FcbOrDcb = %p shared without waiting\n", FcbOrDcb );

                    try_return( PostIrp = TRUE );
                }

                FcbOrDcbAcquired = TRUE;
                FcbAcquiredExclusive = TRUE;

                //
                //  Preacquire pagingio for the flush.
                //

                ExAcquireResourceExclusiveLite( FcbOrDcb->Header.PagingIoResource, TRUE );

#if (NTDDI_VERSION >= NTDDI_WIN7)

                //
                //  Remember that we are holding the paging I/O resource.
                //

                PagingIoResourceAcquired = TRUE;

                //
                //  We hold so that we will prevent a pagefault from occuring and seeing
                //  soon-to-be stale data from the disk. We used to believe this was
                //  something to be left to the app to synchronize; we now realize that
                //  noncached IO on a fileserver is doomed without the filesystem forcing
                //  the coherency issue. By only penalizing noncached coherency when
                //  needed, this is about the best we can do.
                //

                //
                // Now perform the coherency flush and purge operation. This version of the call
                // will try to invalidate mapped pages to prevent data corruption.
                //

                CcCoherencyFlushAndPurgeCache(  FileObject->SectionObjectPointer,
                                                WriteToEof ? &FcbOrDcb->Header.FileSize : &StartingByte,
                                                ByteCount,
                                                &IoStatus,
                                                0 );

                SuccessfulPurge = NT_SUCCESS( IoStatus.Status );

#else

                CcFlushCache( FileObject->SectionObjectPointer,
                              WriteToEof ? &FcbOrDcb->Header.FileSize : &StartingByte,
                              ByteCount,
                              &IoStatus );

                if (!NT_SUCCESS( IoStatus.Status )) {

                    ExReleaseResourceLite( FcbOrDcb->Header.PagingIoResource );
                    try_return( IoStatus.Status );
                }

                //
                //  Remember that we are holding the paging I/O resource.
                //

                PagingIoResourceAcquired = TRUE;

                //
                //  We hold so that we will prevent a pagefault from occuring and seeing
                //  soon-to-be stale data from the disk. We used to believe this was
                //  something to be left to the app to synchronize; we now realize that
                //  noncached IO on a fileserver is doomed without the filesystem forcing
                //  the coherency issue. By only penalizing noncached coherency when
                //  needed, this is about the best we can do.
                //

                SuccessfulPurge = CcPurgeCacheSection( FileObject->SectionObjectPointer,
                                                       WriteToEof ? &FcbOrDcb->Header.FileSize : &StartingByte,
                                                       ByteCount,
                                                       FALSE );

#endif

                if (!SuccessfulPurge && (FcbOrDcb->PurgeFailureModeEnableCount > 0)) {

                    //
                    //  Purge failure mode only applies to user files.
                    //
                    
                    NT_ASSERT( TypeOfOpen == UserFileOpen );

                    //
                    //  Do not swallow the purge failure if in purge failure
                    //  mode. Someone outside the file system intends to handle
                    //  the error and prevent any application compatibilty 
                    //  issue.
                    //
                    //  NOTE: If the file system were not preventing a pagefault
                    //  from processing while this write is in flight, which it does
                    //  by holding the paging resource across the write, it would
                    //  need to fail the operation even if a purge succeeded. If
                    //  not a memory mapped read could bring in a stale page before
                    //  the write makes it to disk.
                    //
                    
                    try_return( Status = STATUS_PURGE_FAILED );                
                }

                //
                //  Indicate we're OK with the fcb being demoted to shared access
                //  if that turns out to be possible later on after VDL extension
                //  is checked for.
                //
                //  PagingIo must be held all the way through.
                //
                
                FcbCanDemoteToShared = TRUE;
            }

            //
            //  We assert that Paging Io writes will never WriteToEof.
            //

            NT_ASSERT( WriteToEof ? !PagingIo : TRUE );
            
            //
            //  First let's acquire the Fcb shared.  Shared is enough if we
            //  are not writing beyond EOF.
            //

            if ( PagingIo ) {

                (VOID)ExAcquireResourceSharedLite( FcbOrDcb->Header.PagingIoResource, TRUE );
                PagingIoResourceAcquired = TRUE;

                if (!Wait) {

                    IrpContext->FatIoContext->Wait.Async.Resource =
                        FcbOrDcb->Header.PagingIoResource;
                }

                //
                //  Check to see if we colided with a MoveFile call, and if
                //  so block until it completes.
                //

                if (FcbOrDcb->MoveFileEvent) {

                    (VOID)KeWaitForSingleObject( FcbOrDcb->MoveFileEvent,
                                                 Executive,
                                                 KernelMode,
                                                 FALSE,
                                                 NULL );
                }

            } else {

                //
                //  We may already have the Fcb due to noncached coherency
                //  work done just above; however, we may still have to extend
                //  valid data length.  We can't demote this to shared, matching
                //  what occured before, until we figure that out a bit later. 
                //
                //  We kept ahold of it since our lockorder is main->paging,
                //  and paging must now held across the noncached write from
                //  the purge on.
                //
                
                //
                //  If this is async I/O, we will wait if there is an exclusive
                //  waiter.
                //

                if (!Wait && NonCachedIo) {

                    if (!FcbOrDcbAcquired &&
                        !FatAcquireSharedFcbWaitForEx( IrpContext, FcbOrDcb )) {

                        DebugTrace( 0, Dbg, "Cannot acquire FcbOrDcb = %p shared without waiting\n", FcbOrDcb );
                        try_return( PostIrp = TRUE );
                    }

                    //
                    //  Note we will have to release this resource elsewhere.  If we came
                    //  out of the noncached coherency path, we will also have to drop
                    //  the paging io resource.
                    //

                    IrpContext->FatIoContext->Wait.Async.Resource = FcbOrDcb->Header.Resource;

                    if (FcbCanDemoteToShared) {
                        
                        IrpContext->FatIoContext->Wait.Async.Resource2 = FcbOrDcb->Header.PagingIoResource;
                    }
                } else {

                    if (!FcbOrDcbAcquired &&
                        !FatAcquireSharedFcb( IrpContext, FcbOrDcb )) {

                        DebugTrace( 0, Dbg, "Cannot acquire FcbOrDcb = %p shared without waiting\n", FcbOrDcb );
                        try_return( PostIrp = TRUE );
                    }
                }

                FcbOrDcbAcquired = TRUE;
            }

            //
            //  Get a first tentative file size and valid data length.
            //  We must get ValidDataLength first since it is always
            //  increased second (in case we are unprotected) and
            //  we don't want to capture ValidDataLength > FileSize.
            //

            ValidDataToDisk = FcbOrDcb->ValidDataToDisk;
            ValidDataLength = FcbOrDcb->Header.ValidDataLength.LowPart;
            FileSize = FcbOrDcb->Header.FileSize.LowPart;

            NT_ASSERT( ValidDataLength <= FileSize );

            //
            // If are paging io, then we do not want
            // to write beyond end of file.  If the base is beyond Eof, we will just
            // Noop the call.  If the transfer starts before Eof, but extends
            // beyond, we will truncate the transfer to the last sector
            // boundary.
            //

            //
            //  Just in case this is paging io, limit write to file size.
            //  Otherwise, in case of write through, since Mm rounds up
            //  to a page, we might try to acquire the resource exclusive
            //  when our top level guy only acquired it shared. Thus, =><=.
            //

            if ( PagingIo ) {

                if (StartingVbo >= FileSize) {

                    DebugTrace( 0, Dbg, "PagingIo started beyond EOF.\n", 0 );

                    Irp->IoStatus.Information = 0;

                    try_return( Status = STATUS_SUCCESS );
                }

                if (ByteCount > FileSize - StartingVbo) {

                    DebugTrace( 0, Dbg, "PagingIo extending beyond EOF.\n", 0 );

                    ByteCount = FileSize - StartingVbo;
                }
            }

            //
            //  Determine if we were called by the lazywriter.
            //  (see resrcsup.c)
            //

            if (FcbOrDcb->Specific.Fcb.LazyWriteThread == PsGetCurrentThread()) {

                CalledByLazyWriter = TRUE;

                if (FlagOn( FcbOrDcb->Header.Flags, FSRTL_FLAG_USER_MAPPED_FILE )) {

                    //
                    //  Fail if the start of this request is beyond valid data length.
                    //  Don't worry if this is an unsafe test.  MM and CC won't
                    //  throw this page away if it is really dirty.
                    //

                    if ((StartingVbo + ByteCount > ValidDataLength) &&
                        (StartingVbo < FileSize)) {

                        //
                        //  It's OK if byte range is within the page containing valid data length,
                        //  since we will use ValidDataToDisk as the start point.
                        //

                        if (StartingVbo + ByteCount > ((ValidDataLength + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1))) {

                            //
                            //  Don't flush this now.
                            //

                            try_return( Status = STATUS_FILE_LOCK_CONFLICT );
                        }
                    }
                }
            }

            //
            //  This code detects if we are a recursive synchronous page write
            //  on a write through file object.
            //

            if (FlagOn(Irp->Flags, IRP_SYNCHRONOUS_PAGING_IO) &&
                FlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_RECURSIVE_CALL)) {

                PIRP TopIrp;

                TopIrp = IoGetTopLevelIrp();

                //
                //  This clause determines if the top level request was
                //  in the FastIo path.  Gack.  Since we don't have a
                //  real sharing protocol for the top level IRP field ...
                //  yet ... if someone put things other than a pure IRP in
                //  there we best be careful.
                //

                if ((ULONG_PTR)TopIrp > FSRTL_MAX_TOP_LEVEL_IRP_FLAG &&
                    NodeType(TopIrp) == IO_TYPE_IRP) {

                    PIO_STACK_LOCATION IrpStack;

                    IrpStack = IoGetCurrentIrpStackLocation(TopIrp);

                    //
                    //  Finally this routine detects if the Top irp was a
                    //  cached write to this file and thus we are the writethrough.
                    //

                    if ((IrpStack->MajorFunction == IRP_MJ_WRITE) &&
                        (IrpStack->FileObject->FsContext == FileObject->FsContext) &&
                        !FlagOn(TopIrp->Flags,IRP_NOCACHE)) {

                        RecursiveWriteThrough = TRUE;
                        SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WRITE_THROUGH );
                    }
                }
            }

            //
            //  Here is the deal with ValidDataLength and FileSize:
            //
            //  Rule 1: PagingIo is never allowed to extend file size.
            //
            //  Rule 2: Only the top level requestor may extend Valid
            //          Data Length.  This may be paging IO, as when a
            //          a user maps a file, but will never be as a result
            //          of cache lazy writer writes since they are not the
            //          top level request.
            //
            //  Rule 3: If, using Rules 1 and 2, we decide we must extend
            //          file size or valid data, we take the Fcb exclusive.
            //

            //
            // Now see if we are writing beyond valid data length, and thus
            // maybe beyond the file size.  If so, then we must
            // release the Fcb and reacquire it exclusive.  Note that it is
            // important that when not writing beyond EOF that we check it
            // while acquired shared and keep the FCB acquired, in case some
            // turkey truncates the file.
            //

            //
            //  Note that the lazy writer must not be allowed to try and
            //  acquire the resource exclusive.  This is not a problem since
            //  the lazy writer is paging IO and thus not allowed to extend
            //  file size, and is never the top level guy, thus not able to
            //  extend valid data length.
            //

            if ( !CalledByLazyWriter &&

                 !RecursiveWriteThrough &&

                 (WriteToEof ||
                  StartingVbo + ByteCount > ValidDataLength)) {

                //
                //  If this was an asynchronous write, we are going to make
                //  the request synchronous at this point, but only kinda.
                //  At the last moment, before sending the write off to the
                //  driver, we may shift back to async.
                //
                //  The modified page writer already has the resources
                //  he requires, so this will complete in small finite
                //  time.
                //

                if (!Wait) {

                    Wait = TRUE;
                    SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );

                    if (NonCachedIo) {

                        NT_ASSERT( TypeOfOpen == UserFileOpen );

                        SwitchBackToAsync = TRUE;
                    }
                }

                //
                // We need Exclusive access to the Fcb/Dcb since we will
                // probably have to extend valid data and/or file.
                //

                //
                //  Y'know, the PagingIo case is a mapped page writer, and
                //  MmFlushSection or the mapped page writer itself already
                //  snatched up the main exclusive for us via the AcquireForCcFlush
                //  or AcquireForModWrite logic (the default logic parallels FAT's
                //  requirements since this order/model came first).  Should ASSERT
                //  this since it'll just go 1->2, and a few more unnecesary DPC
                //  transitions.
                //
                //  The preacquire is done to avoid inversion over the collided flush
                //  meta-resource in Mm.  The one time this is not true is at final
                //  system shutdown time, when Mm goes off and flushes all the dirty
                //  pages.  Since the callback is defined as Wait == FALSE he can't
                //  guarantee acquisition (though with clean process shutdown being
                //  enforced, it really should be now).  Permit this to float.
                //
                //  Note that since we're going to fall back on the acquisition aleady
                //  done for us, don't confuse things by thinking we did the work
                //  for it.
                //

                if ( PagingIo ) {

                    ExReleaseResourceLite( FcbOrDcb->Header.PagingIoResource );
                    PagingIoResourceAcquired = FALSE;

                } else {

                    //
                    //  The Fcb may already be acquired exclusive due to coherency
                    //  work performed earlier.  If so, obviously no work to do.
                    //
                    
                    if (!FcbAcquiredExclusive) {
                        
                        FatReleaseFcb( IrpContext, FcbOrDcb );
                        FcbOrDcbAcquired = FALSE;

                        if (!FatAcquireExclusiveFcb( IrpContext, FcbOrDcb )) {

                            DebugTrace( 0, Dbg, "Cannot acquire FcbOrDcb = %p shared without waiting\n", FcbOrDcb );

                            try_return( PostIrp = TRUE );
                        }

                        FcbOrDcbAcquired = TRUE;
                        
#pragma prefast( suppress:28931, "convenient for debugging" )
                        FcbAcquiredExclusive = TRUE;
                    }
                }

                //
                //  Now that we have the Fcb exclusive, see if this write
                //  qualifies for being made async again.  The key point
                //  here is that we are going to update ValidDataLength in
                //  the Fcb before returning.  We must make sure this will
                //  not cause a problem.  One thing we must do is keep out
                //  the FastIo path.
                //

                if (SwitchBackToAsync) {

                    if ((FcbOrDcb->NonPaged->SectionObjectPointers.DataSectionObject != NULL) ||
                        (StartingVbo + ByteCount > FcbOrDcb->Header.ValidDataLength.LowPart) ||
                        FatNoAsync) {

                        RtlZeroMemory( IrpContext->FatIoContext, sizeof(FAT_IO_CONTEXT) );

                        KeInitializeEvent( &IrpContext->FatIoContext->Wait.SyncEvent,
                                           NotificationEvent,
                                           FALSE );

                        SwitchBackToAsync = FALSE;

                    } else {

                        if (!FcbOrDcb->NonPaged->OutstandingAsyncEvent) {

                            FcbOrDcb->NonPaged->OutstandingAsyncEvent =
                                FsRtlAllocatePoolWithTag( NonPagedPoolNx,
                                                          sizeof(KEVENT),
                                                          TAG_EVENT );

                            KeInitializeEvent( FcbOrDcb->NonPaged->OutstandingAsyncEvent,
                                               NotificationEvent,
                                               FALSE );
                        }

                        //
                        //  If we are transitioning from 0 to 1, reset the event.
                        //

                        if (ExInterlockedAddUlong( &FcbOrDcb->NonPaged->OutstandingAsyncWrites,
                                                   1,
                                                   &FatData.GeneralSpinLock ) == 0) {

                            KeClearEvent( FcbOrDcb->NonPaged->OutstandingAsyncEvent );
                        }

                        UnwindOutstandingAsync = TRUE;

                        IrpContext->FatIoContext->Wait.Async.NonPagedFcb = FcbOrDcb->NonPaged;
                    }
                }

                //
                //  Now that we have the Fcb exclusive, get a new batch of
                //  filesize and ValidDataLength.
                //

                ValidDataToDisk = FcbOrDcb->ValidDataToDisk;
                ValidDataLength = FcbOrDcb->Header.ValidDataLength.LowPart;
                FileSize = FcbOrDcb->Header.FileSize.LowPart;

                //
                //  If this is PagingIo check again if any pruning is
                //  required.  It is important to start from basic
                //  princples in case the file was *grown* ...
                //

                if ( PagingIo ) {

                    if (StartingVbo >= FileSize) {
                        Irp->IoStatus.Information = 0;
                        try_return( Status = STATUS_SUCCESS );
                    }
                    
                    ByteCount = IrpSp->Parameters.Write.Length;

                    if (ByteCount > FileSize - StartingVbo) {
                        ByteCount = FileSize - StartingVbo;
                    }
                }
            }

            //
            //  Remember the final requested byte count
            //

            if (NonCachedIo && !Wait) {

                IrpContext->FatIoContext->Wait.Async.RequestedByteCount =
                    ByteCount;
            }

            //
            //  Remember the initial file size and valid data length,
            //  just in case .....
            //

            InitialFileSize = FileSize;

            InitialValidDataLength = ValidDataLength;

            //
            //  Make sure the FcbOrDcb is still good
            //

            FatVerifyFcb( IrpContext, FcbOrDcb );

            //
            //  Check for writing to end of File.  If we are, then we have to
            //  recalculate a number of fields.
            //

            if ( WriteToEof ) {

                StartingVbo = FileSize;
                StartingByte = FcbOrDcb->Header.FileSize;

                //
                //  Since we couldn't know this information until now, perform the
                //  necessary bounds checking that we ommited at the top because
                //  this is a WriteToEof operation.
                //

                
                if (!FatIsIoRangeValid( Vcb, StartingByte, ByteCount)) {
                    
                    Irp->IoStatus.Information = 0;
                    try_return( Status = STATUS_DISK_FULL );
                }


            }

            //
            //  If this is a non paging write to a data stream object we have to
            //  check for access according to the current state op/filelocks.
            //
            //  Note that after this point, operations will be performed on the file.
            //  No modifying activity can occur prior to this point in the write
            //  path.
            //

            if (!PagingIo && TypeOfOpen == UserFileOpen) {

                Status = FsRtlCheckOplock( FatGetFcbOplock(FcbOrDcb),
                                           Irp,
                                           IrpContext,
                                           FatOplockComplete,
                                           FatPrePostIrp );

                if (Status != STATUS_SUCCESS) {

                    OplockPostIrp = TRUE;
                    PostIrp = TRUE;
                    try_return( NOTHING );
                }

                //
                //  This oplock call can affect whether fast IO is possible.
                //  We may have broken an oplock to no oplock held.  If the
                //  current state of the file is FastIoIsNotPossible then
                //  recheck the fast IO state.
                //

                if (FcbOrDcb->Header.IsFastIoPossible == FastIoIsNotPossible) {

                    FcbOrDcb->Header.IsFastIoPossible = FatIsFastIoPossible( FcbOrDcb );
                }

                //
                //  And finally check the regular file locks.
                //

                if (!FsRtlCheckLockForWriteAccess( &FcbOrDcb->Specific.Fcb.FileLock, Irp )) {

                    try_return( Status = STATUS_FILE_LOCK_CONFLICT );
                }
            }

            //
            //  Determine if we will deal with extending the file. Note that
            //  this implies extending valid data, and so we already have all
            //  of the required synchronization done.
            //

            if (!PagingIo && (StartingVbo + ByteCount > FileSize)) {

                ExtendingFile = TRUE;
            }

            if ( ExtendingFile ) {


                //
                //  EXTENDING THE FILE
                //

                //
                //  For an extending write on hotplug media, we are going to defer the metadata
                //  updates via Cc's lazy writer. They will also be flushed when the handle is closed.
                //

                if (FlagOn(Vcb->VcbState, VCB_STATE_FLAG_DEFERRED_FLUSH)) {
                    
                    SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_DISABLE_WRITE_THROUGH);
                }

                //
                //  Update our local copy of FileSize
                //

                FileSize = StartingVbo + ByteCount;


                if (FcbOrDcb->Header.AllocationSize.QuadPart == FCB_LOOKUP_ALLOCATIONSIZE_HINT) {

                    FatLookupFileAllocationSize( IrpContext, FcbOrDcb );
                }

                //
                //  If the write goes beyond the allocation size, add some
                //  file allocation.
                //


                if ( (FileSize) > FcbOrDcb->Header.AllocationSize.LowPart ) {


                    BOOLEAN AllocateMinimumSize = TRUE;

                    //
                    //  Only do allocation chuncking on writes if this is
                    //  not the first allocation added to the file.
                    //

                    if (FcbOrDcb->Header.AllocationSize.LowPart != 0 ) {

                        ULONGLONG ApproximateClusterCount;
                        ULONGLONG TargetAllocation;
                        ULONGLONG AddedAllocation;                        
                        ULONGLONG Multiplier;
                        ULONG BytesPerCluster;
                        ULONG ClusterAlignedFileSize;

                        //
                        //  We are going to try and allocate a bigger chunk than
                        //  we actually need in order to maximize FastIo usage.
                        //
                        //  The multiplier is computed as follows:
                        //
                        //
                        //            (FreeDiskSpace            )
                        //  Mult =  ( (-------------------------) / 32 ) + 1
                        //            (FileSize - AllocationSize)
                        //
                        //          and max out at 32.
                        //
                        //  With this formula we start winding down chunking
                        //  as we get near the disk space wall.
                        //
                        //  For instance on an empty 1 MEG floppy doing an 8K
                        //  write, the multiplier is 6, or 48K to allocate.
                        //  When this disk is half full, the multipler is 3,
                        //  and when it is 3/4 full, the mupltiplier is only 1.
                        //
                        //  On a larger disk, the multiplier for a 8K read will
                        //  reach its maximum of 32 when there is at least ~8 Megs
                        //  available.
                        //

                        //
                        //  Small write performance note, use cluster aligned
                        //  file size in above equation.
                        //

                        //
                        //  We need to carefully consider what happens when we approach
                        //  a 2^32 byte filesize.  Overflows will cause problems.
                        //

                        BytesPerCluster = 1 << Vcb->AllocationSupport.LogOfBytesPerCluster;

                        //
                        //  This can overflow if the target filesize is in the last cluster.
                        //  In this case, we can obviously skip over all of this fancy
                        //  logic and just max out the file right now.
                        //


                        ClusterAlignedFileSize = ((FileSize) + (BytesPerCluster - 1)) &
                                                 ~(BytesPerCluster - 1);


                        if (ClusterAlignedFileSize != 0) {

                            //
                            //  This actually has a chance but the possibility of overflowing
                            //  the numerator is pretty unlikely, made more unlikely by moving
                            //  the divide by 32 up to scale the BytesPerCluster. However, even if it does the
                            //  effect is completely benign.
                            //
                            //  FAT32 with a 64k cluster and over 2^21 clusters would do it (and
                            //  so forth - 2^(16 - 5 + 21) == 2^32).  Since this implies a partition
                            //  of 32gb and a number of clusters (and cluster size) we plan to
                            //  disallow in format for FAT32, the odds of this happening are pretty
                            //  low anyway.    
                            Multiplier = ((Vcb->AllocationSupport.NumberOfFreeClusters *
                                           (BytesPerCluster >> 5)) /
                                          (ClusterAlignedFileSize -
                                           FcbOrDcb->Header.AllocationSize.LowPart)) + 1;
    
                            if (Multiplier > 32) { Multiplier = 32; }

                            // These computations will never overflow a ULONGLONG because a file is capped at 4GB, and 
                            // a single write can be a max of 4GB.
                            AddedAllocation = Multiplier * (ClusterAlignedFileSize - FcbOrDcb->Header.AllocationSize.LowPart);

                            TargetAllocation = FcbOrDcb->Header.AllocationSize.LowPart + AddedAllocation;
    
                            //
                            //  We know that TargetAllocation is in whole clusters. Now
                            //  we check if it exceeded the maximum valid FAT file size.
                            //  If it did, we fall back to allocating up to the maximum legal size.
                            //
    
                            if (TargetAllocation > ~BytesPerCluster + 1) {
    
                                TargetAllocation = ~BytesPerCluster + 1;
                                AddedAllocation = TargetAllocation - FcbOrDcb->Header.AllocationSize.LowPart;
                            }
    
                            //
                            //  Now do an unsafe check here to see if we should even
                            //  try to allocate this much.  If not, just allocate
                            //  the minimum size we need, if so so try it, but if it
                            //  fails, just allocate the minimum size we need.
                            //
    
                            ApproximateClusterCount = (AddedAllocation / BytesPerCluster);
    
                            if (ApproximateClusterCount <= Vcb->AllocationSupport.NumberOfFreeClusters) {
    
                                try {
    
                                    FatAddFileAllocation( IrpContext,
                                                          FcbOrDcb,
                                                          FileObject,
                                                          (ULONG)TargetAllocation );
    
                                    AllocateMinimumSize = FALSE;
                                    SetFlag( FcbOrDcb->FcbState, FCB_STATE_TRUNCATE_ON_CLOSE );
    
                                } except( GetExceptionCode() == STATUS_DISK_FULL ?
                                          EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH ) {
    
                                      FatResetExceptionState( IrpContext );
                                }
                            }
                        }
                    }

                    if ( AllocateMinimumSize ) {


                        FatAddFileAllocation( IrpContext,
                                              FcbOrDcb,
                                              FileObject,
                                              FileSize );


                    }

                    //
                    //  Assert that the allocation worked
                    //


                    NT_ASSERT( FcbOrDcb->Header.AllocationSize.LowPart >= FileSize );


                }

                //
                //  Set the new file size in the Fcb
                //


                NT_ASSERT( FileSize <= FcbOrDcb->Header.AllocationSize.LowPart );

                
                FcbOrDcb->Header.FileSize.LowPart = FileSize;

                //
                //  Extend the cache map, letting mm knows the new file size.
                //  We only have to do this if the file is cached.
                //

                if (CcIsFileCached(FileObject)) {
                    CcSetFileSizes( FileObject, (PCC_FILE_SIZES)&FcbOrDcb->Header.AllocationSize );
                }
            }

            //
            //  Determine if we will deal with extending valid data.
            //

            if ( !CalledByLazyWriter &&
                 !RecursiveWriteThrough &&
                 (StartingVbo + ByteCount > ValidDataLength) ) {

                ExtendingValidData = TRUE;
            
            } else {

                //
                //  If not extending valid data, and we otherwise believe we
                //  could demote from exclusive to shared, do so.  This will
                //  occur when we synchronize tight for noncached coherency
                //  but must defer the demotion until after we decide about
                //  valid data length, which requires it exclusive.  Since we
                //  can't drop/re-pick the resources without letting a pagefault
                //  squirt through, the resource decision was kept up in the air
                //  until now.
                //
                //  Note that we've still got PagingIo exclusive in these cases.
                //
                
                if (FcbCanDemoteToShared) {

                    NT_ASSERT( FcbAcquiredExclusive && ExIsResourceAcquiredExclusiveLite( FcbOrDcb->Header.Resource ));
                    ExConvertExclusiveToSharedLite( FcbOrDcb->Header.Resource );
                    FcbAcquiredExclusive = FALSE;
                }
            }
            
            if (ValidDataToDisk > ValidDataLength) {
                
                ValidDataToCheck = ValidDataToDisk;
            
            } else {
                
                ValidDataToCheck = ValidDataLength;
            }



            //
            // HANDLE THE NON-CACHED CASE
            //

            if ( NonCachedIo ) {

                //
                // Declare some local variables for enumeration through the
                // runs of the file, and an array to store parameters for
                // parallel I/Os
                //

                ULONG SectorSize;

                ULONG BytesToWrite;

                DebugTrace(0, Dbg, "Non cached write.\n", 0);

                //
                //  Round up to sector boundry.  The end of the write interval
                //  must, however, be beyond EOF.
                //

                SectorSize = (ULONG)Vcb->Bpb.BytesPerSector;

                BytesToWrite = (ByteCount + (SectorSize - 1))
                                         & ~(SectorSize - 1);

                //
                //  All requests should be well formed and
                //  make sure we don't wipe out any data
                //

                if (((StartingVbo & (SectorSize - 1)) != 0) ||

                        ((BytesToWrite != ByteCount) &&
                         (StartingVbo + ByteCount < ValidDataLength))) {

                    NT_ASSERT( FALSE );

                    DebugTrace( 0, Dbg, "FatCommonWrite -> STATUS_NOT_IMPLEMENTED\n", 0);
                    try_return( Status = STATUS_NOT_IMPLEMENTED );
                }

                //
                // If this noncached transfer is at least one sector beyond
                // the current ValidDataLength in the Fcb, then we have to
                // zero the sectors in between.  This can happen if the user
                // has opened the file noncached, or if the user has mapped
                // the file and modified a page beyond ValidDataLength.  It
                // *cannot* happen if the user opened the file cached, because
                // ValidDataLength in the Fcb is updated when he does the cached
                // write (we also zero data in the cache at that time), and
                // therefore, we will bypass this test when the data
                // is ultimately written through (by the Lazy Writer).
                //
                //  For the paging file we don't care about security (ie.
                //  stale data), do don't bother zeroing.
                //
                //  We can actually get writes wholly beyond valid data length
                //  from the LazyWriter because of paging Io decoupling.
                //

                if (!CalledByLazyWriter &&
                    !RecursiveWriteThrough &&
                    (StartingVbo > ValidDataToCheck)) {

                    FatZeroData( IrpContext,
                                 Vcb,
                                 FileObject,
                                 ValidDataToCheck,
                                 StartingVbo - ValidDataToCheck );
                }

                //
                // Make sure we write FileSize to the dirent if we
                // are extending it and we are successful.  (This may or
                // may not occur Write Through, but that is fine.)
                //

                WriteFileSizeToDirent = TRUE;

                //
                //  Perform the actual IO
                //

                if (SwitchBackToAsync) {

                    Wait = FALSE;
                    ClearFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );
                }

#ifdef SYSCACHE_COMPILE

#define MY_SIZE 0x1000000
#define LONGMAP_COUNTER

#ifdef BITMAP
                //
                //  Maintain a bitmap of IO started on this file.
                //

                {
                    PULONG WriteMask = FcbOrDcb->WriteMask;

                    if (NULL == WriteMask) {

                        WriteMask = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
                                                              (MY_SIZE/PAGE_SIZE) / 8,
                                                              'wtaF' );

                        FcbOrDcb->WriteMask = WriteMask;
                        RtlZeroMemory(WriteMask, (MY_SIZE/PAGE_SIZE) / 8);
                    }

                    if (StartingVbo < MY_SIZE) {

                        ULONG Off = StartingVbo;
                        ULONG Len = BytesToWrite;

                        if (Off + Len > MY_SIZE) {
                            Len = MY_SIZE - Off;
                        }

                        while (Len != 0) {
                            WriteMask[(Off/PAGE_SIZE) / 32] |=
                                1 << (Off/PAGE_SIZE) % 32;

                            Off += PAGE_SIZE;
                            if (Len <= PAGE_SIZE) {
                                break;
                            }
                            Len -= PAGE_SIZE;
                        }
                    }
                }
#endif

#ifdef LONGMAP_COUNTER
                //
                //  Maintain a longmap of IO started on this file, each ulong containing
                //  the value of an ascending counter per write (gives us order information).
                //
                //  Unlike the old bitmask stuff, this is mostly well synchronized.
                //

                {
                    PULONG WriteMask = (PULONG)FcbOrDcb->WriteMask;

                    if (NULL == WriteMask) {

                        WriteMask = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
                                                              (MY_SIZE/PAGE_SIZE) * sizeof(ULONG),
                                                              'wtaF' );

                        FcbOrDcb->WriteMask = WriteMask;
                        RtlZeroMemory(WriteMask, (MY_SIZE/PAGE_SIZE) * sizeof(ULONG));
                    }

                    if (StartingVbo < MY_SIZE) {

                        ULONG Off = StartingVbo;
                        ULONG Len = BytesToWrite;
                        ULONG Tick = InterlockedIncrement( &FcbOrDcb->WriteMaskData );

                        if (Off + Len > MY_SIZE) {
                            Len = MY_SIZE - Off;
                        }

                        while (Len != 0) {
                            InterlockedExchange( WriteMask + Off/PAGE_SIZE, Tick );

                            Off += PAGE_SIZE;
                            if (Len <= PAGE_SIZE) {
                                break;
                            }
                            Len -= PAGE_SIZE;
                        }
                    }
                }
#endif

#endif


                if (FatNonCachedIo( IrpContext,
                                    Irp,
                                    FcbOrDcb,
                                    StartingVbo,
                                    BytesToWrite,
                                    BytesToWrite,
                                    0) == STATUS_PENDING) {


                    UnwindOutstandingAsync = FALSE;

#pragma prefast( suppress:28931, "convenient for debugging" )
                    Wait = TRUE;
                    SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT );

                    IrpContext->FatIoContext = NULL;
                    Irp = NULL;

                    //
                    //  As a matter of fact, if we hit this we are in deep trouble
                    //  if VDL is being extended. We are no longer attached to the
                    //  IRP, and have thus lost synchronization.  Note that we should
                    //  not hit this case anymore since we will not re-async vdl extension.
                    //
                    
                    NT_ASSERT( !ExtendingValidData );

                    try_return( Status = STATUS_PENDING );
                }

                //
                //  If the call didn't succeed, raise the error status
                //

                if (!NT_SUCCESS( Status = Irp->IoStatus.Status )) {

                    FatNormalizeAndRaiseStatus( IrpContext, Status );

                } else {

                    ULONG NewValidDataToDisk;

                    //
                    //  Else set the context block to reflect the entire write
                    //  Also assert we got how many bytes we asked for.
                    //

                    NT_ASSERT( Irp->IoStatus.Information == BytesToWrite );

                    Irp->IoStatus.Information = ByteCount;

                    //
                    //  Take this opportunity to update ValidDataToDisk.
                    //

                    NewValidDataToDisk = StartingVbo + ByteCount;

                    if (NewValidDataToDisk > FileSize) {
                        NewValidDataToDisk = FileSize;
                    }

                    if (FcbOrDcb->ValidDataToDisk < NewValidDataToDisk) {
                        FcbOrDcb->ValidDataToDisk = NewValidDataToDisk;
                    }
                }

                //
                // The transfer is either complete, or the Iosb contains the
                // appropriate status.
                //

                try_return( Status );

            } // if No Intermediate Buffering


            //
            // HANDLE CACHED CASE
            //

            else {

                NT_ASSERT( !PagingIo );

                //
                // We delay setting up the file cache until now, in case the
                // caller never does any I/O to the file, and thus
                // FileObject->PrivateCacheMap == NULL.
                //

                if ( FileObject->PrivateCacheMap == NULL ) {

                    DebugTrace(0, Dbg, "Initialize cache mapping.\n", 0);

                    //
                    //  Get the file allocation size, and if it is less than
                    //  the file size, raise file corrupt error.
                    //

                    if (FcbOrDcb->Header.AllocationSize.QuadPart == FCB_LOOKUP_ALLOCATIONSIZE_HINT) {

                        FatLookupFileAllocationSize( IrpContext, FcbOrDcb );
                    }

                    if ( FileSize > FcbOrDcb->Header.AllocationSize.LowPart ) {

                        FatPopUpFileCorrupt( IrpContext, FcbOrDcb );

                        FatRaiseStatus( IrpContext, STATUS_FILE_CORRUPT_ERROR );
                    }

                    //
                    //  Now initialize the cache map.
                    //

                    FatInitializeCacheMap( FileObject,
                                           (PCC_FILE_SIZES)&FcbOrDcb->Header.AllocationSize,
                                           FALSE,
                                           &FatData.CacheManagerCallbacks,
                                           FcbOrDcb );

                    CcSetReadAheadGranularity( FileObject, READ_AHEAD_GRANULARITY );

                    //
                    //  Special case large floppy tranfers, and make the file
                    //  object write through.  For small floppy transfers,
                    //  set a timer to go off in a second and flush the file.
                    //
                    //

                    if (!FlagOn( FileObject->Flags, FO_WRITE_THROUGH ) &&
                        FlagOn(Vcb->VcbState, VCB_STATE_FLAG_DEFERRED_FLUSH)) {

                        if (((StartingByte.LowPart & (PAGE_SIZE-1)) == 0) &&
                            (ByteCount >= PAGE_SIZE)) {

                            SetFlag( FileObject->Flags, FO_WRITE_THROUGH );

                        } else {

                            LARGE_INTEGER OneSecondFromNow;
                            PDEFERRED_FLUSH_CONTEXT FlushContext;

                            //
                            //  Get pool and initialize the timer and DPC
                            //

                            FlushContext = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
                                                                     sizeof(DEFERRED_FLUSH_CONTEXT),
                                                                     TAG_DEFERRED_FLUSH_CONTEXT );

                            KeInitializeTimer( &FlushContext->Timer );

                            KeInitializeDpc( &FlushContext->Dpc,
                                             FatDeferredFlushDpc,
                                             FlushContext );


                            //
                            //  We have to reference the file object here.
                            //

                            ObReferenceObject( FileObject );

                            FlushContext->File = FileObject;

                            //
                            //  Let'er rip!
                            //

                            OneSecondFromNow.QuadPart = (LONG)-1*1000*1000*10;

                            KeSetTimer( &FlushContext->Timer,
                                        OneSecondFromNow,
                                        &FlushContext->Dpc );
                        }
                    }
                }

                //
                // If this write is beyond valid data length, then we
                // must zero the data in between.
                //

                if ( StartingVbo > ValidDataToCheck ) {

                    //
                    // Call the Cache Manager to zero the data.
                    //

                    if (!FatZeroData( IrpContext,
                                      Vcb,
                                      FileObject,
                                      ValidDataToCheck,
                                      StartingVbo - ValidDataToCheck )) {

                        DebugTrace( 0, Dbg, "Cached Write could not wait to zero\n", 0 );

                        try_return( PostIrp = TRUE );
                    }
                }

                WriteFileSizeToDirent = BooleanFlagOn(IrpContext->Flags,
                                                      IRP_CONTEXT_FLAG_WRITE_THROUGH);


                //
                // DO A NORMAL CACHED WRITE, if the MDL bit is not set,
                //

                if (!FlagOn(IrpContext->MinorFunction, IRP_MN_MDL)) {

                    DebugTrace(0, Dbg, "Cached write.\n", 0);

                    //
                    //  Get hold of the user's buffer.
                    //

                    SystemBuffer = FatMapUserBuffer( IrpContext, Irp );

                    //
                    // Do the write, possibly writing through
                    //

#if (NTDDI_VERSION >= NTDDI_WIN8)
                    if (!CcCopyWriteEx( FileObject,
                                        &StartingByte,
                                        ByteCount,
                                        Wait,
                                        SystemBuffer,
                                        Irp->Tail.Overlay.Thread )) {
#else
                    if (!CcCopyWrite( FileObject,
                                      &StartingByte,
                                      ByteCount,
                                      Wait,
                                      SystemBuffer )) {
#endif

                        DebugTrace( 0, Dbg, "Cached Write could not wait\n", 0 );

                        try_return( PostIrp = TRUE );
                    }

                    Irp->IoStatus.Status = STATUS_SUCCESS;
                    Irp->IoStatus.Information = ByteCount;

                    try_return( Status = STATUS_SUCCESS );

                } else {

                    //
                    //  DO AN MDL WRITE
                    //

                    DebugTrace(0, Dbg, "MDL write.\n", 0);

                    NT_ASSERT( Wait );

                    CcPrepareMdlWrite( FileObject,
                                       &StartingByte,
                                       ByteCount,
                                       &Irp->MdlAddress,
                                       &Irp->IoStatus );

                    Status = Irp->IoStatus.Status;

                    try_return( Status );
                }
            }
        }

        //
        //  These two cases correspond to a system write directory file and
        //  ea file.
        //

        if (( TypeOfOpen == DirectoryFile ) || ( TypeOfOpen == EaFile)
            ) {

            ULONG SectorSize;

#if FASTFATDBG
            if ( TypeOfOpen == DirectoryFile ) {
                DebugTrace(0, Dbg, "Type of write is directoryfile\n", 0);                
            } else if ( TypeOfOpen == EaFile) {
                DebugTrace(0, Dbg, "Type of write is eafile\n", 0);
            }
#endif

            //
            //  Make sure the FcbOrDcb is still good
            //

            FatVerifyFcb( IrpContext, FcbOrDcb );

            //
            //  Synchronize here with people deleting directories and
            //  mucking with the internals of the EA file.
            //

            if (!ExAcquireSharedStarveExclusive( FcbOrDcb->Header.PagingIoResource,
                                          Wait )) {

                DebugTrace( 0, Dbg, "Cannot acquire FcbOrDcb = %p shared without waiting\n", FcbOrDcb );

                try_return( PostIrp = TRUE );
            }

            PagingIoResourceAcquired = TRUE;

            if (!Wait) {

                IrpContext->FatIoContext->Wait.Async.Resource =
                    FcbOrDcb->Header.PagingIoResource;
            }

            //
            //  Check to see if we colided with a MoveFile call, and if
            //  so block until it completes.
            //

            if (FcbOrDcb->MoveFileEvent) {

                (VOID)KeWaitForSingleObject( FcbOrDcb->MoveFileEvent,
                                             Executive,
                                             KernelMode,
                                             FALSE,
                                             NULL );
            }

            //
            //  If we weren't called by the Lazy Writer, then this write
            //  must be the result of a write-through or flush operation.
            //  Setting the IrpContext flag, will cause DevIoSup.c to
            //  write-through the data to the disk.
            //

            if (!FlagOn((ULONG_PTR)IoGetTopLevelIrp(), FSRTL_CACHE_TOP_LEVEL_IRP)) {

                SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WRITE_THROUGH );
            }

            //
            //  For the noncached case, assert that everything is sector
            //  alligned.
            //
            
#pragma prefast( suppress:28931, "needed for debug build" )
            SectorSize = (ULONG)Vcb->Bpb.BytesPerSector;

            //
            //  We make several assumptions about these two types of files.
            //  Make sure all of them are true.
            //

            NT_ASSERT( NonCachedIo && PagingIo );
            NT_ASSERT( ((StartingVbo | ByteCount) & (SectorSize - 1)) == 0 );


                //
                //  These calls must always be within the allocation size, which is
                //  convienently the same as filesize, which conveniently doesn't
                //  get reset to a hint value when we verify the volume.
                //

                if (StartingVbo >= FcbOrDcb->Header.FileSize.LowPart) {

                    DebugTrace( 0, Dbg, "PagingIo dirent started beyond EOF.\n", 0 );

                    Irp->IoStatus.Information = 0;

                    try_return( Status = STATUS_SUCCESS );
                }

                if ( StartingVbo + ByteCount > FcbOrDcb->Header.FileSize.LowPart ) {

                    DebugTrace( 0, Dbg, "PagingIo dirent extending beyond EOF.\n", 0 );
                    ByteCount = FcbOrDcb->Header.FileSize.LowPart - StartingVbo;
                }

            
            //
            //  Perform the actual IO
            //

            if (FatNonCachedIo( IrpContext,
                                Irp,
                                FcbOrDcb,
                                StartingVbo,
                                ByteCount,
                                ByteCount,
                                0 ) == STATUS_PENDING) {

                IrpContext->FatIoContext = NULL;

                Irp = NULL;

                try_return( Status = STATUS_PENDING );
            }

            //
            //  The transfer is either complete, or the Iosb contains the
            //  appropriate status.
            //
            //  Also, mark the volume as needing verification to automatically
            //  clean up stuff.
            //

            if (!NT_SUCCESS( Status = Irp->IoStatus.Status )) {

                FatNormalizeAndRaiseStatus( IrpContext, Status );
            }

            try_return( Status );
        }

        //
        // This is the case of a user who openned a directory. No writing is
        // allowed.
        //

        if ( TypeOfOpen == UserDirectoryOpen ) {

            DebugTrace( 0, Dbg, "FatCommonWrite -> STATUS_INVALID_PARAMETER\n", 0);

            try_return( Status = STATUS_INVALID_PARAMETER );
        }

        //
        //  If we get this far, something really serious is wrong.
        //

        DebugDump("Illegal TypeOfOpen\n", 0, FcbOrDcb );

#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )
        FatBugCheck( TypeOfOpen, (ULONG_PTR) FcbOrDcb, 0 );

    try_exit: NOTHING;


        //
        //  If the request was not posted and there is still an Irp,
        //  deal with it.
        //

        if (Irp) {

            if ( !PostIrp ) {

                ULONG ActualBytesWrote;

                DebugTrace( 0, Dbg, "Completing request with status = %08lx\n",
                            Status);

                DebugTrace( 0, Dbg, "                   Information = %08lx\n",
                            Irp->IoStatus.Information);

                //
                //  Record the total number of bytes actually written
                //

                ActualBytesWrote = (ULONG)Irp->IoStatus.Information;

                //
                //  If the file was opened for Synchronous IO, update the current
                //  file position.
                //

                if (SynchronousIo && !PagingIo) {

                    FileObject->CurrentByteOffset.LowPart =
                         StartingVbo + (NT_ERROR( Status ) ? 0 : ActualBytesWrote);
                }

                //
                //  The following are things we only do if we were successful
                //

                if ( NT_SUCCESS( Status ) ) {

                    //
                    //  If this was not PagingIo, mark that the modify
                    //  time on the dirent needs to be updated on close.
                    //

                    if ( !PagingIo ) {

                        SetFlag( FileObject->Flags, FO_FILE_MODIFIED );
                    }

                    //
                    //  If we extended the file size and we are meant to
                    //  immediately update the dirent, do so. (This flag is
                    //  set for either Write Through or noncached, because
                    //  in either case the data and any necessary zeros are
                    //  actually written to the file.)
                    //

                    if ( ExtendingFile && WriteFileSizeToDirent ) {

                        NT_ASSERT( FileObject->DeleteAccess || FileObject->WriteAccess );

                        FatSetFileSizeInDirent( IrpContext, FcbOrDcb, NULL );

                        //
                        //  Report that a file size has changed.
                        //

                        FatNotifyReportChange( IrpContext,
                                               Vcb,
                                               FcbOrDcb,
                                               FILE_NOTIFY_CHANGE_SIZE,
                                               FILE_ACTION_MODIFIED );
                    }

                    if ( ExtendingFile && !WriteFileSizeToDirent ) {

                        SetFlag( FileObject->Flags, FO_FILE_SIZE_CHANGED );
                    }

                    if ( ExtendingValidData ) {

                        ULONG EndingVboWritten = StartingVbo + ActualBytesWrote;

                        //
                        //  Never set a ValidDataLength greater than FileSize.
                        //

                        if ( FileSize < EndingVboWritten ) {

                            FcbOrDcb->Header.ValidDataLength.LowPart = FileSize;

                        } else {

                            FcbOrDcb->Header.ValidDataLength.LowPart = EndingVboWritten;
                        }

                        //
                        //  Now, if we are noncached and the file is cached, we must
                        //  tell the cache manager about the VDL extension so that
                        //  async cached IO will not be optimized into zero-page faults
                        //  beyond where it believes VDL is.
                        //
                        //  In the cached case, since Cc did the work, it has updated
                        //  itself already.
                        //

                        if (NonCachedIo && CcIsFileCached(FileObject)) {
                            CcSetFileSizes( FileObject, (PCC_FILE_SIZES)&FcbOrDcb->Header.AllocationSize );
                        }
                    }
                    
                }
                
                //
                //  Note that we have to unpin repinned Bcbs here after the above
                //  work, but if we are going to post the request, we must do this
                //  before the post (below).
                //

                FatUnpinRepinnedBcbs( IrpContext );

            } else {

                //
                //  Take action if the Oplock package is not going to post the Irp.
                //

                if (!OplockPostIrp) {

                    FatUnpinRepinnedBcbs( IrpContext );

                    if ( ExtendingFile ) {

                        //
                        //  We need the PagingIo resource exclusive whenever we
                        //  pull back either file size or valid data length.
                        //

                        NT_ASSERT( FcbOrDcb->Header.PagingIoResource != NULL );

                        (VOID)ExAcquireResourceExclusiveLite(FcbOrDcb->Header.PagingIoResource, TRUE);

                        FcbOrDcb->Header.FileSize.LowPart = InitialFileSize;

                        NT_ASSERT( FcbOrDcb->Header.FileSize.LowPart <= FcbOrDcb->Header.AllocationSize.LowPart );

                        //
                        //  Pull back the cache map as well
                        //

                        if (FileObject->SectionObjectPointer->SharedCacheMap != NULL) {

                            *CcGetFileSizePointer(FileObject) = FcbOrDcb->Header.FileSize;
                        }

                        ExReleaseResourceLite( FcbOrDcb->Header.PagingIoResource );
                    }

                    DebugTrace( 0, Dbg, "Passing request to Fsp\n", 0 );

                    Status = FatFsdPostRequest(IrpContext, Irp);
                }
            }
        }

    } finally {

        DebugUnwind( FatCommonWrite );

        if (AbnormalTermination()) {

            //
            //  Restore initial file size and valid data length
            //

            if (ExtendingFile || ExtendingValidData) {

                //
                //  We got an error, pull back the file size if we extended it.
                //

                FcbOrDcb->Header.FileSize.LowPart = InitialFileSize;
                FcbOrDcb->Header.ValidDataLength.LowPart = InitialValidDataLength;

                NT_ASSERT( FcbOrDcb->Header.FileSize.LowPart <= FcbOrDcb->Header.AllocationSize.LowPart );

                //
                //  Pull back the cache map as well
                //

                if (FileObject->SectionObjectPointer->SharedCacheMap != NULL) {

                    *CcGetFileSizePointer(FileObject) = FcbOrDcb->Header.FileSize;
                }
            }
        }

        //
        //  Check if this needs to be backed out.
        //

        if (UnwindOutstandingAsync) {

            ExInterlockedAddUlong( &FcbOrDcb->NonPaged->OutstandingAsyncWrites,
                                   0xffffffff,
                                   &FatData.GeneralSpinLock );
        }

        //
        //  If the FcbOrDcb has been acquired, release it.
        //

        if (FcbOrDcbAcquired && Irp) {

            FatReleaseFcb( NULL, FcbOrDcb );
        }

        if (PagingIoResourceAcquired && Irp) {

            ExReleaseResourceLite( FcbOrDcb->Header.PagingIoResource );
        }

        //
        //  Complete the request if we didn't post it and no exception
        //
        //  Note that FatCompleteRequest does the right thing if either
        //  IrpContext or Irp are NULL
        //

        if ( !PostIrp && !AbnormalTermination() ) {

            FatCompleteRequest( IrpContext, Irp, Status );
        }

        DebugTrace(-1, Dbg, "FatCommonWrite -> %08lx\n", Status );
    }

    return Status;
}


//
//  Local support routine
//

VOID
FatDeferredFlushDpc (
    _In_ PKDPC Dpc,
    _In_opt_ PVOID DeferredContext,
    _In_opt_ PVOID SystemArgument1,
    _In_opt_ PVOID SystemArgument2
    )

/*++

Routine Description:

    This routine is dispatched 1 second after a small write to a deferred
    write device that initialized the cache map.  It exqueues an executive
    worker thread to perform the actual task of flushing the file.

Arguments:

    DeferredContext - Contains the deferred flush context.

Return Value:

    None.

--*/

{
    PDEFERRED_FLUSH_CONTEXT FlushContext;

    UNREFERENCED_PARAMETER( SystemArgument1 );
    UNREFERENCED_PARAMETER( SystemArgument2 );
    UNREFERENCED_PARAMETER( Dpc );

    FlushContext = (PDEFERRED_FLUSH_CONTEXT)DeferredContext;

    //
    //  Send it off
    //

#pragma prefast( suppress: 28155, "the function prototype is correct ")
#pragma warning( suppress:4996 )
    ExInitializeWorkItem( &FlushContext->Item,
                          FatDeferredFlush,
                          FlushContext );

#pragma prefast( suppress:28159, "prefast indicates this API is obsolete, but it's ok for fastfat to keep using it" )
#pragma warning( suppress:4996 )
    ExQueueWorkItem( &FlushContext->Item, CriticalWorkQueue );
}


//
//  Local support routine
//

VOID
FatDeferredFlush (
    _In_ PVOID Parameter
    )

/*++

Routine Description:

    This routine performs the actual task of flushing the file.

Arguments:

    DeferredContext - Contains the deferred flush context.

Return Value:

    None.

--*/

{

    PFILE_OBJECT File;
    PVCB Vcb;
    PFCB FcbOrDcb;
    PCCB Ccb;

    PAGED_CODE();

    File = ((PDEFERRED_FLUSH_CONTEXT)Parameter)->File;

    FatDecodeFileObject(File, &Vcb, &FcbOrDcb, &Ccb);
    NT_ASSERT( FcbOrDcb != NULL );
    
    //
    //  Make us appear as a top level FSP request so that we will
    //  receive any errors from the flush.
    //

    IoSetTopLevelIrp( (PIRP)FSRTL_FSP_TOP_LEVEL_IRP );

    ExAcquireResourceExclusiveLite( FcbOrDcb->Header.Resource, TRUE );
    ExAcquireResourceSharedLite( FcbOrDcb->Header.PagingIoResource, TRUE );
    
    CcFlushCache( File->SectionObjectPointer, NULL, 0, NULL );

    ExReleaseResourceLite( FcbOrDcb->Header.PagingIoResource );
    ExReleaseResourceLite( FcbOrDcb->Header.Resource );

    IoSetTopLevelIrp( NULL );

    ObDereferenceObject( File );

    ExFreePool( Parameter );

}