summaryrefslogblamecommitdiffstats
path: root/private/ntos/cntfs/verfysup.c
blob: 869249dbc6b0a207414080b41a36df144092ef30 (plain) (tree)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779


















































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































































                                                                                                                    
/*++

Copyright (c) 1991  Microsoft Corporation

Module Name:

    VerfySup.c

Abstract:

    This module implements the Ntfs Verify volume and fcb support
    routines

Author:

    Gary Kimura         [GaryKi]            30-Jan-1992

Revision History:

--*/

#include "NtfsProc.h"

//
//  The Debug trace level for this module
//

#define Dbg                              (DEBUG_TRACE_VERFYSUP)

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

#undef MODULE_POOL_TAG
#define MODULE_POOL_TAG                  ('VFtN')

extern BOOLEAN NtfsCheckQuota;

//
//  Local procedure prototypes
//

VOID
NtfsPerformVerifyDiskRead (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN PVOID Buffer,
    IN LONGLONG Offset,
    IN ULONG NumberOfBytesToRead
    );

NTSTATUS
NtfsVerifyReadCompletionRoutine(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Contxt
    );

NTSTATUS
NtfsDeviceIoControlAsync (
    IN PIRP_CONTEXT IrpContext,
    IN PDEVICE_OBJECT DeviceObject,
    IN ULONG IoCtl
    );
    
#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, NtfsCheckpointAllVolumes)
#pragma alloc_text(PAGE, NtfsMarkVolumeDirty)
#pragma alloc_text(PAGE, NtfsPerformVerifyOperation)
#pragma alloc_text(PAGE, NtfsPingVolume)
#pragma alloc_text(PAGE, NtfsUpdateVersionNumber)
#pragma alloc_text(PAGE, NtfsVerifyOperationIsLegal)
#endif


BOOLEAN
NtfsPerformVerifyOperation (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine is used to force a verification of the volume.  It assumes
    that everything might be resource/mutex locked so it cannot take out
    any resources.  It will read in the boot sector and the dasd file record
    and from those determine if the volume is okay.  This routine is called
    whenever the real device has started rejecting I/O requests with
    VERIFY_REQUIRED.

    If the volume verifies okay then we will return TRUE otherwise we will
    return FALSE.

    It does not alter the Vcb state.

Arguments:

    Vcb - Supplies the Vcb being queried.

Return Value:

    BOOLEAN - TRUE if the volume verified okay, and FALSE otherwise.

--*/

{
    BOOLEAN Results;

    PPACKED_BOOT_SECTOR BootSector;
    PFILE_RECORD_SEGMENT_HEADER FileRecord;

    LONGLONG Offset;

    PSTANDARD_INFORMATION StandardInformation;

    ASSERT_IRP_CONTEXT( IrpContext );
    ASSERT_VCB( Vcb );

    PAGED_CODE();

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

    BootSector = NULL;
    FileRecord = NULL;

    try {

        //
        //  Allocate a buffer for the boot sector, read it in, and then check if
        //  it some of the fields still match.  The starting lcn is zero and the
        //  size is the size of a disk sector.
        //

        BootSector = NtfsAllocatePool( NonPagedPool,
                                        ROUND_TO_PAGES( Vcb->BytesPerSector ));

        NtfsPerformVerifyDiskRead( IrpContext, Vcb, BootSector, (LONGLONG)0, Vcb->BytesPerSector );

        //
        //  For now we will only check that the serial numbers, mft lcn's and
        //  number of sectors match up with what they use to be.
        //

        if ((BootSector->SerialNumber !=  Vcb->VolumeSerialNumber) ||
            (BootSector->MftStartLcn !=   Vcb->MftStartLcn) ||
            (BootSector->Mft2StartLcn !=  Vcb->Mft2StartLcn) ||
            (BootSector->NumberSectors != Vcb->NumberSectors)) {

            try_return( Results = FALSE );
        }

        //
        //  Allocate a buffer for the dasd file record, read it in, and then check
        //  if some of the fields still match.  The size of the record is the number
        //  of bytes in a file record segment, and because the dasd file record is
        //  known to be contiguous with the start of the mft we can compute the starting
        //  lcn as the base of the mft plus the dasd number mulitplied by the clusters
        //  per file record segment.
        //

        FileRecord = NtfsAllocatePool( NonPagedPoolCacheAligned,
                                        ROUND_TO_PAGES( Vcb->BytesPerFileRecordSegment ));

        Offset = LlBytesFromClusters(Vcb, Vcb->MftStartLcn) +
                 (VOLUME_DASD_NUMBER * Vcb->BytesPerFileRecordSegment);

        NtfsPerformVerifyDiskRead( IrpContext, Vcb, FileRecord, Offset, Vcb->BytesPerFileRecordSegment );

        //
        //  Given a pointer to a file record we want the value of the first attribute which
        //  will be the standard information attribute.  Then we will check the
        //  times stored in the standard information attribute against the times we
        //  have saved in the vcb.  Note that last access time will be modified if
        //  the disk was moved and mounted on a different system without doing a dismount
        //  on this system.
        //

        StandardInformation = NtfsGetValue(((PATTRIBUTE_RECORD_HEADER)Add2Ptr( FileRecord,
                                                                               FileRecord->FirstAttributeOffset )));

        if ((StandardInformation->CreationTime !=         Vcb->VolumeCreationTime) ||
            (StandardInformation->LastModificationTime != Vcb->VolumeLastModificationTime) ||
            (StandardInformation->LastChangeTime !=       Vcb->VolumeLastChangeTime) ||
            (StandardInformation->LastAccessTime !=       Vcb->VolumeLastAccessTime)) {

            try_return( Results = FALSE );
        }

        //
        //  If the device is not writable we won't remount it.
        //

        if (NtfsDeviceIoControlAsync( IrpContext,
                                      Vcb->TargetDeviceObject,
                                      IOCTL_DISK_IS_WRITABLE ) == STATUS_MEDIA_WRITE_PROTECTED) {

            try_return( Results = FALSE );
        }

        //
        //  At this point we believe that the disk has not changed so can return true and
        //  let our caller reenable the device
        //

        Results = TRUE;

    try_exit: NOTHING;
    } finally {

        if (BootSector != NULL) { NtfsFreePool( BootSector ); }
        if (FileRecord != NULL) { NtfsFreePool( FileRecord ); }
    }

    DebugTrace( -1, Dbg, ("NtfsPerformVerifyOperation -> %08lx\n", Results) );

    return Results;
}


VOID
NtfsPerformDismountOnVcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN BOOLEAN DoCompleteDismount
    )

