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

Copyright (c) 1991  Microsoft Corporation

Module Name:

    LogSup.c

Abstract:

    This module implements the Ntfs interfaces to the Log File Service (LFS).

Author:

    Tom Miller      [TomM]          24-Jul-1991

Revision History:

--*/

#include "NtfsProc.h"

//
//  The local debug trace level
//

#define Dbg                              (DEBUG_TRACE_LOGSUP)

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

#undef MODULE_POOL_TAG
#define MODULE_POOL_TAG                  ('LFtN')

#ifdef NTFSDBG

#define ASSERT_RESTART_TABLE(T) {                                           \
    PULONG _p = (PULONG)(((PCHAR)(T)) + sizeof(RESTART_TABLE));             \
    ULONG _Count = ((T)->EntrySize/4) * (T)->NumberEntries;                 \
    ULONG _i;                                                               \
    for (_i = 0; _i < _Count; _i += 1) {                                    \
        if (_p[_i] == 0xDAADF00D) {                                         \
            DbgPrint("DaadFood for table %08lx, At %08lx\n", (T), &_p[_i]); \
            ASSERTMSG("ASSERT_RESTART_TABLE ", FALSE);                      \
        }                                                                   \
    }                                                                       \
}

#else

#define ASSERT_RESTART_TABLE(T) {NOTHING;}

#endif

//
//  Local procedure prototypes
//

typedef LCN UNALIGNED *PLCN_UNALIGNED;

VOID
DirtyPageRoutine (
    IN PFILE_OBJECT FileObject,
    IN PLARGE_INTEGER FileOffset,
    IN ULONG Length,
    IN PLSN OldestLsn,
    IN PLSN NewestLsn,
    IN PVOID Context1,
    IN PVOID Context2
    );

VOID
LookupLcns (
    IN PIRP_CONTEXT IrpContext,
    IN PSCB Scb,
    IN VCN Vcn,
    IN ULONG ClusterCount,
    IN BOOLEAN MustBeAllocated,
    OUT PLCN_UNALIGNED FirstLcn
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, LookupLcns)
#pragma alloc_text(PAGE, NtfsCheckpointCurrentTransaction)
#pragma alloc_text(PAGE, NtfsCheckpointForLogFileFull)
#pragma alloc_text(PAGE, NtfsCheckpointVolume)
#pragma alloc_text(PAGE, NtfsCommitCurrentTransaction)
#pragma alloc_text(PAGE, NtfsFreeRestartTable)
#pragma alloc_text(PAGE, NtfsGetFirstRestartTable)
#pragma alloc_text(PAGE, NtfsGetNextRestartTable)
#pragma alloc_text(PAGE, NtfsInitializeLogging)
#pragma alloc_text(PAGE, NtfsInitializeRestartTable)
#pragma alloc_text(PAGE, NtfsStartLogFile)
#pragma alloc_text(PAGE, NtfsStopLogFile)
#pragma alloc_text(PAGE, NtfsWriteLog)
#endif


LSN
NtfsWriteLog (
    IN PIRP_CONTEXT IrpContext,
    IN PSCB Scb,
    IN PBCB Bcb OPTIONAL,
    IN NTFS_LOG_OPERATION RedoOperation,
    IN PVOID RedoBuffer OPTIONAL,
    IN ULONG RedoLength,
    IN NTFS_LOG_OPERATION UndoOperation,
    IN PVOID UndoBuffer OPTIONAL,
    IN ULONG UndoLength,
    IN LONGLONG StreamOffset,
    IN ULONG RecordOffset,
    IN ULONG AttributeOffset,
    IN ULONG StructureSize
    )

/*++

Routine Description:

    This routine implements an Ntfs-specific interface to LFS for the
    purpose of logging updates to file record segments and resident
    attributes.

    The caller creates one of the predefined log record formats as
    determined by the given LogOperation, and calls this routine with
    this log record and pointers to the respective file and attribute
    records.  The list of log operations along with the respective structure
    expected for the Log Buffer is present in ntfslog.h.

Arguments:

    Scb - Pointer to the Scb for the respective file or Mft.  The caller must
          have at least shared access to this Scb.

    Bcb - If specified, this Bcb will be set dirty specifying the Lsn of
          the log record written.

    RedoOperation - One of the log operation codes defined in ntfslog.h.

    RedoBuffer - A pointer to the structure expected for the given Redo operation,
                 as summarized in ntfslog.h.  This pointer should only be
                 omitted if and only if the table in ntfslog.h does not show
                 a log record for this log operation.

    RedoLength - Length of the Redo buffer in bytes.

    UndoOperation - One of the log operation codes defined in ntfslog.h.

                    Must be CompensationLogRecord if logging the Undo of
                    a previous operation, such as during transaction abort.
                    In this case, of course, the Redo information is from
                    the Undo information of the record being undone.  See
                    next parameter.

    UndoBuffer - A pointer to the structure expected for the given Undo operation,
                 as summarized in ntfslog.h.  This pointer should only be
                 omitted if and only if the table in ntfslog.h does not show
                 a log record for this log operation.  If this pointer is
                 identical to RedoBuffer, then UndoLength is ignored and
                 only a single copy of the RedoBuffer is made, but described
                 by both the Redo and Undo portions of the log record.

                 For a compensation log record (UndoOperation ==
                 CompensationLogRecord), this argument must point to the
                 UndoNextLsn of the log record being compensated.

    UndoLength - Length of the Undo buffer in bytes.  Ignored if RedoBuffer ==
                 UndoBuffer.

                 For a compensation log record, this argument must be the length
                 of the original redo record.  (Used during restart).

    StreamOffset - Offset within the stream for the start of the structure being
                   modified (Mft or Index), or simply the stream offset for the start
                   of the update.

    RecordOffset - Byte offset from StreamOffset above to update reference

    AttributeOffset - Offset within a value to which an update applies, if relevant.

    StructureSize - Size of the entire structure being logged.

Return Value:

    The Lsn of the log record written.  For most callers, this status may be ignored,
    because the Lsn is also correctly recorded in the transaction context.

    If an error occurs this procedure will raise.

--*/

