summaryrefslogblamecommitdiffstats
path: root/private/ntos/cntfs/mcbsup.c
blob: 330925812c49d48a039357911adff68fae1f57b7 (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

















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                              
/*++

Copyright (c) 1991  Microsoft Corporation

Module Name:

    McbSup.c

Abstract:

    This module implements the Ntfs Mcb package.

Author:

    Gary Kimura     [GaryKi]        10-Sep-1994
    Tom Miller      [TomM]

Revision History:

--*/

#include "NtfsProc.h"

#define FIRST_RANGE ((PVOID)1)

#ifndef NTFS_VERIFY_MCB
#define NtfsVerifyNtfsMcb(M)                    NOTHING;
#define NtfsVerifyUncompressedNtfsMcb(M,S,E)    NOTHING;
#endif

//
//  Define a tag for general pool allocations from this module
//

#undef MODULE_POOL_TAG
#define MODULE_POOL_TAG                  ('MFtN')

//
//  Local procedure prototypes
//

ULONG
NtfsMcbLookupArrayIndex (
    IN PNTFS_MCB Mcb,
    IN VCN Vcn
    );

VOID
NtfsInsertNewRange (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN ULONG ArrayIndex,
    IN BOOLEAN MakeNewRangeEmpty
    );

VOID
NtfsCollapseRanges (
    IN PNTFS_MCB Mcb,
    IN ULONG StartingArrayIndex,
    IN ULONG EndingArrayIndex
    );

VOID
NtfsMcbCleanupLruQueue (
    IN PVOID Parameter
    );

#ifdef NTFS_VERIFY_MCB
VOID
NtfsVerifyNtfsMcb (
    IN PNTFS_MCB Mcb
    );

VOID
NtfsVerifyUncompressedNtfsMcb (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN LONGLONG EndingVcn
    );
#endif

BOOLEAN
NtfsLockNtfsMcb (
    IN PNTFS_MCB Mcb
    );

VOID
NtfsUnlockNtfsMcb (
    IN PNTFS_MCB Mcb
    );

//
//  Local macros to ASSERT that caller's resource is exclusive or restart is
//  underway.
//

#define ASSERT_STREAM_EXCLUSIVE(M) {                                    \
    ASSERT( FlagOn( ((PSCB) (M)->FcbHeader)->Vcb->VcbState, VCB_STATE_RESTART_IN_PROGRESS ) ||  \
            ExIsResourceAcquiredExclusive((M)->FcbHeader->Resource ));  \
}

//
//  Local macros to enqueue and dequeue elements from the lru queue
//

#define NtfsMcbEnqueueLruEntry(M,E) {                       \
    InsertTailList( &NtfsMcbLruQueue, &(E)->LruLinks );     \
    NtfsMcbCurrentLevel += 1;                               \
}

#define NtfsMcbDequeueLruEntry(M,E) {      \
    if ((E)->LruLinks.Flink != NULL) {     \
        RemoveEntryList( &(E)->LruLinks ); \
        NtfsMcbCurrentLevel -= 1;          \
    }                                      \
}

//
//  Local macro to unload a single array entry
//

#define UnloadEntry(M,I) {                              \
    PNTFS_MCB_ENTRY _Entry;                             \
    _Entry = (M)->NtfsMcbArray[(I)].NtfsMcbEntry;       \
    (M)->NtfsMcbArray[(I)].NtfsMcbEntry = NULL;         \
    if (_Entry != NULL) {                               \
        ExAcquireFastMutex( &NtfsMcbFastMutex );        \
        NtfsMcbDequeueLruEntry( Mcb, _Entry );          \
        ExReleaseFastMutex( &NtfsMcbFastMutex );        \
        FsRtlUninitializeLargeMcb( &_Entry->LargeMcb ); \
        if ((M)->NtfsMcbArraySize != 1) {               \
            NtfsFreePool( _Entry );                       \
        }                                               \
    }                                                   \
}


VOID
NtfsInitializeNtfsMcb (
    IN PNTFS_MCB Mcb,
    IN PFSRTL_ADVANCED_FCB_HEADER FcbHeader,
    IN PNTFS_MCB_INITIAL_STRUCTS McbStructs,
    IN POOL_TYPE PoolType
    )

/*++

Routine Description:

    This routine initializes a new Ntfs Mcb structure.

Arguments:

    Mcb - Supplies the Mcb being initialized

    FcbHeader - Supplies a pointer to the Fcb header containing
        the resource to grab when accessing the Mcb

    McbStructs - Initial allocation typically coresident in another
                 structure to handle initial structures for small and
                 medium files.  This structure should be initially zeroed.

    PoolType - Supplies the type of pool to use when
        allocating mapping information storage

Return Value:

    None.

--*/

{
    PNTFS_MCB_ARRAY Array;

    RtlZeroMemory( McbStructs, sizeof(NTFS_MCB_INITIAL_STRUCTS) );

    //
    //  Initialize the fcb header field of the mcb
    //

    Mcb->FcbHeader = FcbHeader;

    //
    //  Initialize the pool type
    //

    Mcb->PoolType = PoolType;

    //
    //  Now initialize the initial array element
    //

    Mcb->NtfsMcbArray = Array = &McbStructs->Phase1.SingleMcbArrayEntry;
    Mcb->NtfsMcbArraySize = 1;
    Mcb->NtfsMcbArraySizeInUse = 1;
    Mcb->FastMutex = FcbHeader->FastMutex;

    //
    //  Initialize the first array entry.
    //

    Array[0].StartingVcn = 0;
    Array[0].EndingVcn = -1;

    //
    //  And return to our caller
    //

    NtfsVerifyNtfsMcb(Mcb);

    return;
}


VOID
NtfsUninitializeNtfsMcb (
    IN PNTFS_MCB Mcb
    )

/*++

Routine Description:

    This routine uninitializes an Ntfs Mcb structure.

Arguments:

    Mcb - Supplies the Mcb being decommissioned

Return Value:

    None.

--*/

{
    ULONG i;
    PNTFS_MCB_ENTRY Entry;

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Take out the global mutex
    //

    ExAcquireFastMutex( &NtfsMcbFastMutex );

    //
    //  Deallocate the mcb array if it exists.  For every entry in the array
    //  if the mcb entry is not null then remove the entry from the lru
    //  queue, uninitialize the large mcb, and free the pool.
    //

    if (Mcb->NtfsMcbArray != NULL) {

        for (i = 0; i < Mcb->NtfsMcbArraySizeInUse; i += 1) {

            if ((Entry = Mcb->NtfsMcbArray[i].NtfsMcbEntry) != NULL) {

                //
                //  Remove the entry from the lru queue
                //

                NtfsMcbDequeueLruEntry( Mcb, Entry );

                //
                //  Now release the entry
                //

                FsRtlUninitializeLargeMcb( &Entry->LargeMcb );

                //
                //  We can tell from the array count whether this is
                //  the initial entry and does not need to be deallocated.
                //

                if (Mcb->NtfsMcbArraySize > 1) {
                    NtfsFreePool( Entry );
                }
            }
        }

        //
        //  We can tell from the array count whether this is
        //  the initial array entry(s) and do not need to be deallocated.
        //


        if (Mcb->NtfsMcbArraySize > 3) {
            NtfsFreePool( Mcb->NtfsMcbArray );
        }

        Mcb->NtfsMcbArray = NULL;

        //
        //  Clear the fast mutex field.
        //

        Mcb->FastMutex = NULL;
    }

    ExReleaseFastMutex( &NtfsMcbFastMutex );

    //
    //  And return to our caller
    //

    return;
}


ULONG
NtfsNumberOfRangesInNtfsMcb (
    IN PNTFS_MCB Mcb
    )

/*++

Routine Description:

    This routine returns the total number of ranges stored in
    the mcb

Arguments:

    Mcb - Supplies the Mcb being queried

Return Value:

    ULONG - The number of ranges mapped by the input mcb

--*/

{
    ASSERT_STREAM_EXCLUSIVE(Mcb);

    //
    //  Our answer is the number of ranges in use in the mcb
    //

    NtfsVerifyNtfsMcb(Mcb);

    return Mcb->NtfsMcbArraySizeInUse;
}


BOOLEAN
NtfsNumberOfRunsInRange (
    IN PNTFS_MCB Mcb,
    IN PVOID RangePtr,
    OUT PULONG NumberOfRuns
    )

/*++

Routine Description:

    This routine returns the total number of runs stored withing a range

Arguments:

    Mcb - Supplies the Mcb being queried

    RangePtr - Supplies the range to being queried

    NumberOrRuns - Returns the number of run in the specified range
        but only if the range is loaded

Return Value:

    BOOLEAN - TRUE if the range is loaded and then output variable
        is valid and FALSE if the range is not loaded.

--*/

