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














































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                           
/*++

Copyright (c) 1990  Microsoft Corporation

Module Name:

    fssup.c

Abstract:

    This module implements the File System support routines for the
    Cache subsystem.

Author:

    Tom Miller      [TomM]      4-May-1990

Revision History:

--*/

#include "cc.h"

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

#define BugCheckFileId                   (CACHE_BUG_CHECK_FSSUP)

//
//  Define our debug constant
//

#define me 0x00000001

//
//  For your debugging pleasure, if the flag doesn't move!  (Currently not used)
//

#define IsSyscacheFile(FO) (((FO) != NULL) &&                                               \
                            (*(PUSHORT)(FO)->FsContext == 0X705) &&                         \
                            FlagOn(*(PULONG)((PCHAR)(FO)->FsContext + 0x48), 0x80000000))

extern POBJECT_TYPE IoFileObjectType;
extern ULONG MmLargeSystemCache;

VOID
CcUnmapAndPurge(
    IN PSHARED_CACHE_MAP SharedCacheMap
    );

VOID
CcPurgeAndClearCacheSection (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN PLARGE_INTEGER FileOffset
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(INIT,CcInitializeCacheManager)
#endif


BOOLEAN
CcInitializeCacheManager (
    )

/*++

Routine Description:

    This routine must be called during system initialization before the
    first call to any file system, to allow the Cache Manager to initialize
    its global data structures.  This routine has no dependencies on other
    system components being initialized.

Arguments:

    None

Return Value:

    TRUE if initialization was successful

--*/

{
    CLONG i;
    USHORT NumberOfItems;
    PWORK_QUEUE_ITEM WorkItem;

#ifdef CCDBG_LOCK
    KeInitializeSpinLock( &CcDebugTraceLock );
#endif

#if DBG
    CcBcbCount = 0;
    InitializeListHead( &CcBcbList );
    KeInitializeSpinLock( &CcBcbSpinLock );
#endif

    //
    //  Initialize shared cache map list structures
    //

    KeInitializeSpinLock( &CcMasterSpinLock );
    InitializeListHead( &CcCleanSharedCacheMapList );
    InitializeListHead( &CcDirtySharedCacheMapList.SharedCacheMapLinks );
    CcDirtySharedCacheMapList.Flags = IS_CURSOR;
    InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                    &CcLazyWriterCursor.SharedCacheMapLinks );
    CcLazyWriterCursor.Flags = IS_CURSOR;

    //
    //  Initialize worker thread structures
    //

    KeInitializeSpinLock( &CcWorkQueueSpinlock );
    InitializeListHead( &CcIdleWorkerThreadList );
    InitializeListHead( &CcExpressWorkQueue );
    InitializeListHead( &CcRegularWorkQueue );

    //
    //  Set the number of worker threads based on the system size.
    //

    CcCapturedSystemSize = MmQuerySystemSize();
    if (CcNumberWorkerThreads == 0) {

        switch (CcCapturedSystemSize) {
        case MmSmallSystem:
            CcNumberWorkerThreads = ExCriticalWorkerThreads - 1;
            CcDirtyPageThreshold = MmNumberOfPhysicalPages / 8;
            break;

        case MmMediumSystem:
            CcNumberWorkerThreads = ExCriticalWorkerThreads - 1;
            CcDirtyPageThreshold = MmNumberOfPhysicalPages / 4;
            break;

        case MmLargeSystem:
            CcNumberWorkerThreads = ExCriticalWorkerThreads - 2;
            CcDirtyPageThreshold = MmNumberOfPhysicalPages / 4 +
                                    MmNumberOfPhysicalPages / 8;

#if 0
            //
            //  Use more memory if we are a large server.
            //

            if ((MmLargeSystemCache != 0) &&
                (CcDirtyPageThreshold < (MmNumberOfPhysicalPages - (0xE00000 / PAGE_SIZE)))) {

                CcDirtyPageThreshold = MmNumberOfPhysicalPages - (0xE00000 / PAGE_SIZE);
            }
#endif
            break;

        default:
            CcNumberWorkerThreads = 1;
            CcDirtyPageThreshold = MmNumberOfPhysicalPages / 8;
        }

//        CcDirtyPageThreshold = (2*1024*1024)/PAGE_SIZE;

        if (MmSystemCacheWs.MaximumWorkingSetSize > ((4*1024*1024)/PAGE_SIZE)) {
            CcDirtyPageThreshold = MmSystemCacheWs.MaximumWorkingSetSize -
                                                    ((2*1024*1024)/PAGE_SIZE);
        }

        CcDirtyPageTarget = CcDirtyPageThreshold / 2 +
                            CcDirtyPageThreshold / 4;
    }

    //
    //  Now allocate and initialize the above number of worker thread
    //  items.
    //

    for (i = 0; i < CcNumberWorkerThreads; i++) {

        WorkItem = ExAllocatePool( NonPagedPool, sizeof(WORK_QUEUE_ITEM) );

        //
        //  Initialize the work queue item and insert in our queue
        //  of potential worker threads.
        //

        ExInitializeWorkItem( WorkItem, CcWorkerThread, WorkItem );
        InsertTailList( &CcIdleWorkerThreadList, &WorkItem->List );
    }

    //
    //  Initialize the Lazy Writer thread structure, and start him up.
    //

    RtlZeroMemory( &LazyWriter, sizeof(LAZY_WRITER) );

    KeInitializeSpinLock( &CcWorkQueueSpinlock );
    InitializeListHead( &LazyWriter.WorkQueue );

    //
    //  Store process address
    //

    LazyWriter.OurProcess = PsGetCurrentProcess();

    //
    //  Initialize the Scan Dpc and Timer.
    //

    KeInitializeDpc( &LazyWriter.ScanDpc, &CcScanDpc, NULL );
    KeInitializeTimer( &LazyWriter.ScanTimer );

    //
    //  Now initialize the lookaside list for allocating Work Queue entries.
    //

    switch ( CcCapturedSystemSize ) {

        //
        // ~512 bytes
        //

    case MmSmallSystem :
        NumberOfItems = 32;
        break;

        //
        // ~1k bytes
        //

    case MmMediumSystem :
        NumberOfItems = 64;
        break;

        //
        // ~2k bytes
        //

    case MmLargeSystem :
        NumberOfItems = 128;
        if (MmIsThisAnNtAsSystem()) {
            NumberOfItems += 128;
        }

        break;
    }

    ExInitializeNPagedLookasideList( &CcTwilightLookasideList,
                                     NULL,
                                     NULL,
                                     0,
                                     sizeof( WORK_QUEUE_ENTRY ),
                                     'kwcC',
                                     NumberOfItems );

    //
    //  Now initialize the Bcb zone
    //

    {
        PVOID InitialSegment;
        ULONG InitialSegmentSize;
        ULONG RoundedBcbSize = (sizeof(BCB) + 7) & ~7;
        ULONG NumberOfItems;


        switch ( CcCapturedSystemSize ) {

                //
                // ~1.5k bytes
                //

            case MmSmallSystem :
                NumberOfItems = 8;
                break;

                //
                // ~4k bytes
                //

            case MmMediumSystem :
                NumberOfItems = 20;
                break;

                //
                // ~12k bytes
                //

            case MmLargeSystem :
                NumberOfItems = 64;
                break;
            }

        InitialSegmentSize = sizeof(ZONE_SEGMENT_HEADER) + RoundedBcbSize * NumberOfItems;

        //
        //  Allocate the initial allocation for the zone.  If we cannot get it,
        //  something must really be wrong, so we will just bugcheck.
        //

        if ((InitialSegment = ExAllocatePool( NonPagedPool,
                                              InitialSegmentSize)) == NULL) {

            CcBugCheck( 0, 0, 0 );
        }

        if (!NT_SUCCESS(ExInitializeZone( &LazyWriter.BcbZone,
                                          RoundedBcbSize,
                                          InitialSegment,
                                          InitialSegmentSize ))) {
            CcBugCheck( 0, 0, 0 );
        }
    }

    //
    //  Initialize the Deferred Write List.
    //

    KeInitializeSpinLock( &CcDeferredWriteSpinLock );
    InitializeListHead( &CcDeferredWrites );

    //
    //  Initialize the Vacbs.
    //

    CcInitializeVacbs();

    return TRUE;
}


VOID
CcInitializeCacheMap (
    IN PFILE_OBJECT FileObject,
    IN PCC_FILE_SIZES FileSizes,
    IN BOOLEAN PinAccess,
    IN PCACHE_MANAGER_CALLBACKS Callbacks,
    IN PVOID LazyWriteContext
    )

/*++

Routine Description:

    This routine is intended to be called by File Systems only.  It
    initializes the cache maps for data caching.  It should be called
    every time a file is open or created, and NO_INTERMEDIATE_BUFFERING
    was specified as FALSE.

Arguments:

    FileObject - A pointer to the newly-created file object.

    FileSizes - A pointer to AllocationSize, FileSize and ValidDataLength
                for the file.  ValidDataLength should contain MAXLONGLONG if
                valid data length tracking and callbacks are not desired.

    PinAccess - FALSE if file will be used exclusively for Copy and Mdl
                access, or TRUE if file will be used for Pin access.
                (Files for Pin access are not limited in size as the caller
                must access multiple areas of the file at once.)

    Callbacks - Structure of callbacks used by the Lazy Writer

    LazyWriteContext - Parameter to be passed in to above routine.

Return Value:

    None.  If an error occurs, this routine will Raise the status.

--*/