/*++

Routine Description:

    This routine is called to start the dismount process on a vcb.
    It marks the Vcb as not mounted and dereferences all opened stream
    file objects, and gets the Vcb out of the Vpb's mounted volume
    structures.

Arguments:

    Vcb - Supplies the Vcb being dismounted

    DoCompleteDismount - Indicates if we are to actually mark the volume
        as dismounted or if we are simply to stop the logfile and close
        the internal attribute streams.

Return Value:

    None.

--*/

{
    PFCB Fcb;
    PSCB Scb;
    PVOID RestartKey;

    BOOLEAN Restart;

    PVPB NewVpb;

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

    //
    //  Blow away our delayed close file object.
    //

    if (!IsListEmpty( &NtfsData.AsyncCloseList ) ||
        !IsListEmpty( &NtfsData.DelayedCloseList )) {

        NtfsFspClose( Vcb );
    }

    //
    //  Commit any current transaction before we start tearing down the volume.
    //

    NtfsCommitCurrentTransaction( IrpContext );

    //
    //  Acquire all files exclusively to make dismount atomic.
    //

    NtfsAcquireAllFiles( IrpContext, Vcb, TRUE, FALSE );

    //
    //  Use a try-finally to facilitate cleanup.
    //

    try {

        //
        //  Get rid of Cairo Files
        //

#ifdef _CAIRO_
        if (Vcb->QuotaTableScb != NULL) {
            NtOfsCloseIndex( IrpContext, Vcb->QuotaTableScb );
            Vcb->QuotaTableScb = NULL;
        }
#endif _CAIRO_

        //
        //  Stop the log file.
        //

        NtfsStopLogFile( Vcb );

        //
        //  Now for every file Scb with an opened stream file we will delete
        //  the internal attribute stream
        //

        RestartKey = NULL;
        while (TRUE) {

            NtfsAcquireFcbTable( IrpContext, Vcb );
            Fcb = NtfsGetNextFcbTableEntry(Vcb, &RestartKey);
            NtfsReleaseFcbTable( IrpContext, Vcb );

            if (Fcb == NULL) {

                break;
            }

            ASSERT_FCB( Fcb );

            Scb = NULL;
            while ((Fcb != NULL) && ((Scb = NtfsGetNextChildScb(Fcb, Scb)) != NULL)) {

                ASSERT_SCB( Scb );

                if (Scb->FileObject != NULL) {

                    //
                    //  Assume we want to start from the beginning of the Fcb table.
                    //

                    Restart = TRUE;

                    //
                    //  For the VolumeDasdScb and bad cluster file, we simply decrement
                    //  the counts that we incremented.
                    //

                    if ((Scb == Vcb->VolumeDasdScb) ||
                        (Scb == Vcb->BadClusterFileScb)) {

                        Scb->FileObject = NULL;

                        NtfsDecrementCloseCounts( IrpContext,
                                                  Scb,
                                                  NULL,
                                                  TRUE,
                                                  FALSE,
                                                  FALSE );

                    //
                    //  Dereference the file object in the Scb unless it is the one in
                    //  the Vcb for the Log File.  This routine may not be able to
                    //  dereference file object because of synchronization problems (there
                    //  can be a lazy writer callback in process which owns the paging
                    //  io resource).  In that case we don't want to go back to the beginning
                    //  of Fcb table or we will loop indefinitely.
                    //

                    } else if (Scb->FileObject != Vcb->LogFileObject) {

                        Restart = NtfsDeleteInternalAttributeStream( Scb, TRUE );

                    //
                    //  This is the file object for the Log file.  Remove our
                    //  extra reference on the logfile Scb.
                    //

                    } else if (Scb->FileObject != NULL) {

                        //
                        //  Remember the log file object so we can defer the dereference.
                        //

                        NtfsDecrementCloseCounts( IrpContext,
                                                  Vcb->LogFileScb,
                                                  NULL,
                                                  TRUE,
                                                  FALSE,
                                                  TRUE );

                        Scb->FileObject = NULL;
                    }

                    if (Restart) {

                        if (Scb == Vcb->MftScb)               { Vcb->MftScb = NULL; }
                        if (Scb == Vcb->Mft2Scb)              { Vcb->Mft2Scb = NULL; }
                        if (Scb == Vcb->LogFileScb)           { Vcb->LogFileScb = NULL; }
                        if (Scb == Vcb->VolumeDasdScb)        { Vcb->VolumeDasdScb = NULL; }
                        if (Scb == Vcb->AttributeDefTableScb) { Vcb->AttributeDefTableScb = NULL; }
                        if (Scb == Vcb->UpcaseTableScb)       { Vcb->UpcaseTableScb = NULL; }
                        if (Scb == Vcb->RootIndexScb)         { Vcb->RootIndexScb = NULL; }
                        if (Scb == Vcb->BitmapScb)            { Vcb->BitmapScb = NULL; }
                        if (Scb == Vcb->BadClusterFileScb)    { Vcb->BadClusterFileScb = NULL; }
                        if (Scb == Vcb->QuotaTableScb)        { Vcb->QuotaTableScb = NULL; }
                        if (Scb == Vcb->MftBitmapScb)         { Vcb->MftBitmapScb = NULL; }

#if defined (_CAIRO_)
                        if (Scb == Vcb->SecurityIdIndex)      { Vcb->SecurityIdIndex = NULL; }
                        if (Scb == Vcb->SecurityDescriptorHashIndex)
                                                              { Vcb->SecurityDescriptorHashIndex = NULL; }
                        if (Scb == Vcb->SecurityDescriptorStream)
                                                              { Vcb->SecurityDescriptorStream = NULL; }
#endif  //  defined (_CAIRO_)

                        //
                        //  Now zero out the enumerations so we will start all over again because
                        //  our call to Delete Internal Attribute Stream just messed up our
                        //  enumeration.
                        //

                        Scb = NULL;
                        Fcb = NULL;
                        RestartKey = NULL;
                    }
                }
            }
        }

        //
        //  Mark the volume as not mounted.
        //

        ClearFlag( Vcb->VcbState, VCB_STATE_VOLUME_MOUNTED );

        //
        //  Now only really dismount the volume if that's what our caller wants
        //

        if (DoCompleteDismount) {

            PREVENT_MEDIA_REMOVAL Prevent;
            KIRQL SavedIrql;

            //
            //  Attempt to unlock any removable media, ignoring status.
            //

            Prevent.PreventMediaRemoval = FALSE;
            (PVOID)NtfsDeviceIoControl( IrpContext,
                                        Vcb->TargetDeviceObject,
                                        IOCTL_DISK_MEDIA_REMOVAL,
                                        &Prevent,
                                        sizeof(PREVENT_MEDIA_REMOVAL),
                                        NULL,
                                        0 );

            //
            //  Remove this voldo from the mounted disk structures
            //
            //  Assume we will need a new Vpb.  Deallocate it later if not needed.
            //

            NewVpb = NtfsAllocatePoolWithTag( NonPagedPoolMustSucceed, sizeof( VPB ), 'VftN' );
            RtlZeroMemory( NewVpb, sizeof( VPB ) );

            IoAcquireVpbSpinLock( &SavedIrql );

            //
            //  If there are no file objects and no reference counts in the
            //  Vpb then we can use the existing Vpb.
            //

            if ((Vcb->CloseCount == 0) &&
                (Vcb->Vpb->ReferenceCount == 0)) {

                Vcb->Vpb->DeviceObject = NULL;
                ClearFlag( Vcb->Vpb->Flags, VPB_MOUNTED );

            //
            //  Otherwise we will swap out the Vpb.
            //

            } else {

                NewVpb->Type = IO_TYPE_VPB;
                NewVpb->Size = sizeof( VPB );
                NewVpb->RealDevice = Vcb->Vpb->RealDevice;
                Vcb->Vpb->RealDevice->Vpb = NewVpb;

                SetFlag( Vcb->VcbState, VCB_STATE_TEMP_VPB );

                NewVpb = NULL;
            }

            IoReleaseVpbSpinLock( SavedIrql );

            SetFlag( Vcb->VcbState, VCB_STATE_PERFORMED_DISMOUNT );

            //
            //  Free the temp Vpb if not used.
            //

            if (NewVpb) {

                NtfsFreePool( NewVpb );
            }
        }

    } finally {

        NtfsReleaseAllFiles( IrpContext, Vcb, FALSE );

        //
        //  And return to our caller
        //

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

    return;
}


BOOLEAN
NtfsPingVolume (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine will ping the volume to see if the device needs to
    be verified.  It is used for create operations to see if the
    create should proceed or if we should complete the create Irp
    with a remount status.

Arguments:

    Vcb - Supplies the Vcb being pinged

Return Value:

    BOOLEAN - TRUE if the volume is fine and the operation should
        proceed and FALSE if the volume needs to be verified

--*/

{
    BOOLEAN Results;

    PAGED_CODE();

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

    //
    //  If the media is removable and the verify volume flag in the
    //  device object is not set then we want to ping the device
    //  to see if it needs to be verified.
    //
    //  Note that we only force this ping for create operations.
    //  For others we take a sporting chance.  If in the end we
    //  have to physically access the disk, the right thing will happen.
    //

    if ( FlagOn(Vcb->VcbState, VCB_STATE_REMOVABLE_MEDIA) &&
         !FlagOn(Vcb->Vpb->RealDevice->Flags, DO_VERIFY_VOLUME) ) {

        PIRP Irp;
        KEVENT Event;
        PDEVICE_OBJECT TargetDevice;
        IO_STATUS_BLOCK Iosb;
        NTSTATUS Status;
        LONGLONG ThirtySeconds = (-10 * 1000 * 1000) * 30;

        KeInitializeEvent( &Event, NotificationEvent, FALSE );
        TargetDevice = Vcb->TargetDeviceObject;

        Irp = IoBuildDeviceIoControlRequest( IOCTL_DISK_CHECK_VERIFY,
                                             TargetDevice,
                                             NULL,
                                             0,
                                             NULL,
                                             0,
                                             FALSE,
                                             &Event,
                                             &Iosb );

        if (Irp == NULL) {

            NtfsRaiseStatus( IrpContext, STATUS_INSUFFICIENT_RESOURCES, NULL, NULL );
        }

        Status = IoCallDriver( TargetDevice, Irp );


        if (Status == STATUS_PENDING) {

            Status = KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, (PLARGE_INTEGER)&ThirtySeconds );

            ASSERT( Status == STATUS_SUCCESS );

            if ( !NT_SUCCESS(Iosb.Status) ) {

                NtfsRaiseStatus( IrpContext, Iosb.Status, NULL, NULL );
            }

        } else {

            if ( !NT_SUCCESS(Status) ) {

                NtfsRaiseStatus( IrpContext, Status, NULL, NULL );
            }
        }
    }

    if (FlagOn( Vcb->Vpb->RealDevice->Flags, DO_VERIFY_VOLUME)) {

        Results = FALSE;

    } else {

        Results = TRUE;
    }

    DebugTrace( -1, Dbg, ("NtfsPingVolume -> %08lx\n", Results) );

    return Results;
}


VOID
NtfsVolumeCheckpointDpc (
    IN PKDPC Dpc,
    IN PVOID DeferredContext,
    IN PVOID SystemArgument1,
    IN PVOID SystemArgument2
    )

/*++

Routine Description:

    This routine is dispatched every 5 seconds when disk structure is being
    modified.  It had the ExWorker thread to volume checkpoints.

Arguments:

    DeferredContext - Not Used

Return Value:

    None.

--*/

{
    TIMER_STATUS TimerStatus;

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

    //
    //  Atomic reset of status indicating the timer is currently fired.  This
    //  synchronizes with NtfsSetDirtyBcb.  After NtfsSetDirtyBcb dirties
    //  a Bcb, it sees if it should enable this timer routine.
    //
    //  If the status indicates that a timer is active, it does nothing.  In this
    //  case it is guaranteed that when the timer fires, it causes a checkpoint (to
    //  force out the dirty Bcb data).
    //
    //  If there is no timer active, it enables it, thus queueing a checkpoint later.
    //
    //  If the timer routine actually fires between the dirtying of the Bcb and the
    //  testing of the status then a single extra checkpoint is generated.  This
    //  extra checkpoint is not considered harmful.
    //

    //
    //  Atomically reset status and get previous value
    //

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

    //
    //  We have only one instance of the work queue item.  It can only be
    //  queued once.  In a slow system, this checkpoint item may not be processed
    //  by the time this timer routine fires again.
    //

    if (NtfsData.VolumeCheckpointItem.List.Flink == NULL) {
        ExQueueWorkItem( &NtfsData.VolumeCheckpointItem, CriticalWorkQueue );
    }
}


VOID
NtfsCheckpointAllVolumes (
    PVOID Parameter
    )

/*++

Routine Description:

    This routine searches all of the vcbs for Ntfs and tries to clean
    them.  If the vcb is good and dirty but not almost clean then
    we set it almost clean.  If the Vcb is good and dirty and almost clean
    then we clean it.

Arguments:

    Parameter - Not Used.

Return Value:

    None.

--*/

{
    TOP_LEVEL_CONTEXT TopLevelContext;
    PTOP_LEVEL_CONTEXT ThreadTopLevelContext;

    IRP_CONTEXT LocalIrpContext;
    IRP LocalIrp;

    PIRP_CONTEXT IrpContext;

    PLIST_ENTRY Links;
    PVCB Vcb;

    BOOLEAN AcquiredGlobal = FALSE;
    BOOLEAN StartTimer = FALSE;

    TIMER_STATUS TimerStatus;

    UNREFERENCED_PARAMETER( Parameter );

    PAGED_CODE();

    RtlZeroMemory( &LocalIrpContext, sizeof(LocalIrpContext) );
    RtlZeroMemory( &LocalIrp, sizeof(LocalIrp) );

    IrpContext = &LocalIrpContext;
    IrpContext->NodeTypeCode = NTFS_NTC_IRP_CONTEXT;
    IrpContext->NodeByteSize = sizeof(IRP_CONTEXT);
    IrpContext->OriginatingIrp = &LocalIrp;
    SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT);
    InitializeListHead( &IrpContext->ExclusiveFcbList );

    //
    //  Make sure we don't get any pop-ups
    //

    ThreadTopLevelContext = NtfsSetTopLevelIrp( &TopLevelContext, TRUE, FALSE );
    ASSERT( ThreadTopLevelContext == &TopLevelContext );

    (VOID) ExAcquireResourceShared( &NtfsData.Resource, TRUE );
    AcquiredGlobal = TRUE;

    try {

        NtfsUpdateIrpContextWithTopLevel( IrpContext, ThreadTopLevelContext );

        try {

            for (Links = NtfsData.VcbQueue.Flink;
                 Links != &NtfsData.VcbQueue;
                 Links = Links->Flink) {

                Vcb = CONTAINING_RECORD(Links, VCB, VcbLinks);

                IrpContext->Vcb = Vcb;

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

                    NtfsCheckpointVolume( IrpContext, Vcb, FALSE, FALSE, TRUE, Li0 );

                    //
                    //  Check to see whether this was not a clean checkpoint.
                    //

                    if (!FlagOn( Vcb->CheckpointFlags, VCB_LAST_CHECKPOINT_CLEAN )) {

                        StartTimer = TRUE;
                    }

                    NtfsCommitCurrentTransaction( IrpContext );
#ifdef _CAIRO_
                    if (NtfsCheckQuota && Vcb->QuotaTableScb != NULL) {
                        NtfsPostRepairQuotaIndex( IrpContext, Vcb );
                    }
#endif // _CAIRO_

                }
            }

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

            NOTHING;
        }

        //
        //  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.
        //

        if (StartTimer) {

            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 );
            }
        }

    } finally {

        if (AcquiredGlobal) {
            ExReleaseResource( &NtfsData.Resource );
        }

        NtfsRestoreTopLevelIrp( ThreadTopLevelContext );
    }

    //
    //  And return to our caller
    //

    return;
}