{
    VCN TempVcn;
    LCN TempLcn;
    PNTFS_MCB_ENTRY Entry = (PNTFS_MCB_ENTRY)RangePtr;

    //
    //  Null RangePtr means first range
    //

    if (Entry == FIRST_RANGE) {
        Entry = Mcb->NtfsMcbArray[0].NtfsMcbEntry;

        //
        //  If not loaded, return FALSE
        //

        if (Entry == NULL) {
            return FALSE;
        }
    }

    ASSERT_STREAM_EXCLUSIVE(Mcb);

    NtfsVerifyNtfsMcb(Mcb);

    ASSERT( Mcb == Entry->NtfsMcb );

    *NumberOfRuns = FsRtlNumberOfRunsInLargeMcb( &Entry->LargeMcb );

    //
    //  Check if the current entry ends with a hole and increment the run count
    //  to reflect this.  Detect the case where the range has length 0 for a
    //  file with no allocation.  EndingVcn will be less than the starting Vcn
    //  in this case.
    //

    if (!FsRtlLookupLastLargeMcbEntry( &Entry->LargeMcb, &TempVcn, &TempLcn )) {

        //
        //  If this is a non-zero length range then add one for the implied hole.
        //

        if (Entry->NtfsMcbArray->EndingVcn >= Entry->NtfsMcbArray->StartingVcn) {

            *NumberOfRuns += 1;
        }

    //
    //  There is an entry then check if it reaches the end boundary of the range.
    //

    } else if (TempVcn != (Entry->NtfsMcbArray->EndingVcn - Entry->NtfsMcbArray->StartingVcn)) {

        *NumberOfRuns += 1;
    }

    return TRUE;
}


BOOLEAN
NtfsLookupLastNtfsMcbEntry (
    IN PNTFS_MCB Mcb,
    OUT PLONGLONG Vcn,
    OUT PLONGLONG Lcn
    )

/*++

Routine Description:

    This routine returns the last mapping stored in the mcb

Arguments:

    Mcb - Supplies the Mcb being queried

    Vcn - Receives the Vcn of the last mapping

    Lcn - Receives the Lcn corresponding to the Vcn

Return Value:

    BOOLEAN - TRUE if the mapping exist and FALSE if no mapping has been
        defined or it is unloaded

--*/

{
    PNTFS_MCB_ENTRY Entry;
    LONGLONG StartingVcn;

    ASSERT_STREAM_EXCLUSIVE(Mcb);

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Get the last entry and compute its starting vcn, and make sure
    //  the entry is valid
    //

    if ((Entry = Mcb->NtfsMcbArray[Mcb->NtfsMcbArraySizeInUse - 1].NtfsMcbEntry) == NULL) {

        return FALSE;
    }

    StartingVcn = Mcb->NtfsMcbArray[Mcb->NtfsMcbArraySizeInUse - 1].StartingVcn;

    //
    //  Otherwise lookup the last entry and compute the real vcn
    //

    if (FsRtlLookupLastLargeMcbEntry( &Entry->LargeMcb, Vcn, Lcn )) {

        *Vcn += StartingVcn;

    } else {

        *Vcn = Mcb->NtfsMcbArray[Mcb->NtfsMcbArraySizeInUse - 1].EndingVcn;
        *Lcn = UNUSED_LCN;
    }

    return TRUE;
}


BOOLEAN
NtfsLookupNtfsMcbEntry (
    IN PNTFS_MCB Mcb,
    IN LONGLONG Vcn,
    OUT PLONGLONG Lcn OPTIONAL,
    OUT PLONGLONG CountFromLcn OPTIONAL,
    OUT PLONGLONG StartingLcn OPTIONAL,
    OUT PLONGLONG CountFromStartingLcn OPTIONAL,
    OUT PVOID *RangePtr OPTIONAL,
    OUT PULONG RunIndex OPTIONAL
    )

/*++

Routine Description:

    This routine is used to query mapping information

Arguments:

    Mcb - Supplies the Mcb being queried

    Vcn - Supplies the Vcn being queried

    Lcn - Optionally receives the lcn corresponding to the input vcn

    CountFromLcn - Optionally receives the number of clusters following
        the lcn in the run

    StartingLcn - Optionally receives the start of the run containing the
        input vcn

    CountFromStartingLcn - Optionally receives the number of clusters in
        the entire run

    RangePtr - Optionally receives the index for the range that we're returning

    RunIndex - Optionally receives the index for the run within the range that
        we're returning

Return Value:

    BOOLEAN - TRUE if the mapping exists and FALSE if it doesn't exist
        or if it is unloaded.

--*/

{
    ULONG LocalRangeIndex;

    PNTFS_MCB_ENTRY Entry;

    NtfsAcquireNtfsMcbMutex( Mcb );

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Locate the array entry that has the hit for the input vcn, and
    //  make sure it is valid.  Also set the output range index if present
    //

    LocalRangeIndex = NtfsMcbLookupArrayIndex(Mcb, Vcn);

    //
    //  Now lookup the large mcb entry.  The Vcn we pass in is
    //  biased by the starting vcn.  If we miss then we'll just return false
    //

    if (((Entry = Mcb->NtfsMcbArray[LocalRangeIndex].NtfsMcbEntry) == NULL) ||
        (Vcn > Entry->NtfsMcbArray->EndingVcn)) {

        if (ARGUMENT_PRESENT(RangePtr)) {

            *RangePtr = (PVOID)Entry;

            //
            //  If this is the first range, always normalize back to the reserved pointer,
            //  since this is the only range which can move if we split out of our
            //  initial static allocation!
            //

            if (LocalRangeIndex == 0) {
                *RangePtr = FIRST_RANGE;
            }
        }

        NtfsReleaseNtfsMcbMutex( Mcb );

        return FALSE;
    }

    if (!FsRtlLookupLargeMcbEntry( &Entry->LargeMcb,
                                   Vcn - Mcb->NtfsMcbArray[LocalRangeIndex].StartingVcn,
                                   Lcn,
                                   CountFromLcn,
                                   StartingLcn,
                                   CountFromStartingLcn,
                                   RunIndex )) {

        //
        //  If we go off the end of the Mcb, but are in the range, then we
        //  return a hole to the end of the range.
        //

        if (ARGUMENT_PRESENT(Lcn)) {
            *Lcn = UNUSED_LCN;
        }

        if (ARGUMENT_PRESENT(CountFromLcn)) {
            *CountFromLcn = Mcb->NtfsMcbArray[LocalRangeIndex].EndingVcn - Vcn + 1;
        }

        if (ARGUMENT_PRESENT(StartingLcn)) {
            *StartingLcn = UNUSED_LCN;
        }

        ASSERTMSG("Brian's bogus CountFromStartingLcn is not implemented\n",
                  !ARGUMENT_PRESENT(CountFromStartingLcn));

        if (ARGUMENT_PRESENT(RunIndex)) {
            *RunIndex = FsRtlNumberOfRunsInLargeMcb( &Entry->LargeMcb );
        }
    }

    if (ARGUMENT_PRESENT(RangePtr)) {

        *RangePtr = (PVOID)Entry;

        //
        //  If this is the first range, always normalize back to the reserved pointer,
        //  since this is the only range which can move if we split out of our
        //  initial static allocation!
        //

        if (LocalRangeIndex == 0) {
            *RangePtr = FIRST_RANGE;
        }
    }

    //
    //  Now move this entry to the tail of the lru queue.
    //  We need to take out the global mutex to do this.
    //  Only do this if he is already in the queue - we can
    //  deadlock if we take a fault in the paging file path.
    //

    if (Entry->LruLinks.Flink != NULL) {

        if (ExTryToAcquireFastMutex( &NtfsMcbFastMutex )) {

            NtfsMcbDequeueLruEntry( Mcb, Entry );
            NtfsMcbEnqueueLruEntry( Mcb, Entry );

            ExReleaseFastMutex( &NtfsMcbFastMutex );
        }
    }

    NtfsReleaseNtfsMcbMutex( Mcb );

    return TRUE;
}


BOOLEAN
NtfsGetNextNtfsMcbEntry (
    IN PNTFS_MCB Mcb,
    IN PVOID *RangePtr,
    IN ULONG RunIndex,
    OUT PLONGLONG Vcn,
    OUT PLONGLONG Lcn,
    OUT PLONGLONG Count
    )