{
    KIRQL OldIrql;
    PSHARED_CACHE_MAP SharedCacheMap = NULL;
    PVOID CacheMapToFree = NULL;
    CC_FILE_SIZES LocalSizes;
    BOOLEAN WeSetBeingCreated = FALSE;
    BOOLEAN SharedListOwned = FALSE;
    BOOLEAN MustUninitialize = FALSE;
    BOOLEAN WeCreated = FALSE;

    DebugTrace(+1, me, "CcInitializeCacheMap:\n", 0 );
    DebugTrace( 0, me, "    FileObject = %08lx\n", FileObject );
    DebugTrace( 0, me, "    FileSizes = %08lx\n", FileSizes );

    //
    //  Make a local copy of the passed in file sizes before acquiring
    //  the spin lock.
    //

    LocalSizes = *FileSizes;

    //
    //  If no FileSize was given, set to one byte before maximizing below.
    //

    if (LocalSizes.AllocationSize.QuadPart == 0) {
        LocalSizes.AllocationSize.LowPart += 1;
    }

    //
    //  If caller has Write access or will allow write, then round
    //  size to next create modulo.  (***Temp*** there may be too many
    //  apps that end up allowing shared write, thanks to our Dos heritage,
    //  to keep that part of the check in.)
    //

    if (FileObject->WriteAccess /*|| FileObject->SharedWrite */) {

        LocalSizes.AllocationSize.QuadPart = LocalSizes.AllocationSize.QuadPart + (LONGLONG)(DEFAULT_CREATE_MODULO - 1);
        LocalSizes.AllocationSize.LowPart &= ~(DEFAULT_CREATE_MODULO - 1);

    } else {

        LocalSizes.AllocationSize.QuadPart = LocalSizes.AllocationSize.QuadPart + (LONGLONG)(VACB_MAPPING_GRANULARITY - 1);
        LocalSizes.AllocationSize.LowPart &= ~(VACB_MAPPING_GRANULARITY - 1);
    }

    //
    //  Do the allocate of the SharedCacheMap, based on an unsafe test,
    //  while not holding a spinlock.  Allocation failures look like we
    //  never decided to allocate one here!
    //

    if (FileObject->SectionObjectPointer->SharedCacheMap == NULL) {
        CacheMapToFree = ExAllocatePool( NonPagedPool, sizeof(SHARED_CACHE_MAP) );
    }

    //
    //  Serialize Creation/Deletion of all Shared CacheMaps
    //

    ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
    SharedListOwned = TRUE;

    //
    //  Insure release of our global resource
    //

    try {

        //
        //  Check for second initialization of same file object
        //

        if (FileObject->PrivateCacheMap != NULL) {

            DebugTrace( 0, 0, "CacheMap already initialized\n", 0 );
            try_return( NOTHING );
        }

        //
        //  Get current Shared Cache Map pointer indirectly off of the file object.
        //  (The actual pointer is typically in a file system data structure, such
        //  as an Fcb.)
        //

        SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

        //
        //  If there is no SharedCacheMap, then we must create a section and
        //  the SharedCacheMap structure.
        //

        if (SharedCacheMap == NULL) {

            //
            //  After successfully creating the section, allocate the SharedCacheMap.
            //

            WeCreated = TRUE;

            if (CacheMapToFree == NULL) {
                CacheMapToFree = (PSHARED_CACHE_MAP)ExAllocatePool( NonPagedPool,
                                                                    sizeof(SHARED_CACHE_MAP) );
            }

            SharedCacheMap = CacheMapToFree;
            CacheMapToFree = NULL;

            if (SharedCacheMap == NULL) {

                DebugTrace( 0, 0, "Failed to allocate SharedCacheMap\n", 0 );

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                SharedListOwned = FALSE;

                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            //
            //  Zero the SharedCacheMap and fill in the nonzero portions later.
            //

            RtlZeroMemory( SharedCacheMap, sizeof(SHARED_CACHE_MAP) );

            //
            //  Now initialize the Shared Cache Map.
            //

            SharedCacheMap->NodeTypeCode = CACHE_NTC_SHARED_CACHE_MAP;
            SharedCacheMap->NodeByteSize = sizeof(SHARED_CACHE_MAP);
            SharedCacheMap->FileSize = LocalSizes.FileSize;
            SharedCacheMap->ValidDataLength =
            SharedCacheMap->ValidDataGoal = LocalSizes.ValidDataLength;
            SharedCacheMap->FileObject = FileObject;
            //  SharedCacheMap->Section set below

            //
            //  Initialize the ActiveVacbSpinLock.
            //

            KeInitializeSpinLock( &SharedCacheMap->ActiveVacbSpinLock );

            if (PinAccess) {
                SetFlag(SharedCacheMap->Flags, PIN_ACCESS);
            }

            //
            //  If this file has FO_SEQUENTIAL_ONLY set, then remember that
            //  in the SharedCacheMap.
            //

            if (FlagOn(FileObject->Flags, FO_SEQUENTIAL_ONLY)) {
                SetFlag(SharedCacheMap->Flags, ONLY_SEQUENTIAL_ONLY_SEEN);
            }

            //
            //  Do the round-robin allocation of the spinlock for the shared
            //  cache map.  Note the manipulation of the next
            //  counter is safe, since we have the CcMasterSpinLock
            //  exclusive.
            //

            InitializeListHead( &SharedCacheMap->BcbList );
            SharedCacheMap->Callbacks = Callbacks;
            SharedCacheMap->LazyWriteContext = LazyWriteContext;

            //
            //  Initialize the pointer to the uninitialize event chain.
            //

            SharedCacheMap->UninitializeEvent = NULL;

            //
            //  Initialize listhead for all PrivateCacheMaps
            //

            InitializeListHead( &SharedCacheMap->PrivateList );

            //
            //  Insert the new Shared Cache Map in the global list
            //

            InsertTailList( &CcCleanSharedCacheMapList,
                            &SharedCacheMap->SharedCacheMapLinks );

            //
            //  Finally, store the pointer to the Shared Cache Map back
            //  via the indirect pointer in the File Object.
            //

            FileObject->SectionObjectPointer->SharedCacheMap = SharedCacheMap;

            //
            //  We must reference this file object so that it cannot go away
            //  until we do CcUninitializeCacheMap below.  Note we cannot
            //  find or rely on the FileObject that Memory Management has,
            //  although normally it will be this same one anyway.
            //

            ObReferenceObject ( FileObject );

        } else {

            //
            //  If this file has FO_SEQUENTIAL_ONLY clear, then remember that
            //  in the SharedCacheMap.
            //

            if (!FlagOn(FileObject->Flags, FO_SEQUENTIAL_ONLY)) {
                ClearFlag(SharedCacheMap->Flags, ONLY_SEQUENTIAL_ONLY_SEEN);
            }
        }

        //
        //  Make sure that no one is trying to lazy delete it in the case
        //  that the Cache Map was already there.
        //

        ClearFlag(SharedCacheMap->Flags, TRUNCATE_REQUIRED);

        //
        //  In case there has been a CcUnmapAndPurge call, we check here if we
        //  if we need to recreate the section and map it.
        //

        if ((SharedCacheMap->Vacbs == NULL) &&
            !FlagOn(SharedCacheMap->Flags, BEING_CREATED)) {

            //
            //  Increment the OpenCount on the CacheMap.
            //

            SharedCacheMap->OpenCount += 1;
            MustUninitialize = TRUE;

            //
            //  We still want anyone else to wait.
            //

            SetFlag(SharedCacheMap->Flags, BEING_CREATED);
            WeSetBeingCreated = TRUE;

            //
            //  If there is a create event, then this must be the path where we
            //  we were only unmapped.  We will just clear it here again in case
            //  someone needs to wait again this time too.
            //

            if (SharedCacheMap->CreateEvent != NULL) {

                KeInitializeEvent( SharedCacheMap->CreateEvent,
                                   NotificationEvent,
                                   FALSE );
            }

            //
            //  Release global resource
            //

            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
            SharedListOwned = FALSE;

            //
            //  We have to test this, because the section may only be unmapped.
            //

            if (SharedCacheMap->Section == NULL) {

                LARGE_INTEGER LargeZero = {0,0};

                //
                //  Call MM to create a section for this file, for the calculated
                //  section size.  Note that we have the choice in this service to
                //  pass in a FileHandle or a FileObject pointer, but not both.
                //  Naturally we want to pass in the handle.
                //

                DebugTrace( 0, mm, "MmCreateSection:\n", 0 );
                DebugTrace2(0, mm, "    MaximumSize = %08lx, %08lx\n",
                            LocalSizes.AllocationSize.LowPart,
                            LocalSizes.AllocationSize.HighPart );
                DebugTrace( 0, mm, "    FileObject = %08lx\n", FileObject );

                SharedCacheMap->Status = MmCreateSection( &SharedCacheMap->Section,
                                                          SECTION_MAP_READ
                                                            | SECTION_MAP_WRITE
                                                            | SECTION_QUERY,
                                                          NULL,
                                                          &LocalSizes.AllocationSize,
                                                          PAGE_READWRITE,
                                                          SEC_COMMIT,
                                                          NULL,
                                                          FileObject );

                DebugTrace( 0, mm, "    <Section = %08lx\n", SharedCacheMap->Section );

                if (!NT_SUCCESS( SharedCacheMap->Status )){
                    DebugTrace( 0, 0, "Error from MmCreateSection = %08lx\n",
                                SharedCacheMap->Status );

                    SharedCacheMap->Section = NULL;
                    ExRaiseStatus( FsRtlNormalizeNtstatus( SharedCacheMap->Status,
                                                           STATUS_UNEXPECTED_MM_CREATE_ERR ));
                }

                ObDeleteCapturedInsertInfo(SharedCacheMap->Section);

                //
                //  If this is a stream file object, then no user can map it,
                //  and we should keep the modified page writer out of it.
                //

                if (!FlagOn(((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->Flags2,
                            FSRTL_FLAG2_DO_MODIFIED_WRITE) &&
                    (FileObject->FsContext2 == NULL)) {

                    BOOLEAN Disabled;

                    Disabled = MmDisableModifiedWriteOfSection( FileObject->SectionObjectPointer );
                    ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );
                    SetFlag(SharedCacheMap->Flags, MODIFIED_WRITE_DISABLED);
                    ExReleaseFastLock( &CcMasterSpinLock, OldIrql );

                    //**** ASSERT( Disabled );
                }

                //
                //  Create the Vacb array.
                //

                CcCreateVacbArray( SharedCacheMap, LocalSizes.AllocationSize );
            }

            //
            //  If the section already exists, we still have to call MM to
            //  extend, in case it is not large enough.
            //

            else {

                if ( LocalSizes.AllocationSize.QuadPart > SharedCacheMap->SectionSize.QuadPart ) {

                    NTSTATUS Status;

                    DebugTrace( 0, mm, "MmExtendSection:\n", 0 );
                    DebugTrace( 0, mm, "    Section = %08lx\n", SharedCacheMap->Section );
                    DebugTrace2(0, mm, "    Size = %08lx, %08lx\n",
                                LocalSizes.AllocationSize.LowPart,
                                LocalSizes.AllocationSize.HighPart );

                    Status = MmExtendSection( SharedCacheMap->Section,
                                              &LocalSizes.AllocationSize,
                                              TRUE );

                    if (!NT_SUCCESS(Status)) {

                        DebugTrace( 0, 0, "Error from MmExtendSection, Status = %08lx\n",
                                    Status );

                        ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
                                                               STATUS_UNEXPECTED_MM_EXTEND_ERR ));
                    }
                }

                //
                //  Extend the Vacb array.
                //

                CcExtendVacbArray( SharedCacheMap, LocalSizes.AllocationSize );
            }

            //
            //  Now show that we are all done and resume any waiters.
            //

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
            ClearFlag(SharedCacheMap->Flags, BEING_CREATED);
            WeSetBeingCreated = FALSE;
            if (SharedCacheMap->CreateEvent != NULL) {
                KeSetEvent( SharedCacheMap->CreateEvent, 0, FALSE );
            }
            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
        }

        //
        //  Else if the section is already there, we make sure it is large
        //  enough by calling CcExtendCacheSection.
        //

        else {

            //
            //  If the SharedCacheMap is currently being created we have
            //  to optionally create and wait on an event for it.  Note that
            //  the only safe time to delete the event is in
            //  CcUninitializeCacheMap, because we otherwise have no way of
            //  knowing when everyone has reached the KeWaitForSingleObject.
            //

            if (FlagOn(SharedCacheMap->Flags, BEING_CREATED)) {
                if (SharedCacheMap->CreateEvent == NULL) {

                    //
                    //  We create for the loacl event with the WaitOnActiveCount
                    //  event, and we synchronize the claiming of that event with
                    //  CcVacbSpinLock.
                    //

                    ExAcquireSpinLockAtDpcLevel( &CcVacbSpinLock );

                    //
                    //  If the local even is not being used as a create event,
                    //  then we can use it.  (Should be quite rare that it is in use.)
                    //

                    if (SharedCacheMap->WaitOnActiveCount == NULL) {

                        SharedCacheMap->CreateEvent = &SharedCacheMap->Event;

                    } else {

                        SharedCacheMap->CreateEvent = (PKEVENT)ExAllocatePool( NonPagedPool, sizeof(KEVENT) );
                    }

                    ExReleaseSpinLockFromDpcLevel( &CcVacbSpinLock );

                    if (SharedCacheMap->CreateEvent == NULL) {
                        DebugTrace( 0, 0, "Failed to allocate CreateEvent\n", 0 );

                        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                        SharedListOwned = FALSE;

                        ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES);
                    }

                    KeInitializeEvent( SharedCacheMap->CreateEvent,
                                       NotificationEvent,
                                       FALSE );
                }

                //
                //  Increment the OpenCount on the CacheMap.
                //

                SharedCacheMap->OpenCount += 1;
                MustUninitialize = TRUE;

                //
                //  Release global resource before waiting
                //

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                SharedListOwned = FALSE;

                DebugTrace( 0, 0, "Waiting on CreateEvent\n", 0 );

                KeWaitForSingleObject( SharedCacheMap->CreateEvent,
                                       Executive,
                                       KernelMode,
                                       FALSE,
                                       (PLARGE_INTEGER)NULL);

                //
                //  If the real creator got an error, then we must bomb
                //  out too.
                //

                if (!NT_SUCCESS(SharedCacheMap->Status)) {
                    ExRaiseStatus( FsRtlNormalizeNtstatus( SharedCacheMap->Status,
                                                           STATUS_UNEXPECTED_MM_CREATE_ERR ));
                }
            }
            else {

                PCACHE_UNINITIALIZE_EVENT CUEvent;

                //
                //  Increment the OpenCount on the CacheMap.
                //

                SharedCacheMap->OpenCount += 1;
                MustUninitialize = TRUE;

                //
                //  If there is a process waiting on an uninitialize on this
                //  cache map to complete, let the thread that is waiting go,
                //  since the uninitialize is now complete.
                //
                CUEvent = SharedCacheMap->UninitializeEvent;

                while (CUEvent != NULL) {
                    PCACHE_UNINITIALIZE_EVENT EventNext = CUEvent->Next;
                    KeSetEvent(&CUEvent->Event, 0, FALSE);
                    CUEvent = EventNext;
                }

                SharedCacheMap->UninitializeEvent = NULL;

                //
                //  Release global resource
                //

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                SharedListOwned = FALSE;
            }
        }

        {
            PPRIVATE_CACHE_MAP PrivateCacheMap;

            //
            //  Now allocate (if local one already in use) and initialize
            //  the Private Cache Map.
            //

            PrivateCacheMap = &SharedCacheMap->PrivateCacheMap;

            //
            //  See if we should allocate a PrivateCacheMap while not holding
            //  a spinlock.
            //

            if (CacheMapToFree != NULL) {
                ExFreePool( CacheMapToFree );
                CacheMapToFree = NULL;
            }

            if (PrivateCacheMap->NodeTypeCode != 0) {
                CacheMapToFree = ExAllocatePool( NonPagedPool, sizeof(PRIVATE_CACHE_MAP) );
            }

            //
            //  Insert the new PrivateCacheMap in the list off the SharedCacheMap.
            //

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
            SharedListOwned = TRUE;

            //
            //  Now make sure there is still no PrivateCacheMap, and if so just get out.
            //

            if (FileObject->PrivateCacheMap == NULL) {

                //
                //  Is the local one already in use?
                //

                if (PrivateCacheMap->NodeTypeCode != 0) {

                    //
                    //  Use the one allocated above, if there is one, else go to pool now.
                    //

                    if (CacheMapToFree == NULL) {
                        CacheMapToFree =
                            (PPRIVATE_CACHE_MAP)ExAllocatePool( NonPagedPool,
                                                                sizeof(PRIVATE_CACHE_MAP) );
                    }
                    PrivateCacheMap = CacheMapToFree;
                    CacheMapToFree = NULL;
                }

                if (PrivateCacheMap == NULL) {

                    DebugTrace( 0, 0, "Failed to allocate PrivateCacheMap\n", 0 );

                    ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                    SharedListOwned = FALSE;

                    ExRaiseStatus(STATUS_INSUFFICIENT_RESOURCES);
                }

                RtlZeroMemory( PrivateCacheMap, sizeof(PRIVATE_CACHE_MAP) );

                PrivateCacheMap->NodeTypeCode = CACHE_NTC_PRIVATE_CACHE_MAP;
                PrivateCacheMap->NodeByteSize = sizeof(PRIVATE_CACHE_MAP);
                PrivateCacheMap->FileObject = FileObject;
                PrivateCacheMap->ReadAheadMask = PAGE_SIZE - 1;

                //
                //  Initialize the spin lock.
                //

                KeInitializeSpinLock( &PrivateCacheMap->ReadAheadSpinLock );

                InsertTailList( &SharedCacheMap->PrivateList, &PrivateCacheMap->PrivateLinks );

                FileObject->PrivateCacheMap = PrivateCacheMap;
            }
        }

        MustUninitialize = FALSE;
    try_exit: NOTHING;
    }
    finally {

        //
        //  See if we got an error and must uninitialize the SharedCacheMap
        //

        if (MustUninitialize) {

            if (!SharedListOwned) {
                ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
            }
            if (WeSetBeingCreated) {
                if (SharedCacheMap->CreateEvent != NULL) {
                    KeSetEvent( SharedCacheMap->CreateEvent, 0, FALSE );
                }
                ClearFlag(SharedCacheMap->Flags, BEING_CREATED);
            }

            //
            //  Now release our open count.
            //

            SharedCacheMap->OpenCount -= 1;

            if ((SharedCacheMap->OpenCount == 0) &&
                !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED) &&
                (SharedCacheMap->DirtyPages == 0)) {

                //
                //  On PinAccess it is safe and necessary to eliminate
                //  the structure immediately.
                //

                if (PinAccess) {

                    CcDeleteSharedCacheMap( SharedCacheMap, OldIrql, FALSE );

                //
                //  If it is not PinAccess, we must lazy delete, because
                //  we could get into a deadlock trying to acquire the
                //  stream exclusive when we dereference the file object.
                //

                } else {

                    //
                    //  Move it to the dirty list so the lazy write scan will
                    //  see it.
                    //

                    RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
                    InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                                    &SharedCacheMap->SharedCacheMapLinks );

                    //
                    //  Make sure the Lazy Writer will wake up, because we
                    //  want him to delete this SharedCacheMap.
                    //

                    LazyWriter.OtherWork = TRUE;
                    if (!LazyWriter.ScanActive) {
                        CcScheduleLazyWriteScan();
                    }

                    ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                }

            } else {

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
            }

            SharedListOwned = FALSE;

        //
        //  If we did not create this SharedCacheMap, then there is a
        //  possibility that it is in the dirty list.  Once we are sure
        //  we have the spinlock, just make sure it is in the clean list
        //  if there are no dirty bytes and the open count is nonzero.
        //  (The latter test is almost guaranteed, of course, but we check
        //  it to be safe.)
        //

        } else if (!WeCreated &&
                   (SharedCacheMap != NULL)) {

            if (!SharedListOwned) {

                ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
                SharedListOwned = TRUE;
            }

            if ((SharedCacheMap->DirtyPages == 0) &&
                (SharedCacheMap->OpenCount != 0)) {

                RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
                InsertTailList( &CcCleanSharedCacheMapList,
                                &SharedCacheMap->SharedCacheMapLinks );
            }
        }

        //
        //  Release global resource
        //

        if (SharedListOwned) {
            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
        }

        if (CacheMapToFree != NULL) {
            ExFreePool(CacheMapToFree);
        }

    }

    DebugTrace(-1, me, "CcInitializeCacheMap -> VOID\n", 0 );

    return;
}