VOID
NtfsVerifyOperationIsLegal (
    IN PIRP_CONTEXT IrpContext,
    IN PIRP Irp
    )

/*++

Routine Description:

    This routine determines is the requested operation should be allowed to
    continue.  It either returns to the user if the request is Okay, or
    raises an appropriate status.

Arguments:

    Irp - Supplies the Irp to check

Return Value:

    None.

--*/

{
    PFILE_OBJECT FileObject;
    PIO_STACK_LOCATION IrpSp;

    PAGED_CODE();

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

    //
    //  We may be called during a clean all volumes operation.  In this case
    //  we have a dummy Irp that we created.  If the Irp stack
    //  count is zero then there is nothing to do here.
    //

    if (Irp->StackCount == 0) {

        return;
    }

    //
    //  If there is not a file object, we cannot continue.
    //

    if (FileObject == NULL) {

        return;
    }

    //
    //  If we are trying to do any other operation than close on a file
    //  object marked for delete, raise STATUS_DELETE_PENDING.
    //

    if (FileObject->DeletePending == TRUE
        && IrpContext->MajorFunction != IRP_MJ_CLEANUP
        && IrpContext->MajorFunction != IRP_MJ_CLOSE ) {

        NtfsRaiseStatus( IrpContext, STATUS_DELETE_PENDING, NULL, NULL );
    }

    //
    //  If we are doing a create, and there is a related file objects, and
    //  it it is marked for delete, raise STATUS_DELETE_PENDING.
    //

    if (IrpContext->MajorFunction == IRP_MJ_CREATE) {

        PFILE_OBJECT RelatedFileObject;

        PVCB Vcb;
        PFCB Fcb;
        PSCB Scb;
        PCCB Ccb;

        RelatedFileObject = FileObject->RelatedFileObject;

        NtfsDecodeFileObject( IrpContext,
                              RelatedFileObject,
                              &Vcb,
                              &Fcb,
                              &Scb,
                              &Ccb,
                              TRUE );

        if (RelatedFileObject != NULL
            && Fcb->LinkCount == 0)  {

            NtfsRaiseStatus( IrpContext, STATUS_DELETE_PENDING, NULL, NULL );
        }
    }

    //
    //  If the file object has already been cleaned up, and
    //
    //  A) This request is a paging io read or write, or
    //  B) This request is a close operation, or
    //  C) This request is a set or query info call (for Lou)
    //  D) This is an MDL complete
    //
    //  let it pass, otherwise return STATUS_FILE_CLOSED.
    //

    if ( FlagOn(FileObject->Flags, FO_CLEANUP_COMPLETE) ) {

        PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation( Irp );

        if ( (FlagOn(Irp->Flags, IRP_PAGING_IO)) ||
             (IrpSp->MajorFunction == IRP_MJ_CLOSE ) ||
             (IrpSp->MajorFunction == IRP_MJ_SET_INFORMATION) ||
             (IrpSp->MajorFunction == IRP_MJ_QUERY_INFORMATION) ||
             ( ( (IrpSp->MajorFunction == IRP_MJ_READ) ||
                 (IrpSp->MajorFunction == IRP_MJ_WRITE) ) &&
               FlagOn(IrpSp->MinorFunction, IRP_MN_COMPLETE) ) ) {

            NOTHING;

        } else {

            NtfsRaiseStatus( IrpContext, STATUS_FILE_CLOSED, NULL, NULL );
        }
    }

    return;
}