/*++

Routine Description:

    This routine returns the range denoted by the type index values

Arguments:

    Mcb - Supplies the Mcb being queried

    RangePtr - Supplies the pointer to the range being queried, or NULL for the first one,
               returns next range

    RunIndex - Supplies the index within then being queried, or MAXULONG for first in next

    Vcn - Receives the starting Vcn of the run being returned

    Lcn - Receives the starting Lcn of the run being returned or unused
        lbn value of -1

    Count - Receives the number of clusters within this run

Return Value:

    BOOLEAN - TRUE if the two input indices are valid and FALSE if the
        the index are not valid or if the range is not loaded

--*/

{
    PNTFS_MCB_ENTRY Entry = (PNTFS_MCB_ENTRY)*RangePtr;
    BOOLEAN Result = FALSE;

    NtfsAcquireNtfsMcbMutex( Mcb );

    NtfsVerifyNtfsMcb(Mcb);

    try {

        //
        //  Null RangePtr means first range
        //

        if (Entry == FIRST_RANGE) {
            Entry = Mcb->NtfsMcbArray[0].NtfsMcbEntry;
        }

        //
        //  If there is no entry 0, get out.
        //

        if (Entry == NULL) {

            try_return(Result = FALSE);
        }

        //
        //  RunIndex of MAXULONG means first of next
        //

        if (RunIndex == MAXULONG) {

            //
            //  If we are already in the last range, get out.
            //

            if (Entry->NtfsMcbArray == (Mcb->NtfsMcbArray + Mcb->NtfsMcbArraySizeInUse - 1)) {

                try_return(Result = FALSE);
            }

            *RangePtr = Entry = (Entry->NtfsMcbArray + 1)->NtfsMcbEntry;
            RunIndex = 0;
        }

        //
        //  If there is no next entry, get out.
        //

        if (Entry == NULL) {

            try_return(Result = FALSE);
        }

        ASSERT( Mcb == Entry->NtfsMcb );

        //
        //  Lookup the large mcb entry.  If we get a miss then the we're
        //  beyond the end of the ntfs mcb and should return false
        //

        if (!FsRtlGetNextLargeMcbEntry( &Entry->LargeMcb, RunIndex, Vcn, Lcn, Count )) {

            //
            //  Our caller should only be off by one or two (if there is
            //  a hole) runs.
            //

            ASSERT(RunIndex <= (FsRtlNumberOfRunsInLargeMcb(&Entry->LargeMcb) + 1));

            //
            //  Get the first Vcn past the last Vcn in a run.  It is -1 if there
            //  are no runs.
            //

            if (!FsRtlLookupLastLargeMcbEntry( &Entry->LargeMcb, Vcn, Lcn )) {

                *Vcn = -1;
            }

            *Vcn += Entry->NtfsMcbArray->StartingVcn + 1;

            //
            //  If that one is beyond the ending Vcn, then get out.
            //  Otherwise there is a hole at the end of the range, and we
            //  must return that when he is reading one index beyond the
            //  last run.  If we have a run index beyond that, then it is
            //  time to return FALSE as well.
            //

            if ((*Vcn  > Entry->NtfsMcbArray->EndingVcn) ||
                (RunIndex > FsRtlNumberOfRunsInLargeMcb(&Entry->LargeMcb))) {

                try_return(Result = FALSE);
            }

            //
            //  If we go off the end of the Mcb, but are in the range, then we
            //  return a hole to the end of the range.
            //

            *Lcn = UNUSED_LCN;
            *Count = Entry->NtfsMcbArray->EndingVcn - *Vcn + 1;

        } else {

            //
            //  Otherwise we have a hit on the large mcb and need to bias the returned
            //  vcn by the starting vcn value for this range.
            //

            *Vcn = *Vcn + Entry->NtfsMcbArray->StartingVcn;
        }

        //
        //  Make certain we aren't returning a VCN that maps over to
        //  the next range.
        //

        ASSERT(*Vcn - 1 != Entry->NtfsMcbArray->EndingVcn);

        Result = TRUE;

    try_exit: NOTHING;

    } finally {

        NtfsReleaseNtfsMcbMutex( Mcb );
    }

    return Result;
}


BOOLEAN
NtfsSplitNtfsMcb (
    IN PNTFS_MCB Mcb,
    IN LONGLONG Vcn,
    IN LONGLONG Amount
    )

/*++

Routine Description:

    This routine splits an mcb

Arguments:

    Mcb - Supplies the Mcb being maniuplated

    Vcn - Supplies the Vcn to be shifted

    Amount - Supplies the amount to shift by

Return Value:

    BOOLEAN - TRUE if worked okay and FALSE otherwise

--*/

{
    ULONG RangeIndex;
    PNTFS_MCB_ENTRY Entry;
    ULONG i;

    ASSERT_STREAM_EXCLUSIVE(Mcb);

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Locate the array entry that has the hit for the input vcn
    //

    RangeIndex = NtfsMcbLookupArrayIndex(Mcb, Vcn);

    Entry = Mcb->NtfsMcbArray[RangeIndex].NtfsMcbEntry;

    //
    //  Now if the entry is not null then we have to call the large
    //  mcb package to split the mcb.  Bias the vcn by the starting vcn
    //

    if (Entry != NULL) {

        if (!FsRtlSplitLargeMcb( &Entry->LargeMcb,
                                 Vcn - Mcb->NtfsMcbArray[RangeIndex].StartingVcn,
                                 Amount )) {

            NtfsVerifyNtfsMcb(Mcb);

            return FALSE;
        }
    }

    //
    //  Even if the entry is null we will march through the rest of our ranges
    //  updating the ending vcn and starting vcn as we go.  We will update the
    //  ending vcn for the range we split and only update the starting vcn
    //  for the last entry, because its ending vcn is already max long long
    //

    for (i = RangeIndex + 1; i < Mcb->NtfsMcbArraySizeInUse; i += 1) {

        Mcb->NtfsMcbArray[i - 1].EndingVcn += Amount;
        Mcb->NtfsMcbArray[i].StartingVcn += Amount;
    }

    //
    //  And grow the last range unless it would wrap.
    //

    if ((Mcb->NtfsMcbArray[i - 1].EndingVcn + Amount) > Mcb->NtfsMcbArray[i - 1].EndingVcn) {
        Mcb->NtfsMcbArray[i - 1].EndingVcn += Amount;
    }

    //
    //  Then return to our caller
    //

    NtfsVerifyNtfsMcb(Mcb);

    return TRUE;
}


VOID
NtfsRemoveNtfsMcbEntry (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN LONGLONG Count
    )

/*++

Routine Description:

    This routine removes an range of mappings from the Mcb.  After
    the call the mapping for the range will be a hole.  It is an
    error to call this routine with the mapping range being removed
    also being unloaded.

Arguments:

    Mcb - Supplies the Mcb being maniuplated

    StartingVcn - Supplies the starting Vcn to remove

    Count - Supplies the number of mappings to remove

Return Value:

    None.

--*/

{
    LONGLONG Vcn;
    LONGLONG RunLength;
    LONGLONG RemainingCount;

    ULONG RangeIndex;
    PNTFS_MCB_ENTRY Entry;
    VCN EntryStartingVcn;
    VCN EntryEndingVcn;

    ASSERT_STREAM_EXCLUSIVE(Mcb);

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Loop through the range of vcn's that we need to remove
    //

    for (Vcn = StartingVcn, RemainingCount = Count;
         Vcn < StartingVcn + Count;
         Vcn += RunLength, RemainingCount -= RunLength) {

        //
        //  Locate the array entry that has the hit for the vcn
        //

        RangeIndex = NtfsMcbLookupArrayIndex(Mcb, Vcn);

        Entry = Mcb->NtfsMcbArray[RangeIndex].NtfsMcbEntry;
        EntryStartingVcn = Mcb->NtfsMcbArray[RangeIndex].StartingVcn;
        EntryEndingVcn = Mcb->NtfsMcbArray[RangeIndex].EndingVcn;

        //
        //  Compute how much to delete from the entry.  We will delete to
        //  to end of the entry or as much as count is remaining
        //

        RunLength = EntryEndingVcn - Vcn + 1;

        //
        //  If the Mcb is set up correctly, the only way we can get
        //  RunLength == 0 is if the Mcb is completely empty.  Assume
        //  that this is error recovery, and that it is ok.
        //

        if ((Entry == NULL) || (RunLength == 0)) {
            break;
        }

        //
        //  If that is too much, then just delete what we need.
        //

        if ((ULONGLONG)RunLength > (ULONGLONG)RemainingCount) { RunLength = RemainingCount; }

        //
        //  Now remove the mapping from the large mcb, bias the vcn
        //  by the start of the range
        //

        FsRtlRemoveLargeMcbEntry( &Entry->LargeMcb, Vcn - EntryStartingVcn,  RunLength );
    }

    NtfsVerifyNtfsMcb(Mcb);

    return;
}