BOOLEAN
CcUninitializeCacheMap (
    IN PFILE_OBJECT FileObject,
    IN PLARGE_INTEGER TruncateSize OPTIONAL,
    IN PCACHE_UNINITIALIZE_EVENT UninitializeEvent OPTIONAL
    )

/*++

Routine Description:

    This routine uninitializes the previously initialized Shared and Private
    Cache Maps.  This routine is only intended to be called by File Systems.
    It should be called when the File System receives a cleanup call on the
    File Object.

    A File System which supports data caching must always call this routine
    whenever it closes a file, whether the caller opened the file with
    NO_INTERMEDIATE_BUFFERING as FALSE or not.  This is because the final
    cleanup of a file related to truncation or deletion of the file, can
    only occur on the last close, whether the last closer cached the file
    or not.  When CcUnitializeCacheMap is called on a file object for which
    CcInitializeCacheMap was never called, the call has a benign effect
    iff no one has truncated or deleted the file; otherwise the necessary
    cleanup relating to the truncate or close is performed.

    In summary, CcUnitializeCacheMap does the following:

        If the caller had Write or Delete access, the cache is flushed.
        (This could change with lazy writing.)

        If a Cache Map was initialized on this File Object, it is
        unitialized (unmap any views, delete section, and delete
        Cache Map structures).

        On the last Cleanup, if the file has been deleted, the
        Section is forced closed.  If the file has been truncated, then
        the truncated pages are purged from the cache.

Arguments:

    FileObject - File Object which was previously supplied to
                 CcInitializeCacheMap.

    TruncateSize - If specified, the file was truncated to the specified
                   size, and the cache should be purged accordingly.

    UninitializeEvent - If specified, then the provided event
                   will be set to the signalled state when the actual flush is
                   completed.  This is only of interest to file systems that
                   require that they be notified when a cache flush operation
                   has completed.  Due to network protocol restrictions, it
                   is critical that network file systems know exactly when
                   a cache flush operation completes, by specifying this
                   event, they can be notified when the cache section is
                   finally purged if the section is "lazy-deleted".

ReturnValue:

    FALSE if Section was not closed.
    TRUE if Section was closed.

--*/