{
    LFS_WRITE_ENTRY WriteEntries[3];

    struct {

        NTFS_LOG_RECORD_HEADER LogRecordHeader;
        LCN Runs[PAGE_SIZE/512 - 1];

    } LocalHeader;

    PNTFS_LOG_RECORD_HEADER MyHeader;
    PVCB Vcb;

    LSN UndoNextLsn;
    LSN ReturnLsn;
    PLSN DirtyLsn = NULL;

    ULONG WriteIndex = 0;
    ULONG UndoIndex = 0;
    ULONG RedoIndex = 0;
    LONG UndoBytes = 0;
    LONG UndoAdjustmentForLfs = 0;
    LONG UndoRecords = 0;

    PTRANSACTION_ENTRY TransactionEntry;
    POPEN_ATTRIBUTE_ENTRY OpenAttributeEntry = NULL;
    ULONG OpenAttributeIndex = 0;
    BOOLEAN AttributeTableAcquired = FALSE;
    BOOLEAN TransactionTableAcquired = FALSE;

    ULONG LogClusterCount = ClustersFromBytes( Scb->Vcb, StructureSize );
    VCN LogVcn = LlClustersFromBytesTruncate( Scb->Vcb, StreamOffset );

    PAGED_CODE();

    Vcb = Scb->Vcb;

    //
    //  If the log handle is gone, then we noop this call.
    //

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

        return Li0; //**** LfsZeroLsn;
    }

    DebugTrace( +1, Dbg, ("NtfsWriteLog:\n") );
    DebugTrace( 0, Dbg, ("Scb = %08lx\n", Scb) );
    DebugTrace( 0, Dbg, ("Bcb = %08lx\n", Bcb) );
    DebugTrace( 0, Dbg, ("RedoOperation = %08lx\n", RedoOperation) );
    DebugTrace( 0, Dbg, ("RedoBuffer = %08lx\n", RedoBuffer) );
    DebugTrace( 0, Dbg, ("RedoLength = %08lx\n", RedoLength) );
    DebugTrace( 0, Dbg, ("UndoOperation = %08lx\n", UndoOperation) );
    DebugTrace( 0, Dbg, ("UndoBuffer = %08lx\n", UndoBuffer) );
    DebugTrace( 0, Dbg, ("UndoLength = %08lx\n", UndoLength) );
    DebugTrace( 0, Dbg, ("StreamOffset = %016I64x\n", StreamOffset) );
    DebugTrace( 0, Dbg, ("RecordOffset = %08lx\n", RecordOffset) );
    DebugTrace( 0, Dbg, ("AttributeOffset = %08lx\n", AttributeOffset) );
    DebugTrace( 0, Dbg, ("StructureSize = %08lx\n", StructureSize) );

    //
    //  Check Redo and Undo lengths
    //

    ASSERT(((RedoOperation == UpdateNonresidentValue) && (RedoLength <= PAGE_SIZE))

            ||

           !ARGUMENT_PRESENT(Scb)

            ||

           !ARGUMENT_PRESENT(Bcb)

            ||

           ((Scb->AttributeTypeCode == $INDEX_ALLOCATION) &&
            (RedoLength <= Scb->ScbType.Index.BytesPerIndexBuffer))

            ||

           (RedoLength <= Scb->Vcb->BytesPerFileRecordSegment));

    ASSERT(((UndoOperation == UpdateNonresidentValue) && (UndoLength <= PAGE_SIZE))

            ||

           !ARGUMENT_PRESENT(Scb)

            ||

           !ARGUMENT_PRESENT(Bcb)

            ||

           ((Scb->AttributeTypeCode == $INDEX_ALLOCATION) &&
            (UndoLength <= Scb->ScbType.Index.BytesPerIndexBuffer))

            ||

           (UndoLength <= Scb->Vcb->BytesPerFileRecordSegment)

            ||

           (UndoOperation == CompensationLogRecord));

    //
    //  Initialize local pointers.
    //

    MyHeader = (PNTFS_LOG_RECORD_HEADER)&LocalHeader;

    try {

        //
        //  If the structure size is nonzero, then create an open attribute table
        //  entry.
        //

        if (StructureSize != 0) {

            //
            //  Allocate an entry in the open attribute table and initialize it,
            //  if it does not already exist.  If we subsequently fail, we do
            //  not have to clean this up.  It will go away on the next checkpoint.
            //

            if (Scb->NonpagedScb->OpenAttributeTableIndex == 0) {

                OPEN_ATTRIBUTE_ENTRY LocalOpenEntry;

                NtfsAcquireExclusiveRestartTable( &Vcb->OpenAttributeTable, TRUE );
                AttributeTableAcquired = TRUE;

                //
                //  Only proceed if the OpenAttributeTableIndex is still 0.
                //  We may reach this point for the MftScb.  It may not be
                //  acquired when logging changes to file records.  We will
                //  use the OpenAttributeTable for final synchronization
                //  for the Mft open attribute table entry.
                //

                if (Scb->NonpagedScb->OpenAttributeTableIndex == 0) {

                    //
                    //  Our structures require tables to stay within 64KB, since
                    //  we use USHORT offsets.  Things are getting out of hand
                    //  at this point anyway.  Raise log file full to reset the
                    //  table sizes if we get to this point.
                    //

                    if (SizeOfRestartTable(&Vcb->OpenAttributeTable) > 0xF000) {
                        NtfsRaiseStatus( IrpContext, STATUS_LOG_FILE_FULL, NULL, NULL );
                    }

                    Scb->NonpagedScb->OpenAttributeTableIndex =
                    OpenAttributeIndex = NtfsAllocateRestartTableIndex( &Vcb->OpenAttributeTable );
                    OpenAttributeEntry = GetRestartEntryFromIndex( &Vcb->OpenAttributeTable,
                                                                   OpenAttributeIndex );
                    OpenAttributeEntry->Overlay.Scb = Scb;
                    OpenAttributeEntry->FileReference = Scb->Fcb->FileReference;
                    //  OpenAttributeEntry->LsnOfOpenRecord = ???
                    OpenAttributeEntry->AttributeTypeCode = Scb->AttributeTypeCode;
                    OpenAttributeEntry->AttributeName = Scb->AttributeName;
                    OpenAttributeEntry->AttributeNamePresent = FALSE;
                    if (Scb->AttributeTypeCode == $INDEX_ALLOCATION) {

                        OpenAttributeEntry->BytesPerIndexBuffer = Scb->ScbType.Index.BytesPerIndexBuffer;

                    } else {
                        OpenAttributeEntry->BytesPerIndexBuffer = 0;
                    }

                    RtlMoveMemory( &LocalOpenEntry, OpenAttributeEntry, sizeof(OPEN_ATTRIBUTE_ENTRY) );

                    NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
                    AttributeTableAcquired = FALSE;

                    //
                    //  Now log the new open attribute table entry before goin on,
                    //  to insure that the application of the caller's log record
                    //  will have the information he needs on the attribute.  We will
                    //  use the Undo buffer to convey the attribute name.  We will
                    //  not infinitely recurse, because now this Scb already has an
                    //  open attribute table index.
                    //

                    NtfsWriteLog( IrpContext,
                                  Scb,
                                  NULL,
                                  OpenNonresidentAttribute,
                                  &LocalOpenEntry,
                                  sizeof(OPEN_ATTRIBUTE_ENTRY),
                                  Noop,
                                  Scb->AttributeName.Length != 0 ?
                                    Scb->AttributeName.Buffer : NULL,
                                  Scb->AttributeName.Length,
                                  (LONGLONG)0,
                                  0,
                                  0,
                                  0 );

                } else {

                    NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
                    AttributeTableAcquired = FALSE;
                }
            }
        }

        //
        //  Allocate a transaction ID and initialize it, if it does not already exist.
        //  If we subsequently fail, we clean it up when the current request is
        //  completed.
        //

        if (IrpContext->TransactionId == 0) {

            NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable, TRUE );
            TransactionTableAcquired = TRUE;

            //
            //  Our structures require tables to stay within 64KB, since
            //  we use USHORT offsets.  Things are getting out of hand
            //  at this point anyway.  Raise log file full to reset the
            //  table sizes if we get to this point.
            //

            if (SizeOfRestartTable(&Vcb->TransactionTable) > 0xF000) {
                NtfsRaiseStatus( IrpContext, STATUS_LOG_FILE_FULL, NULL, NULL );
            }

            IrpContext->TransactionId =
              NtfsAllocateRestartTableIndex( &Vcb->TransactionTable );

            ClearFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WROTE_LOG );

            TransactionEntry = (PTRANSACTION_ENTRY)GetRestartEntryFromIndex(
                                &Vcb->TransactionTable,
                                IrpContext->TransactionId );
            TransactionEntry->TransactionState = TransactionActive;
            TransactionEntry->FirstLsn =
            TransactionEntry->PreviousLsn =
            TransactionEntry->UndoNextLsn = Li0; //**** LfsZeroLsn;

            //
            //  Remember that we will need a commit record even if we abort
            //  the transaction.
            //

            TransactionEntry->UndoBytes = QuadAlign( sizeof( NTFS_LOG_RECORD_HEADER ));
            TransactionEntry->UndoRecords = 1;

            NtfsReleaseRestartTable( &Vcb->TransactionTable );
            TransactionTableAcquired = FALSE;

            //
            //  Remember the space for the commit record in our Lfs adjustment.
            //

            UndoAdjustmentForLfs += QuadAlign( sizeof( NTFS_LOG_RECORD_HEADER ));

            //
            //  If there is an undo operation for this log record, we reserve
            //  the space for another Lfs log record.
            //

            if (UndoOperation != Noop) {
                UndoAdjustmentForLfs += Vcb->LogHeaderReservation;
            }
        }

        //
        //  At least for now, assume update is contained in one physical page.
        //

        //ASSERT( (StructureSize == 0) || (StructureSize <= PAGE_SIZE) );

        //
        //  If there isn't enough room for this structure on the stack, we
        //  need to allocate an auxilary buffer.
        //

        if (LogClusterCount > (PAGE_SIZE / 512)) {

            MyHeader = (PNTFS_LOG_RECORD_HEADER)
                       NtfsAllocatePool(PagedPool, sizeof( NTFS_LOG_RECORD_HEADER )
                                              + (LogClusterCount - 1) * sizeof( LCN ));

        }

        //
        //  Now fill in the WriteEntries array and the log record header.
        //

        WriteEntries[0].Buffer = (PVOID)MyHeader;
        WriteEntries[0].ByteLength = sizeof(NTFS_LOG_RECORD_HEADER);
        WriteIndex += 1;

        //
        //  Lookup the Runs for this log record
        //

        MyHeader->LcnsToFollow = (USHORT)LogClusterCount;

        if (LogClusterCount != 0) {
            LookupLcns( IrpContext,
                        Scb,
                        LogVcn,
                        LogClusterCount,
                        TRUE,
                        &MyHeader->LcnsForPage[0] );

            WriteEntries[0].ByteLength += (LogClusterCount - 1) * sizeof(LCN);
        }

        //
        //  If there is a Redo buffer, fill in its write entry.
        //

        if (RedoLength != 0) {

            WriteEntries[1].Buffer = RedoBuffer;
            WriteEntries[1].ByteLength = RedoLength;
            UndoIndex = RedoIndex = WriteIndex;
            WriteIndex += 1;
        }

        //
        //  If there is an undo buffer, and it is at a different address than
        //  the redo buffer, then fill in its write entry.
        //

        if ((RedoBuffer != UndoBuffer) && (UndoLength != 0) &&
            (UndoOperation != CompensationLogRecord)) {

            WriteEntries[WriteIndex].Buffer = UndoBuffer;
            WriteEntries[WriteIndex].ByteLength = UndoLength;
            UndoIndex = WriteIndex;
            WriteIndex += 1;
        }

        //
        //  Now fill in the rest of the header.  Assume Redo and Undo buffer is
        //  the same, then fix them up if they are not.
        //

        MyHeader->RedoOperation = (USHORT)RedoOperation;
        MyHeader->UndoOperation = (USHORT)UndoOperation;
        MyHeader->RedoOffset = (USHORT)WriteEntries[0].ByteLength;
        MyHeader->RedoLength = (USHORT)RedoLength;
        MyHeader->UndoOffset = MyHeader->RedoOffset;
        if (RedoBuffer != UndoBuffer) {
            MyHeader->UndoOffset += (USHORT)QuadAlign(MyHeader->RedoLength);
        }
        MyHeader->UndoLength = (USHORT)UndoLength;
        MyHeader->TargetAttribute = (USHORT)Scb->NonpagedScb->OpenAttributeTableIndex;
        MyHeader->RecordOffset = (USHORT)RecordOffset;
        MyHeader->AttributeOffset = (USHORT)AttributeOffset;
        MyHeader->Reserved = 0;

        MyHeader->TargetVcn = LogVcn;
        MyHeader->ClusterBlockOffset = (USHORT) LogBlocksFromBytesTruncate( ClusterOffset( Vcb, StreamOffset ));

        //
        //  Finally, get our current transaction entry and call Lfs.  We acquire
        //  the transaction table exclusive both to synchronize the Lsn updates
        //  on return from Lfs, and also to mark the Bcb dirty before any more
        //  log records are written.
        //
        //  If we do not do serialize the LfsWrite and CcSetDirtyPinnedData, here is
        //  what can happen:
        //
        //      We log an update for a page and get an Lsn back
        //
        //          Another thread writes a start of checkpoint record
        //          This thread then collects all of the dirty pages at that time
        //          Sometime it writes the dirty page table
        //
        //      The former thread which had been preempted, now sets the Bcb dirty
        //
        //  If we crash at this time, the page we updated is not in the dirty page
        //  table of the checkpoint, and it its update record is also not seen since
        //  it was written before the start of the checkpoint!
        //
        //  Note however, since the page being updated is pinned and cannot be written,
        //  updating the Lsn in the page may simply be considered part of the update.
        //  Whoever is doing this update (to the Mft or an Index buffer), must have the
        //  Mft or Index acquired exclusive anyway.
        //

        NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable, TRUE );
        TransactionTableAcquired = TRUE;

        TransactionEntry = (PTRANSACTION_ENTRY)GetRestartEntryFromIndex(
                            &Vcb->TransactionTable,
                            IrpContext->TransactionId );

        //
        //  Set up the UndoNextLsn.  If this is a normal log record, then use
        //  the UndoNextLsn stored in the transaction entry; otherwise, use
        //  the one passed in as the Undo buffer.
        //

        if (UndoOperation != CompensationLogRecord) {

            UndoNextLsn = TransactionEntry->UndoNextLsn;

            //
            //  If there is undo information, calculate the number to pass to Lfs
            //  for undo bytes to reserve.
            //

            if (UndoOperation != Noop) {

                UndoBytes += QuadAlign(WriteEntries[0].ByteLength);

                if (UndoIndex != 0) {

                    UndoBytes += QuadAlign(WriteEntries[UndoIndex].ByteLength);
                }

                UndoRecords += 1;
            }

        } else {

            UndoNextLsn = *(PLSN)UndoBuffer;

            //
            //  We can reduce our Undo requirements, by the Redo data being
            //  logged.  This is either an abort record for a previous action
            //  or a commit record.  If it is a commit record we accounted
            //  for it above on the first NtfsWriteLog, and NtfsCommitTransaction
            //  will adjust for the rest.
            //

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

                UndoBytes -= QuadAlign(WriteEntries[0].ByteLength);

                if (RedoIndex != 0) {

                    UndoBytes -= QuadAlign(WriteEntries[RedoIndex].ByteLength);
                }

                UndoRecords -= 1;
            }
        }

#ifdef NTFSDBG
        //
        //  Perform log-file-full fail checking.  We do not perform this check if
        //  we are writing an undo record (since we are guaranteed space to undo
        //  things).
        //

        if (UndoOperation != CompensationLogRecord &&
            (IrpContext->MajorFunction != IRP_MJ_FILE_SYSTEM_CONTROL ||
             IrpContext->MinorFunction != IRP_MN_MOUNT_VOLUME)) {
            //
            //  There should never be any log records during clean checkpoints
            //

            ASSERT( !FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_CHECKPOINT_ACTIVE ));

            LogFileFullFailCheck( IrpContext );
        }