//
//  Local Support routine
//

VOID
NtfsPerformVerifyDiskRead (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN PVOID Buffer,
    IN LONGLONG Offset,
    IN ULONG NumberOfBytesToRead
    )

/*++

Routine Description:

    This routine is used to read in a range of bytes from the disk.  It
    bypasses all of the caching and regular I/O logic, and builds and issues
    the requests itself.  It does this operation overriding the verify
    volume flag in the device object.

Arguments:

    Vcb - Supplies the Vcb denoting the device for this operation

    Buffer - Supplies the buffer that will recieve the results of this operation

    Offset - Supplies the offset of where to start reading

    NumberOfBytesToRead - Supplies the number of bytes to read, this must
        be in multiple of bytes units acceptable to the disk driver.

Return Value:

    None.

--*/

{
    KEVENT Event;
    PIRP Irp;
    NTSTATUS Status;

    ASSERT_IRP_CONTEXT( IrpContext );
    ASSERT_VCB( Vcb );

    PAGED_CODE();

    //
    //  Initialize the event we're going to use
    //

    KeInitializeEvent( &Event, NotificationEvent, FALSE );

    //
    //  Build the irp for the operation and also set the overrride flag
    //
    //  Note that we may be at APC level, so do this asyncrhonously and
    //  use an event for synchronization normal request completion
    //  cannot occur at APC level.
    //

    Irp = IoBuildAsynchronousFsdRequest( IRP_MJ_READ,
                                         Vcb->TargetDeviceObject,
                                         Buffer,
                                         NumberOfBytesToRead,
                                         (PLARGE_INTEGER)&Offset,
                                         NULL );

    if ( Irp == NULL ) {

        NtfsRaiseStatus( IrpContext, STATUS_INSUFFICIENT_RESOURCES, NULL, NULL );
    }

    SetFlag( IoGetNextIrpStackLocation( Irp )->Flags, SL_OVERRIDE_VERIFY_VOLUME );

    //
    //  Set up the completion routine
    //

    IoSetCompletionRoutine( Irp,
                            NtfsVerifyReadCompletionRoutine,
                            &Event,
                            TRUE,
                            TRUE,
                            TRUE );

    //
    //  Call the device to do the write and wait for it to finish.
    //

    try {

        (VOID)IoCallDriver( Vcb->TargetDeviceObject, Irp );
        (VOID)KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, (PLARGE_INTEGER)NULL );

        //
        //  Grab the Status.
        //

        Status = Irp->IoStatus.Status;

    } finally {

        //
        //  If there is an MDL (or MDLs) associated with this I/O
        //  request, Free it (them) here.  This is accomplished by
        //  walking the MDL list hanging off of the IRP and deallocating
        //  each MDL encountered.
        //

        while (Irp->MdlAddress != NULL) {

            PMDL NextMdl;

            NextMdl = Irp->MdlAddress->Next;

            MmUnlockPages( Irp->MdlAddress );

            IoFreeMdl( Irp->MdlAddress );

            Irp->MdlAddress = NextMdl;
        }

        IoFreeIrp( Irp );
    }

    //
    //  If it doesn't succeed then raise the error
    //

    if (!NT_SUCCESS(Status)) {

        NtfsNormalizeAndRaiseStatus( IrpContext,
                                     Status,
                                     STATUS_UNEXPECTED_IO_ERROR );
    }

    //
    //  And return to our caller
    //

    return;
}