{
    KIRQL OldIrql;
    PSHARED_CACHE_MAP SharedCacheMap;
    ULONG ActivePage;
    ULONG PageIsDirty;
    PVACB ActiveVacb = NULL;
    BOOLEAN SectionClosed = FALSE;
    BOOLEAN SharedListAcquired = FALSE;
    PPRIVATE_CACHE_MAP PrivateCacheMap;

    DebugTrace(+1, me, "CcUninitializeCacheMap:\n", 0 );
    DebugTrace( 0, me, "    FileObject = %08lx\n", FileObject );
    DebugTrace( 0, me, "    &TruncateSize = %08lx\n", TruncateSize );

    //
    //  Insure release of resources
    //

    try {

        //
        //  Serialize Creation/Deletion of all Shared CacheMaps
        //

        ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
        SharedListAcquired = TRUE;

        //
        //  Get pointer to SharedCacheMap via File Object.
        //

        SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;
        PrivateCacheMap = FileObject->PrivateCacheMap;

        //
        //  Decrement Open Count on SharedCacheMap, if we did a cached open.
        //  Also unmap PrivateCacheMap if it is mapped and deallocate it.
        //

        if (PrivateCacheMap != NULL) {

            SharedCacheMap->OpenCount -= 1;

            //
            //  Remove PrivateCacheMap from list in SharedCacheMap.
            //

            RemoveEntryList( &PrivateCacheMap->PrivateLinks );

            //
            //  Free local or allocated PrivateCacheMap
            //

            if (PrivateCacheMap == &SharedCacheMap->PrivateCacheMap) {
                PrivateCacheMap->NodeTypeCode = 0;
                PrivateCacheMap = NULL;
            }

            FileObject->PrivateCacheMap = (PPRIVATE_CACHE_MAP)NULL;
        }

        //
        //  Now if we have a SharedCacheMap whose Open Count went to 0, we
        //  have some additional cleanup.
        //

        if (SharedCacheMap != NULL) {

            //
            //  If a Truncate Size was specified, then remember that we want to
            //  truncate the FileSize and purge the unneeded pages when OpenCount
            //  goes to 0.
            //

            if (ARGUMENT_PRESENT(TruncateSize)) {

                if ( (TruncateSize->QuadPart == 0) && (SharedCacheMap->FileSize.QuadPart != 0) ) {
                    SetFlag(SharedCacheMap->Flags, TRUNCATE_REQUIRED);
                }

                //
                //  If this is the last guy, I can drop the file size down
                //  now.
                //

                if (IsListEmpty(&SharedCacheMap->PrivateList)) {
                    SharedCacheMap->FileSize = *TruncateSize;
                }
            }

            //
            //  If other file objects are still using this SharedCacheMap,
            //  then we are done now.
            //

            if (SharedCacheMap->OpenCount != 0) {

                DebugTrace(-1, me, "SharedCacheMap OpenCount != 0\n", 0);

                //
                //  If the caller specified an event to be set when
                //  the cache uninitialize is completed, set the event
                //  now, because the uninitialize is complete for this file.
                //  (Note, we make him wait if he is the last guy.)
                //

                if (ARGUMENT_PRESENT(UninitializeEvent)) {

                    if (!IsListEmpty(&SharedCacheMap->PrivateList)) {
                        KeSetEvent(&UninitializeEvent->Event, 0, FALSE);
                    } else {

                        UninitializeEvent->Next = SharedCacheMap->UninitializeEvent;
                        SharedCacheMap->UninitializeEvent = UninitializeEvent;
                    }
                }

                try_return( SectionClosed = FALSE );
            }

            //
            //  Set the "uninitialize complete" in the shared cache map
            //  so that CcDeleteSharedCacheMap will delete it.
            //

            if (ARGUMENT_PRESENT(UninitializeEvent)) {
                UninitializeEvent->Next = SharedCacheMap->UninitializeEvent;
                SharedCacheMap->UninitializeEvent = UninitializeEvent;
            }

            //
            //  We are in the process of deleting this cache map.  If the
            //  Lazy Writer is active or the Bcb list is not empty or the Lazy
            //  Writer will hit this SharedCacheMap because we are purging
            //  the file to 0, then get out and let the Lazy Writer clean
            //  up.
            //

            if ((!FlagOn(SharedCacheMap->Flags, PIN_ACCESS) &&
                 !ARGUMENT_PRESENT(UninitializeEvent))

                    ||

                FlagOn(SharedCacheMap->Flags, WRITE_QUEUED)

                    ||

                (SharedCacheMap->DirtyPages != 0)) {

                //
                //  Move it to the dirty list so the lazy write scan will
                //  see it.
                //

                if (!FlagOn(SharedCacheMap->Flags, WRITE_QUEUED)) {
                    RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
                    InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                                    &SharedCacheMap->SharedCacheMapLinks );
                }

                //
                //  Make sure the Lazy Writer will wake up, because we
                //  want him to delete this SharedCacheMap.
                //

                LazyWriter.OtherWork = TRUE;
                if (!LazyWriter.ScanActive) {
                    CcScheduleLazyWriteScan();
                }

                //
                //  Get the active Vacb if we are going to lazy delete, to
                //  free it for someone who can use it.
                //

                GetActiveVacbAtDpcLevel( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

                DebugTrace(-1, me, "SharedCacheMap has Bcbs and not purging to 0\n", 0);

                try_return( SectionClosed = FALSE );
            }

            //
            //  Now we can delete the SharedCacheMap.  If there are any Bcbs,
            //  then we must be truncating to 0, and they will also be deleted.
            //  On return the Shared Cache Map List Spinlock will be released.
            //

            CcDeleteSharedCacheMap( SharedCacheMap, OldIrql, FALSE );

            SharedListAcquired = FALSE;

            try_return( SectionClosed = TRUE );
        }

        //
        //  No Shared Cache Map.  To make the file go away, we still need to
        //  purge the section, if one exists.  (And we still need to release
        //  our global list first to avoid deadlocks.)
        //

        else {
            if (ARGUMENT_PRESENT(TruncateSize) &&
                ( TruncateSize->QuadPart == 0 ) &&
                (*(PCHAR *)FileObject->SectionObjectPointer != NULL)) {

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
                SharedListAcquired = FALSE;

                DebugTrace( 0, mm, "MmPurgeSection:\n", 0 );
                DebugTrace( 0, mm, "    SectionObjectPointer = %08lx\n",
                            FileObject->SectionObjectPointer );
                DebugTrace2(0, mm, "    Offset = %08lx\n",
                            TruncateSize->LowPart,
                            TruncateSize->HighPart );

                //
                //  0 Length means to purge from the TruncateSize on.
                //

                CcPurgeCacheSection( FileObject->SectionObjectPointer,
                                     TruncateSize,
                                     0,
                                     FALSE );
            }

            //
            //  If the caller specified an event to be set when
            //  the cache uninitialize is completed, set the event
            //  now, because the uninitialize is complete for this file.
            //

            if (ARGUMENT_PRESENT(UninitializeEvent)) {
                KeSetEvent(&UninitializeEvent->Event, 0, FALSE);
            }

        }

    try_exit: NOTHING;
    }
    finally {

        //
        //  Release global resources
        //

        if (SharedListAcquired) {
            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
        }

        //
        //  Free the active vacb, if we found one.
        //

        if (ActiveVacb != NULL) {

            CcFreeActiveVacb( ActiveVacb->SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
        }

        //
        //  Free PrivateCacheMap now that we no longer have the spinlock.
        //

        if (PrivateCacheMap != NULL) {
            ExFreePool( PrivateCacheMap );
        }
    }

    DebugTrace(-1, me, "CcUnitializeCacheMap -> %02lx\n", SectionClosed );

    return SectionClosed;

}


//
//  Internal support routine.
//

VOID
FASTCALL
CcDeleteSharedCacheMap (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN KIRQL ListIrql,
    IN ULONG ReleaseFile
    )

/*++

Routine Description:

    The specified SharedCacheMap is removed from the global list of
    SharedCacheMap's and deleted with all of its related structures.
    Other objects which were referenced in CcInitializeCacheMap are
    dereferenced here.

    NOTE:   The CcMasterSpinLock must already be acquired
            on entry.  It is released on return.

Arguments:

    SharedCacheMap - Pointer to Cache Map to delete

    ListIrql - priority to restore to when releasing shared cache map list

    ReleaseFile - Supplied as nonzero if file was acquired exclusive and
                  should be released.

ReturnValue:

    None.

--*/

{
    LIST_ENTRY LocalList;
    PFILE_OBJECT FileObject;
    PVACB ActiveVacb;
    ULONG ActivePage;
    ULONG PageIsDirty;
    KIRQL OldIrql;
    PMBCB Mbcb;

    DebugTrace(+1, me, "CcDeleteSharedCacheMap:\n", 0 );
    DebugTrace( 0, me, "    SharedCacheMap = %08lx\n", SharedCacheMap );

    //
    //  Remove it from the global list and clear the pointer to it via
    //  the File Object.
    //

    RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );

    //
    //  Zero pointer to SharedCacheMap.  Once we have cleared the pointer,
    //  we can/must release the global list to avoid deadlocks.
    //

    FileObject = SharedCacheMap->FileObject;

    FileObject->SectionObjectPointer->SharedCacheMap = (PSHARED_CACHE_MAP)NULL;
    SetFlag( SharedCacheMap->Flags, WRITE_QUEUED );

    //
    //  The OpenCount is 0, but we still need to flush out any dangling
    //  cache read or writes.
    //

    if ((SharedCacheMap->VacbActiveCount != 0) || (SharedCacheMap->NeedToZero != NULL)) {

        //
        //  We will put it in a local list and set a flag
        //  to keep the Lazy Writer away from it, so that we can wrip it out
        //  below if someone manages to sneak in and set something dirty, etc.
        //  If the file system does not synchronize cleanup calls with an
        //  exclusive on the stream, then this case is possible.
        //

        InitializeListHead( &LocalList );
        InsertTailList( &LocalList, &SharedCacheMap->SharedCacheMapLinks );

        //
        //  If there is an active Vacb, then nuke it now (before waiting!).
        //

        GetActiveVacbAtDpcLevel( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

        ExReleaseSpinLock( &CcMasterSpinLock, ListIrql );

        CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

        while (SharedCacheMap->VacbActiveCount != 0) {
            CcWaitOnActiveCount( SharedCacheMap );
        }

        //
        //  Now in case we hit the rare path where someone moved the
        //  SharedCacheMap again, do a remove again now.  It may be
        //  from our local list or it may be from the dirty list,
        //  but who cares?  The important thing is to remove it in
        //  the case it was the dirty list, since we will delete it
        //  below.
        //

        ExAcquireSpinLock( &CcMasterSpinLock, &ListIrql );
        RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
    }

    //
    //  If there are Bcbs, then empty the list, asserting that none of them
    //  can be pinned now if we have gotten this far!
    //

    while (!IsListEmpty( &SharedCacheMap->BcbList )) {

        PBCB Bcb;

        Bcb = (PBCB)CONTAINING_RECORD( SharedCacheMap->BcbList.Flink,
                                       BCB,
                                       BcbLinks );

        RemoveEntryList( &Bcb->BcbLinks );

        //
        //  Skip over the pendaflex entries
        //

        if (Bcb->NodeTypeCode == CACHE_NTC_BCB) {

            ASSERT( Bcb->PinCount == 0 );

            //
            //  If the Bcb is dirty, we have to synchronize with the Lazy Writer
            //  and reduce the total number of dirty.
            //

            if (Bcb->Dirty) {

                CcTotalDirtyPages -= Bcb->ByteLength >> PAGE_SHIFT;
            }

            //
            //  There is a small window where the data could still be mapped
            //  if (for example) the Lazy Writer collides with a CcCopyWrite
            //  in the foreground, and then someone calls CcUninitializeCacheMap
            //  while the Lazy Writer is active.  This is because the Lazy
            //  Writer biases the pin count.  Deal with that here.
            //

            if (Bcb->BaseAddress != NULL) {
                CcFreeVirtualAddress( Bcb->Vacb );
            }

            //
            //  Debug routines used to remove Bcbs from the global list
            //

#if LIST_DBG

            {
                KIRQL OldIrql;

                ExAcquireSpinLock( &CcBcbSpinLock, &OldIrql );

                if (Bcb->CcBcbLinks.Flink != NULL) {

                    RemoveEntryList( &Bcb->CcBcbLinks );
                    CcBcbCount -= 1;
                }

                ExReleaseSpinLock( &CcBcbSpinLock, OldIrql );
            }

#endif

            CcDeallocateBcb( Bcb );
        }
    }
    ExReleaseSpinLock( &CcMasterSpinLock, ListIrql );

    //
    //  Call local routine to unmap, and purge if necessary.
    //

    CcUnmapAndPurge( SharedCacheMap );

    //
    //  Now release the file now that the purge is done.
    //

    if (ReleaseFile) {
        FsRtlReleaseFile( SharedCacheMap->FileObject );
    }

    //
    //  Dereference our pointer to the Section and FileObject
    //  (We have to test the Section pointer since CcInitializeCacheMap
    //  calls this routine for error recovery.  Release our global
    //  resource before dereferencing the FileObject to avoid deadlocks.
    //

    if (SharedCacheMap->Section != NULL) {
        ObDereferenceObject( SharedCacheMap->Section );
    }
    ObDereferenceObject( FileObject );

    //
    //  If there is an Mbcb, deduct any dirty pages and deallocate.
    //

    ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
    Mbcb = SharedCacheMap->Mbcb;
    if (Mbcb != NULL) {

        if (Mbcb->DirtyPages != 0) {

            CcTotalDirtyPages -= Mbcb->DirtyPages;
        }

        CcDeallocateBcb( (PBCB)Mbcb );
    }

    ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

    //
    //  If there was an uninitialize event specified for this shared cache
    //  map, then set it to the signalled state, indicating that we are
    //  removing the section and deleting the shared cache map.
    //

    if (SharedCacheMap->UninitializeEvent != NULL) {
        PCACHE_UNINITIALIZE_EVENT CUEvent = SharedCacheMap->UninitializeEvent;

        while (CUEvent != NULL) {
            PCACHE_UNINITIALIZE_EVENT EventNext = CUEvent->Next;

            KeSetEvent(&CUEvent->Event, 0, FALSE);

            CUEvent = EventNext;
        }
    }

    //
    //  Now delete the Vacb vector.
    //

    if ((SharedCacheMap->Vacbs != &SharedCacheMap->InitialVacbs[0])

            &&

        (SharedCacheMap->Vacbs != NULL)) {

        ExFreePool( SharedCacheMap->Vacbs );
    }

    //
    //  If an event had to be allocated for this SharedCacheMap,
    //  deallocate it.
    //

    if ((SharedCacheMap->CreateEvent != NULL) && (SharedCacheMap->CreateEvent != &SharedCacheMap->Event)) {
        ExFreePool( SharedCacheMap->CreateEvent );
    }

    if ((SharedCacheMap->WaitOnActiveCount != NULL) && (SharedCacheMap->WaitOnActiveCount != &SharedCacheMap->Event)) {
        ExFreePool( SharedCacheMap->WaitOnActiveCount );
    }

    //
    //  Deallocate the storeage for the SharedCacheMap.
    //

    ExFreePool( SharedCacheMap );

    DebugTrace(-1, me, "CcDeleteSharedCacheMap -> VOID\n", 0 );

    return;

}


VOID
CcSetFileSizes (
    IN PFILE_OBJECT FileObject,
    IN PCC_FILE_SIZES FileSizes
    )

/*++

Routine Description:

    This routine must be called whenever a file has been extended to reflect
    this extension in the cache maps and underlying section.  Calling this
    routine has a benign effect if the current size of the section is
    already greater than or equal to the new AllocationSize.

    This routine must also be called whenever the FileSize for a file changes
    to reflect these changes in the Cache Manager.

    This routine seems rather large, but in the normal case it only acquires
    a spinlock, updates some fields, and exits.  Less often it will either
    extend the section, or truncate/purge the file, but it would be unexpected
    to do both.  On the other hand, the idea of this routine is that it does
    "everything" required when AllocationSize or FileSize change.

Arguments:

    FileObject - A file object for which CcInitializeCacheMap has been
                 previously called.

    FileSizes - A pointer to AllocationSize, FileSize and ValidDataLength
                for the file.  AllocationSize is ignored if it is not larger
                than the current section size (i.e., it is ignored unless it
                has grown).  ValidDataLength is not used.


Return Value:

    None

--*/

{
    LARGE_INTEGER NewSectionSize;
    LARGE_INTEGER NewFileSize;
    IO_STATUS_BLOCK IoStatus;
    PSHARED_CACHE_MAP SharedCacheMap;
    NTSTATUS Status;
    KIRQL OldIrql;
    PVACB ActiveVacb;
    ULONG ActivePage;
    ULONG PageIsDirty;

    DebugTrace(+1, me, "CcSetFileSizes:\n", 0 );
    DebugTrace( 0, me, "    FileObject = %08lx\n", FileObject );
    DebugTrace( 0, me, "    FileSizes = %08lx\n", FileSizes );

    //
    //  Make a local copy of the new file size and section size.
    //

    NewFileSize = FileSizes->FileSize;
    NewSectionSize = FileSizes->AllocationSize;

    //
    //  Serialize Creation/Deletion of all Shared CacheMaps
    //

    ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );

    //
    //  Get pointer to SharedCacheMap via File Object.
    //

    SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

    //
    //  If the file is not cached, just get out.
    //

    if ((SharedCacheMap == NULL) || (SharedCacheMap->Section == NULL)) {

        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

        //
        //  Let's try to purge the file incase this is a truncate.  In the
        //  vast majority of cases when there is no shared cache map, there
        //  is no data section either, so this call will eventually be
        //  no-oped in Mm.
        //

        //
        //  First flush the first page we are keeping, if it has data, before
        //  we throw it away.
        //

        if (NewFileSize.LowPart & (PAGE_SIZE - 1)) {
            MmFlushSection( FileObject->SectionObjectPointer, &NewFileSize, 1, &IoStatus, FALSE );
        }

        CcPurgeCacheSection( FileObject->SectionObjectPointer,
                             &NewFileSize,
                             0,
                             FALSE );

        DebugTrace(-1, me, "CcSetFileSizes -> VOID\n", 0 );

        return;
    }

    //
    //  Make call a Noop if file is not mapped, or section already big enough.
    //

    if ( NewSectionSize.QuadPart > SharedCacheMap->SectionSize.QuadPart ) {

        //
        //  Increment open count to make sure the SharedCacheMap stays around,
        //  then release the spinlock so that we can call Mm.
        //

        SharedCacheMap->OpenCount += 1;
        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

        //
        //  Round new section size to pages.
        //

        NewSectionSize.QuadPart = NewSectionSize.QuadPart + (LONGLONG)(DEFAULT_EXTEND_MODULO - 1);
        NewSectionSize.LowPart &= ~(DEFAULT_EXTEND_MODULO - 1);

        //
        //  Use try-finally to make sure we get the open count decremented.
        //

        try {

            //
            //  Call MM to extend the section.
            //

            DebugTrace( 0, mm, "MmExtendSection:\n", 0 );
            DebugTrace( 0, mm, "    Section = %08lx\n", SharedCacheMap->Section );
            DebugTrace2(0, mm, "    Size = %08lx, %08lx\n",
                        NewSectionSize.LowPart, NewSectionSize.HighPart );

            Status = MmExtendSection( SharedCacheMap->Section, &NewSectionSize, TRUE );

            if (!NT_SUCCESS(Status)) {

                DebugTrace( 0, 0, "Error from MmExtendSection, Status = %08lx\n",
                            Status );

                ExRaiseStatus( FsRtlNormalizeNtstatus( Status,
                                                       STATUS_UNEXPECTED_MM_EXTEND_ERR ));
            }

            //
            //  Extend the Vacb array.
            //

            CcExtendVacbArray( SharedCacheMap, NewSectionSize );

        } finally {

            //
            //  Serialize again to decrement the open count.
            //

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );

            SharedCacheMap->OpenCount -= 1;

            if ((SharedCacheMap->OpenCount == 0) &&
                !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED) &&
                (SharedCacheMap->DirtyPages == 0)) {

                //
                //  Move to the dirty list.
                //

                RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
                InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                                &SharedCacheMap->SharedCacheMapLinks );

                //
                //  Make sure the Lazy Writer will wake up, because we
                //  want him to delete this SharedCacheMap.
                //

                LazyWriter.OtherWork = TRUE;
                if (!LazyWriter.ScanActive) {
                    CcScheduleLazyWriteScan();
                }
            }

            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
        }

        //
        //  It is now very unlikely that we have any more work to do, but just
        //  in case we reacquire the spinlock and check again if we are cached.
        //

        ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );

        //
        //  Get pointer to SharedCacheMap via File Object.
        //

        SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

        //
        //  If the file is not cached, just get out.
        //

        if (SharedCacheMap == NULL) {

            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

            DebugTrace(-1, me, "CcSetFileSizes -> VOID\n", 0 );

            return;
        }
    }

    //
    //  If we are shrinking either of these two sizes, then we must free the
    //  active page, since it may be locked.
    //

    SharedCacheMap->OpenCount += 1;

    try {

        if ( ( NewFileSize.QuadPart < SharedCacheMap->ValidDataGoal.QuadPart ) ||
             ( NewFileSize.QuadPart < SharedCacheMap->FileSize.QuadPart )) {

            GetActiveVacbAtDpcLevel( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

            if ((ActiveVacb != NULL) || (SharedCacheMap->NeedToZero != NULL)) {

                ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

                CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

                //
                //  Serialize again to reduce ValidDataLength.  It cannot change
                //  because the caller must have the file exclusive.
                //

                ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
            }
        }

        //
        //  If the section did not grow, see if the file system supports ValidDataLength,
        //  then update the valid data length in the file system.
        //

        if ( SharedCacheMap->ValidDataLength.QuadPart != MAXLONGLONG ) {

            if ( NewFileSize.QuadPart < SharedCacheMap->ValidDataLength.QuadPart ) {
                SharedCacheMap->ValidDataLength = NewFileSize;
            }

            //
            //  When truncating Valid Data Goal, remember that it must always
            //  stay rounded to the top of the page, to protect writes of user-mapped
            //  files.  ** no longer rounding **
            //

            if ( NewFileSize.QuadPart < SharedCacheMap->ValidDataGoal.QuadPart ) {

                SharedCacheMap->ValidDataGoal = NewFileSize;
            }
        }

        //
        //  On truncate, be nice guys and actually purge away user data from
        //  the cache.  However, the PinAccess check is important to avoid deadlocks
        //  in Ntfs.
        //
        //  It is also important to check the Vacb Active count.  The caller
        //  must have the file exclusive, therefore, no one else can be actively
        //  doing anything in the file.  Normally the Active count will be zero
        //  (like in a normal call from Set File Info), and we can go ahead and truncate.
        //  However, if the active count is nonzero, chances are this very thread has
        //  something pinned or mapped, and we will deadlock if we try to purge and
        //  wait for the count to go zero.  A rare case of this which deadlocked DaveC
        //  on Christmas Day of 1992, is where Ntfs was trying to convert an attribute
        //  from resident to nonresident - which is a good example of a case where the
        //  purge was not needed.
        //

        if ( (NewFileSize.QuadPart < SharedCacheMap->FileSize.QuadPart ) &&
            !FlagOn(SharedCacheMap->Flags, PIN_ACCESS) &&
            (SharedCacheMap->VacbActiveCount == 0)) {

            //
            //  If we are actually truncating to zero (a size which has particular
            //  meaning to the Lazy Writer scan!), then we must reset the Mbcb if
            //  there is one, so that we do not keep dirty pages around forever.
            //

            if ((NewFileSize.QuadPart == 0) && (SharedCacheMap->Mbcb != NULL)) {

                PMBCB Mbcb = SharedCacheMap->Mbcb;

                CcTotalDirtyPages -= Mbcb->DirtyPages;
                SharedCacheMap->DirtyPages -= Mbcb->DirtyPages;
                Mbcb->DirtyPages = 0;
                Mbcb->FirstDirtyPage = MAXULONG;
                Mbcb->LastDirtyPage = 0;
                Mbcb->ResumeWritePage = 0;
                Mbcb->PagesToWrite = 0;
                RtlZeroMemory( Mbcb->Bitmap.Buffer, Mbcb->Bitmap.SizeOfBitMap / 8 );
            }

            //
            //  Increment open count to make sure the SharedCacheMap stays around,
            //  then release the spinlock so that we can call Mm.
            //

            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );

            CcPurgeAndClearCacheSection( SharedCacheMap, &NewFileSize );

            //
            //  Serialize again to decrement the open count.
            //

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
        }

    } finally {

        //
        //  We should only be raising without owning the spinlock.
        //

        if (AbnormalTermination()) {

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );
        }

        SharedCacheMap->OpenCount -= 1;

        SharedCacheMap->FileSize = NewFileSize;

        if ((SharedCacheMap->OpenCount == 0) &&
            !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED) &&
            (SharedCacheMap->DirtyPages == 0)) {

            //
            //  Move to the dirty list.
            //

            RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
            InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                            &SharedCacheMap->SharedCacheMapLinks );

            //
            //  Make sure the Lazy Writer will wake up, because we
            //  want him to delete this SharedCacheMap.
            //

            LazyWriter.OtherWork = TRUE;
            if (!LazyWriter.ScanActive) {
                CcScheduleLazyWriteScan();
            }
        }

        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
    }

    DebugTrace(-1, me, "CcSetFileSizes -> VOID\n", 0 );

    return;
}