#endif

        //
        //  Call Lfs to write the record.
        //

        LfsWrite( Vcb->LogHandle,
                  WriteIndex,
                  &WriteEntries[0],
                  LfsClientRecord,
                  &IrpContext->TransactionId,
                  UndoNextLsn,
                  TransactionEntry->PreviousLsn,
                  UndoBytes + UndoAdjustmentForLfs,
                  &ReturnLsn );

        //
        //  Now that we are successful, update the transaction entry appropriately.
        //

        TransactionEntry->UndoBytes += UndoBytes;
        TransactionEntry->UndoRecords += UndoRecords;
        TransactionEntry->PreviousLsn = ReturnLsn;

        //
        //  The UndoNextLsn for the transaction depends on whether we are
        //  doing a compensation log record or not.
        //

        if (UndoOperation != CompensationLogRecord) {
            TransactionEntry->UndoNextLsn = ReturnLsn;
        } else {
            TransactionEntry->UndoNextLsn = UndoNextLsn;
        }

        //
        //  If this is the first Lsn, then we have to update that as
        //  well.
        //

        if (TransactionEntry->FirstLsn.QuadPart == 0) {

            TransactionEntry->FirstLsn = ReturnLsn;
        }

        //
        //  Set to use this Lsn when marking dirty below
        //

        DirtyLsn = &ReturnLsn;

        //
        //  Set the flag in the Irp Context which indicates we wrote
        //  a log record to disk.
        //

        SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WROTE_LOG );

    } finally {

        DebugUnwind( NtfsWriteLog );

        //
        //  Now set the Bcb dirty if specified.  We want to set it no matter
        //  what happens, because our caller has modified the buffer and is
        //  counting on us to call the Cache Manager.
        //

        if (ARGUMENT_PRESENT(Bcb)) {

            TIMER_STATUS TimerStatus;

            CcSetDirtyPinnedData( Bcb, DirtyLsn );

            //
            //  Synchronize with the checkpoint timer and other instances of this routine.
            //
            //  Perform an interlocked exchange to indicate that a timer is being set.
            //
            //  If the previous value indicates that no timer was set, then we
            //  enable the volume checkpoint timer.  This will guarantee that a checkpoint
            //  will occur to flush out the dirty Bcb data.
            //
            //  If the timer was set previously, then it is guaranteed that a checkpoint
            //  will occur without this routine having to reenable the timer.
            //
            //  If the timer and checkpoint occurred between the dirtying of the Bcb and
            //  the setting of the timer status, then we will be queueing a single extra
            //  checkpoint on a clean volume.  This is not considered harmful.
            //

            //
            //  Atomically set the timer status to indicate a timer is being set and
            //  retrieve the previous value.
            //

            TimerStatus = InterlockedExchange( &NtfsData.TimerStatus, TIMER_SET );

            //
            //  If the timer is not currently set then we must start the checkpoint timer
            //  to make sure the above dirtying is flushed out.
            //

            if (TimerStatus == TIMER_NOT_SET) {

                LONGLONG FiveSecondsFromNow = -5*1000*1000*10;

                KeSetTimer( &NtfsData.VolumeCheckpointTimer,
                            *(PLARGE_INTEGER)&FiveSecondsFromNow,
                            &NtfsData.VolumeCheckpointDpc );
            }
        }

        if (TransactionTableAcquired) {
            NtfsReleaseRestartTable( &Vcb->TransactionTable );
        }

        if (AttributeTableAcquired) {
            NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
        }

        if (MyHeader != (PNTFS_LOG_RECORD_HEADER)&LocalHeader) {

            NtfsFreePool( MyHeader );
        }
    }

    DebugTrace( -1, Dbg, ("NtfsWriteLog -> %016I64x\n", ReturnLsn ) );

    return ReturnLsn;
}


VOID
NtfsCheckpointVolume (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN BOOLEAN OwnsCheckpoint,
    IN BOOLEAN CleanVolume,
    IN BOOLEAN FlushVolume,
    IN LSN LastKnownLsn
    )

/*++

Routine Description:

    This routine is called periodically to perform a checkpoint on the volume
    with respect to the log file.  The checkpoint dumps a bunch of log file
    state information to the log file, and finally writes a summary of the
    dumped information in its Restart Area.

    This checkpoint dumps the following:

        Open Attribute Table
        (all of the attribute names for the Attribute Table)
        Dirty Pages Table
        Transaction Table

Arguments:

    Vcb - Pointer to the Vcb on which the checkpoint is to occur.

    OwnsCheckpoint - TRUE if the caller has already taken steps to insure
        that he may proceed with the checkpointing.  In this case we
        don't do any checks for other checkpoints and don't clear the
        checkpoint flag or notify any waiting checkpoint threads.

    CleanVolume - TRUE if the caller wishes to clean the volume before doing
        the checkpoint, or FALSE for a normal periodic checkpoint.

    FlushVolume - Applies only if CleanVolume is TRUE.  This indicates if we should
        should flush the volume or only Lsn streams.

    LastKnownLsn - Applies only if CleanVolume is TRUE.  Only perform the
        clean checkpoint if this value is the same as the last restart area
        in the Vcb.  This will prevent us from doing unecesary clean
        checkpoints.

Return Value:

    None

--*/

{
    RESTART_AREA RestartArea;
    RESTART_POINTERS DirtyPages;
    RESTART_POINTERS Pointers;
    LSN BaseLsn;
    PATTRIBUTE_NAME_ENTRY NamesBuffer = NULL;
    PTRANSACTION_ENTRY TransactionEntry;
    BOOLEAN DirtyPageTableInitialized = FALSE;
    BOOLEAN OpenAttributeTableAcquired = FALSE;
    BOOLEAN TransactionTableAcquired = FALSE;
    LSN OldestDirtyPageLsn = Li0;
    BOOLEAN AcquireFiles = FALSE;
    BOOLEAN BitmapAcquired = FALSE;
    BOOLEAN PostDefrag = FALSE;
    KPRIORITY PreviousPriority;
    BOOLEAN RestorePreviousPriority = FALSE;

    PAGED_CODE();

    DebugTrace( +1, Dbg, ("NtfsCheckpointVolume:\n") );
    DebugTrace( 0, Dbg, ("Vcb = %08lx\n", Vcb) );

    if (!OwnsCheckpoint) {

        //
        //  Acquire the checkpoint event.
        //

        NtfsAcquireCheckpoint( IrpContext, Vcb );

        //
        //  We will want to post a defrag if defragging is permitted and enabled
        //  and we have begun the defrag operation or have excess mapping.
        //  If the defrag hasn't been triggered then check the Mft free
        //  space.  We can skip defragging if a defrag operation is
        //  currently active.
        //

        if (!CleanVolume
            && FlagOn( Vcb->MftDefragState, VCB_MFT_DEFRAG_PERMITTED )
            && FlagOn( Vcb->MftDefragState, VCB_MFT_DEFRAG_ENABLED )
            && !FlagOn( Vcb->MftDefragState, VCB_MFT_DEFRAG_ACTIVE )) {

            if (FlagOn( Vcb->MftDefragState,
                        VCB_MFT_DEFRAG_TRIGGERED | VCB_MFT_DEFRAG_EXCESS_MAP )) {

                PostDefrag = TRUE;

            } else {

                NtfsCheckForDefrag( Vcb );

                if (FlagOn( Vcb->MftDefragState, VCB_MFT_DEFRAG_TRIGGERED )) {

                    PostDefrag = TRUE;

                } else {

                    ClearFlag( Vcb->MftDefragState, VCB_MFT_DEFRAG_ENABLED );
                }
            }
        }

        //
        //  If a checkpoint is already active, we either have to get out,
        //  or wait for it.
        //

        while (FlagOn( Vcb->CheckpointFlags, VCB_CHECKPOINT_IN_PROGRESS )) {

            //
            //  Release the checkpoint event because we cannot checkpoint now.
            //

            NtfsReleaseCheckpoint( IrpContext, Vcb );

            if (CleanVolume) {

                NtfsWaitOnCheckpointNotify( IrpContext, Vcb );

                NtfsAcquireCheckpoint( IrpContext, Vcb );

            } else {

                return;
            }
        }

        //
        //  We now have the checkpoint event.  Check if there is still
        //  a need to perform the checkpoint.
        //

        if (CleanVolume &&
            LastKnownLsn.QuadPart != Vcb->LastRestartArea.QuadPart) {

            NtfsReleaseCheckpoint( IrpContext, Vcb );
                return;
        }

        SetFlag( Vcb->CheckpointFlags, VCB_CHECKPOINT_IN_PROGRESS );
        NtfsResetCheckpointNotify( IrpContext, Vcb );
        NtfsReleaseCheckpoint( IrpContext, Vcb );

        //
        //  If this is a clean volume checkpoint then boost the priority of
        //  this thread.
        //

        if (CleanVolume) {

            PreviousPriority = KeSetPriorityThread( &PsGetCurrentThread()->Tcb,
                                                    LOW_REALTIME_PRIORITY );

            if (PreviousPriority != LOW_REALTIME_PRIORITY) {

                RestorePreviousPriority = TRUE;
            }
        }
    }

    RtlZeroMemory( &RestartArea, sizeof(RESTART_AREA) );
    RtlZeroMemory( &DirtyPages, sizeof(RESTART_POINTERS) );

    //
    //  Insure cleanup on the way out
    //

    try {

        POPEN_ATTRIBUTE_ENTRY AttributeEntry;
        ULONG NameBytes = 0;

        //
        //  Now remember the current "last Lsn" value as the start of
        //  our checkpoint.  We acquire the transaction table to capture
        //  this value to synchronize with threads who are writing log
        //  records and setting pages dirty as atomic actions.
        //

        NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable, TRUE );
        BaseLsn =
        RestartArea.StartOfCheckpoint = LfsQueryLastLsn( Vcb->LogHandle );
        NtfsReleaseRestartTable( &Vcb->TransactionTable );


        ASSERT( (RestartArea.StartOfCheckpoint.QuadPart != 0) ||
                FlagOn(Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN) );

        //
        //  If the last checkpoint was completely clean, and no one has
        //  written to the log since then, we can just return.
        //

        if (FlagOn( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN )

                &&

            (RestartArea.StartOfCheckpoint.QuadPart == Vcb->EndOfLastCheckpoint.QuadPart)

                &&

            !CleanVolume) {

            //
            //  Let's take this opportunity to shrink the Open Attribute and Transaction
            //  table back if they have gotten large.
            //

            //
            //  First the Open Attribute Table
            //

            NtfsAcquireExclusiveRestartTable( &Vcb->OpenAttributeTable, TRUE );
            OpenAttributeTableAcquired = TRUE;

            if (IsRestartTableEmpty(&Vcb->OpenAttributeTable)

                    &&

                (Vcb->OpenAttributeTable.Table->NumberEntries >
                 HIGHWATER_ATTRIBUTE_COUNT)) {

                //
                //  Initialize first in case we get an allocation failure.
                //

                InitializeNewTable( sizeof(OPEN_ATTRIBUTE_ENTRY),
                                    INITIAL_NUMBER_ATTRIBUTES,
                                    &Pointers );

                NtfsFreePool( Vcb->OpenAttributeTable.Table );
                Vcb->OpenAttributeTable.Table = Pointers.Table;
            }

            NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
            OpenAttributeTableAcquired = FALSE;

            //
            //  Now check the transaction table (freeing in the finally clause).
            //

            NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable, TRUE );
            TransactionTableAcquired = TRUE;

            if (IsRestartTableEmpty(&Vcb->TransactionTable)

                    &&

                (Vcb->TransactionTable.Table->NumberEntries >
                 HIGHWATER_TRANSACTION_COUNT)) {

                //
                //  Initialize first in case we get an allocation failure.
                //

                InitializeNewTable( sizeof(TRANSACTION_ENTRY),
                                    INITIAL_NUMBER_TRANSACTIONS,
                                    &Pointers );

                NtfsFreePool( Vcb->TransactionTable.Table );
                Vcb->TransactionTable.Table = Pointers.Table;
            }

            try_return( NOTHING );
        }

        //
        //  Flush any dangling dirty pages from before the last restart.
        //  Note that it is arbitrary what Lsn we flush to here, and, in fact,
        //  it is not absolutely required that we flush anywhere at all - we
        //  could actually rely on the Lazy Writer.  All we are trying to do
        //  is reduce the amount of work that we will have to do at Restart,
        //  by not forcing ourselves to have to go too far back in the log.
        //  Presumably this can only happen for some reason the system is
        //  starting to produce dirty pages faster than the lazy writer is
        //  writing them.
        //
        //  (We may wish to play with taking this call out...)
        //
        //  This may be an appropriate place to worry about this, but, then
        //  again, the Lazy Writer is using (currently) five threads.  It may
        //  not be appropriate to hold up this one thread doing the checkpoint
        //  if the Lazy Writer is getting behind.  How many dirty pages we
        //  can even have is limited by the size of memory, so if the log file
        //  is large enough, this may not be an issue.  It seems kind of nice
        //  to just let the Lazy Writer keep writing dirty pages as he does
        //  now.
        //
        //  if (!FlagOn(Vcb->VcbState, VCB_STATE_LAST_CHECKPOINT_CLEAN)) {
        //      CcFlushPagesToLsn( Vcb->LogHandle, &Vcb->LastRestartArea );
        //  }
        //

        //
        //  Now we must clean the volume here if that is what the caller wants.
        //

        if (CleanVolume) {

            NtfsCleanCheckpoints += 1;

            //
            //  Lock down the volume if this is a clean checkpoint.
            //

            NtfsAcquireAllFiles( IrpContext, Vcb, FlushVolume, FALSE );

#ifdef NTFSDBG
            ASSERT( !FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_CHECKPOINT_ACTIVE ));
            DebugDoit( SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_CHECKPOINT_ACTIVE ));