BOOLEAN
NtfsAddNtfsMcbEntry (
    IN PNTFS_MCB Mcb,
    IN LONGLONG Vcn,
    IN LONGLONG Lcn,
    IN LONGLONG RunCount,
    IN BOOLEAN AlreadySynchronized
    )

/*++

Routine Description:

    This routine add a new entry to a Mcb

Arguments:

    Mcb - Supplies the Mcb being modified

    Vcn - Supplies the Vcn that we are providing a mapping for

    Lcn - Supplies the Lcn corresponding to the input Vcn if run count is non zero

    RunCount - Supplies the size of the run following the hole

    AlreadySynchronized - Indicates if the caller has already acquired the mcb mutex

Return Value:

    BOOLEAN - TRUE if the mapping was added successfully and FALSE otherwise

--*/

{
    LONGLONG LocalVcn;
    LONGLONG LocalLcn;
    LONGLONG RunLength;
    LONGLONG RemainingCount;

    ULONG RangeIndex;
    PNTFS_MCB_ENTRY Entry;
    PNTFS_MCB_ENTRY NewEntry = NULL;
    LONGLONG EntryStartingVcn;
    LONGLONG EntryEndingVcn;

    BOOLEAN Result = FALSE;

    if (!AlreadySynchronized) { NtfsAcquireNtfsMcbMutex( Mcb ); }

    NtfsVerifyNtfsMcb(Mcb);

    try {

        //
        //  Loop through the range of vcn's that we need to add
        //

        for (LocalVcn = Vcn, LocalLcn = Lcn, RemainingCount = RunCount;
             LocalVcn < Vcn + RunCount;
             LocalVcn += RunLength, LocalLcn += RunLength, RemainingCount -= RunLength) {

            //
            //  Locate the array entry that has the hit for the vcn
            //

            RangeIndex = NtfsMcbLookupArrayIndex(Mcb, LocalVcn);

            Entry = Mcb->NtfsMcbArray[RangeIndex].NtfsMcbEntry;
            EntryStartingVcn = Mcb->NtfsMcbArray[RangeIndex].StartingVcn;

            //
            //  Now if the entry doesn't exist then we'll need to create one
            //

            if (Entry == NULL) {

                //
                //  See if we need to get the first entry in the initial structs.
                //

                if (Mcb->NtfsMcbArraySize == 1) {
                    Entry = &CONTAINING_RECORD(&Mcb->NtfsMcbArray[0],
                                               NTFS_MCB_INITIAL_STRUCTS,
                                               Phase1.SingleMcbArrayEntry)->Phase1.McbEntry;

                //
                //  Allocate pool and initialize the fields in of the entry
                //

                } else {
                    NewEntry =
                    Entry = NtfsAllocatePoolWithTag( Mcb->PoolType, sizeof(NTFS_MCB_ENTRY), 'MftN' );
                }

                //
                //  Initialize the entry but don't put into the Mcb array until
                //  initialization is complete.
                //

                Entry->NtfsMcb = Mcb;
                Entry->NtfsMcbArray = &Mcb->NtfsMcbArray[RangeIndex];
                FsRtlInitializeLargeMcb( &Entry->LargeMcb, Mcb->PoolType );

                //
                //  Now put the entry into the lru queue under the protection of
                //  the global mutex
                //

                ExAcquireFastMutex( &NtfsMcbFastMutex );

                //
                //  Only put paged Mcb entries in the queue.
                //

                if (Mcb->PoolType == PagedPool) {
                    NtfsMcbEnqueueLruEntry( Mcb, Entry );
                }

                //
                //  Now that the initialization is complete we can store
                //  this entry in the Mcb array.  This will now be cleaned
                //  up with the Scb if there is a future error.
                //

                Mcb->NtfsMcbArray[RangeIndex].NtfsMcbEntry = Entry;
                NewEntry = NULL;

                //
                //  Check if we should fire off the cleanup lru queue work item
                //

                if ((NtfsMcbCurrentLevel > NtfsMcbHighWaterMark) && !NtfsMcbCleanupInProgress) {

                    NtfsMcbCleanupInProgress = TRUE;

                    ExInitializeWorkItem( &NtfsMcbWorkItem, NtfsMcbCleanupLruQueue, NULL );

                    ExQueueWorkItem( &NtfsMcbWorkItem, CriticalWorkQueue );
                }

                ExReleaseFastMutex( &NtfsMcbFastMutex );
            }

            //
            //  Get out if he is trying to add a hole.  At least we created the LargeMcb
            //

            if (Lcn == UNUSED_LCN) {
                try_return( Result = TRUE );
            }

            //
            //  If this request goes beyond the end of the range,
            //  and it is the last range, and we will simply
            //  grow it.
            //

            EntryEndingVcn = LocalVcn + RemainingCount - 1;

            if ((EntryEndingVcn > Mcb->NtfsMcbArray[RangeIndex].EndingVcn) &&
                ((RangeIndex + 1) == Mcb->NtfsMcbArraySizeInUse)) {

                Mcb->NtfsMcbArray[RangeIndex].EndingVcn = EntryEndingVcn;

            //
            //  Otherwise, just insert enough of this run to go to the end
            //  of the range.
            //

            } else {
                EntryEndingVcn = Mcb->NtfsMcbArray[RangeIndex].EndingVcn;
            }

            //
            //  At this point the entry exists so now compute how much to add
            //  We will add to end of the entry or as much as count allows us
            //

            RunLength = EntryEndingVcn - LocalVcn + 1;

            if (((ULONGLONG)RunLength) > ((ULONGLONG)RemainingCount)) { RunLength = RemainingCount; }

            //
            //  Now add the mapping from the large mcb, bias the vcn
            //  by the start of the range
            //

            ASSERT( (LocalVcn - EntryStartingVcn) >= 0 );

            if (!FsRtlAddLargeMcbEntry( &Entry->LargeMcb,
                                        LocalVcn - EntryStartingVcn,
                                        LocalLcn,
                                        RunLength )) {

                try_return( Result = FALSE );
            }
        }

        Result = TRUE;

    try_exit: NOTHING;

    } finally {

        NtfsVerifyNtfsMcb(Mcb);

        if (!AlreadySynchronized) { NtfsReleaseNtfsMcbMutex( Mcb ); }

        if (NewEntry != NULL) { NtfsFreePool( NewEntry ); }
    }

    return Result;
}


VOID
NtfsUnloadNtfsMcbRange (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN LONGLONG EndingVcn,
    IN BOOLEAN TruncateOnly,
    IN BOOLEAN AlreadySynchronized
    )

/*++

Routine Description:

    This routine unloads the mapping stored in the Mcb.  After
    the call everything from startingVcn and endingvcn is now unmapped and unknown.

Arguments:

    Mcb - Supplies the Mcb being manipulated

    StartingVcn - Supplies the first Vcn which is no longer being mapped

    EndingVcn - Supplies the last vcn to be unloaded

    TruncateOnly - Supplies TRUE if last affected range should only be
                   truncated, or FALSE if it should be unloaded (as during
                   error recovery)

    AlreadySynchronized - Supplies TRUE if our caller already owns the Mcb mutex.

Return Value:

    None.

--*/