VOID
CcPurgeAndClearCacheSection (
    IN PSHARED_CACHE_MAP SharedCacheMap,
    IN PLARGE_INTEGER FileOffset
    )

/*++

Routine Description:

    This routine calls CcPurgeCacheSection after zeroing the end any
    partial page at the start of the range.  If the file is not cached
    it flushes this page before the purge.

Arguments:

    SectionObjectPointer - A pointer to the Section Object Pointers
                           structure in the nonpaged Fcb.

    FileOffset - Offset from which file should be purged - rounded down
               to page boundary.  If NULL, purge the entire file.

ReturnValue:

    FALSE - if the section was not successfully purged
    TRUE - if the section was successfully purged

--*/

{
    ULONG TempLength, Length;
    LARGE_INTEGER LocalFileOffset;
    IO_STATUS_BLOCK IoStatus;
    PVOID TempVa;
    PVACB Vacb;

    //
    //  If a range was specified, then we have to see if we need to
    //  save any user data before purging.
    //

    if ((FileOffset->LowPart & (PAGE_SIZE - 1)) != 0) {

        //
        //  Switch to LocalFileOffset.  We do it this way because we
        //  still pass it on as an optional parameter.
        //

        LocalFileOffset = *FileOffset;
        FileOffset = &LocalFileOffset;

        //
        //  If the file is cached, then we can actually zero the data to
        //  be purged in memory, and not purge those pages.  This is a huge
        //  savings, because sometimes the flushes in the other case cause
        //  us to kill lots of stack, time and I/O doing CcZeroData in especially
        //  large user-mapped files.
        //

        if ((SharedCacheMap->Section != NULL) &&
            (SharedCacheMap->Vacbs != NULL)) {

            //
            //  First zero the first page we are keeping, if it has data, and
            //  adjust FileOffset and Length to allow it to stay.
            //

            TempLength = PAGE_SIZE - (FileOffset->LowPart & (PAGE_SIZE - 1));

            TempVa = CcGetVirtualAddress( SharedCacheMap, *FileOffset, &Vacb, &Length );

            try {

                //
                //  Do not map and zero the page if we are not reducing our notion
                //  of Valid Data, because that does two bad things.  First CcSetDirtyInMask
                //  will arbitrarily smash up ValidDataGoal (causing a potential invalid
                //  CcSetValidData call).  Secondly, if the Lazy Writer writes the last
                //  page ahead of another flush through MM, then the file system will
                //  never see a write from MM, and will not include the last page in
                //  ValidDataLength on disk.
                //

                RtlZeroMemory( TempVa, TempLength );

                if (FileOffset->QuadPart <= SharedCacheMap->ValidDataGoal.QuadPart) {

                    //
                    //  Make sure the Lazy Writer writes it.
                    //

                    CcSetDirtyInMask( SharedCacheMap, FileOffset, TempLength );

                //
                //  Otherwise, we are mapped, so make sure at least that Mm
                //  knows the page is dirty since we zeroed it.
                //

                } else {

                    MmSetAddressRangeModified( TempVa, 1 );
                }

                FileOffset->QuadPart += (LONGLONG)TempLength;

            //
            //  If we get any kind of error, like failing to read the page from
            //  the network, just charge on.  Note that we only read it in order
            //  to zero it and avoid the flush below, so if we cannot read it
            //  there is really no stale data problem.
            //

            } except(EXCEPTION_EXECUTE_HANDLER) {

                NOTHING;
            }

            CcFreeVirtualAddress( Vacb );

        } else {

            //
            //  First flush the first page we are keeping, if it has data, before
            //  we throw it away.
            //

            MmFlushSection( SharedCacheMap->FileObject->SectionObjectPointer, FileOffset, 1, &IoStatus, FALSE );
        }
    }

    CcPurgeCacheSection( SharedCacheMap->FileObject->SectionObjectPointer,
                         FileOffset,
                         0,
                         FALSE );
}