NTSTATUS
NtfsIoCallSelf (
    IN PIRP_CONTEXT IrpContext,
    IN PFILE_OBJECT FileObject,
    IN UCHAR MajorFunction
    )

/*++

Routine Description:

    This routine is used to call ourselves for a simple function.  Note that
    if more use is found for this routine than the few current uses, its interface
    may be easily expanded.

Arguments:

    FileObject - FileObject for request.

    MajorFunction - function to be performed.

Return Value:

    Status code resulting from the driver call

--*/

{
    KEVENT Event;
    PIRP Irp;
    PDEVICE_OBJECT DeviceObject;
    PIO_STACK_LOCATION IrpSp;
    NTSTATUS Status;

    ASSERT_IRP_CONTEXT( IrpContext );

    PAGED_CODE();

    //
    //  Initialize the event we're going to use
    //

    KeInitializeEvent( &Event, NotificationEvent, FALSE );
    DeviceObject = IoGetRelatedDeviceObject( FileObject );

    //
    // Reference the file object here so that no special checks need be made
    // in I/O completion to determine whether or not to dereference the file
    // object.
    //

    if (MajorFunction != IRP_MJ_CLOSE) {
        ObReferenceObject( FileObject );
    }

    //
    //  Build the irp for the operation and also set the overrride flag
    //
    //  Note that we may be at APC level, so do this asyncrhonously and
    //  use an event for synchronization normal request completion
    //  cannot occur at APC level.
    //


    Irp = IoBuildAsynchronousFsdRequest( IRP_MJ_SHUTDOWN,
                                         DeviceObject,
                                         NULL,
                                         0,
                                         NULL,
                                         NULL );

    if (Irp == NULL) {
        return STATUS_INSUFFICIENT_RESOURCES;
    }

    //
    //  Fill in a few remaining items
    //

    Irp->Tail.Overlay.OriginalFileObject = FileObject;

    IrpSp = IoGetNextIrpStackLocation(Irp);
    IrpSp->MajorFunction = MajorFunction;
    IrpSp->FileObject = FileObject;

    //
    //  Set up the completion routine
    //

    IoSetCompletionRoutine( Irp,
                            NtfsVerifyReadCompletionRoutine,
                            &Event,
                            TRUE,
                            TRUE,
                            TRUE );

    //
    //  Call the device to do the write and wait for it to finish.
    //

    try {

        (VOID)IoCallDriver( DeviceObject, Irp );
        (VOID)KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, (PLARGE_INTEGER)NULL );

        //
        //  Grab the Status.
        //

        Status = Irp->IoStatus.Status;

    } finally {

        //
        //  There should never be an MDL here.
        //

        ASSERT(Irp->MdlAddress == NULL);

        IoFreeIrp( Irp );
    }

    //
    //  If it doesn't succeed then raise the error
    //
    //  And return to our caller
    //

    return Status;
}