#endif  //  NTFSDBG


            AcquireFiles = TRUE;

            //
            //  Now we will acquire the Open Attribute Table exclusive to delete
            //  all of the entries, since we want to write a clean checkpoint.
            //  This is OK, since we have the global resource and nothing else
            //  can be going on.  (Similarly we are writing an empty transaction
            //  table, while in fact we will be the only transaction, but there
            //  is no need to capture our guy, nor explicitly empty this table.)
            //

            NtfsAcquireExclusiveRestartTable( &Vcb->OpenAttributeTable, TRUE );
            OpenAttributeTableAcquired = TRUE;

            //
            //  First reclaim the page we have reserved in the undo total, to
            //  guarantee that we can flush the log file.
            //

            LfsResetUndoTotal( Vcb->LogHandle, 1, -(LONG)(2 * PAGE_SIZE) );

            if (FlushVolume) {

                (VOID)NtfsFlushVolume( IrpContext, Vcb, TRUE, FALSE, FALSE, FALSE );

            } else {

                NtfsFlushLsnStreams( Vcb );
            }

            SetFlag( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN );

            //
            //  Loop through to deallocate all of the open attribute entries.  Any
            //  that point to an Scb need to get the index in the Scb zeroed.  If
            //  they do not point to an Scb, we have to see if there is a name to
            //  free.
            //

            AttributeEntry = NtfsGetFirstRestartTable( &Vcb->OpenAttributeTable );

            while (AttributeEntry != NULL) {

                ULONG Index;

                if (AttributeEntry->Overlay.Scb != NULL) {

                    AttributeEntry->Overlay.Scb->NonpagedScb->OpenAttributeTableIndex = 0;

                 } else {

                    //
                    //  Delete its name, if it has one.  Check that we aren't
                    //  using the hardcode $I30 name.
                    //

                    if ((AttributeEntry->AttributeName.Buffer != NULL) &&
                        (AttributeEntry->AttributeName.Buffer != NtfsFileNameIndexName)) {

                        NtfsFreePool( AttributeEntry->AttributeName.Buffer );
                    }
                }

                //
                //  Get the index for the entry.
                //

                Index = GetIndexFromRestartEntry( &Vcb->OpenAttributeTable,
                                                  AttributeEntry );

                NtfsFreeRestartTableIndex( &Vcb->OpenAttributeTable,
                                           Index );

                AttributeEntry = NtfsGetNextRestartTable( &Vcb->OpenAttributeTable,
                                                          AttributeEntry );
            }

            //
            //  Initialize first in case we get an allocation failure.
            //

            ASSERT(IsRestartTableEmpty(&Vcb->OpenAttributeTable));

            InitializeNewTable( sizeof(OPEN_ATTRIBUTE_ENTRY),
                                INITIAL_NUMBER_ATTRIBUTES,
                                &Pointers );

            NtfsFreePool( Vcb->OpenAttributeTable.Table );
            Vcb->OpenAttributeTable.Table = Pointers.Table;

            //
            //  Initialize first in case we get an allocation failure.
            //  Make sure we commit the current transaction.
            //

            NtfsCommitCurrentTransaction( IrpContext );

            ASSERT(IsRestartTableEmpty(&Vcb->TransactionTable));

            InitializeNewTable( sizeof(TRANSACTION_ENTRY),
                                INITIAL_NUMBER_TRANSACTIONS,
                                &Pointers );

            NtfsFreePool( Vcb->TransactionTable.Table );
            Vcb->TransactionTable.Table = Pointers.Table;

            //
            //  Make sure we do not process any log file before the restart
            //  area, because we did not dump the open attribute table.
            //

            RestartArea.StartOfCheckpoint = LfsQueryLastLsn( Vcb->LogHandle );

        //
        //  Save some work if this is a clean checkpoint
        //

        } else {

            PDIRTY_PAGE_ENTRY DirtyPage;
            POPEN_ATTRIBUTE_ENTRY OpenEntry;
            ULONG JustMe = 0;

            //
            //  Now we construct the dirty page table by calling the Cache Manager.
            //  For each dirty page on files tagged with our log handle, he will
            //  call us back at our DirtyPageRoutine.  We will allocate the initial
            //  Dirty Page Table, but we will let the call back routine grow it as
            //  necessary.
            //

            NtfsInitializeRestartTable( sizeof(DIRTY_PAGE_ENTRY) +
                                          (Vcb->ClustersPerPage - 1) * sizeof(LCN),
                                        32,
                                        &DirtyPages );

            NtfsAcquireExclusiveRestartTable( &DirtyPages, TRUE );

            DirtyPageTableInitialized = TRUE;

            //
            //  Now we will acquire the Open Attribute Table shared to freeze changes.
            //

            NtfsAcquireExclusiveRestartTable( &Vcb->OpenAttributeTable, TRUE );
            OpenAttributeTableAcquired = TRUE;

            //
            //  Loop to see how much we will have to allocate for attribute names.
            //

            AttributeEntry = NtfsGetFirstRestartTable( &Vcb->OpenAttributeTable );

            while (AttributeEntry != NULL) {

                //
                //  This checks for one type of aliasing.
                //

                //  ASSERT( (AttributeEntry->Overlay.Scb == NULL) ||
                //          (AttributeEntry->Overlay.Scb->OpenAttributeTableIndex ==
                //           GetIndexFromRestartEntry( &Vcb->OpenAttributeTable,
                //                                    AttributeEntry )));

                //
                //  Clear the DirtyPageSeen flag prior to collecting the dirty pages,
                //  to help us figure out which Open Attribute Entries we still need.
                //

                AttributeEntry->DirtyPagesSeen = FALSE;

                if (AttributeEntry->AttributeName.Length != 0) {

                    //
                    //  Add to our name total, the size of an Attribute Entry,
                    //  which includes the size of the terminating UNICODE_NULL.
                    //

                    NameBytes += AttributeEntry->AttributeName.Length +
                                 sizeof(ATTRIBUTE_NAME_ENTRY);
                }

                AttributeEntry = NtfsGetNextRestartTable( &Vcb->OpenAttributeTable,
                                                          AttributeEntry );
            }

            //
            //  Now call the Cache Manager to give us all of our dirty pages
            //  via the DirtyPageRoutine callback, and remember what the oldest
            //  Lsn is for a dirty page.
            //

            OldestDirtyPageLsn = CcGetDirtyPages( Vcb->LogHandle,
                                                  &DirtyPageRoutine,
                                                  (PVOID)IrpContext,
                                                  (PVOID)&DirtyPages );

            if (OldestDirtyPageLsn.QuadPart != 0 &&
                OldestDirtyPageLsn.QuadPart < Vcb->LastBaseLsn.QuadPart) {

                OldestDirtyPageLsn = Vcb->LastBaseLsn;
            }

            //
            //  Now loop through the dirty page table to extract all of the Vcn/Lcn
            //  Mapping that we have, and insert it into the appropriate Scb.
            //

            DirtyPage = NtfsGetFirstRestartTable( &DirtyPages );

            //
            //  The dirty page routine is called while holding spin locks,
            //  so it cannot take page faults.  Thus we must scan the dirty
            //  page table we just built and fill in the Lcns here.
            //

            while (DirtyPage != NULL) {

                PSCB Scb;

                OpenEntry = GetRestartEntryFromIndex( &Vcb->OpenAttributeTable,
                                                      DirtyPage->TargetAttribute );

                ASSERT(IsRestartTableEntryAllocated(OpenEntry));

                ASSERT( DirtyPage->OldestLsn.QuadPart >= Vcb->LastBaseLsn.QuadPart );

                Scb = OpenEntry->Overlay.Scb;

                //
                //  If we have Lcn's then look them up.
                //

                if (DirtyPage->LcnsToFollow != 0) {

                    LookupLcns( IrpContext,
                                Scb,
                                DirtyPage->Vcn,
                                DirtyPage->LcnsToFollow,
                                FALSE,
                                &DirtyPage->LcnsForPage[0] );

                //
                //  Other free this dirty page entry.
                //

                } else {

                    NtfsFreeRestartTableIndex( &DirtyPages,
                                               GetIndexFromRestartEntry( &DirtyPages,
                                                                         DirtyPage ));
                }

                //
                //  Point to next entry in table, or NULL.
                //

                DirtyPage = NtfsGetNextRestartTable( &DirtyPages,
                                                     DirtyPage );
            }

            //
            //  If there were any names, then allocate space for them and copy
            //  them out.
            //

            if (NameBytes != 0) {

                PATTRIBUTE_NAME_ENTRY Name;

                //
                //  Allocate the buffer, with space for two terminating 0's on
                //  the end.
                //

                NameBytes += 4;
                Name =
                NamesBuffer = NtfsAllocatePool( NonPagedPool, NameBytes );

                //
                //  Now loop to copy the names.
                //

                AttributeEntry = NtfsGetFirstRestartTable( &Vcb->OpenAttributeTable );

                while (AttributeEntry != NULL) {

                    //
                    //  Free the Open Attribute Entry if there were no
                    //  dirty pages and the Scb is gone.  This is the only
                    //  place they are deleted.  (Yes, I know we allocated
                    //  space for its name, but I didn't want to make three
                    //  passes through the open attribute table.  Permeter
                    //  is running as we speak, and showing 407 open files
                    //  on NT/IDW5.)
                    //

                    if (!AttributeEntry->DirtyPagesSeen

                            &&

                        (AttributeEntry->Overlay.Scb == NULL)) {

                        ULONG Index;

                        //
                        //  Get the index for the entry.
                        //

                        Index = GetIndexFromRestartEntry( &Vcb->OpenAttributeTable,
                                                          AttributeEntry );

                        //
                        //  Delete its name and free it up.
                        //

                        if ((AttributeEntry->AttributeName.Buffer != NULL) &&
                            (AttributeEntry->AttributeName.Buffer != NtfsFileNameIndexName)) {

                            NtfsFreePool( AttributeEntry->AttributeName.Buffer );
                        }

                        NtfsFreeRestartTableIndex( &Vcb->OpenAttributeTable,
                                                   Index );

                    //
                    //  Otherwise, if we are not deleting it, we have to
                    //  copy its name into the buffer we allocated.
                    //

                    } else if (AttributeEntry->AttributeName.Length != 0) {

                        //
                        //  Prefix each name in the buffer with the attribute index
                        //  and name length.
                        //

                        Name->Index = (USHORT)GetIndexFromRestartEntry( &Vcb->OpenAttributeTable,
                                                                        AttributeEntry );
                        Name->NameLength = AttributeEntry->AttributeName.Length;
                        RtlMoveMemory( &Name->Name[0],
                                       AttributeEntry->AttributeName.Buffer,
                                       AttributeEntry->AttributeName.Length );

                        Name->Name[Name->NameLength/2] = 0;

                        Name = (PATTRIBUTE_NAME_ENTRY)((PCHAR)Name +
                                                       sizeof(ATTRIBUTE_NAME_ENTRY) +
                                                       Name->NameLength);

                        ASSERT( (PCHAR)Name <= ((PCHAR)NamesBuffer + NameBytes - 4) );
                    }

                    AttributeEntry = NtfsGetNextRestartTable( &Vcb->OpenAttributeTable,
                                                              AttributeEntry );
                }

                //
                //  Terminate the Names Buffer.
                //

                Name->Index = 0;
                Name->NameLength = 0;
            }

            //
            //  Now write all of the non-empty tables to the log.
            //

            //
            //  Write the Open Attribute Table
            //

            if (!IsRestartTableEmpty(&Vcb->OpenAttributeTable)) {
                RestartArea.OpenAttributeTableLsn =
                NtfsWriteLog( IrpContext,
                              Vcb->MftScb,
                              NULL,
                              OpenAttributeTableDump,
                              Vcb->OpenAttributeTable.Table,
                              SizeOfRestartTable(&Vcb->OpenAttributeTable),
                              Noop,
                              NULL,
                              0,
                              (LONGLONG)0,
                              0,
                              0,
                              0 );

                RestartArea.OpenAttributeTableLength =
                  SizeOfRestartTable(&Vcb->OpenAttributeTable);
                JustMe = 1;
            }

            NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
            OpenAttributeTableAcquired = FALSE;

            //
            //  Write the Open Attribute Names
            //

            if (NameBytes != 0) {
                RestartArea.AttributeNamesLsn =
                NtfsWriteLog( IrpContext,
                              Vcb->MftScb,
                              NULL,
                              AttributeNamesDump,
                              NamesBuffer,
                              NameBytes,
                              Noop,
                              NULL,
                              0,
                              (LONGLONG)0,
                              0,
                              0,
                              0 );

                RestartArea.AttributeNamesLength = NameBytes;
                JustMe = 1;
            }

            //
            //  Write the Dirty Page Table
            //

            if (!IsRestartTableEmpty(&DirtyPages)) {
                RestartArea.DirtyPageTableLsn =
                NtfsWriteLog( IrpContext,
                              Vcb->MftScb,
                              NULL,
                              DirtyPageTableDump,
                              DirtyPages.Table,
                              SizeOfRestartTable(&DirtyPages),
                              Noop,
                              NULL,
                              0,
                              (LONGLONG)0,
                              0,
                              0,
                              0 );

                RestartArea.DirtyPageTableLength = SizeOfRestartTable(&DirtyPages);
                JustMe = 1;
            }

            //
            //  Write the Transaction Table if there is more than just us.  We
            //  are a transaction if we wrote any log records above.
            //

            NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable, TRUE );
            TransactionTableAcquired = TRUE;

            //
            //  Assumee will want to do at least one more checkpoint.
            //

            ClearFlag( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN );

            if ((ULONG)Vcb->TransactionTable.Table->NumberAllocated > JustMe) {
                RestartArea.TransactionTableLsn =
                NtfsWriteLog( IrpContext,
                              Vcb->MftScb,
                              NULL,
                              TransactionTableDump,
                              Vcb->TransactionTable.Table,
                              SizeOfRestartTable(&Vcb->TransactionTable),
                              Noop,
                              NULL,
                              0,
                              (LONGLONG)0,
                              0,
                              0,
                              0 );

                RestartArea.TransactionTableLength =
                  SizeOfRestartTable(&Vcb->TransactionTable);

                //
                //  Loop to see if the oldest Lsn comes from the transaction table.
                //

                TransactionEntry = NtfsGetFirstRestartTable( &Vcb->TransactionTable );

                while (TransactionEntry != NULL) {
                    if ((TransactionEntry->FirstLsn.QuadPart != 0)

                            &&

                        (TransactionEntry->FirstLsn.QuadPart < BaseLsn.QuadPart)) {

                        BaseLsn = TransactionEntry->FirstLsn;
                    }

                    TransactionEntry = NtfsGetNextRestartTable( &Vcb->TransactionTable,
                                                                TransactionEntry );
                }

            //
            //  If the transaction table is otherwise empty, then this is a good
            //  time to reset our totals with Lfs, in case our counts get off a bit.
            //

            } else {

                //
                //  If we are a transaction, then we have to add in our counts.
                //

                if (IrpContext->TransactionId != 0) {

                    TransactionEntry = (PTRANSACTION_ENTRY)GetRestartEntryFromIndex(
                                        &Vcb->TransactionTable, IrpContext->TransactionId );

                    LfsResetUndoTotal( Vcb->LogHandle,
                                       TransactionEntry->UndoRecords + 2,
                                       TransactionEntry->UndoBytes +
                                         QuadAlign(sizeof(RESTART_AREA)) + (2 * PAGE_SIZE) );

                //
                //  Otherwise, we reset to our "idle" requirements.
                //

                } else {
                    LfsResetUndoTotal( Vcb->LogHandle,
                                       2,
                                       QuadAlign(sizeof(RESTART_AREA)) + (2 * PAGE_SIZE) );
                }

                //
                //  If the DirtyPage table is entry then mark this as a clean checkpoint.
                //

                if (IsRestartTableEmpty( &DirtyPages )) {

                    SetFlag( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN );
                }
            }

            NtfsReleaseRestartTable( &Vcb->TransactionTable );
            TransactionTableAcquired = FALSE;
        }

        //
        //  So far BaseLsn holds the minimum of the start Lsn for the checkpoint,
        //  or any of the FirstLsn fields for active transactions.  Now we see
        //  if the oldest Lsn we need in the log should actually come from the
        //  oldest page in the dirty page table.
        //

        if ((OldestDirtyPageLsn.QuadPart != 0)

                &&

            (OldestDirtyPageLsn.QuadPart < BaseLsn.QuadPart)) {

            BaseLsn = OldestDirtyPageLsn;
        }

        //
        //  Finally, write our Restart Area to describe all of the above, and
        //  give Lfs our new BaseLsn.
        //

        Vcb->LastBaseLsn = Vcb->LastRestartArea = BaseLsn;
        LfsWriteRestartArea( Vcb->LogHandle,
                             sizeof(RESTART_AREA),
                             &RestartArea,
                             &Vcb->LastRestartArea );

        //
        //  If this is a clean checkpoint then initialize our reserved area.
        //

        if (CleanVolume) {

            LfsResetUndoTotal( Vcb->LogHandle, 2, QuadAlign(sizeof(RESTART_AREA)) + (2 * PAGE_SIZE) );
        }

        //
        //  Now remember where the log file is at now, so we know when to
        //  go idle above.
        //

        Vcb->EndOfLastCheckpoint = LfsQueryLastLsn( Vcb->LogHandle );

        //
        //  Now we want to check if we can release any of the clusters in the
        //  deallocated cluster arrays.  We know we can look at the
        //  fields in the PriorDeallocatedClusters structure because they
        //  are never modified in the running system.
        //
        //  We compare the Lsn in the Prior structure to see if it is older
        //  than the new BaseLsn value.  If so we will acquire the volume
        //  bitmap in order to swap the structures.
        //

        if ((Vcb->ActiveDeallocatedClusters != NULL) &&

            ((Vcb->PriorDeallocatedClusters->ClusterCount != 0) ||
             (Vcb->ActiveDeallocatedClusters->ClusterCount != 0))) {

            if (BaseLsn.QuadPart > Vcb->PriorDeallocatedClusters->Lsn.QuadPart) {

                NtfsAcquireExclusiveScb( IrpContext, Vcb->BitmapScb );
                BitmapAcquired = TRUE;

                //
                //  If the Prior Mcb is not empty then empty it.
                //

                if (Vcb->PriorDeallocatedClusters->ClusterCount != 0) {

                    //
                    //  Decrement the count of deallocated clusters by the amount stored here.
                    //

                    Vcb->DeallocatedClusters =
                        Vcb->DeallocatedClusters - Vcb->PriorDeallocatedClusters->ClusterCount;

                    //
                    //  Remove all of the mappings in the Mcb.
                    //

                    FsRtlTruncateLargeMcb( &Vcb->PriorDeallocatedClusters->Mcb,  (LONGLONG)0 );

                    //
                    //  Remember that there are no deallocated structures left in
                    //  the Mcb.
                    //

                    Vcb->PriorDeallocatedClusters->ClusterCount = 0;
                }

                //
                //  If this is a clean checkpoint then free the active deallocated
                //  clusters.  Otherwise do at least one more checkpoint.
                //

                if (Vcb->ActiveDeallocatedClusters->ClusterCount != 0) {

                    if (CleanVolume) {

                        //
                        //  Decrement the count of deallocated clusters by the amount stored here.
                        //

                        Vcb->DeallocatedClusters =
                            Vcb->DeallocatedClusters - Vcb->ActiveDeallocatedClusters->ClusterCount;

                        //
                        //  Remove all of the mappings in the Mcb.
                        //

                        FsRtlTruncateLargeMcb( &Vcb->ActiveDeallocatedClusters->Mcb,  (LONGLONG)0 );

                        //
                        //  Remember that there are no deallocated structures left in
                        //  the Mcb.
                        //

                        Vcb->ActiveDeallocatedClusters->ClusterCount = 0;

                        //
                        //  We know the count has gone to zero.
                        //

                        ASSERT( Vcb->DeallocatedClusters == 0 );

                    } else {

                        PDEALLOCATED_CLUSTERS Temp;

                        Temp = Vcb->PriorDeallocatedClusters;

                        Vcb->PriorDeallocatedClusters = Vcb->ActiveDeallocatedClusters;
                        Vcb->ActiveDeallocatedClusters = Temp;

                        //
                        //  Remember the last Lsn for the prior Mcb.
                        //

                        Vcb->PriorDeallocatedClusters->Lsn = LfsQueryLastLsn( Vcb->LogHandle );

                        //
                        //  Always do at least one more checkpoint.
                        //

                        ClearFlag( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN );
                    }
                }

            } else {

                ClearFlag( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN );
            }
        }

    try_exit: NOTHING;
    } finally {

        DebugUnwind( NtfsCheckpointVolume );

        if (BitmapAcquired) {

            NtfsReleaseScb( IrpContext, Vcb->BitmapScb );
        }

        //
        //  If the Dirty Page Table got initialized, free it up.
        //

        if (DirtyPageTableInitialized) {
            NtfsFreeRestartTable( &DirtyPages );
        }

        //
        //  Release any resources
        //

        if (OpenAttributeTableAcquired) {
            NtfsReleaseRestartTable( &Vcb->OpenAttributeTable );
        }

        if (TransactionTableAcquired) {
            NtfsReleaseRestartTable( &Vcb->TransactionTable );
        }

        //
        //  Release any names buffer.
        //

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

        //
        //  If this checkpoint created a transaction, free the index now.
        //

        if (IrpContext->TransactionId != 0) {

            NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable,
                                              TRUE );

            NtfsFreeRestartTableIndex( &Vcb->TransactionTable,
                                       IrpContext->TransactionId );

            NtfsReleaseRestartTable( &Vcb->TransactionTable );

            IrpContext->TransactionId = 0;
        }

        if (AcquireFiles) {

#ifdef NTFSDBG
            ASSERT( FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_CHECKPOINT_ACTIVE ));
            DebugDoit( ClearFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_CHECKPOINT_ACTIVE ));