BOOLEAN
CcPurgeCacheSection (
    IN PSECTION_OBJECT_POINTERS SectionObjectPointer,
    IN PLARGE_INTEGER FileOffset,
    IN ULONG Length,
    IN BOOLEAN UninitializeCacheMaps
    )

/*++

Routine Description:

    This routine may be called to force a purge of the cache section,
    even if it is cached.  Note, if a user has the file mapped, then the purge
    will *not* take effect, and this must be considered part of normal application
    interaction.  The purpose of purge is to throw away potentially nonzero
    data, so that it will be read in again and presumably zeroed.  This is
    not really a security issue, but rather an effort to not confuse the
    application when it sees nonzero data.  We cannot help the fact that
    a user-mapped view forces us to hang on to stale data.

    This routine is intended to be called whenever previously written
    data is being truncated from the file, and the file is not being
    deleted.

    The file must be acquired exclusive in order to call this routine.

Arguments:

    SectionObjectPointer - A pointer to the Section Object Pointers
                           structure in the nonpaged Fcb.

    FileOffset - Offset from which file should be purged - rounded down
               to page boundary.  If NULL, purge the entire file.

    Length - Defines the length of the byte range to purge, starting at
             FileOffset.  This parameter is ignored if FileOffset is
             specified as NULL.  If FileOffset is specified and Length
             is 0, then purge from FileOffset to the end of the file.

    UninitializeCacheMaps - If TRUE, we should uninitialize all the private
                            cache maps before purging the data.

ReturnValue:

    FALSE - if the section was not successfully purged
    TRUE - if the section was successfully purged

--*/

{
    KIRQL OldIrql;
    PSHARED_CACHE_MAP SharedCacheMap;
    PPRIVATE_CACHE_MAP PrivateCacheMap;
    ULONG ActivePage;
    ULONG PageIsDirty;
    BOOLEAN PurgeWorked = TRUE;
    PVACB Vacb = NULL;

    DebugTrace(+1, me, "CcPurgeCacheSection:\n", 0 );
    DebugTrace( 0, mm, "    SectionObjectPointer = %08lx\n", SectionObjectPointer );
    DebugTrace2(0, me, "    FileOffset = %08lx, %08lx\n",
                            ARGUMENT_PRESENT(FileOffset) ? FileOffset->LowPart
                                                         : 0,
                            ARGUMENT_PRESENT(FileOffset) ? FileOffset->HighPart
                                                         : 0 );
    DebugTrace( 0, me, "    Length = %08lx\n", Length );


    //
    //  If you want us to uninitialize cache maps, the RtlZeroMemory paths
    //  below depend on actually having to purge something after zeroing.
    //

    ASSERT(!UninitializeCacheMaps || (Length == 0) || (Length >= PAGE_SIZE * 2));

    //
    //  Serialize Creation/Deletion of all Shared CacheMaps
    //

    ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );

    //
    //  Get pointer to SharedCacheMap via File Object.
    //

    SharedCacheMap = SectionObjectPointer->SharedCacheMap;

    //
    //  Increment open count to make sure the SharedCacheMap stays around,
    //  then release the spinlock so that we can call Mm.
    //

    if (SharedCacheMap != NULL) {

        SharedCacheMap->OpenCount += 1;

        //
        //  If there is an active Vacb, then nuke it now (before waiting!).
        //

        GetActiveVacbAtDpcLevel( SharedCacheMap, Vacb, ActivePage, PageIsDirty );
    }

    ExReleaseFastLock( &CcMasterSpinLock, OldIrql );

    if (Vacb != NULL) {

        CcFreeActiveVacb( SharedCacheMap, Vacb, ActivePage, PageIsDirty );
    }

    //
    //  Use try-finally to insure cleanup of the Open Count and Vacb on the
    //  way out.
    //

    try {

        //
        //  Increment open count to make sure the SharedCacheMap stays around,
        //  then release the spinlock so that we can call Mm.
        //

        if (SharedCacheMap != NULL) {

            //
            // Now loop to make sure that no one is currently caching the file.
            //

            if (UninitializeCacheMaps) {

                while (!IsListEmpty( &SharedCacheMap->PrivateList )) {

                    PrivateCacheMap = CONTAINING_RECORD( SharedCacheMap->PrivateList.Flink,
                                                         PRIVATE_CACHE_MAP,
                                                         PrivateLinks );

                    CcUninitializeCacheMap( PrivateCacheMap->FileObject, NULL, NULL );
                }
            }

            //
            //  Now, let's unmap and purge here.
            //
            //  We still need to wait for any dangling cache read or writes.
            //
            //  In fact we have to loop and wait because the lazy writer can
            //  sneak in and do an CcGetVirtualAddressIfMapped, and we are not
            //  synchronized.
            //

            while ((SharedCacheMap->Vacbs != NULL) &&
                   !CcUnmapVacbArray( SharedCacheMap, FileOffset, Length )) {

                CcWaitOnActiveCount( SharedCacheMap );
            }
        }

        //
        //  Purge failures are extremely rare if there are no user mapped sections.
        //  However, it is possible that we will get one from our own mapping, if
        //  the file is being lazy deleted from a previous open.  For that case
        //  we wait here until the purge succeeds, so that we are not left with
        //  old user file data.  Although Length is actually invariant in this loop,
        //  we do need to keep checking that we are allowed to truncate in case a
        //  user maps the file during a delay.
        //

        while (!(PurgeWorked = MmPurgeSection(SectionObjectPointer,
                                              FileOffset,
                                              Length,
                                              (BOOLEAN)((SharedCacheMap !=NULL) &&
                                                        ARGUMENT_PRESENT(FileOffset)))) &&
               (Length == 0) &&
               MmCanFileBeTruncated(SectionObjectPointer, FileOffset)) {

            (VOID)KeDelayExecutionThread( KernelMode, FALSE, &CcCollisionDelay );
        }

    } finally {

        //
        //  Reduce the open count on the SharedCacheMap if there was one.
        //

        if (SharedCacheMap != NULL) {

            //
            //  Serialize again to decrement the open count.
            //

            ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );

            SharedCacheMap->OpenCount -= 1;

            if ((SharedCacheMap->OpenCount == 0) &&
                !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED) &&
                (SharedCacheMap->DirtyPages == 0)) {

                //
                //  Move to the dirty list.
                //

                RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
                InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                                &SharedCacheMap->SharedCacheMapLinks );

                //
                //  Make sure the Lazy Writer will wake up, because we
                //  want him to delete this SharedCacheMap.
                //

                LazyWriter.OtherWork = TRUE;
                if (!LazyWriter.ScanActive) {
                    CcScheduleLazyWriteScan();
                }
            }

            ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
        }
    }

    DebugTrace(-1, me, "CcPurgeCacheSection -> %02lx\n", PurgeWorked );

    return PurgeWorked;
}


//
//  Internal support routine.
//

VOID
CcUnmapAndPurge(
    IN PSHARED_CACHE_MAP SharedCacheMap
    )

/*++

Routine Description:

    This routine may be called to unmap and purge a section, causing Memory
    Management to throw the pages out and reset his notion of file size.

Arguments:

    SharedCacheMap - Pointer to SharedCacheMap of section to purge.

Return Value:

    None.

--*/

{
    PFILE_OBJECT FileObject;
    KIRQL OldIrql;

    FileObject = SharedCacheMap->FileObject;

    //
    //  Unmap all Vacbs
    //

    if (SharedCacheMap->Vacbs != NULL) {
        (VOID)CcUnmapVacbArray( SharedCacheMap, NULL, 0 );
    }

    //
    //  Now that the file is unmapped, we can purge the truncated
    //  pages from memory, if TRUNCATE_REQUIRED.  Note that if all
    //  of the section is being purged (FileSize == 0), the purge
    //  and subsequent delete  of the SharedCacheMap should drop
    //  all references on the section and file object clearing the
    //  way for the Close Call and actual file delete to occur
    //  immediately.
    //

    if (FlagOn(SharedCacheMap->Flags, TRUNCATE_REQUIRED)) {

        DebugTrace( 0, mm, "MmPurgeSection:\n", 0 );
        DebugTrace( 0, mm, "    SectionObjectPointer = %08lx\n",
                    FileObject->SectionObjectPointer );
        DebugTrace2(0, mm, "    Offset = %08lx\n",
                    SharedCacheMap->FileSize.LowPart,
                    SharedCacheMap->FileSize.HighPart );

        //
        //  0 Length means to purge from the TruncateSize on.
        //

        CcPurgeCacheSection( FileObject->SectionObjectPointer,
                             &SharedCacheMap->FileSize,
                             0,
                             FALSE );
    }
}