BOOLEAN
NtfsLogEvent (
    IN PIRP_CONTEXT IrpContext,
    IN PQUOTA_USER_DATA UserData OPTIONAL,
    IN NTSTATUS LogCode,
    IN NTSTATUS FinalStatus
    )

/*++

Routine Description:

    This routine logs an io event. If UserData is supplied then the
    data logged is a FILE_QUOTA_INFORMATION structure; otherwise the
    volume label is included.

Arguments:

    UserData - Supplies the optional quota user data index entry.

    LogCode - Supplies the Io Log code to use for the ErrorCode field.

    FinalStauts - Supplies the final status of the operation.

Return Value:

    True - if the event was successfully logged.

--*/

{
    PIO_ERROR_LOG_PACKET ErrorLogEntry;
    PFILE_QUOTA_INFORMATION FileQuotaInfo;
    ULONG SidLength;
    ULONG DumpDataLength = 0;
    ULONG LabelLength = 0;

    if (IrpContext->Vcb == NULL) {
        return FALSE;
    }

    if (UserData == NULL) {

        LabelLength = IrpContext->Vcb->Vpb->VolumeLabelLength + sizeof(WCHAR);

#ifdef _CAIRO_

    } else {

        //
        //  Calculate the required length of the Sid.
        //

        SidLength = RtlLengthSid( &UserData->QuotaSid );

        DumpDataLength = SidLength +
                         FIELD_OFFSET( FILE_QUOTA_INFORMATION, Sid );

#endif // _CAIRO_

    }

    ErrorLogEntry = (PIO_ERROR_LOG_PACKET)
                    IoAllocateErrorLogEntry( IrpContext->Vcb->TargetDeviceObject,
                                             (UCHAR) (DumpDataLength +
                                                      LabelLength +
                                             sizeof(IO_ERROR_LOG_PACKET)) );

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

    ErrorLogEntry->ErrorCode = LogCode;
    ErrorLogEntry->FinalStatus = FinalStatus;

    ErrorLogEntry->SequenceNumber = IrpContext->TransactionId;
    ErrorLogEntry->MajorFunctionCode = IrpContext->MajorFunction;
    ErrorLogEntry->RetryCount = 0;
    ErrorLogEntry->DumpDataSize = (USHORT) DumpDataLength;

    if (UserData == NULL) {

        PWCHAR String;

        //
        //  The label string at the end of the error log entry.
        //

        String = (PWCHAR) (ErrorLogEntry + 1);

        ErrorLogEntry->NumberOfStrings = 1;
        ErrorLogEntry->StringOffset = sizeof( IO_ERROR_LOG_PACKET );
        RtlCopyMemory( String,
                       IrpContext->Vcb->Vpb->VolumeLabel,
                       IrpContext->Vcb->Vpb->VolumeLabelLength );

        //
        //  Make sure the string is null terminated.
        //

        String += IrpContext->Vcb->Vpb->VolumeLabelLength / sizeof( WCHAR );

        *String = L'\0';

#ifdef _CAIRO_

    } else {

        FileQuotaInfo = (PFILE_QUOTA_INFORMATION) ErrorLogEntry->DumpData;

        FileQuotaInfo->NextEntryOffset = 0;
        FileQuotaInfo->SidLength = SidLength;
        FileQuotaInfo->ChangeTime.QuadPart = UserData->QuotaChangeTime;
        FileQuotaInfo->QuotaUsed.QuadPart = UserData->QuotaUsed;
        FileQuotaInfo->QuotaThreshold.QuadPart = UserData->QuotaThreshold;
        FileQuotaInfo->QuotaLimit.QuadPart = UserData->QuotaLimit;
        RtlCopyMemory( &FileQuotaInfo->Sid,
                       &UserData->QuotaSid,
                       SidLength );

#endif // _CAIRO

    }

    IoWriteErrorLogEntry( ErrorLogEntry );

    return TRUE;
}