{
    ULONG StartingRangeIndex;
    ULONG EndingRangeIndex;

    ULONG i;

    if (!AlreadySynchronized) { NtfsAcquireNtfsMcbMutex( Mcb ); }

    NtfsVerifyNtfsMcb(Mcb);
    NtfsVerifyUncompressedNtfsMcb(Mcb,StartingVcn,EndingVcn);

    //
    //  Get the starting and ending range indices for this call
    //

    StartingRangeIndex = NtfsMcbLookupArrayIndex( Mcb, StartingVcn );
    EndingRangeIndex = NtfsMcbLookupArrayIndex( Mcb, EndingVcn );

    //
    //  Use try finally to enforce common termination processing.
    //

    try {

        //
        //  For all nonpaged Mcbs, just unload all ranges touched by the
        //  unload range, and collapse with any unloaded neighbors.
        //

        if (Mcb->PoolType == PagedPool) {

            //
            //  Handle truncate case.  The first test insures that we only truncate
            //  the Mcb were were initialized with (we cannot deallocate it).
            //
            //  Also only truncate if ending is MAXLONGLONG and we are not eliminating
            //  the entire range, because that is the common truncate case, and we
            //  do not want to unload the last range every time we truncate on close.
            //

            if (((StartingRangeIndex == 0) && (Mcb->NtfsMcbArraySizeInUse == 1))

                ||

                (TruncateOnly && (StartingVcn != Mcb->NtfsMcbArray[StartingRangeIndex].StartingVcn))) {

                //
                //  If this is not a truncate call, make sure to eliminate the
                //  entire range.
                //

                if (!TruncateOnly) {
                    StartingVcn = 0;
                }

                if (Mcb->NtfsMcbArray[StartingRangeIndex].NtfsMcbEntry != NULL) {

                    FsRtlTruncateLargeMcb( &Mcb->NtfsMcbArray[StartingRangeIndex].NtfsMcbEntry->LargeMcb,
                                           StartingVcn - Mcb->NtfsMcbArray[StartingRangeIndex].StartingVcn );
                }

                Mcb->NtfsMcbArray[StartingRangeIndex].EndingVcn = StartingVcn - 1;

                StartingRangeIndex += 1;
            }

            //
            //  Unload entries that are beyond the starting range index
            //

            for (i = StartingRangeIndex; i <= EndingRangeIndex; i += 1) {

                UnloadEntry( Mcb, i );
            }

            //
            //  If there is a preceding unloaded range, we must collapse him too.
            //

            if ((StartingRangeIndex != 0) &&
                (Mcb->NtfsMcbArray[StartingRangeIndex - 1].NtfsMcbEntry == NULL)) {

                StartingRangeIndex -= 1;
            }

            //
            //  If there is a subsequent unloaded range, we must collapse him too.
            //

            if ((EndingRangeIndex != (Mcb->NtfsMcbArraySizeInUse - 1)) &&
                (Mcb->NtfsMcbArray[EndingRangeIndex + 1].NtfsMcbEntry == NULL)) {

                EndingRangeIndex += 1;
            }

            //
            //  Now collapse empty ranges.
            //

            if (StartingRangeIndex < EndingRangeIndex) {
                NtfsCollapseRanges( Mcb, StartingRangeIndex, EndingRangeIndex );
            }

            try_return(NOTHING);
        }

        //
        //  For nonpaged Mcbs, there is only one range and we truncate it.
        //

        ASSERT((StartingRangeIndex | EndingRangeIndex) == 0);

        if (Mcb->NtfsMcbArray[0].NtfsMcbEntry != NULL) {

            FsRtlTruncateLargeMcb( &Mcb->NtfsMcbArray[0].NtfsMcbEntry->LargeMcb, StartingVcn );
        }

        Mcb->NtfsMcbArray[0].EndingVcn = StartingVcn - 1;

    try_exit: NOTHING;

    } finally {

        //
        //  Truncate all unused entries from the end by dropping ArraySizeInUse
        //  to be the index of the last loaded entry + 1.
        //

        for (i = Mcb->NtfsMcbArraySizeInUse - 1;
             (Mcb->NtfsMcbArray[i].NtfsMcbEntry == NULL);
             i--) {

            //
            //  If the first range is unloaded, set it to its initial state
            //  (empty) and break out.
            //

            if (i==0) {
                Mcb->NtfsMcbArray[0].EndingVcn = -1;
                break;
            }
        }
        Mcb->NtfsMcbArraySizeInUse = i + 1;

        //
        //  See if we broke anything.
        //

        NtfsVerifyNtfsMcb(Mcb);
        NtfsVerifyUncompressedNtfsMcb(Mcb,StartingVcn,EndingVcn);

        if (!AlreadySynchronized) { NtfsReleaseNtfsMcbMutex( Mcb ); }
    }

    return;
}


VOID
NtfsDefineNtfsMcbRange (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN LONGLONG EndingVcn,
    IN BOOLEAN AlreadySynchronized
    )

/*++

Routine Description:

    This routine splits an existing range within the Mcb into two ranges

Arguments:

    Mcb - Supplies the Mcb being modified

    StartingVcn - Supplies the beginning of the new range being split

    EndingVcn - Supplies the ending vcn to include in this new range

    AlreadySynchronized - Indicates if the caller has already acquired the mcb mutex

Return Value:

    None.

--*/