VOID
CcSetDirtyPageThreshold (
    IN PFILE_OBJECT FileObject,
    IN ULONG DirtyPageThreshold
    )

/*++

Routine Description:

    This routine may be called to set a dirty page threshold for this
    stream.  The write throttling will kick in whenever the file system
    attempts to exceed the dirty page threshold for this file.

Arguments:

    FileObject - Supplies file object for the stream

    DirtyPageThreshold - Supplies the dirty page threshold for this stream,
                         or 0 for no threshold.

Return Value:

    None

--*/

{
    KIRQL OldIrql;
    PSHARED_CACHE_MAP SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

    if (SharedCacheMap != NULL) {

        SharedCacheMap->DirtyPageThreshold = DirtyPageThreshold;

        ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );
        SetFlag(((PFSRTL_COMMON_FCB_HEADER)(FileObject->FsContext))->Flags,
                FSRTL_FLAG_LIMIT_MODIFIED_PAGES);
        ExReleaseFastLock( &CcMasterSpinLock, OldIrql );
    }
}


VOID
CcZeroEndOfLastPage (
    IN PFILE_OBJECT FileObject
    )

/*++

Routine Description:

    This routine is only called by Mm before mapping a user view to
    a section.  If there is an uninitialized page at the end of the
    file, we zero it by freeing that page.

Parameters:

    FileObject - File object for section to be mapped

Return Value:

    None
--*/