#endif  //  NTFSDBG

            NtfsReleaseAllFiles( IrpContext, Vcb, FALSE );
        }

        //
        //  If we didn't own the checkpoint operation then indicate
        //  that someone else is free to checkpoint.
        //

        if (!OwnsCheckpoint) {

            NtfsAcquireCheckpoint( IrpContext, Vcb );
            ClearFlag( Vcb->CheckpointFlags,
                       VCB_CHECKPOINT_IN_PROGRESS | VCB_DUMMY_CHECKPOINT_POSTED);

            NtfsSetCheckpointNotify( IrpContext, Vcb );
            NtfsReleaseCheckpoint( IrpContext, Vcb );
        }

        if (RestorePreviousPriority) {

            KeSetPriorityThread( &PsGetCurrentThread()->Tcb,
                                 PreviousPriority );
        }
    }

    //
    //  If we need to post a defrag request then do so now.
    //

    if (PostDefrag) {

        PDEFRAG_MFT DefragMft;

        //
        //  Use a try-except to ignore allocation errors.
        //

        try {

            NtfsAcquireCheckpoint( IrpContext, Vcb );

            if (!FlagOn( Vcb->MftDefragState, VCB_MFT_DEFRAG_ACTIVE )) {

                SetFlag( Vcb->MftDefragState, VCB_MFT_DEFRAG_ACTIVE );
                NtfsReleaseCheckpoint( IrpContext, Vcb );

                DefragMft = NtfsAllocatePool( NonPagedPool, sizeof( DEFRAG_MFT ));

                DefragMft->Vcb = Vcb;
                DefragMft->DeallocateWorkItem = TRUE;

                //
                //  Send it off.....
                //

                ExInitializeWorkItem( &DefragMft->WorkQueueItem,
                                      (PWORKER_THREAD_ROUTINE)NtfsDefragMft,
                                      (PVOID)DefragMft );

                ExQueueWorkItem( &DefragMft->WorkQueueItem, CriticalWorkQueue );

            } else {

                NtfsReleaseCheckpoint( IrpContext, Vcb );
            }

        } except( FsRtlIsNtstatusExpected( GetExceptionCode() )
                  ? EXCEPTION_EXECUTE_HANDLER
                  : EXCEPTION_CONTINUE_SEARCH ) {

            NtfsAcquireCheckpoint( IrpContext, Vcb );
            ClearFlag( Vcb->MftDefragState, VCB_MFT_DEFRAG_ACTIVE );
            NtfsReleaseCheckpoint( IrpContext, Vcb );
        }
    }

    DebugTrace( -1, Dbg, ("NtfsCheckpointVolume -> VOID\n") );
}