{
    ULONG StartingRangeIndex, EndingRangeIndex;

    if (!AlreadySynchronized) { NtfsAcquireNtfsMcbMutex( Mcb ); }

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Make sure we're of the right pool type
    //
    //  If the ending vcn is less than or equal to the starting vcn then we will no op
    //  this call
    //

    if ((Mcb->PoolType != PagedPool) || (EndingVcn < StartingVcn)) {

        if (!AlreadySynchronized) { NtfsReleaseNtfsMcbMutex( Mcb ); }

        return;
    }

    try {

        PNTFS_MCB_ARRAY Array1;
        PNTFS_MCB_ARRAY Array2;
        PNTFS_MCB_ENTRY Entry1;
        PNTFS_MCB_ENTRY Entry2;

        //
        //  Lookup the index for the starting Vcn and make sure it is equivalent to the ending
        //  range index
        //

        StartingRangeIndex = NtfsMcbLookupArrayIndex( Mcb, StartingVcn );
        EndingRangeIndex = NtfsMcbLookupArrayIndex( Mcb, EndingVcn );
        Array1 = &Mcb->NtfsMcbArray[StartingRangeIndex];
        Array2 = &Mcb->NtfsMcbArray[EndingRangeIndex];
        Entry1 = Array1->NtfsMcbEntry;
        Entry2 = Array2->NtfsMcbEntry;

        //
        //  We handle two cases where the specified range overlaps two
        //  existing ranges.
        //

        if (EndingRangeIndex == (StartingRangeIndex + 1)) {

            //
            //  If an existing range wants to grow into the next range, and the next
            //  range is unloaded, then make it happen.
            //

            if (Array2->NtfsMcbEntry == NULL) {

                //
                //  Grow the first range and shrink the second range.
                //

                Array1->EndingVcn = EndingVcn;
                Array2->StartingVcn = EndingVcn + 1;

                //
                //  If we did not empty the second range, NULL out Array2,
                //  so that we will not eliminate a range below.
                //

                if (EndingVcn < Array2->EndingVcn) {
                    Array2 = NULL;
                }

            //
            //  Otherwise, we will split the second range, and move the entries
            //  from the end of the first range into the start of the second range.
            //  (Other optimizations in Ntfs are designed to make sure we do not
            //  end up sliding too much stuff around!)
            //

            } else {

                ULONG Index;
                VCN Vcn;
                LCN Lcn;
                LONGLONG Count;
                VCN StartingVcn1 = Array1->StartingVcn;
                BOOLEAN MoreEntries;

                //
                //  Both Mcbs better be there.
                //

                ASSERT((Entry1 != NULL) && (Entry2 != NULL));

                //
                //  Make room in the second Mcb for the entries we will move into there.
                //

                FsRtlSplitLargeMcb( &Entry2->LargeMcb,
                                    0,
                                    (ULONG)(Array2->StartingVcn - StartingVcn) );

                //
                //  Now look up the first Vcn to move in the first Mcb.  If this
                //  Mcb consists of one large hole then there is nothing to
                //  move.
                //

                Vcn = StartingVcn - StartingVcn1;
                MoreEntries = FsRtlLookupLargeMcbEntry( &Entry1->LargeMcb,
                                                        Vcn,
                                                        &Lcn,
                                                        &Count,
                                                        NULL,
                                                        NULL,
                                                        &Index );

                //
                //  Loop to move entries over.
                //

                while (MoreEntries) {

                    //
                    //  If this entry is not a hole, move it.
                    //

                    if (Lcn != UNUSED_LCN) {

                        ASSERT( (Vcn - (StartingVcn - StartingVcn1)) >= 0 );

                        FsRtlAddLargeMcbEntry( &Entry2->LargeMcb,
                                               Vcn - (StartingVcn - StartingVcn1),
                                               Lcn,
                                               Count );
                    }

                    Index += 1;

                    MoreEntries = FsRtlGetNextLargeMcbEntry( &Entry1->LargeMcb,
                                                             Index,
                                                             &Vcn,
                                                             &Lcn,
                                                             &Count );
                }

                //
                //  Now truncate the original Mcb.
                //

                FsRtlTruncateLargeMcb( &Entry1->LargeMcb, StartingVcn - StartingVcn1 );

                //
                //  Update the range boundaries.
                //

                Array1->EndingVcn = StartingVcn - 1;
                Array2->StartingVcn = StartingVcn;

                if (EndingVcn > Array2->EndingVcn) {
                    Array2->EndingVcn = EndingVcn;
                }

                //
                //  In the unusual case that we moved the entire first range over,
                //  set to eliminate that range by setting the following variables.
                //

                if (StartingVcn == Array1->StartingVcn) {

                    Array2 = Array1;
                    EndingRangeIndex = StartingRangeIndex;

                //
                //  Otherwise make sure we do not eliminate a range below.
                //

                } else {
                    Array2 = NULL;
                }
            }

            //
            //  We may have emptied all of a range, and
            //  have to eliminate him if so.
            //

            if (Array2 != NULL) {

                ULONG i;

                //
                //  Make sure the entry is unloaded.
                //

                UnloadEntry( Mcb, EndingRangeIndex );

                //
                //  We will eliminate one array entry.
                //

                Mcb->NtfsMcbArraySizeInUse -= 1;

                //
                //  Check if we need to move the ending entries up the array
                //  if so then move them forward, and adjust the back pointers.
                //

                if (EndingRangeIndex < Mcb->NtfsMcbArraySizeInUse) {

                    RtlMoveMemory( Array2,
                                   Array2 + 1,
                                   sizeof(NTFS_MCB_ARRAY) * (Mcb->NtfsMcbArraySizeInUse - EndingRangeIndex));

                    for (i = EndingRangeIndex;
                         i < Mcb->NtfsMcbArraySizeInUse;
                         i += 1) {

                        if (Mcb->NtfsMcbArray[i].NtfsMcbEntry != NULL) {
                            Mcb->NtfsMcbArray[i].NtfsMcbEntry->NtfsMcbArray = &Mcb->NtfsMcbArray[i];
                        }
                    }
                }
            }

            try_return( NOTHING );
        }

        //
        //  For all remaining cases, the indices must be the same.
        //

        ASSERT( StartingRangeIndex == EndingRangeIndex );

        //
        //  First catch the case of extending the last range
        //

        if (((StartingRangeIndex + 1) == Mcb->NtfsMcbArraySizeInUse) &&
            (StartingVcn == Array1->StartingVcn) &&
            (EndingVcn >= Array1->EndingVcn)) {

            Array1->EndingVcn = EndingVcn;

            try_return( NOTHING );
        }

        //
        //  Now handle the case of a disjoint overlap, which can only happen in the
        //  last range.  (If this test fails our range is included in an existing
        //  range, and we handle that after this case.)
        //

        if (StartingVcn > Array2->EndingVcn) {

            LONGLONG OldEndingVcn = Array2->EndingVcn;

            //
            //  Has to be the last range.
            //

            ASSERT( (EndingRangeIndex + 1) == Mcb->NtfsMcbArraySizeInUse );

            //
            //  First extend the last range to include our new range.
            //

            Array2->EndingVcn = EndingVcn;

            //
            //  We will be adding a new range and inserting or growing the
            //  previous range up to the new range.  If the previous range is
            //  *empty* but has an NtfsMcbEntry then we want to unload the entry.
            //  Otherwise we will grow that range to the correct value but
            //  the Mcb won't contain the clusters for the range.  We want
            //  to unload that range and update the OldEndingVcn value so
            //  as not to create two empty ranges prior to this.
            //

            if ((OldEndingVcn == -1) &&
                (Array2->NtfsMcbEntry != NULL)) {

                UnloadEntry( Mcb, EndingRangeIndex );
            }

            //
            //  Now create the range the caller specified.
            //

            NtfsInsertNewRange( Mcb, StartingVcn, EndingRangeIndex, TRUE );

            //
            //  Now, if this range does not abut the previous last range, *and*
            //  the previous range was not *empty*, then we have to define a
            //  range to contain the unloaded space in the middle.
            //

            if (((OldEndingVcn + 1) < StartingVcn) &&
                ((OldEndingVcn + 1) != 0)) {

                NtfsInsertNewRange( Mcb, OldEndingVcn + 1, StartingRangeIndex, TRUE );
            }

            try_return( NOTHING );
        }

        //
        //  Check if we really need to insert a new range at the ending vcn
        //  we only need to do the work if there is not already one at that vcn
        //  and this is not the last range
        //
        //  We do the ending range first, because its index will change if we
        //  insert in the starting range.
        //

        if (Array2->EndingVcn > EndingVcn) {

            NtfsInsertNewRange( Mcb, EndingVcn + 1, EndingRangeIndex, FALSE );
            Array1 = &Mcb->NtfsMcbArray[StartingRangeIndex];
        }

        //
        //  Check if we really need to insert a new range at the starting vcn
        //  we only need to do the work if there is not already one at that vcn
        //

        if (Array1->StartingVcn < StartingVcn) {

            NtfsInsertNewRange( Mcb, StartingVcn, StartingRangeIndex, FALSE );

            //
            //  In the last range, we may still need to extend.
            //

            if (EndingVcn > Mcb->NtfsMcbArray[StartingRangeIndex + 1].EndingVcn) {
                ASSERT((StartingRangeIndex + 2) == Mcb->NtfsMcbArraySizeInUse);
                Mcb->NtfsMcbArray[StartingRangeIndex + 1].EndingVcn = EndingVcn;
            }
        }

    try_exit: NOTHING;

    } finally {

        NtfsVerifyNtfsMcb(Mcb);

        if (!AlreadySynchronized) { NtfsReleaseNtfsMcbMutex( Mcb ); }
    }

    return;
}


//
//  Local support routines
//

ULONG
NtfsMcbLookupArrayIndex (
    IN PNTFS_MCB Mcb,
    IN VCN Vcn
    )

/*++

Routine Description:

    This routines searches the mcb array for an entry that contains
    the input vcn value

Arguments:

    Mcb - Supplies the Mcb being queried

    Vcn - Supplies the Vcn to lookup

Return Value:

    ULONG - The index of the entry containing the input Vcn value

--*/

{
    ULONG Index;
    ULONG MinIndex;
    ULONG MaxIndex;

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Do a quick binary search for the entry containing the vcn
    //

    MinIndex = 0;
    MaxIndex = Mcb->NtfsMcbArraySizeInUse - 1;

    while (TRUE) {

        Index = (MaxIndex + MinIndex) / 2;

        if (Mcb->NtfsMcbArray[Index].StartingVcn > Vcn) {

            MaxIndex = Index - 1;

        } else if ((Mcb->NtfsMcbArray[Index].EndingVcn < Vcn) &&
                   (Index != Mcb->NtfsMcbArraySizeInUse - 1)) {

            MinIndex = Index + 1;

        } else {

            return Index;
        }
    }
}


//
//  Local support routines
//

VOID
NtfsInsertNewRange (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN ULONG ArrayIndex,
    IN BOOLEAN MakeNewRangeEmpty
    )

/*++

    This routine is used to add a new range at the specified vcn and index location

Arguments:

    Mcb - Supplies the Mcb being modified

    StartingVcn - Supplies the vcn for the new range

    ArrayIndex - Supplies the index currently containing the starting vcn

    MakeNewRangeEmpty - TRUE if the caller wants the new range unloaded regardless
                        of the state of the current range

Return Value:

    None.

--*/