{
    PSHARED_CACHE_MAP SharedCacheMap;
    ULONG ActivePage;
    ULONG PageIsDirty;
    KIRQL OldIrql;
    PVOID NeedToZero = NULL;
    PVACB ActiveVacb = NULL;

    //
    //  See if we have an active Vacb, that we need to free.
    //

    FsRtlAcquireFileExclusive( FileObject );
    ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );
    SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

    if (SharedCacheMap != NULL) {

        //
        //  See if there is an active vacb.
        //

        if ((SharedCacheMap->ActiveVacb != NULL) || ((NeedToZero = SharedCacheMap->NeedToZero) != NULL)) {

            SharedCacheMap->OpenCount += 1;
            GetActiveVacbAtDpcLevel( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );
        }
    }

    ExReleaseFastLock( &CcMasterSpinLock, OldIrql );

    //
    //  Remember in FsRtl header is there is a user section.
    //  If this is an advanced header then also acquire the mutex to access
    //  this field.
    //

    if (FlagOn( ((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->Flags,
                FSRTL_FLAG_ADVANCED_HEADER )) {

        ExAcquireFastMutex( ((PFSRTL_ADVANCED_FCB_HEADER)FileObject->FsContext)->FastMutex );

        SetFlag( ((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->Flags,
                 FSRTL_FLAG_USER_MAPPED_FILE );

        ExReleaseFastMutex( ((PFSRTL_ADVANCED_FCB_HEADER)FileObject->FsContext)->FastMutex );

    } else {

        SetFlag( ((PFSRTL_COMMON_FCB_HEADER)FileObject->FsContext)->Flags,
                 FSRTL_FLAG_USER_MAPPED_FILE );
    }

    FsRtlReleaseFile( FileObject );

    //
    //  If the file is cached and we have a Vacb to free, we need to
    //  use the lazy writer callback to synchronize so no one will be
    //  extending valid data.
    //

    if ((ActiveVacb != NULL) || (NeedToZero != NULL)) {

        CcFreeActiveVacb( SharedCacheMap, ActiveVacb, ActivePage, PageIsDirty );

        //
        //  Serialize again to decrement the open count.
        //

        ExAcquireSpinLock( &CcMasterSpinLock, &OldIrql );

        SharedCacheMap->OpenCount -= 1;

        if ((SharedCacheMap->OpenCount == 0) &&
            !FlagOn(SharedCacheMap->Flags, WRITE_QUEUED) &&
            (SharedCacheMap->DirtyPages == 0)) {

            //
            //  Move to the dirty list.
            //

            RemoveEntryList( &SharedCacheMap->SharedCacheMapLinks );
            InsertTailList( &CcDirtySharedCacheMapList.SharedCacheMapLinks,
                            &SharedCacheMap->SharedCacheMapLinks );

            //
            //  Make sure the Lazy Writer will wake up, because we
            //  want him to delete this SharedCacheMap.
            //

            LazyWriter.OtherWork = TRUE;
            if (!LazyWriter.ScanActive) {
                CcScheduleLazyWriteScan();
            }
        }

        ExReleaseSpinLock( &CcMasterSpinLock, OldIrql );
    }
}


BOOLEAN
CcZeroData (
    IN PFILE_OBJECT FileObject,
    IN PLARGE_INTEGER StartOffset,
    IN PLARGE_INTEGER EndOffset,
    IN BOOLEAN Wait
    )

/*++

Routine Description:

    This routine attempts to zero the specified file data and deliver the
    correct I/O status.

    If the caller does not want to block (such as for disk I/O), then
    Wait should be supplied as FALSE.  If Wait was supplied as FALSE and
    it is currently impossible to zero all of the requested data without
    blocking, then this routine will return FALSE.  However, if the
    required space is immediately accessible in the cache and no blocking is
    required, this routine zeros the data and returns TRUE.

    If the caller supplies Wait as TRUE, then this routine is guaranteed
    to zero the data and return TRUE.  If the correct space is immediately
    accessible in the cache, then no blocking will occur.  Otherwise,
    the necessary work will be initiated to read and/or free cache data,
    and the caller will be blocked until the data can be received.

    File system Fsd's should typically supply Wait = TRUE if they are
    processing a synchronous I/O requests, or Wait = FALSE if they are
    processing an asynchronous request.

    File system threads should supply Wait = TRUE.

    IMPORTANT NOTE: File systems which call this routine must be prepared
    to handle a special form of a write call where the Mdl is already
    supplied.  Namely, if Irp->MdlAddress is supplied, the file system
    must check the low order bit of Irp->MdlAddress->ByteOffset.  If it
    is set, that means that the Irp was generated in this routine and
    the file system must do two things:

        Decrement Irp->MdlAddress->ByteOffset and Irp->UserBuffer

        Clear Irp->MdlAddress immediately prior to completing the
        request, as this routine expects to reuse the Mdl and
        ultimately deallocate the Mdl itself.

Arguments:

    FileObject - pointer to the FileObject for which a range of bytes
                 is to be zeroed.  This FileObject may either be for
                 a cached file or a noncached file.  If the file is
                 not cached, then WriteThrough must be TRUE and
                 StartOffset and EndOffset must be on sector boundaries.

    StartOffset - Start offset in file to be zeroed.

    EndOffset - End offset in file to be zeroed.

    Wait - FALSE if caller may not block, TRUE otherwise (see description
           above)

Return Value:

    FALSE - if Wait was supplied as FALSE and the data was not zeroed.

    TRUE - if the data has been zeroed.

Raises:

    STATUS_INSUFFICIENT_RESOURCES - If a pool allocation failure occurs.
        This can only occur if Wait was specified as TRUE.  (If Wait is
        specified as FALSE, and an allocation failure occurs, this
        routine simply returns FALSE.)

--*/

{
    PSHARED_CACHE_MAP SharedCacheMap;
    PVOID CacheBuffer;
    LARGE_INTEGER FOffset;
    LARGE_INTEGER ToGo;
    ULONG ZeroBytes, ZeroTransfer;
    ULONG i;
    BOOLEAN WriteThrough;
    ULONG SavedState = 0;
    ULONG MaxZerosInCache = MAX_ZEROS_IN_CACHE;

    PBCB Bcb = NULL;
    PCHAR Zeros = NULL;
    PMDL ZeroMdl = NULL;
    ULONG MaxBytesMappedInMdl = 0;
    BOOLEAN Result = TRUE;

    DebugTrace(+1, me, "CcZeroData\n", 0 );

    WriteThrough = (BOOLEAN)(((FileObject->Flags & FO_WRITE_THROUGH) != 0) ||
                   (FileObject->PrivateCacheMap == NULL));

    //
    //  If the caller specified Wait, but the FileObject is WriteThrough,
    //  then we need to just get out.
    //

    if (WriteThrough && !Wait) {

        DebugTrace(-1, me, "CcZeroData->FALSE (WriteThrough && !Wait)\n", 0 );

        return FALSE;
    }

    SharedCacheMap = FileObject->SectionObjectPointer->SharedCacheMap;

    FOffset = *StartOffset;

    //
    //  Calculate how much to zero this time.
    //

    ToGo.QuadPart = EndOffset->QuadPart - FOffset.QuadPart;

    //
    //  We will only do zeroing in the cache if the caller is using a
    //  cached file object, and did not specify WriteThrough.  We are
    //  willing to zero some data in the cache if our total is not too
    //  much, or there is sufficient available pages.
    //

    if (((ToGo.QuadPart <= 0x2000) ||
         (MmAvailablePages >= ((MAX_ZEROS_IN_CACHE / PAGE_SIZE) * 4))) && !WriteThrough) {

        try {

            while (MaxZerosInCache != 0) {

                ULONG ReceivedLength;
                LARGE_INTEGER BeyondLastByte;

                if ( ToGo.QuadPart > (LONGLONG)MaxZerosInCache ) {

                    //
                    //  If Wait == FALSE, then there is no point in getting started,
                    //  because we would have to start all over again zeroing with
                    //  Wait == TRUE, since we would fall out of this loop and
                    //  start synchronously writing pages to disk.
                    //

                    if (!Wait) {

                        DebugTrace(-1, me, "CcZeroData -> FALSE\n", 0 );

                        try_return( Result = FALSE );
                    }
                }
                else {
                    MaxZerosInCache = ToGo.LowPart;
                }

                //
                //  Call local routine to Map or Access the file data, then zero the data,
                //  then call another local routine to free the data.  If we cannot map
                //  the data because of a Wait condition, return FALSE.
                //
                //  Note that this call may result in an exception, however, if it
                //  does no Bcb is returned and this routine has absolutely no
                //  cleanup to perform.  Therefore, we do not have a try-finally
                //  and we allow the possibility that we will simply be unwound
                //  without notice.
                //

                if (!CcPinFileData( FileObject,
                                    &FOffset,
                                    MaxZerosInCache,
                                    FALSE,
                                    TRUE,
                                    Wait,
                                    &Bcb,
                                    &CacheBuffer,
                                    &BeyondLastByte )) {

                    DebugTrace(-1, me, "CcZeroData -> FALSE\n", 0 );

                    try_return( Result = FALSE );
                }

                //
                //  Calculate how much data is described by Bcb starting at our desired
                //  file offset.  If it is more than we need, we will zero the whole thing
                //  anyway.
                //

                ReceivedLength = (ULONG)(BeyondLastByte.QuadPart - FOffset.QuadPart );

                //
                //  Now attempt to allocate an Mdl to describe the mapped data.
                //

                ZeroMdl = IoAllocateMdl( CacheBuffer,
                                         ReceivedLength,
                                         FALSE,
                                         FALSE,
                                         NULL );

                if (ZeroMdl == NULL) {

                    ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
                }

                //
                //  It is necessary to probe and lock the pages, or else
                //  the pages may not still be in memory when we do the
                //  MmSetAddressRangeModified for the dirty Bcb.
                //

                MmDisablePageFaultClustering(&SavedState);
                MmProbeAndLockPages( ZeroMdl, KernelMode, IoReadAccess );
                MmEnablePageFaultClustering(SavedState);
                SavedState = 0;

                //
                //  Assume we did not get all the data we wanted, and set FOffset
                //  to the end of the returned data, and advance buffer pointer.
                //

                FOffset = BeyondLastByte;

                //
                //  Figure out how many bytes we are allowed to zero in the cache.
                //  Note it is possible we have zeroed a little more than our maximum,
                //  because we hit an existing Bcb that extended beyond the range.
                //

                if (MaxZerosInCache <= ReceivedLength) {
                    MaxZerosInCache = 0;
                }
                else {
                    MaxZerosInCache -= ReceivedLength;
                }

                //
                //  Now set the Bcb dirty.  We have to explicitly set the address
                //  range modified here, because that work otherwise gets deferred
                //  to the Lazy Writer.
                //

                MmSetAddressRangeModified( CacheBuffer, ReceivedLength );
                CcSetDirtyPinnedData( Bcb, NULL );

                //
                //  Unmap the data now
                //

                CcUnpinFileData( Bcb, FALSE, UNPIN );
                Bcb = NULL;

                //
                //  Unlock and free the Mdl (we only loop back if we crossed
                //  a 256KB boundary.
                //

                MmUnlockPages( ZeroMdl );
                IoFreeMdl( ZeroMdl );
                ZeroMdl = NULL;
            }

        try_exit: NOTHING;
        } finally {

            if (SavedState != 0) {
                MmEnablePageFaultClustering(SavedState);
            }

            //
            //  Clean up only necessary in abnormal termination.
            //

            if (Bcb != NULL) {

                CcUnpinFileData( Bcb, FALSE, UNPIN );
            }

            //
            //  Since the last thing in the above loop which can
            //  fail is the MmProbeAndLockPages, we only need to
            //  free the Mdl here.
            //

            if (ZeroMdl != NULL) {

                IoFreeMdl( ZeroMdl );
            }
        }

        //
        //  If hit a wait condition above, return it now.
        //

        if (!Result) {
            return FALSE;
        }

        //
        //  If we finished, get out nbow.
        //

        if ( FOffset.QuadPart >= EndOffset->QuadPart ) {
            return TRUE;
        }
    }

    //
    //  We either get here because we decided above not to zero anything in
    //  the cache directly, or else we zeroed up to our maximum and still
    //  have some left to zero direct to the file on disk.  In either case,
    //  we will now zero from FOffset to *EndOffset, and then flush this
    //  range in case the file is cached/mapped, and there are modified
    //  changes in memory.
    //

    //
    //  try-finally to guarantee cleanup.
    //

    try {
        PULONG Page;
        ULONG SavedByteCount;
        LARGE_INTEGER SizeLeft;

        //
        //  Round FOffset and EndOffset up to sector boundaries, since
        //  we will be doing disk I/O, and calculate size left.
        //

        i = IoGetRelatedDeviceObject(FileObject)->SectorSize - 1;
        FOffset.QuadPart += (LONGLONG)i;
        FOffset.LowPart &= ~i;
        SizeLeft.QuadPart = EndOffset->QuadPart + (LONGLONG)i;
        SizeLeft.LowPart &= ~i;
        SizeLeft.QuadPart -= FOffset.QuadPart;

        if (SizeLeft.QuadPart == 0) {
            return TRUE;
        }

        //
        //  Allocate a page to hold the zeros we will write, and
        //  zero it.
        //

        ZeroBytes = MmNumberOfColors * PAGE_SIZE;

        if (SizeLeft.QuadPart < (LONGLONG)ZeroBytes) {
            ZeroBytes = SizeLeft.LowPart;
        }

        Zeros = (PCHAR)ExAllocatePool( NonPagedPoolCacheAligned, ZeroBytes );

        if (Zeros != NULL) {

            //
            //  Allocate and initialize an Mdl to describe the zeros
            //  we need to transfer.  Allocate to cover the maximum
            //  size required, and we will use and reuse it in the
            //  loop below, initialized correctly.
            //

            ZeroTransfer = MAX_ZERO_TRANSFER;

            if (ZeroBytes < MmNumberOfColors * PAGE_SIZE) {
                ZeroTransfer = ZeroBytes;
            }

            ZeroMdl = IoAllocateMdl( Zeros, ZeroTransfer, FALSE, FALSE, NULL );

            if (ZeroMdl == NULL) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            //
            //  Now we will temporarily lock the allocated pages
            //  only, and then replicate the page frame numbers through
            //  the entire Mdl to keep writing the same pages of zeros.
            //

            SavedByteCount = ZeroMdl->ByteCount;
            ZeroMdl->ByteCount = ZeroBytes;
            MmBuildMdlForNonPagedPool( ZeroMdl );

            ZeroMdl->MdlFlags &= ~MDL_SOURCE_IS_NONPAGED_POOL;
            ZeroMdl->MdlFlags |= MDL_PAGES_LOCKED;
            ZeroMdl->MappedSystemVa = NULL;
            ZeroMdl->ByteCount = SavedByteCount;
            Page = (PULONG)(ZeroMdl + 1);
            for (i = MmNumberOfColors;
                 i < (COMPUTE_PAGES_SPANNED( 0, SavedByteCount ));
                 i++) {

                *(Page + i) = *(Page + i - MmNumberOfColors);
            }

        //
        //  We failed to allocate the space we wanted, so we will go to
        //  half of page of must succeed pool.
        //

        } else {

            ZeroBytes = PAGE_SIZE / 2;
            Zeros = (PCHAR)ExAllocatePool( NonPagedPoolCacheAligned, ZeroBytes );

            //
            //  If we cannot get even that much, then let's write a sector at a time.
            //

            if (Zeros == NULL) {
                ZeroBytes = IoGetRelatedDeviceObject(FileObject)->SectorSize;
                Zeros = (PCHAR)ExAllocatePool( NonPagedPoolCacheAligned, ZeroBytes );
            }

            //
            //  Allocate and initialize an Mdl to describe the zeros
            //  we need to transfer.  Allocate to cover the maximum
            //  size required, and we will use and reuse it in the
            //  loop below, initialized correctly.
            //

            ZeroTransfer = ZeroBytes;
            ZeroMdl = IoAllocateMdl( Zeros, ZeroBytes, FALSE, FALSE, NULL );

            if ((Zeros == NULL) || (ZeroMdl == NULL)) {
                ExRaiseStatus( STATUS_INSUFFICIENT_RESOURCES );
            }

            //
            //  Now we will lock the allocated pages
            //

            MmBuildMdlForNonPagedPool( ZeroMdl );
        }

#ifdef MIPS
#ifdef MIPS_PREFILL
        RtlFillMemory( Zeros, ZeroBytes, 0xDD );
        KeSweepDcache( TRUE );
#endif
#endif

        //
        //  Zero the buffer now.
        //

        RtlZeroMemory( Zeros, ZeroBytes );

        //
        //  Map the full Mdl even if we will only use a part of it.  This
        //  allow the unmapping operation to be deterministic.
        //

        (VOID)MmGetSystemAddressForMdl(ZeroMdl);
        MaxBytesMappedInMdl = ZeroMdl->ByteCount;

        //
        //  Now loop to write buffers full of zeros through to the file
        //  until we reach the starting Vbn for the transfer.
        //

        while ( SizeLeft.QuadPart != 0 ) {

            IO_STATUS_BLOCK IoStatus;
            NTSTATUS Status;
            KEVENT Event;

            //
            //  See if we really need to write that many zeros, and
            //  trim the size back if not.
            //

            if ( (LONGLONG)ZeroTransfer > SizeLeft.QuadPart ) {

                ZeroTransfer = SizeLeft.LowPart;
            }

            //
            //  (Re)initialize the kernel event to FALSE.
            //

            KeInitializeEvent( &Event, NotificationEvent, FALSE );

            //
            //  Initiate and wait for the synchronous transfer.
            //

            ZeroMdl->ByteCount = ZeroTransfer;

            Status = IoSynchronousPageWrite( FileObject,
                                             ZeroMdl,
                                             &FOffset,
                                             &Event,
                                             &IoStatus );

            //
            //  If pending is returned (which is a successful status),
            //  we must wait for the request to complete.
            //

            if (Status == STATUS_PENDING) {
                KeWaitForSingleObject( &Event,
                                       Executive,
                                       KernelMode,
                                       FALSE,
                                       (PLARGE_INTEGER)NULL);
            }


            //
            //  If we got an error back in Status, then the Iosb
            //  was not written, so we will just copy the status
            //  there, then test the final status after that.
            //

            if (!NT_SUCCESS(Status)) {
                ExRaiseStatus( Status );
            }

            if (!NT_SUCCESS(IoStatus.Status)) {
                ExRaiseStatus( IoStatus.Status );
            }

            //
            //  If we succeeded, then update where we are at by how much
            //  we wrote, and loop back to see if there is more.
            //

            FOffset.QuadPart = FOffset.QuadPart + (LONGLONG)ZeroTransfer;
            SizeLeft.QuadPart = SizeLeft.QuadPart - (LONGLONG)ZeroTransfer;
        }
    }
    finally{

        //
        //  Clean up anything from zeroing pages on a noncached
        //  write.
        //

        if (ZeroMdl != NULL) {

            if ((MaxBytesMappedInMdl != 0) &&
                !FlagOn(ZeroMdl->MdlFlags, MDL_SOURCE_IS_NONPAGED_POOL)) {
                ZeroMdl->ByteCount = MaxBytesMappedInMdl;
                MmUnmapLockedPages (ZeroMdl->MappedSystemVa, ZeroMdl);
            }

            IoFreeMdl( ZeroMdl );
        }

        if (Zeros != NULL) {
            ExFreePool( Zeros );
        }

        DebugTrace(-1, me, "CcZeroData -> TRUE\n", 0 );
    }

    return TRUE;
}


PFILE_OBJECT
CcGetFileObjectFromSectionPtrs (
    IN PSECTION_OBJECT_POINTERS SectionObjectPointer
    )

/*++

This routine may be used to retrieve a pointer to the FileObject that the
Cache Manager is using for a given file from the Section Object Pointers
in the nonpaged File System structure Fcb.  The use of this function is
intended for exceptional use unrelated to the processing of user requests,
when the File System would otherwise not have a FileObject at its disposal.
An example is for mount verification.

Note that the File System is responsible for insuring that the File
Object does not go away while in use.  It is impossible for the Cache
Manager to guarantee this.

Arguments:

    SectionObjectPointer - A pointer to the Section Object Pointers
                           structure in the nonpaged Fcb.

Return Value:

    Pointer to the File Object, or NULL if the file is not cached or no
    longer cached

--*/

{
    KIRQL OldIrql;
    PFILE_OBJECT FileObject = NULL;

    //
    //  Serialize with Creation/Deletion of all Shared CacheMaps
    //

    ExAcquireFastLock( &CcMasterSpinLock, &OldIrql );

    if (SectionObjectPointer->SharedCacheMap != NULL) {

        FileObject = ((PSHARED_CACHE_MAP)SectionObjectPointer->SharedCacheMap)->FileObject;
    }

    ExReleaseFastLock( &CcMasterSpinLock, OldIrql );

    return FileObject;
}


PFILE_OBJECT
CcGetFileObjectFromBcb (
    IN PVOID Bcb
    )

/*++

This routine may be used to retrieve a pointer to the FileObject that the
Cache Manager is using for a given file from a Bcb of that file.

Note that the File System is responsible for insuring that the File
Object does not go away while in use.  It is impossible for the Cache
Manager to guarantee this.

Arguments:

    Bcb - A pointer to the pinned Bcb.

Return Value:

    Pointer to the File Object, or NULL if the file is not cached or no
    longer cached

--*/

{
    return ((PBCB)Bcb)->SharedCacheMap->FileObject;
}