VOID
NtfsCheckpointForLogFileFull (
    IN PIRP_CONTEXT IrpContext
    )

/*++

Routine Description:

    This routine is called to perform the clean checkpoint generated after
    a log file full.  This routine will call the clean checkpoint routine
    and then release all of the resources acquired.

Arguments:

Return Value:

    None.

--*/

{
    PAGED_CODE();

    IrpContext->ExceptionStatus = 0;

    //
    //  Call the checkpoint routine to do the actual work.
    //

    NtfsCheckpointVolume( IrpContext,
                          IrpContext->Vcb,
                          FALSE,
                          TRUE,
                          FALSE,
                          IrpContext->LastRestartArea );

    ASSERT( IrpContext->TransactionId == 0 );

    while (!IsListEmpty(&IrpContext->ExclusiveFcbList)) {

        NtfsReleaseFcb( IrpContext,
                        (PFCB)CONTAINING_RECORD(IrpContext->ExclusiveFcbList.Flink,
                                                FCB,
                                                ExclusiveFcbLinks ));
    }

    //
    //  Go through and free any Scb's in the queue of shared Scb's for transactions.
    //

    if (IrpContext->SharedScb != NULL) {

        NtfsReleaseSharedResources( IrpContext );
    }

    IrpContext->LastRestartArea = Li0;

    return;
}



VOID
NtfsCommitCurrentTransaction (
    IN PIRP_CONTEXT IrpContext
    )

/*++

Routine Description:

    This routine commits the current transaction by writing a final record
    to the log and deallocating the transaction Id.

Arguments:

Return Value:

    None.

--*/

{
    PTRANSACTION_ENTRY TransactionEntry;
    PVCB Vcb = IrpContext->Vcb;

    PAGED_CODE();

    //
    //  If this request created a transaction, complete it now.
    //

    if (IrpContext->TransactionId != 0) {

        LSN CommitLsn;

        //
        //  It is possible to get a LOG_FILE_FULL before writing
        //  out the first log record of a transaction.  In that
        //  case there is a transaction Id but we haven't reserved
        //  space in the log file.  It is wrong to write the
        //  commit record in this case because we can get an
        //  unexpected LOG_FILE_FULL.  We can also test the UndoRecords
        //  count in the transaction entry but don't want to acquire
        //  the restart table to make this check.
        //

        if (FlagOn( IrpContext->Flags, IRP_CONTEXT_FLAG_WROTE_LOG )) {

            //
            //  Write the log record to "forget" this transaction,
            //  because it should not be aborted.  Until if/when we
            //  do real TP, commit and forget are atomic.
            //

            CommitLsn =
            NtfsWriteLog( IrpContext,
                          Vcb->MftScb,
                          NULL,
                          ForgetTransaction,
                          NULL,
                          0,
                          CompensationLogRecord,
                          (PVOID)&Li0,
                          sizeof(LSN),
                          (LONGLONG)0,
                          0,
                          0,
                          0 );
        }

        //
        //  We can now free the transaction table index, because we are
        //  done with it now.
        //

        NtfsAcquireExclusiveRestartTable( &Vcb->TransactionTable,
                                          TRUE );

        TransactionEntry = (PTRANSACTION_ENTRY)GetRestartEntryFromIndex(
                            &Vcb->TransactionTable,
                            IrpContext->TransactionId );

        //
        //  Call Lfs to free our undo space.
        //

        if ((TransactionEntry->UndoRecords != 0) &&
            (!FlagOn( Vcb->VcbState, VCB_STATE_RESTART_IN_PROGRESS ))) {

            LfsResetUndoTotal( Vcb->LogHandle,
                               TransactionEntry->UndoRecords,
                               -TransactionEntry->UndoBytes );
        }

        NtfsFreeRestartTableIndex( &Vcb->TransactionTable,
                                   IrpContext->TransactionId );

        IrpContext->TransactionId = 0;

        NtfsReleaseRestartTable( &Vcb->TransactionTable );

        //
        //  One way we win by being recoverable, is that we do not really
        //  have to do write-through - flushing the updates to the log
        //  is enough.  We don't make this call if we are in the abort
        //  transaction path.  Otherwise we could get a log file full
        //  while aborting.
        //

        if (FlagOn( IrpContext->TopLevelIrpContext->Flags, IRP_CONTEXT_FLAG_WRITE_THROUGH ) &&
            (IrpContext == IrpContext->TopLevelIrpContext) &&
            (IrpContext->TopLevelIrpContext->ExceptionStatus == STATUS_SUCCESS)) {

            NtfsUpdateScbSnapshots( IrpContext );
            LfsFlushToLsn( Vcb->LogHandle, CommitLsn );
        }
    }
}


VOID
NtfsCheckpointCurrentTransaction (
    IN PIRP_CONTEXT IrpContext
    )

/*++

Routine Description:

    This routine checkpoints the current transaction by commiting it
    to the log and deallocating the transaction Id.  The current request
    cann keep running, but changes to date are committed and will not be
    backed out.

Arguments:

Return Value:

    None.

--*/

{
    PAGED_CODE();

    NtfsCommitCurrentTransaction( IrpContext );

    NtfsUpdateScbSnapshots( IrpContext );

    //
    //  Cleanup any recently deallocated record information for this transaction.
    //

    NtfsDeallocateRecordsComplete( IrpContext );
    IrpContext->DeallocatedClusters = 0;
    IrpContext->FreeClusterChange = 0;
}


VOID
NtfsInitializeLogging (
    )

/*

Routine Description:

    This routine is to be called once during startup of Ntfs (not once
    per volume), to initialize the logging support.

Parameters:

    None

Return Value:

    None

--*/

{
    PAGED_CODE();

    DebugTrace( +1, Dbg, ("NtfsInitializeLogging:\n") );
    LfsInitializeLogFileService();
    DebugTrace( -1, Dbg, ("NtfsInitializeLogging -> VOID\n") );
}


VOID
NtfsStartLogFile (
    IN PSCB LogFileScb,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine opens the log file for a volume by calling Lfs.  The returned
    LogHandle is stored in the Vcb.  If the log file has not been initialized,
    Lfs detects this and initializes it automatically.

Arguments:

    LogFileScb - The Scb for the log file

    Vcb - Pointer to the Vcb for this volume

Return Value:

    None.

--*/

{
    UNICODE_STRING UnicodeName;
    LFS_INFO LfsInfo;

    PAGED_CODE();

    DebugTrace( +1, Dbg, ("NtfsStartLogFile:\n") );

    RtlInitUnicodeString( &UnicodeName, L"NTFS" );

    LfsInfo = LfsPackLog;

    //
    //  Slam the allocation size into file size and valid data in case there
    //  is some error.
    //

    LogFileScb->Header.FileSize = LogFileScb->Header.AllocationSize;
    LogFileScb->Header.ValidDataLength = LogFileScb->Header.AllocationSize;

    Vcb->LogHeaderReservation = LfsOpenLogFile( LogFileScb->FileObject,
                                                UnicodeName,
                                                1,
                                                0,
                                                LogFileScb->Header.AllocationSize.QuadPart,
                                                &LfsInfo,
                                                &Vcb->LogHandle );

    SetFlag( Vcb->VcbState, VCB_STATE_VALID_LOG_HANDLE );
    DebugTrace( -1, Dbg, ("NtfsStartLogFile -> VOID\n") );
}


VOID
NtfsStopLogFile (
    IN PVCB Vcb
    )

/*

Routine Description:

    This routine should be called during volume dismount to close the volume's
    log file with the log file service.

Arguments:

    Vcb - Pointer to the Vcb for the volume

Return Value:

    None

--*/

{
    LFS_LOG_HANDLE LogHandle = Vcb->LogHandle;

    PAGED_CODE();

    DebugTrace( +1, Dbg, ("NtfsStopLogFile:\n") );

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

        ASSERT( LogHandle != NULL );
        LfsFlushToLsn( LogHandle, LfsQueryLastLsn(LogHandle) );

        ClearFlag( Vcb->VcbState, VCB_STATE_VALID_LOG_HANDLE );
        LfsCloseLogFile( LogHandle );
    }

    DebugTrace( -1, Dbg, ("NtfsStopLogFile -> VOID\n") );
}


VOID
NtfsInitializeRestartTable (
    IN ULONG EntrySize,
    IN ULONG NumberEntries,
    OUT PRESTART_POINTERS TablePointer
    )

/*++

Routine Description:

    This routine is called to allocate and initialize a new Restart Table,
    and return a pointer to it.

Arguments:

    EntrySize - Size of the table entries, in bytes.

    NumberEntries - Number of entries to allocate for the table.

    TablePointer - Returns a pointer to the table.

Return Value:

    None

--*/

{
    PAGED_CODE();

    try {

        RtlZeroMemory( TablePointer, sizeof(RESTART_POINTERS) );

        //
        //  Call common routine to allocate the actual table.
        //

        InitializeNewTable( EntrySize, NumberEntries, TablePointer );

        //
        //  Initialiaze the resource and spin lock.
        //

        KeInitializeSpinLock( &TablePointer->SpinLock );
        ExInitializeResource( &TablePointer->Resource );
        TablePointer->ResourceInitialized = TRUE;

    } finally {

        DebugUnwind( NtfsInitializeRestartTable );

        //
        //  On error, clean up any partial work that was done.
        //

        if (AbnormalTermination()) {

            NtfsFreeRestartTable( TablePointer );
        }
    }
}


VOID
NtfsFreeRestartTable (
    IN PRESTART_POINTERS TablePointer
    )

/*++

Routine Description:

    This routine frees a previously allocated Restart Table.

Arguments:

    TablePointer - Pointer to the Restart Table to delete.

Return Value:

    None.

--*/

{
    PAGED_CODE();

    if (TablePointer->Table != NULL) {
        NtfsFreePool( TablePointer->Table );
        TablePointer->Table = NULL;
    }

    if (TablePointer->ResourceInitialized) {
        ExDeleteResource( &TablePointer->Resource );
        TablePointer->ResourceInitialized = FALSE;
    }
}


VOID
NtfsExtendRestartTable (
    IN PRESTART_POINTERS TablePointer,
    IN ULONG NumberNewEntries,
    IN ULONG FreeGoal
    )

/*++

Routine Description:

    This routine extends a previously allocated Restart Table, by
    creating and initializing a new one, and copying over the the
    table entries from the old one.  The old table is then deallocated.
    On return, the table pointer points to the new Restart Table.

Arguments:

    TablePointer - Address of the pointer to the previously created table.

    NumberNewEntries - The number of addtional entries to be allocated
                       in the new table.

    FreeGoal - A hint as to what point the caller would like to truncate
               the table back to, when sufficient entries are deleted.
               If truncation is not desired, then MAXULONG may be specified.

Return Value:

    None.

--*/