VOID
NtfsPostVcbIsCorrupt (
    IN PIRP_CONTEXT IrpContext,
    IN NTSTATUS  Status OPTIONAL,
    IN PFILE_REFERENCE FileReference OPTIONAL,
    IN PFCB Fcb OPTIONAL
    )

/*++

Routine Description:

    This routine is called to mark the volume dirty and possibly raise a hard error.

Arguments:

    Status - If not zero, then this is the error code for the popup.

    FileReference - If specified, then this is the file reference for the corrupt file.

    Fcb - If specified, then this is the Fcb for the corrupt file.

Return Value:

    None

--*/
{
    PVCB Vcb = IrpContext->Vcb;

#ifdef NTFS_CORRUPT
{
    KdPrint(("NTFS: Post Vcb is corrupt\n", 0));
    DbgBreakPoint();
}
#endif

    //
    //  Set this flag to keep the volume from ever getting set clean.
    //

    if (Vcb != NULL) {

        NtfsMarkVolumeDirty( IrpContext, Vcb );

        //
        //  This would be the appropriate place to raise a hard error popup,
        //  ala the code in FastFat.  We should do it after marking the volume
        //  dirty so that if anything goes wrong with the popup, the volume is
        //  already marked anyway.
        //

        if (Status != 0) {

            NtfsRaiseInformationHardError( IrpContext,
                                           Status,
                                           FileReference,
                                           Fcb );
        }
    }
}