{
    ULONG i;
    PNTFS_MCB_ENTRY Entry;
    PNTFS_MCB_ENTRY NewEntry;

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Check if we need to grow the array
    //

    if (Mcb->NtfsMcbArraySizeInUse >= Mcb->NtfsMcbArraySize) {

        PNTFS_MCB_ARRAY NewArray;
        ULONG OldArraySize = Mcb->NtfsMcbArraySize;

        //
        //  Test for initial case where we only have one array entry.
        //

        if (Mcb->NtfsMcbArraySize == 1) {

            //
            //  Convince ourselves that we do not have to move the array entry.
            //

            ASSERT(FIELD_OFFSET(NTFS_MCB_INITIAL_STRUCTS, Phase1.SingleMcbArrayEntry) ==
                   FIELD_OFFSET(NTFS_MCB_INITIAL_STRUCTS, Phase2.ThreeMcbArrayEntries));

            if (Mcb->NtfsMcbArray[0].NtfsMcbEntry != NULL) {

                //
                //  Allocate a new Mcb Entry, copy the current one over and change the pointer.
                //

                Entry = NtfsAllocatePoolWithTag( Mcb->PoolType, sizeof(NTFS_MCB_ENTRY), 'MftN' );

                //
                //  Once space is allocated, dequeue the old entry.
                //

                ExAcquireFastMutex( &NtfsMcbFastMutex );
                NtfsMcbDequeueLruEntry( Mcb, Mcb->NtfsMcbArray[0].NtfsMcbEntry );

                RtlCopyMemory( Entry, Mcb->NtfsMcbArray[0].NtfsMcbEntry, sizeof(NTFS_MCB_ENTRY) );

                Mcb->NtfsMcbArray[0].NtfsMcbEntry = Entry;

                NtfsMcbEnqueueLruEntry( Mcb, Entry );
                ExReleaseFastMutex( &NtfsMcbFastMutex );
            }

            //
            //  Now change to using the three array elements
            //

            Mcb->NtfsMcbArraySize = 3;

        } else {

            //
            //  If we do then allocate an array that can contain 8 more entires
            //

            NewArray = NtfsAllocatePoolWithTag( Mcb->PoolType, sizeof(NTFS_MCB_ARRAY) * (Mcb->NtfsMcbArraySize + 8), 'mftN' );
            Mcb->NtfsMcbArraySize += 8;

            //
            //  Copy over the memory from the old array to the new array and then
            //  for every loaded entry we need to adjust its back pointer to the
            //  array
            //

            RtlCopyMemory( NewArray, Mcb->NtfsMcbArray, sizeof(NTFS_MCB_ARRAY) * Mcb->NtfsMcbArraySizeInUse);

            for (i = 0; i < Mcb->NtfsMcbArraySizeInUse; i += 1) {

                if (NewArray[i].NtfsMcbEntry != NULL) {

                    NewArray[i].NtfsMcbEntry->NtfsMcbArray = &NewArray[i];
                }
            }

            //
            //  Free the old array if it was not the original array.
            //

            if (OldArraySize > 3) {
               NtfsFreePool( Mcb->NtfsMcbArray );
            }

            Mcb->NtfsMcbArray = NewArray;
        }

        //
        //  Zero the new part of the array.
        //

        ASSERT(sizeof(NTFS_MCB_ARRAY) == ((PCHAR)&NewArray[1] - (PCHAR)&NewArray[0]));

        RtlZeroMemory( &Mcb->NtfsMcbArray[OldArraySize],
                       (Mcb->NtfsMcbArraySize - OldArraySize) * sizeof(NTFS_MCB_ARRAY) );
    }

    //
    //  Now move entries that are beyond the array index over by one to make
    //  room for the new entry
    //

    if (ArrayIndex + 2 <= Mcb->NtfsMcbArraySizeInUse) {

        RtlMoveMemory( &Mcb->NtfsMcbArray[ArrayIndex + 2],
                       &Mcb->NtfsMcbArray[ArrayIndex + 1],
                       sizeof(NTFS_MCB_ARRAY) * (Mcb->NtfsMcbArraySizeInUse - ArrayIndex - 1));

        for (i = ArrayIndex + 2; i < Mcb->NtfsMcbArraySizeInUse + 1; i += 1) {

            if (Mcb->NtfsMcbArray[i].NtfsMcbEntry != NULL) {

                Mcb->NtfsMcbArray[i].NtfsMcbEntry->NtfsMcbArray = &Mcb->NtfsMcbArray[i];
            }
        }
    }

    //
    //  Increment our in use count by one
    //

    Mcb->NtfsMcbArraySizeInUse += 1;

    //
    //  Now fix the starting and ending Vcn values for the old entry and the
    //  new entry
    //

    Mcb->NtfsMcbArray[ArrayIndex + 1].StartingVcn = StartingVcn;
    Mcb->NtfsMcbArray[ArrayIndex + 1].EndingVcn = Mcb->NtfsMcbArray[ArrayIndex].EndingVcn;
    Mcb->NtfsMcbArray[ArrayIndex + 1].NtfsMcbEntry = NULL;

    Mcb->NtfsMcbArray[ArrayIndex].EndingVcn = StartingVcn - 1;

    //
    //  Now if the entry is old entry is not null then we have a bunch of work to do
    //

    if (!MakeNewRangeEmpty && (Entry = Mcb->NtfsMcbArray[ArrayIndex].NtfsMcbEntry) != NULL) {

        LONGLONG Vcn;
        LONGLONG Lcn;
        LONGLONG RunLength;
        ULONG Index;
        BOOLEAN FreeNewEntry = FALSE;

        //
        //  Use a try-finally in case the Mcb initialization fails.
        //

        try {

            //
            //  Allocate the new entry slot
            //

            NewEntry = NtfsAllocatePoolWithTag( Mcb->PoolType, sizeof(NTFS_MCB_ENTRY), 'MftN' );

            FreeNewEntry = TRUE;
            NewEntry->NtfsMcb = Mcb;
            NewEntry->NtfsMcbArray = &Mcb->NtfsMcbArray[ArrayIndex + 1];
            FsRtlInitializeLargeMcb( &NewEntry->LargeMcb, Mcb->PoolType );

            ExAcquireFastMutex( &NtfsMcbFastMutex );
            NtfsMcbEnqueueLruEntry( Mcb, NewEntry );
            ExReleaseFastMutex( &NtfsMcbFastMutex );

            //
            //  Now that the initialization is complete we can store
            //  this entry in the Mcb array.  This will now be cleaned
            //  up with the Scb if there is a future error.
            //

            Mcb->NtfsMcbArray[ArrayIndex + 1].NtfsMcbEntry = NewEntry;
            FreeNewEntry = FALSE;

            //
            //  Lookup the entry containing the starting vcn in the old entry and put it
            //  in the new entry.  But only if the entry exists otherwise we know that
            //  the large mcb doesn't extend into the new range
            //

            if (FsRtlLookupLargeMcbEntry( &Entry->LargeMcb,
                                          StartingVcn - Mcb->NtfsMcbArray[ArrayIndex].StartingVcn,
                                          &Lcn,
                                          &RunLength,
                                          NULL,
                                          NULL,
                                          &Index )) {

                if (Lcn != UNUSED_LCN) {

                    FsRtlAddLargeMcbEntry( &NewEntry->LargeMcb,
                                           0,
                                           Lcn,
                                           RunLength );
                }

                //
                //  Now for every run in the old entry that is beyond the starting vcn we will
                //  copy it into the new entry. This will also copy over the dummy run at the end
                //  of the mcb if it exists
                //

                for (i = Index + 1; FsRtlGetNextLargeMcbEntry( &Entry->LargeMcb, i, &Vcn, &Lcn, &RunLength ); i += 1) {

                    if (Lcn != UNUSED_LCN) {
                        ASSERT( (Vcn - (StartingVcn - Mcb->NtfsMcbArray[ArrayIndex].StartingVcn)) >= 0 );
                        FsRtlAddLargeMcbEntry( &NewEntry->LargeMcb,
                                               Vcn - (StartingVcn - Mcb->NtfsMcbArray[ArrayIndex].StartingVcn),
                                               Lcn,
                                               RunLength );
                    }
                }

                //
                //  Now modify the old mcb to be smaller and put in the dummy run
                //

                FsRtlTruncateLargeMcb( &Entry->LargeMcb,
                                       StartingVcn - Mcb->NtfsMcbArray[ArrayIndex].StartingVcn );
            }

        } finally {

            if (FreeNewEntry) { NtfsFreePool( NewEntry ); }
        }
    }

    NtfsVerifyNtfsMcb(Mcb);

    return;
}


//
//  Local support routines
//

VOID
NtfsCollapseRanges (
    IN PNTFS_MCB Mcb,
    IN ULONG StartingArrayIndex,
    IN ULONG EndingArrayIndex
    )

/*++

Routine Description:

    This routine will remove the indicated array entries

Arguments:

    Mcb - Supplies the Mcb being modified

    StartingArrayIndex - Supplies the first index to remove

    EndingArrayIndex - Supplies the last index to remove

Return Value:

    None.

--*/

{
    ULONG i;

    NtfsVerifyNtfsMcb(Mcb);

    //
    //  Make sure all the ranges are unloaded.
    //

    DebugDoit(

        for (i = StartingArrayIndex; i <= EndingArrayIndex; i++) {
            ASSERT(Mcb->NtfsMcbArray[i].NtfsMcbEntry == NULL);
        }
    );

    //
    //  We keep the first entry by we need to copy over
    //  the ending vcn of the last entry
    //

    Mcb->NtfsMcbArray[StartingArrayIndex].EndingVcn = Mcb->NtfsMcbArray[EndingArrayIndex].EndingVcn;

    //
    //  Check if we need to move the ending entries up the array
    //  if so then move them forward, and adjust the back pointers.
    //

    if (EndingArrayIndex < Mcb->NtfsMcbArraySizeInUse - 1) {

        RtlMoveMemory( &Mcb->NtfsMcbArray[StartingArrayIndex + 1],
                       &Mcb->NtfsMcbArray[EndingArrayIndex + 1],
                       sizeof(NTFS_MCB_ARRAY) * (Mcb->NtfsMcbArraySizeInUse - EndingArrayIndex - 1));

        for (i = StartingArrayIndex + 1;
             i <= (StartingArrayIndex + Mcb->NtfsMcbArraySizeInUse - EndingArrayIndex - 1);
             i += 1) {

            if (Mcb->NtfsMcbArray[i].NtfsMcbEntry != NULL) {

                Mcb->NtfsMcbArray[i].NtfsMcbEntry->NtfsMcbArray = &Mcb->NtfsMcbArray[i];
            }
        }
    }

    //
    //  Decrement the in use count and return to our caller
    //

    Mcb->NtfsMcbArraySizeInUse -= (EndingArrayIndex - StartingArrayIndex);

    NtfsVerifyNtfsMcb(Mcb);

    return;
}