{
    PRESTART_TABLE NewTable, OldTable;
    ULONG OldSize;

    OldSize = SizeOfRestartTable(TablePointer);

    //
    //  Get pointer to old table.
    //

    OldTable = TablePointer->Table;
    ASSERT_RESTART_TABLE(OldTable);

    //
    //  Start by initializing a table for the new size.
    //

    InitializeNewTable( OldTable->EntrySize,
                        OldTable->NumberEntries + NumberNewEntries,
                        TablePointer );

    //
    //  Copy body of old table in place to new table.
    //

    NewTable = TablePointer->Table;
    RtlMoveMemory( (NewTable + 1),
                   (OldTable + 1),
                   OldTable->EntrySize * OldTable->NumberEntries );

    //
    //  Fix up new table's header, and fix up free list.
    //

    NewTable->FreeGoal = MAXULONG;
    if (FreeGoal != MAXULONG) {
        NewTable->FreeGoal = sizeof(RESTART_TABLE) + FreeGoal * NewTable->EntrySize;
    }

    if (OldTable->FirstFree != 0) {

        NewTable->FirstFree = OldTable->FirstFree;
        *(PULONG)GetRestartEntryFromIndex( TablePointer, OldTable->LastFree ) =
            OldSize;;
    } else {

        NewTable->FirstFree = OldSize;
    }

    //
    //  Copy number allocated
    //

    NewTable->NumberAllocated = OldTable->NumberAllocated;

    //
    //  Free the old table and return the new one.
    //

    NtfsFreePool( OldTable );

    ASSERT_RESTART_TABLE(NewTable);
}


ULONG
NtfsAllocateRestartTableIndex (
    IN PRESTART_POINTERS TablePointer
    )

/*++

Routine Description:

    This routine allocates an index from within a previously initialized
    Restart Table.  If the table is empty, it is extended.

    Note that the table must already be acquired either shared or exclusive,
    and if it must be extended, then the table is released and will be
    acquired exclusive on return.

Arguments:

    TablePointer - Pointer to the Restart Table in which an index is to
                   be allocated.

Return Value:

    The allocated index.

--*/

{
    PRESTART_TABLE Table;
    ULONG EntryIndex;
    KIRQL OldIrql;
    PULONG Entry;

    DebugTrace( +1, Dbg, ("NtfsAllocateRestartTableIndex:\n") );
    DebugTrace( 0, Dbg, ("TablePointer = %08lx\n", TablePointer) );

    Table = TablePointer->Table;
    ASSERT_RESTART_TABLE(Table);

    //
    //  Acquire the spin lock to synchronize the allocation.
    //

    KeAcquireSpinLock( &TablePointer->SpinLock, &OldIrql );

    //
    //  If the table is empty, then we have to extend it.
    //

    if (Table->FirstFree == 0) {

        //
        //  First release the spin lock and the table resource, and get
        //  the resource exclusive.
        //

        KeReleaseSpinLock( &TablePointer->SpinLock, OldIrql );
        NtfsReleaseRestartTable( TablePointer );
        NtfsAcquireExclusiveRestartTable( TablePointer, TRUE );

        //
        //  Now extend the table.  Note that if this routine raises, we have
        //  nothing to release.
        //

        NtfsExtendRestartTable( TablePointer, 16, MAXULONG );

        //
        //  And re-get our pointer to the restart table
        //

        Table = TablePointer->Table;

        //
        //  Now get the spin lock again and proceed.
        //

        KeAcquireSpinLock( &TablePointer->SpinLock, &OldIrql );
    }

    //
    //  Get First Free to return it.
    //

    EntryIndex = Table->FirstFree;

    ASSERT( EntryIndex != 0 );

    //
    //  Dequeue this entry and zero it.
    //

    Entry = (PULONG)GetRestartEntryFromIndex( TablePointer, EntryIndex );

    Table->FirstFree = *Entry;
    ASSERT( Table->FirstFree != RESTART_ENTRY_ALLOCATED );

    RtlZeroMemory( Entry, Table->EntrySize );

    //
    //  Show that it's allocated.
    //

    *Entry = RESTART_ENTRY_ALLOCATED;

    //
    //  If list is going empty, then we fix the LastFree as well.
    //

    if (Table->FirstFree == 0) {

        Table->LastFree = 0;
    }

    Table->NumberAllocated += 1;

    //
    //  Now just release the spin lock before returning.
    //

    KeReleaseSpinLock( &TablePointer->SpinLock, OldIrql );

    DebugTrace( -1, Dbg, ("NtfsAllocateRestartTableIndex -> %08lx\n", EntryIndex) );

    return EntryIndex;
}


PVOID
NtfsAllocateRestartTableFromIndex (
    IN PRESTART_POINTERS TablePointer,
    IN ULONG Index
    )

/*++

Routine Description:

    This routine allocates a specific index from within a previously
    initialized Restart Table.  If the index does not exist within the
    existing table, the table is extended.

    Note that the table must already be acquired either shared or exclusive,
    and if it must be extended, then the table is released and will be
    acquired exclusive on return.

Arguments:

    TablePointer - Pointer to the Restart Table in which an index is to
                   be allocated.

    Index - The index to be allocated.

Return Value:

    The table entry allocated.

--*/

{
    PULONG Entry;
    PULONG LastEntry;

    PRESTART_TABLE Table;
    KIRQL OldIrql;

    ULONG ThisIndex;
    ULONG LastIndex;

    DebugTrace( +1, Dbg, ("NtfsAllocateRestartTableFromIndex\n") );
    DebugTrace( 0, Dbg, ("TablePointer  = %08lx\n", TablePointer) );
    DebugTrace( 0, Dbg, ("Index         = %08lx\n", Index) );

    Table = TablePointer->Table;
    ASSERT_RESTART_TABLE(Table);

    //
    //  Acquire the spin lock to synchronize the allocation.
    //

    KeAcquireSpinLock( &TablePointer->SpinLock, &OldIrql );

    //
    //  If the entry is not in the table, we will have to extend the table.
    //

    if (!IsRestartIndexWithinTable( TablePointer, Index )) {

        ULONG TableSize;
        ULONG BytesToIndex;
        ULONG AddEntries;

        //
        //  We extend the size by computing the number of entries
        //  between the existing size and the desired index and
        //  adding 1 to that.
        //

        TableSize = SizeOfRestartTable( TablePointer );;
        BytesToIndex = Index - TableSize;

        AddEntries = BytesToIndex / Table->EntrySize + 1;

        //
        //  There should always be an integral number of entries being added.
        //

        ASSERT( BytesToIndex % Table->EntrySize == 0 );

        //
        //  First release the spin lock and the table resource, and get
        //  the resource exclusive.
        //

        KeReleaseSpinLock( &TablePointer->SpinLock, OldIrql );
        NtfsReleaseRestartTable( TablePointer );
        NtfsAcquireExclusiveRestartTable( TablePointer, TRUE );

        //
        //  Now extend the table.  Note that if this routine raises, we have
        //  nothing to release.
        //

        NtfsExtendRestartTable( TablePointer,
                                AddEntries,
                                TableSize );

        Table = TablePointer->Table;
        ASSERT_RESTART_TABLE(Table);

        //
        //  Now get the spin lock again and proceed.
        //

        KeAcquireSpinLock( &TablePointer->SpinLock, &OldIrql );
    }

    //
    //  Now see if the entry is already allocated, and just return if it is.
    //

    Entry = (PULONG)GetRestartEntryFromIndex( TablePointer, Index );

    if (!IsRestartTableEntryAllocated(Entry)) {

        //
        //  We now have to walk through the table, looking for the entry
        //  we're interested in and the previous entry.  Start by looking at the
        //  first entry.
        //

        ThisIndex = Table->FirstFree;

        //
        //  Get the Entry from the list.
        //

        Entry = (PULONG) GetRestartEntryFromIndex( TablePointer, ThisIndex );

        //
        //  If this is a match, then we pull it out of the list and are done.
        //

        if (ThisIndex == Index) {

            //
            //  Dequeue this entry.
            //

            Table->FirstFree = *Entry;
            ASSERT( Table->FirstFree != RESTART_ENTRY_ALLOCATED );

        //
        //  Otherwise we need to walk through the list looking for the
        //  predecessor of our entry.
        //

        } else {

            while (TRUE) {

                //
                //  Remember the entry just found.
                //

                LastIndex = ThisIndex;
                LastEntry = Entry;

                //
                //  We should never run out of entries.
                //

                ASSERT( *LastEntry != 0 );

                //
                //  Lookup up the next entry in the list.
                //

                ThisIndex = *LastEntry;
                Entry = (PULONG) GetRestartEntryFromIndex( TablePointer, ThisIndex );

                //
                //  If this is our match we are done.
                //

                if (ThisIndex == Index) {

                    //
                    //  Dequeue this entry.
                    //

                    *LastEntry = *Entry;

                    //
                    //  If this was the last entry, we update that in the
                    //  table as well.
                    //

                    if (Table->LastFree == ThisIndex) {

                        Table->LastFree = LastIndex;
                    }

                    break;
                }
            }
        }

        //
        //  If the list is now empty, we fix the LastFree as well.
        //

        if (Table->FirstFree == 0) {

            Table->LastFree = 0;
        }

        //
        //  Zero this entry.  Then show that this is allocated and increment the
        //  allocated count.
        //

        RtlZeroMemory( Entry, Table->EntrySize );
        *Entry = RESTART_ENTRY_ALLOCATED;

        Table->NumberAllocated += 1;
    }


    //
    //  Now just release the spin lock before returning.
    //

    KeReleaseSpinLock( &TablePointer->SpinLock, OldIrql );

    DebugTrace( -1, Dbg, ("NtfsAllocateRestartTableFromIndex -> %08lx\n", Entry) );

    return (PVOID)Entry;
}


VOID
NtfsFreeRestartTableIndex (
    IN PRESTART_POINTERS TablePointer,
    IN ULONG Index
    )

/*++

Routine Description:

    This routine frees a previously allocated index in a Restart Table.
    If the index is before FreeGoal for the table, it is simply deallocated to
    the front of the list for immediate reuse.  If the index is beyond
    FreeGoal, then it is deallocated to the end of the list, to facilitate
    truncation of the list in the event that all of the entries beyond
    FreeGoal are freed.  However, this routine does not automatically
    truncate the list, as this would cause too much overhead.  The list
    is checked during periodic checkpoint processing.

Arguments:

    TablePointer - Pointer to the Restart Table to which the index is to be
                   deallocated.

    Index - The index being deallocated.

Return Value:

    None.

--*/

{
    PRESTART_TABLE Table;
    PULONG Entry, OldLastEntry;
    KIRQL OldIrql;

    DebugTrace( +1, Dbg, ("NtfsFreeRestartTableIndex:\n") );
    DebugTrace( 0, Dbg, ("TablePointer = %08lx\n", TablePointer) );
    DebugTrace( 0, Dbg, ("Index = %08lx\n", Index) );

    //
    //  Get pointers to table and the entry we are freeing.
    //

    Table = TablePointer->Table;
    ASSERT_RESTART_TABLE(Table);

    ASSERT( Table->FirstFree == 0
            || (Table->FirstFree >= 0x18)
                && ((Table->FirstFree - 0x18) % Table->EntrySize) == 0 );

    ASSERT( (Index >= 0x18)
             && ((Index - 0x18) % Table->EntrySize) == 0 );

    Entry = GetRestartEntryFromIndex( TablePointer, Index );

    //
    //  Acquire the spin lock to synchronize the allocation.
    //

    KeAcquireSpinLock( &TablePointer->SpinLock, &OldIrql );

    //
    //  If the index is before FreeGoal, then do a normal deallocation at
    //  the front of the list.
    //

    if (Index < Table->FreeGoal) {

        *Entry = Table->FirstFree;
        Table->FirstFree = Index;
        if (Table->LastFree == 0) {
            Table->LastFree = Index;
        }

    //
    //  Otherwise we will deallocate this guy to the end of the list.
    //

    } else {

        if (Table->LastFree != 0) {
            OldLastEntry = GetRestartEntryFromIndex( TablePointer,
                                                     Table->LastFree );
            *OldLastEntry = Index;
        } else {
            Table->FirstFree = Index;
        }
        Table->LastFree = Index;
        *Entry = 0;
    }

    Table->NumberAllocated -= 1;

    //
    //  Now just release the spin lock before returning.
    //

    KeReleaseSpinLock( &TablePointer->SpinLock, OldIrql );

    DebugTrace( -1, Dbg, ("NtfsFreeRestartTableIndex -> VOID\n") );
}