VOID
NtfsMarkVolumeDirty (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine may be called any time the Mft is open to mark the volume
    dirty.

Arguments:

    Vcb - Vcb for volume to mark dirty

Return Value:

    None

--*/

{
    ATTRIBUTE_ENUMERATION_CONTEXT AttributeContext;
    PVOLUME_INFORMATION VolumeInformation;

    PAGED_CODE();

#if DBG
    KdPrint(("NTFS: Marking volume dirty, Vcb: %08lx\n", Vcb));
#endif

#ifdef NTFS_CORRUPT
{
    KdPrint(("NTFS: Marking volume dirty\n", 0));
    DbgBreakPoint();
}
#endif

    //  if (FlagOn(*(PULONG)NtGlobalFlag, 0x00080000)) {
    //      KdPrint(("NTFS: marking volume dirty\n", 0));
    //      DbgBreakPoint();
    //  }

    //
    //  Return if the volume is already marked dirty.  This also prevents
    //  endless recursion if the volume file itself is corrupt.
    //

    if (FlagOn(Vcb->VcbState, VCB_STATE_VOLUME_MOUNTED_DIRTY)) {
        return;
    }

    SetFlag(Vcb->VcbState, VCB_STATE_VOLUME_MOUNTED_DIRTY);

    NtfsInitializeAttributeContext( &AttributeContext );

    try {

        if (NtfsLookupAttributeByCode( IrpContext,
                                       Vcb->VolumeDasdScb->Fcb,
                                       &Vcb->VolumeDasdScb->Fcb->FileReference,
                                       $VOLUME_INFORMATION,
                                       &AttributeContext )) {

            VolumeInformation =
              (PVOLUME_INFORMATION)NtfsAttributeValue( NtfsFoundAttribute( &AttributeContext ));

            NtfsPinMappedAttribute( IrpContext, Vcb, &AttributeContext );

            SetFlag(VolumeInformation->VolumeFlags, VOLUME_DIRTY);

            CcSetDirtyPinnedData( NtfsFoundBcb(&AttributeContext), NULL );

            NtfsCleanupAttributeContext( &AttributeContext );
        }

    } finally {

        NtfsCleanupAttributeContext( &AttributeContext );
    }

    NtfsLogEvent( IrpContext,
                  NULL,
                  IO_FILE_SYSTEM_CORRUPT,
                  STATUS_DISK_CORRUPT_ERROR );
}


VOID
NtfsUpdateVersionNumber (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN UCHAR MajorVersion,
    IN UCHAR MinorVersion
    )

/*++

Routine Description:

    This routine is called to update the version number on disk, without
    going through the logging package.

Arguments:

    Vcb - Vcb for volume.

    MajorVersion - This is the Major Version number to write out.

    MinorVersion - This is the Minor Version number to write out.

Return Value:

    None

--*/

{
    ATTRIBUTE_ENUMERATION_CONTEXT AttributeContext;
    PVOLUME_INFORMATION VolumeInformation;

    PAGED_CODE();

    NtfsInitializeAttributeContext( &AttributeContext );

    try {

        //
        //  Lookup the volume information attribute.
        //

        if (NtfsLookupAttributeByCode( IrpContext,
                                       Vcb->VolumeDasdScb->Fcb,
                                       &Vcb->VolumeDasdScb->Fcb->FileReference,
                                       $VOLUME_INFORMATION,
                                       &AttributeContext )) {

            VolumeInformation =
              (PVOLUME_INFORMATION)NtfsAttributeValue( NtfsFoundAttribute( &AttributeContext ));

            NtfsPinMappedAttribute( IrpContext, Vcb, &AttributeContext );

            //
            //  Now update the version number fields.
            //

            VolumeInformation->MajorVersion = MajorVersion;
            VolumeInformation->MinorVersion = MinorVersion;

            CcSetDirtyPinnedData( NtfsFoundBcb(&AttributeContext), NULL );

            NtfsCleanupAttributeContext( &AttributeContext );

            //
            //  Now flush it out, so the new version numbers will be present on
            //  the next mount.
            //

            CcFlushCache( Vcb->MftScb->FileObject->SectionObjectPointer,
                          (PLARGE_INTEGER)&AttributeContext.FoundAttribute.MftFileOffset,
                          Vcb->BytesPerFileRecordSegment,
                          NULL );
        }

    } finally {

        NtfsCleanupAttributeContext( &AttributeContext );
    }
}

//
//  Local support routine
//

NTSTATUS
NtfsVerifyReadCompletionRoutine(
    IN PDEVICE_OBJECT DeviceObject,
    IN PIRP Irp,
    IN PVOID Contxt
    )

{
    //
    //  Set the event so that our call will wake up.
    //

    KeSetEvent( (PKEVENT)Contxt, 0, FALSE );

    UNREFERENCED_PARAMETER( DeviceObject );
    UNREFERENCED_PARAMETER( Irp );

    return STATUS_MORE_PROCESSING_REQUIRED;
}

//
//  Local support routine
//

NTSTATUS
NtfsDeviceIoControlAsync (
    IN PIRP_CONTEXT IrpContext,
    IN PDEVICE_OBJECT DeviceObject,
    IN ULONG IoCtl
    )
    
/*++

Routine Description:

    This routine is used to perform an IoCtl when we may be at the APC level
    and calling NtfsDeviceIoControl could be unsafe.

Arguments:

    DeviceObject - Supplies the device object to which to send the ioctl.

    IoCtl - Supplies the I/O control code.

Return Value:

    Status.

--*/

{
    KEVENT Event;
    PIRP Irp;
    NTSTATUS Status;
    PIO_STACK_LOCATION IrpSp;

    ASSERT_IRP_CONTEXT( IrpContext );

    //
    //  We'll be leaving the event on the stack, so let's be sure 
    //  that we've done an FsRtlEnterFileSystem before we got here.
    //  I claim that we're never going to end up here in the fast 
    //  io path, but let's make certain.
    //

    ASSERTMSG( "Didn't FsRtlEnterFileSystem", KeGetCurrentThread()->KernelApcDisable != 0 );

    //
    //  Initialize the event we're going to use
    //

    KeInitializeEvent( &Event, NotificationEvent, FALSE );

    //
    //  Build the irp for the operation and also set the overrride flag
    //
    //  Note that we may be at APC level, so do this asyncrhonously and
    //  use an event for synchronization normal request completion
    //  cannot occur at APC level.
    //

    //  ****  Change this irp_mj_ back after Jeff or Peter changes io so
    //  ****  that we can pass in the right irp_mj_ and no buffers.

    Irp = IoBuildAsynchronousFsdRequest( IRP_MJ_FLUSH_BUFFERS, // **** IRP_MJ_DEVICE_CONTROL,
                                         DeviceObject,
                                         NULL,
                                         0,
                                         NULL,
                                         NULL );

    if ( Irp == NULL ) {

        NtfsRaiseStatus( IrpContext, STATUS_INSUFFICIENT_RESOURCES, NULL, NULL );
    }

    IrpSp = IoGetNextIrpStackLocation( Irp );
    SetFlag( IrpSp->Flags, SL_OVERRIDE_VERIFY_VOLUME );
    
    IrpSp->Parameters.DeviceIoControl.IoControlCode = IoCtl;
    
    // **** Remove this, too.
    
    IrpSp->MajorFunction = IRP_MJ_DEVICE_CONTROL;
    
    //
    //  Set up the completion routine.
    //

    IoSetCompletionRoutine( Irp,
                            NtfsVerifyReadCompletionRoutine,
                            &Event,
                            TRUE,
                            TRUE,
                            TRUE );

    //
    //  Call the device to do the io and wait for it to finish.
    //

    (VOID)IoCallDriver( DeviceObject, Irp );
    (VOID)KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, (PLARGE_INTEGER)NULL );

    //
    //  Grab the Status.
    //

    Status = Irp->IoStatus.Status;

    IoFreeIrp( Irp );

    //
    //  And return to our caller.
    //

    return Status;
}