//
//  Local support routine
//

VOID
NtfsMcbCleanupLruQueue (
    IN PVOID Parameter
    )

/*++

Routine Description:

    This routine is called as an ex work queue item and its job is
    to free up the lru queue until we reach the low water mark


Arguments:

    Parameter - ignored

Return Value:

    None.

--*/

{
    PLIST_ENTRY Links;

    PNTFS_MCB Mcb;
    PNTFS_MCB_ARRAY Array;
    PNTFS_MCB_ENTRY Entry;

    UNREFERENCED_PARAMETER( Parameter );

    //
    //  Grab the global lock
    //

    ExAcquireFastMutex( &NtfsMcbFastMutex );

    try {

        //
        //  Scan through the lru queue until we either exhaust the queue
        //  or we've trimmed enough
        //

        for (Links = NtfsMcbLruQueue.Flink;
             (Links != &NtfsMcbLruQueue) && (NtfsMcbCurrentLevel > NtfsMcbLowWaterMark);
             Links = Links->Flink ) {

            //
            //  Get the entry and the mcb it points to
            //

            Entry = CONTAINING_RECORD( Links, NTFS_MCB_ENTRY, LruLinks );

            Mcb = Entry->NtfsMcb;

            //
            //  Skip this entry if it is in the open attribute table.
            //

            if (((PSCB)(Mcb->FcbHeader))->NonpagedScb->OpenAttributeTableIndex != 0) {

                continue;
            }

            //
            //  Try and lock the mcb
            //

            if (NtfsLockNtfsMcb( Mcb )) {

                NtfsVerifyNtfsMcb(Mcb);

                //
                //  The previous test was an unsafe test.  Check again in case
                //  this entry has been added.
                //

                if (((PSCB)(Mcb->FcbHeader))->NonpagedScb->OpenAttributeTableIndex == 0) {

                    //
                    //  We locked the mcb so we can remove this entry, but
                    //  first backup our links pointer so we can continue with the loop
                    //

                    Links = Links->Blink;

                    //
                    //  Get a point to the array entry and then remove this entry and return
                    //  it to pool
                    //

                    Array = Entry->NtfsMcbArray;

                    Array->NtfsMcbEntry = NULL;
                    NtfsMcbDequeueLruEntry( Mcb, Entry );
                    FsRtlUninitializeLargeMcb( &Entry->LargeMcb );
                    if (Mcb->NtfsMcbArraySize != 1) {
                        NtfsFreePool( Entry );
                    }
                }

                NtfsUnlockNtfsMcb( Mcb );
            }
        }

    } finally {

        //
        //  Say we're done with the cleanup so that another one can be fired off when
        //  necessary
        //

        NtfsMcbCleanupInProgress = FALSE;

        ExReleaseFastMutex( &NtfsMcbFastMutex );
    }

    //
    //  Return to our caller
    //

    return;
}


//
//  Local support routine
//

BOOLEAN
NtfsLockNtfsMcb (
    IN PNTFS_MCB Mcb
    )

/*++

Routine Description:

    This routine attempts to get the Fcb resource(s) exclusive so that
    ranges may be unloaded.

Arguments:

    Mcb - Supplies the mcb being queried

Return Value:

--*/

{
    //
    //  Try to acquire paging resource exclusive.
    //

    if ((Mcb->FcbHeader->PagingIoResource == NULL) ||
        ExAcquireResourceExclusive(Mcb->FcbHeader->PagingIoResource, FALSE)) {

        //
        //  Now we can try to acquire the main resource exclusively as well.
        //

        if (ExAcquireResourceExclusive(Mcb->FcbHeader->Resource, FALSE)) {
            return TRUE;
        }

        //
        //  We failed to acquire the paging I/O resource, so free the main one
        //  on the way out.
        //

        if (Mcb->FcbHeader->PagingIoResource != NULL) {
            ExReleaseResource( Mcb->FcbHeader->PagingIoResource );
        }
    }

    //
    //  Could not get this file exclusive.
    //

    return FALSE;
}


//
//  Local support routine
//

VOID
NtfsUnlockNtfsMcb (
    IN PNTFS_MCB Mcb
    )

/*++

Routine Description:

    This routine verifies that an mcb is properly formed

Arguments:

    Mcb - Supplies the mcb being queried

Return Value:

    None.

--*/

{
    //
    //  If there is a paging I/O resource, release it first.
    //

    if (Mcb->FcbHeader->PagingIoResource != NULL) {
        ExReleaseResource(Mcb->FcbHeader->PagingIoResource);
    }

    //
    //  Now release the main resource.
    //

    ExReleaseResource(Mcb->FcbHeader->Resource);
}

#ifdef NTFS_VERIFY_MCB

//
//  Local support routine
//

VOID
NtfsVerifyNtfsMcb (
    IN PNTFS_MCB Mcb
    )

/*++

Routine Description:

    This routine verifies that an mcb is properly formed

Arguments:

    Mcb - Supplies the mcb being queried

Return Value:

--*/

{
    ULONG i;
    PNTFS_MCB_ARRAY Array;
    PNTFS_MCB_ENTRY Entry;

    LONGLONG Vbn;
    LONGLONG Lbn;

    ASSERT(Mcb->FcbHeader != NULL);
    ASSERT(Mcb->FcbHeader->NodeTypeCode != 0);

    ASSERT((Mcb->PoolType == PagedPool) || (Mcb->PoolType == NonPagedPool));

    ASSERT(Mcb->NtfsMcbArraySizeInUse <= Mcb->NtfsMcbArraySize);

    for (i = 0; i < Mcb->NtfsMcbArraySizeInUse; i += 1) {

        Array = &Mcb->NtfsMcbArray[i];

        ASSERT(((i == 0) && (Array->StartingVcn == 0)) ||
               ((i != 0) && (Array->StartingVcn != 0)));

        ASSERT(Array->StartingVcn <= (Array->EndingVcn + 1));

        if ((Entry = Array->NtfsMcbEntry) != NULL) {

            ASSERT(Entry->NtfsMcb == Mcb);
            ASSERT(Entry->NtfsMcbArray == Array);

            if (FsRtlLookupLastLargeMcbEntry( &Entry->LargeMcb, &Vbn, &Lbn )) {
                ASSERT( Vbn <= (Array->EndingVcn - Array->StartingVcn) );
            }
        }
    }
}


//
//  Local support routine
//

VOID
NtfsVerifyUncompressedNtfsMcb (
    IN PNTFS_MCB Mcb,
    IN LONGLONG StartingVcn,
    IN LONGLONG EndingVcn
    )

/*++

Routine Description:

    This routines checks if an mcb is for an uncompressed scb and then
    checks that there are no holes in the mcb.  Holes within the range being
    removed are legal provided EndingVcn is max long long.

Arguments:

    Mcb - Supplies the Mcb being examined

    StartingVcn - The starting Vcn being unloaded

    EndingVcn - The ending Vcn being unloaded

Return Value:

    None

--*/

{
    ULONG i;
    ULONG j;
    PNTFS_MCB_ARRAY Array;
    PNTFS_MCB_ENTRY Entry;

    LONGLONG Vbn;
    LONGLONG Lbn;
    LONGLONG Count;

    //
    //  Check if the scb is compressed
    //

    if (((PSCB)Mcb->FcbHeader)->CompressionUnit != 0) { return; }

    //
    //  For each large mcb in the ntfs mcb we will make sure it doesn't
    //  have any holes.
    //

    for (i = 0; i < Mcb->NtfsMcbArraySizeInUse; i += 1) {

        Array = &Mcb->NtfsMcbArray[i];

        if ((Entry = Array->NtfsMcbEntry) != NULL) {

            for (j = 0; FsRtlGetNextLargeMcbEntry(&Entry->LargeMcb,j,&Vbn,&Lbn,&Count); j += 1) {

                ASSERT((Lbn != -1) ||
                       ((Vbn + Array->StartingVcn >= StartingVcn) && (EndingVcn == MAXLONGLONG)) ||
                       FlagOn(((PSCB)Mcb->FcbHeader)->Vcb->VcbState, VCB_STATE_RESTART_IN_PROGRESS));
            }
        }
    }

    return;
}
#endif