PVOID
NtfsGetFirstRestartTable (
    IN PRESTART_POINTERS TablePointer
    )

/*++

Routine Description:

    This routine returns the first allocated entry from a Restart Table.

Arguments:

    TablePointer - Pointer to the respective Restart Table Pointers structure.

Return Value:

    Pointer to the first entry, or NULL if none are allocated.

--*/

{
    PCHAR Entry;

    PAGED_CODE();

    //
    //  If we know the table is empty, we can return immediately.
    //

    if (IsRestartTableEmpty( TablePointer )) {

        return NULL;
    }

    //
    //  Otherwise point to the first table entry.
    //

    Entry = (PCHAR)(TablePointer->Table + 1);

    //
    //  Loop until we hit the first one allocated, or the end of the list.
    //

    while ((ULONG)(Entry - (PCHAR)TablePointer->Table) <
           SizeOfRestartTable(TablePointer)) {

        if (IsRestartTableEntryAllocated(Entry)) {
            return (PVOID)Entry;
        }

        Entry += TablePointer->Table->EntrySize;
    }

    return NULL;
}


PVOID
NtfsGetNextRestartTable (
    IN PRESTART_POINTERS TablePointer,
    IN PVOID Current
    )

/*++

Routine Description:

    This routine returns the next allocated entry from a Restart Table.

Arguments:

    TablePointer - Pointer to the respective Restart Table Pointers structure.

    Current - Current entry pointer.

Return Value:

    Pointer to the next entry, or NULL if none are allocated.

--*/


{
    PCHAR Entry = (PCHAR)Current;

    PAGED_CODE();

    //
    //  Point to the next entry.
    //

    Entry += TablePointer->Table->EntrySize;

    //
    //  Loop until we hit the first one allocated, or the end of the list.
    //

    while ((ULONG)(Entry - (PCHAR)TablePointer->Table) <
           SizeOfRestartTable(TablePointer)) {

        if (IsRestartTableEntryAllocated(Entry)) {
            return (PVOID)Entry;
        }

        Entry += TablePointer->Table->EntrySize;
    }

    return NULL;
}


//
//  Internal support routine
//

VOID
DirtyPageRoutine (
    IN PFILE_OBJECT FileObject,
    IN PLARGE_INTEGER FileOffset,
    IN ULONG Length,
    IN PLSN OldestLsn,
    IN PLSN NewestLsn,
    IN PVOID Context1,
    IN PVOID Context2
    )

/*++

Routine Description:

    This routine is used as the call back routine for retrieving dirty pages
    from the Cache Manager.  It adds them to the Dirty Table list whose
    pointer is pointed to by the Context parameter.

Arguments:

    FileObject - Pointer to the file object which has the dirty page

    FileOffset - File offset for start of dirty page

    Length - Length recorded for the dirty page

    OldestLsn - Oldest Lsn of an update not written through stored for that page

    Context1 - IrpContext

    Context2 - Pointer to the pointer to the Restart Table

Return Value:

    None

--*/

{
    PVCB Vcb;
    VCN Vcn;
    ULONG ClusterCount;
    PDIRTY_PAGE_ENTRY PageEntry;
    POPEN_ATTRIBUTE_ENTRY AttributeEntry;
    ULONG PageIndex;
    PIRP_CONTEXT IrpContext = (PIRP_CONTEXT)Context1;
    PRESTART_POINTERS DirtyPageTable = (PRESTART_POINTERS)Context2;
    PSCB_NONPAGED NonpagedScb;

    UNREFERENCED_PARAMETER( NewestLsn );

    DebugTrace( +1, Dbg, ("DirtyPageRoutine:\n") );
    DebugTrace( 0, Dbg, ("FileObject = %08lx\n", FileObject) );
    DebugTrace( 0, Dbg, ("FileOffset = %016I64x\n", *FileOffset) );
    DebugTrace( 0, Dbg, ("Length = %08lx\n", Length) );
    DebugTrace( 0, Dbg, ("OldestLsn = %016I64x\n", *OldestLsn) );
    DebugTrace( 0, Dbg, ("Context2 = %08lx\n", Context2) );

    //
    //  Get the Vcb out of the file object.
    //

    NonpagedScb = CONTAINING_RECORD( FileObject->SectionObjectPointer,
                                     SCB_NONPAGED,
                                     SegmentObject );

    Vcb = NonpagedScb->Vcb;

    //
    //  We noop this call if the open attribute entry for this Scb is 0.  We assume
    //  there was a clean volume checkpoint which cleared this field.
    //

    if (NonpagedScb->OpenAttributeTableIndex == 0 ) {

        DebugTrace( -1, Dbg, ("DirtyPageRoutine -> VOID\n") );
        return;
    }

    //
    //  First allocate an entry in the dirty page table.
    //

    PageIndex = NtfsAllocateRestartTableIndex( DirtyPageTable );

    //
    //  Get a pointer to the entry we just allocated.
    //

    PageEntry = GetRestartEntryFromIndex( DirtyPageTable, PageIndex );

    //
    //  Calculate the range of Vcns which are dirty.
    //

    Vcn = Int64ShraMod32(FileOffset->QuadPart, Vcb->ClusterShift);
    ClusterCount = ClustersFromBytes( Vcb, Length );

    //
    //  Now fill in the Dirty Page Entry, except for the Lcns, because
    //  we are not allowed to take page faults now.
    //

    PageEntry->TargetAttribute = NonpagedScb->OpenAttributeTableIndex;
    PageEntry->LengthOfTransfer = Length;
    PageEntry->LcnsToFollow = ClusterCount;
    PageEntry->Reserved = 0;
    PageEntry->Vcn = Vcn;

    //
    //  We don't use an Lsn which is prior to our current base Lsn
    //  or the known flushed lsn for a fuzzy checkpoint.
    //

    if (OldestLsn->QuadPart < Vcb->LastBaseLsn.QuadPart) {

        PageEntry->OldestLsn = Vcb->LastBaseLsn;


    } else {

        PageEntry->OldestLsn = *OldestLsn;
    }

    //
    //  Mark the Open Attribute Table Entry for this file.
    //

    AttributeEntry = (POPEN_ATTRIBUTE_ENTRY)GetRestartEntryFromIndex(
                       &Vcb->OpenAttributeTable, PageEntry->TargetAttribute );

    AttributeEntry->DirtyPagesSeen = TRUE;

    DebugTrace( -1, Dbg, ("DirtyPageRoutine -> VOID\n") );
}


//
//  Internal support routine
//

VOID
LookupLcns (
    IN PIRP_CONTEXT IrpContext,
    IN PSCB Scb,
    IN VCN Vcn,
    IN ULONG ClusterCount,
    IN BOOLEAN MustBeAllocated,
    OUT PLCN_UNALIGNED FirstLcn
    )

/*++

Routine Description:

    This routine looks up the Lcns for a range of Vcns, and stores them in
    an output array.  One Lcn is stored for each Vcn in the range, even
    if the Lcns are contiguous.

Arguments:

    Scb - Scb for stream on which lookup should occur.

    Vcn - Start of range of Vcns to look up.

    ClusterCount - Number of Vcns to look up.

    MustBeAllocated - FALSE - if need not be allocated, and should check Mcb only
                      TRUE - if it must be allocated as far as caller knows (i.e.,
                             NtfsLookupAllocation also has checks)

    FirstLcn - Pointer to storage for first Lcn.  The caller must guarantee
               that there is enough space to store ClusterCount Lcns.

Return Value:

    None

--*/

{
    BOOLEAN Allocated;
    LONGLONG Clusters;
    LCN Lcn;
    ULONG i;

    PAGED_CODE();

    DebugTrace( +1, Dbg, ("LookupLcns:\n") );
    DebugTrace( 0, Dbg, ("Scb = %08l\n", Scb) );
    DebugTrace( 0, Dbg, ("Vcn = %016I64x\n", Vcn) );
    DebugTrace( 0, Dbg, ("ClusterCount = %08l\n", ClusterCount) );
    DebugTrace( 0, Dbg, ("FirstLcn = %08lx\n", FirstLcn) );

    //
    //  Loop until we have looked up all of the clusters
    //

    while (ClusterCount != 0) {

        if (MustBeAllocated) {

            //
            //  Lookup the next run.
            //

            Allocated = NtfsLookupAllocation( IrpContext,
                                              Scb,
                                              Vcn,
                                              &Lcn,
                                              &Clusters,
                                              NULL,
                                              NULL );

            ASSERT( Allocated && (Lcn != 0) );

        } else {

           Allocated = NtfsLookupNtfsMcbEntry( &Scb->Mcb, Vcn, &Lcn, &Clusters, NULL, NULL, NULL, NULL );

           //
           //   If we are off the end of the Mcb, then set up to just return
           //   Li0 for as many Lcns as are being looked up.
           //

           if (!Allocated ||
               (Lcn == UNUSED_LCN)) {
               Lcn = 0;
               Clusters = ClusterCount;
               Allocated = FALSE;
           }
        }

        //
        //  If we got as many clusters as we were looking for, then just
        //  take the number we were looking for.
        //

        if (Clusters > ClusterCount) {

            Clusters = ClusterCount;
        }

        //
        //  Fill in the Lcns in the header.
        //

        for (i = 0; i < (ULONG)Clusters; i++) {

            *(FirstLcn++) = Lcn;

            if (Allocated) {
                Lcn = Lcn + 1;
            }
        }

        //
        //  Adjust loop variables for the number Lcns we just received.
        //

        Vcn = Vcn + Clusters;
        ClusterCount -= (ULONG)Clusters;
    }
    DebugTrace( -1, Dbg, ("LookupLcns -> VOID\n") );
}


VOID
InitializeNewTable (
    IN ULONG EntrySize,
    IN ULONG NumberEntries,
    OUT PRESTART_POINTERS TablePointer
    )

/*++

Routine Description:

    This routine is called to allocate and initialize a new table when the
    associated Restart Table is being allocated or extended.

Arguments:

    EntrySize - Size of the table entries, in bytes.

    NumberEntries - Number of entries to allocate for the table.

    TablePointer - Returns a pointer to the table.

Return Value:

    None

--*/

{
    PRESTART_TABLE Table;
    PULONG Entry;
    ULONG Size;
    ULONG Offset;

    //
    //  Calculate size of table to allocate.
    //

    Size = EntrySize * NumberEntries + sizeof(RESTART_TABLE);

    //
    //  Allocate and zero out the table.
    //

    Table =
    TablePointer->Table = NtfsAllocatePool( NonPagedPool, Size );

    RtlZeroMemory( Table, Size );

    //
    //  Initialize the table header.
    //

    Table->EntrySize = (USHORT)EntrySize;
    Table->NumberEntries = (USHORT)NumberEntries;
    Table->FreeGoal = MAXULONG;
    Table->FirstFree = sizeof(RESTART_TABLE);
    Table->LastFree = Table->FirstFree + (NumberEntries - 1) * EntrySize;

    //
    //  Initialize the free list.
    //

    for (Entry = (PULONG)(Table + 1), Offset = sizeof(RESTART_TABLE) + EntrySize;
         Entry < (PULONG)((PCHAR)Table + Table->LastFree);
         Entry = (PULONG)((PCHAR)Entry + EntrySize), Offset += EntrySize) {

        *Entry = Offset;
    }

    ASSERT_RESTART_TABLE(Table);
}