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

Copyright (c) 1989-2000 Microsoft Corporation

Module Name:

    VerfySup.c

Abstract:

    This module implements the Fat Verify volume and fcb/dcb support
    routines


--*/

#include "FatProcs.h"

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

#define BugCheckFileId                   (FAT_BUG_CHECK_VERFYSUP)

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

#define Dbg                              (DEBUG_TRACE_VERFYSUP)

//
//  Local procedure prototypes
//

VOID
FatResetFcb (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb
    );

BOOLEAN
FatMatchFileSize (
    __in PIRP_CONTEXT IrpContext,
    __in PDIRENT Dirent,
    __in PFCB Fcb
    );

_Requires_lock_held_(_Global_critical_region_)
VOID
FatDetermineAndMarkFcbCondition (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb
    );

WORKER_THREAD_ROUTINE FatDeferredCleanVolume;

VOID
FatDeferredCleanVolume (
    _In_ PVOID Parameter
    );

IO_COMPLETION_ROUTINE FatMarkVolumeCompletionRoutine;

NTSTATUS
FatMarkVolumeCompletionRoutine(
    _In_ PDEVICE_OBJECT DeviceObject,
    _In_ PIRP Irp,
    _In_reads_opt_(_Inexpressible_("varies")) PVOID Contxt
    );

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FatCheckDirtyBit)
#pragma alloc_text(PAGE, FatVerifyOperationIsLegal)
#pragma alloc_text(PAGE, FatDeferredCleanVolume)
#pragma alloc_text(PAGE, FatMatchFileSize)
#pragma alloc_text(PAGE, FatDetermineAndMarkFcbCondition)
#pragma alloc_text(PAGE, FatQuickVerifyVcb)
#pragma alloc_text(PAGE, FatPerformVerify)
#pragma alloc_text(PAGE, FatMarkFcbCondition)
#pragma alloc_text(PAGE, FatResetFcb)
#pragma alloc_text(PAGE, FatVerifyVcb)
#pragma alloc_text(PAGE, FatVerifyFcb)
#endif


VOID
FatMarkFcbCondition (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb,
    IN FCB_CONDITION FcbCondition,
    IN BOOLEAN Recursive
    )

/*++

Routine Description:

    This routines marks the entire Fcb/Dcb structure from Fcb down with
    FcbCondition.

Arguments:

    Fcb - Supplies the Fcb/Dcb being marked

    FcbCondition - Supplies the setting to use for the Fcb Condition

    Recursive - Specifies whether this condition should be applied to
        all children (see the case where we are invalidating a live volume
        for a case where this is now desireable).

Return Value:

    None.

--*/

{
    PAGED_CODE();

    DebugTrace(+1, Dbg, "FatMarkFcbCondition, Fcb = %p\n", Fcb );

    //
    //  If we are marking this Fcb something other than Good, we will need
    //  to have the Vcb exclusive.
    //

    NT_ASSERT( FcbCondition != FcbNeedsToBeVerified ? TRUE :
            FatVcbAcquiredExclusive(IrpContext, Fcb->Vcb) );

    //
    //  If this is a PagingFile it has to be good unless media underneath is
    //  removable. The "removable" check was added specifically for ReadyBoost,
    //  which opens its cache file on a removable device as a paging file and
    //  relies on the file system to validate its mapping information after a
    //  power transition.
    //

    if (!FlagOn(Fcb->Vcb->VcbState, VCB_STATE_FLAG_REMOVABLE_MEDIA) &&
        FlagOn(Fcb->FcbState, FCB_STATE_PAGING_FILE)) {

        Fcb->FcbCondition = FcbGood;
        return;
    }

    //
    //  Update the condition of the Fcb.
    //

    Fcb->FcbCondition = FcbCondition;

    DebugTrace(0, Dbg, "MarkFcb: %wZ\n", &Fcb->FullFileName);

    //
    //  This FastIo flag is based on FcbCondition, so update it now.  This only
    //  applies to regular FCBs, of course.
    //

    if (Fcb->Header.NodeTypeCode == FAT_NTC_FCB) {

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

    if (FcbCondition == FcbNeedsToBeVerified) {
        FatResetFcb( IrpContext, Fcb );
    }

    //
    //  Now if we marked NeedsVerify or Bad a directory then we also need to
    //  go and mark all of our children with the same condition.
    //

    if ( ((FcbCondition == FcbNeedsToBeVerified) ||
          (FcbCondition == FcbBad)) &&
         Recursive &&
         ((Fcb->Header.NodeTypeCode == FAT_NTC_DCB) ||
          (Fcb->Header.NodeTypeCode == FAT_NTC_ROOT_DCB)) ) {

        PFCB OriginalFcb = Fcb;

        while ( (Fcb = FatGetNextFcbTopDown(IrpContext, Fcb, OriginalFcb)) != NULL ) {

            DebugTrace(0, Dbg, "MarkFcb: %wZ\n", &Fcb->FullFileName);

            Fcb->FcbCondition = FcbCondition;

            //
            //  We already know that FastIo is not possible since we are propagating
            //  a parent's bad/verify flag down the tree - IO to the children must
            //  take the long route for now.
            //

            Fcb->Header.IsFastIoPossible = FastIoIsNotPossible;

            //
            //  Leave all the Fcbs in a condition to be verified.
            //

            if (FcbCondition == FcbNeedsToBeVerified) {
                FatResetFcb( IrpContext, Fcb );
            }

        }
    }

    DebugTrace(-1, Dbg, "FatMarkFcbCondition -> VOID\n", 0);

    return;
}

BOOLEAN
FatMarkDevForVerifyIfVcbMounted(
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine checks to see if the specified Vcb is currently mounted on
    the device or not.  If it is,  it sets the verify flag on the device, if
    not then the state is noted in the Vcb.

Arguments:

    Vcb - This is the volume to check.

Return Value:

    TRUE if the device has been marked for verify here,  FALSE otherwise.

--*/
{
    BOOLEAN Marked = FALSE;
    KIRQL SavedIrql;

    IoAcquireVpbSpinLock( &SavedIrql );

#pragma prefast( push )
#pragma prefast( disable: 28175, "touching Vpb is ok for a filesystem" )

    if (Vcb->Vpb->RealDevice->Vpb == Vcb->Vpb)  {

        SetFlag( Vcb->Vpb->RealDevice->Flags, DO_VERIFY_VOLUME);
        Marked = TRUE;
    }
    else {

        //
        //  Flag this to avoid the VPB spinlock in future passes.
        //

        SetFlag( Vcb->VcbState, VCB_STATE_VPB_NOT_ON_DEVICE);
    }

#pragma prefast( pop )

    IoReleaseVpbSpinLock( SavedIrql );

    return Marked;
}


VOID
FatVerifyVcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routines verifies that the Vcb still denotes a valid Volume
    If the Vcb is bad it raises an error condition.

Arguments:

    Vcb - Supplies the Vcb being verified

Return Value:

    None.

--*/

{
    BOOLEAN DevMarkedForVerify;

    PAGED_CODE();

    DebugTrace(+1, Dbg, "FatVerifyVcb, Vcb = %p\n", Vcb );

    //
    //  If the verify volume flag in the device object is set
    //  this means the media has potentially changed.
    //
    //  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.
    //

    DevMarkedForVerify = BooleanFlagOn(Vcb->Vpb->RealDevice->Flags, DO_VERIFY_VOLUME);

    //
    //  We ALWAYS force CREATE requests on unmounted volumes through the
    //  verify path.  These requests could have been in limbo between
    //  IoCheckMountedVpb and us, when a verify/mount took place and caused
    //  a completely different fs/volume to be mounted.  In this case the
    //  checks above may not have caught the condition, since we may already
    //  have verified (wrong volume) and decided that we have nothing to do.
    //  We want the requests to be re routed to the currently mounted volume,
    //  since they were directed at the 'drive',  not our volume.  So we take
    //  the verify path for synchronisation,  and the request will eventually
    //  be bounced back to IO with STATUS_REPARSE by our verify handler.
    //

    if (!DevMarkedForVerify &&
        (IrpContext->MajorFunction == IRP_MJ_CREATE) &&
        (IrpContext->OriginatingIrp != NULL)) {

        PIO_STACK_LOCATION IrpSp = IoGetCurrentIrpStackLocation( IrpContext->OriginatingIrp);

        if ((IrpSp->FileObject->RelatedFileObject == NULL) &&
            (Vcb->VcbCondition == VcbNotMounted)) {

            DevMarkedForVerify = TRUE;
        }
    }

    //
    //  Raise any error condition otherwise.
    //

    if (DevMarkedForVerify) {

        DebugTrace(0, Dbg, "The Vcb needs to be verified\n", 0);

        IoSetHardErrorOrVerifyDevice( IrpContext->OriginatingIrp,
                                      Vcb->Vpb->RealDevice );

        FatNormalizeAndRaiseStatus( IrpContext, STATUS_VERIFY_REQUIRED );
    }

    //
    //  Check the operation is legal for current Vcb state.
    //

    FatQuickVerifyVcb( IrpContext, Vcb );

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


_Requires_lock_held_(_Global_critical_region_)
VOID
FatVerifyFcb (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb
    )

/*++

Routine Description:

    This routines verifies that the Fcb still denotes the same file.
    If the Fcb is bad it raises a error condition.

Arguments:

    Fcb - Supplies the Fcb being verified

Return Value:

    None.

--*/

{
    PFCB CurrentFcb;

    PAGED_CODE();

    DebugTrace(+1, Dbg, "FatVerifyFcb, Vcb = %p\n", Fcb );

    //
    //  Always refuse operations on dismounted volumes.
    //

    if (FlagOn( Fcb->Vcb->VcbState, VCB_STATE_FLAG_VOLUME_DISMOUNTED )) {

        FatRaiseStatus( IrpContext, STATUS_VOLUME_DISMOUNTED );
    }

    //
    //  If this is the Fcb of a deleted dirent or our parent is deleted,
    //  no-op this call with the hope that the caller will do the right thing.
    //  The only caller we really have to worry about is the AdvanceOnly
    //  callback for setting valid data length from Cc, this will happen after
    //  cleanup (and file deletion), just before the SCM is ripped down.
    //

    if (IsFileDeleted( IrpContext, Fcb ) ||
        ((NodeType(Fcb) != FAT_NTC_ROOT_DCB) &&
         IsFileDeleted( IrpContext, Fcb->ParentDcb ))) {

        return;
    }

    //
    //  If we are not in the process of doing a verify,
    //  first do a quick spot check on the Vcb.
    //

    if ( Fcb->Vcb->VerifyThread != KeGetCurrentThread() ) {

        FatQuickVerifyVcb( IrpContext, Fcb->Vcb );
    }

    //
    //  Now based on the condition of the Fcb we'll either return
    //  immediately to the caller, raise a condition, or do some work
    //  to verify the Fcb.
    //

    switch (Fcb->FcbCondition) {

    case FcbGood:

        DebugTrace(0, Dbg, "The Fcb is good\n", 0);
        break;

    case FcbBad:

        FatRaiseStatus( IrpContext, STATUS_FILE_INVALID );
        break;

    case FcbNeedsToBeVerified:

        //
        //  We loop here checking our ancestors until we hit an Fcb which
        //  is either good or bad.
        //

        CurrentFcb = Fcb;

        while (CurrentFcb->FcbCondition == FcbNeedsToBeVerified) {

            FatDetermineAndMarkFcbCondition(IrpContext, CurrentFcb);

            //
            //  If this Fcb didn't make it, or it was the Root Dcb, exit
            //  the loop now, else continue with out parent.
            //

            if ( (CurrentFcb->FcbCondition != FcbGood) ||
                 (NodeType(CurrentFcb) == FAT_NTC_ROOT_DCB) ) {

                break;
            }

            CurrentFcb = CurrentFcb->ParentDcb;
        }

        //
        //  Now we can just look at ourselves to see how we did.
        //

        if (Fcb->FcbCondition != FcbGood) {

            FatRaiseStatus( IrpContext, STATUS_FILE_INVALID );
        }

        break;

    default:

        DebugDump("Invalid FcbCondition\n", 0, Fcb);

#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )
        FatBugCheck( Fcb->FcbCondition, 0, 0 );
    }

    DebugTrace(-1, Dbg, "FatVerifyFcb -> VOID\n", 0);

    return;
}


VOID
FatDeferredCleanVolume (
    _In_ PVOID Parameter
    )

/*++

Routine Description:

    This is the routine that performs the actual FatMarkVolumeClean call.
    It assures that the target volume still exists as there ia a race
    condition between queueing the ExWorker item and volumes going away.

Arguments:

    Parameter - Points to a clean volume packet that was allocated from pool

Return Value:

    None.

--*/

{
    PCLEAN_AND_DIRTY_VOLUME_PACKET Packet;
    PLIST_ENTRY Links;
    PVCB Vcb;
    IRP_CONTEXT IrpContext;
    BOOLEAN VcbExists = FALSE;

    PAGED_CODE();

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

    Packet = (PCLEAN_AND_DIRTY_VOLUME_PACKET)Parameter;

    Vcb = Packet->Vcb;

    //
    //  Make us appear as a top level FSP request so that we will
    //  receive any errors from the operation.
    //

    IoSetTopLevelIrp( (PIRP)FSRTL_FSP_TOP_LEVEL_IRP );

    //
    //  Dummy up and Irp Context so we can call our worker routines
    //

    RtlZeroMemory( &IrpContext, sizeof(IRP_CONTEXT));

    SetFlag(IrpContext.Flags, IRP_CONTEXT_FLAG_WAIT);

    //
    //  Acquire shared access to the global lock and make sure this volume
    //  still exists.
    //

#pragma prefast( push )
#pragma prefast( disable: 28193, "this will always wait" )
    FatAcquireSharedGlobal( &IrpContext );
#pragma prefast( pop )

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

        PVCB ExistingVcb;

        ExistingVcb = CONTAINING_RECORD(Links, VCB, VcbLinks);

        if ( Vcb == ExistingVcb ) {

            VcbExists = TRUE;
            break;
        }
    }

    //
    //  If the vcb is good then mark it clean.  Ignore any problems.
    //

    if ( VcbExists &&
         (Vcb->VcbCondition == VcbGood) &&
         !FlagOn(Vcb->VcbState, VCB_STATE_FLAG_SHUTDOWN) ) {

        try {

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

                FatMarkVolume( &IrpContext, Vcb, VolumeClean );
            }

            //
            //  Check for a pathological race condition, and fix it.
            //

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

                FatMarkVolume( &IrpContext, Vcb, VolumeDirty );

            } else {

                //
                //  Unlock the volume if it is removable.
                //

                if (FlagOn(Vcb->VcbState, VCB_STATE_FLAG_REMOVABLE_MEDIA) &&
                    !FlagOn(Vcb->VcbState, VCB_STATE_FLAG_BOOT_OR_PAGING_FILE)) {

                    FatToggleMediaEjectDisable( &IrpContext, Vcb, FALSE );
                }
            }

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

              NOTHING;
        }
    }

    //
    //  Release the global resource, unpin and repinned Bcbs and return.
    //

    FatReleaseGlobal( &IrpContext );

    try {

        FatUnpinRepinnedBcbs( &IrpContext );

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

          NOTHING;
    }

    IoSetTopLevelIrp( NULL );

    //
    //  and finally free the packet.
    //

    ExFreePool( Packet );

    return;
}


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

/*++

Routine Description:

    This routine is dispatched 5 seconds after the last disk structure was
    modified in a specific volume, and exqueues an execuative worker thread
    to perform the actual task of marking the volume dirty.

Arguments:

    DefferedContext - Contains the Vcb to process.

Return Value:

    None.

--*/

{
    PVCB Vcb;
    PCLEAN_AND_DIRTY_VOLUME_PACKET Packet;

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

    Vcb = (PVCB)DeferredContext;


    //
    //  If there is still dirty data (highly unlikely), set the timer for a
    //  second in the future.
    //

    if (CcIsThereDirtyData(Vcb->Vpb)) {

        LARGE_INTEGER TwoSecondsFromNow;

        TwoSecondsFromNow.QuadPart = (LONG)-2*1000*1000*10;

        KeSetTimer( &Vcb->CleanVolumeTimer,
                    TwoSecondsFromNow,
                    &Vcb->CleanVolumeDpc );

        return;
    }

    //
    //  If we couldn't get pool, oh well....
    //

    Packet = ExAllocatePoolZero(NonPagedPoolNx, sizeof(CLEAN_AND_DIRTY_VOLUME_PACKET), ' taF');

    if ( Packet ) {

        Packet->Vcb = Vcb;
        Packet->Irp = NULL;

        //
        //  Clear the dirty flag now since we cannot synchronize after this point.
        //

        ClearFlag( Packet->Vcb->VcbState, VCB_STATE_FLAG_VOLUME_DIRTY );

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

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

    return;
}


_Requires_lock_held_(_Global_critical_region_)
VOID
FatMarkVolume (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN FAT_VOLUME_STATE VolumeState
    )

/*++

Routine Description:

    This routine moves the physically marked volume state between the clean
    and dirty states.  For compatibility with Win9x, we manipulate both the
    historical DOS (on==clean in index 1 of the FAT) and NT (on==dirty in
    the CurrentHead field of the BPB) dirty bits.

Arguments:

    Vcb - Supplies the Vcb being modified

    VolumeState - Supplies the state the volume is transitioning to

Return Value:

    None.

--*/

{
    PCHAR Sector;
    PBCB Bcb = NULL;
    KEVENT Event;
    PIRP Irp = NULL;
    NTSTATUS Status;
    BOOLEAN FsInfoUpdate = FALSE;
    ULONG FsInfoOffset = 0;
    ULONG ThisPass;
    LARGE_INTEGER Offset;
    BOOLEAN abort = FALSE;

    DebugTrace(+1, Dbg, "FatMarkVolume, Vcb = %p\n", Vcb);

    //
    //  We had best not be trying to scribble dirty/clean bits if the
    //  volume is write protected.  The responsibility lies with the
    //  callers to make sure that operations that could cause a state
    //  change cannot happen.  There are a few, though, that show it
    //  just doesn't make sense to force everyone to do the dinky
    //  check.
    //

    //
    //  If we were called for FAT12 or readonly media, return immediately.
    //

    if (FlagOn(Vcb->VcbState, VCB_STATE_FLAG_WRITE_PROTECTED) ||
        FatIsFat12( Vcb )) {

        return;
    }

    //
    //  We have two possible additional tasks to do to mark a volume
    //
    //      Pass 0) Flip the dirty bit in the Bpb
    //      Pass 1) Rewrite the FsInfo sector for FAT32 if needed
    //
    //  In most cases we can collapse these two either because the volume
    //  is either not FAT32 or the FsInfo sector is adjacent to the boot sector.
    //

    for (ThisPass = 0; ThisPass < 2; ThisPass++) {

        //
        //  If this volume is being dirtied, or isn't FAT32, or if it is and
        //  we were able to perform the fast update, or the bpb lied to us
        //  about where the FsInfo went, we're done - no FsInfo to update in
        //  a seperate write.
        //

        if (ThisPass == 1 && (!FatIsFat32( Vcb ) ||
                              VolumeState != VolumeClean ||
                              FsInfoUpdate ||
                              Vcb->Bpb.FsInfoSector == 0)) {

            break;
        }

        //
        //  Bail if we get an IO error.
        //

        try {

            ULONG PinLength;
            ULONG WriteLength;

            //
            // If the FAT table is 12-bit then our strategy is to pin the entire
            // thing when any of it is modified.  Here we're going to pin the
            // first page, so in the 12-bit case we also want to pin the rest
            // of the FAT table.
            //

            Offset.QuadPart = 0;

            if (Vcb->AllocationSupport.FatIndexBitSize == 12) {

                //
                //  But we only write back the first sector.
                //

                PinLength = FatReservedBytes(&Vcb->Bpb) + FatBytesPerFat(&Vcb->Bpb);
                WriteLength = Vcb->Bpb.BytesPerSector;

            } else {

                WriteLength = PinLength = Vcb->Bpb.BytesPerSector;

                //
                //  If this is a FAT32 volume going into the clean state,
                //  see about doing the FsInfo sector.
                //

                if (FatIsFat32( Vcb ) && VolumeState == VolumeClean) {

                    //
                    //  If the FsInfo sector immediately follows the boot sector,
                    //  we can do this in a single operation by rewriting both
                    //  sectors at once.
                    //

                    if (Vcb->Bpb.FsInfoSector == 1) {

                        NT_ASSERT( ThisPass == 0 );

                        FsInfoUpdate = TRUE;
                        FsInfoOffset = Vcb->Bpb.BytesPerSector;
                        WriteLength = PinLength = Vcb->Bpb.BytesPerSector * 2;

                    } else if (ThisPass == 1) {

                        //
                        //  We are doing an explicit write to the FsInfo sector.
                        //

                        FsInfoUpdate = TRUE;
                        FsInfoOffset = 0;

                        Offset.QuadPart = Vcb->Bpb.BytesPerSector * Vcb->Bpb.FsInfoSector;
                    }
                }
            }

            //
            //  Call Cc directly here so that we can avoid overhead and push this
            //  right down to the disk.
            //

            CcPinRead( Vcb->VirtualVolumeFile,
                       &Offset,
                       PinLength,
                       TRUE,
                       &Bcb,
                       (PVOID *)&Sector );

            DbgDoit( IrpContext->PinCount += 1 )

            //
            //  Set the Bpb on Pass 0 always
            //

            if (ThisPass == 0) {

                PCHAR CurrentHead;

                //
                //  Before we do anything, doublecheck that this still looks like a
                //  FAT bootsector.  If it doesn't, something remarkable happened
                //  and we should avoid touching the volume.
                //
                //  THIS IS TEMPORARY (but may last a while)
                //

                if (!FatIsBootSectorFat( (PPACKED_BOOT_SECTOR) Sector )) {
                    abort = TRUE;
                    leave;
                }

                if (FatIsFat32( Vcb )) {

                    CurrentHead = (PCHAR)&((PPACKED_BOOT_SECTOR_EX) Sector)->CurrentHead;

                } else {

                    CurrentHead = (PCHAR)&((PPACKED_BOOT_SECTOR) Sector)->CurrentHead;
                }

                if (VolumeState == VolumeClean) {

                    ClearFlag( *CurrentHead, FAT_BOOT_SECTOR_DIRTY );

                } else {

                    SetFlag( *CurrentHead, FAT_BOOT_SECTOR_DIRTY );

                    //
                    //  In addition, if this request received an error that may indicate
                    //  media corruption, have autochk perform a surface test.
                    //

                    if ( VolumeState == VolumeDirtyWithSurfaceTest ) {

                        SetFlag( *CurrentHead, FAT_BOOT_SECTOR_TEST_SURFACE );
                    }
                }
            }

            //
            //  Update the FsInfo as appropriate.
            //

            if (FsInfoUpdate) {

                PFSINFO_SECTOR FsInfoSector = (PFSINFO_SECTOR) ((PCHAR)Sector + FsInfoOffset);

                //
                //  We just rewrite all of the spec'd fields.  Note that we don't
                //  care to synchronize with the allocation package - this will be
                //  quickly taken care of by a re-dirtying of the volume if a change
                //  is racing with us.  Remember that this is all a compatibility
                //  deference for Win9x FAT32 - NT will never look at this information.
                //

                FsInfoSector->SectorBeginSignature = FSINFO_SECTOR_BEGIN_SIGNATURE;
                FsInfoSector->FsInfoSignature = FSINFO_SIGNATURE;
                FsInfoSector->FreeClusterCount = Vcb->AllocationSupport.NumberOfFreeClusters;
                FsInfoSector->NextFreeCluster = Vcb->ClusterHint;
                FsInfoSector->SectorEndSignature = FSINFO_SECTOR_END_SIGNATURE;
            }

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

            KeInitializeEvent( &Event, NotificationEvent, FALSE );

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

            Irp = IoBuildAsynchronousFsdRequest( IRP_MJ_WRITE,
                                                 Vcb->TargetDeviceObject,
                                                 (PVOID)Sector,
                                                 WriteLength,
                                                 &Offset,
                                                 NULL );

            if ( Irp == NULL ) {

                try_return(NOTHING);
            }

            //
            //  Make this operation write-through.  It never hurts to try to be
            //  safer about this, even though we aren't logged.
            //

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

            //
            //  Set up the completion routine
            //

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

            //
            //  Call the device to do the write and wait for it to finish.
            //  Igmore any return status.
            //

            Status = IoCallDriver( Vcb->TargetDeviceObject, Irp );

            if (Status == STATUS_PENDING) {

                (VOID)KeWaitForSingleObject( &Event, Executive, KernelMode, FALSE, (PLARGE_INTEGER)NULL );
            }

        try_exit: NOTHING;
        } finally {

            //
            //  Clean up the Irp and Mdl
            //


            if (Irp) {

                //
                //  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 (Bcb != NULL) {

                FatUnpinBcb( IrpContext, Bcb );
            }
        }
    }

    if (!abort) {

        //
        //  Flip the dirty bit in the FAT
        //

        if (VolumeState == VolumeDirty) {

           FatSetFatEntry( IrpContext, Vcb, FAT_DIRTY_BIT_INDEX, FAT_DIRTY_VOLUME);

        } else {

           FatSetFatEntry( IrpContext, Vcb, FAT_DIRTY_BIT_INDEX, FAT_CLEAN_VOLUME);
        }
    }

    DebugTrace(-1, Dbg, "FatMarkVolume -> VOID\n", 0);

    return;
}


VOID
FatFspMarkVolumeDirtyWithRecover(
    PVOID Parameter
    )

/*++

Routine Description:

    This is the routine that performs the actual FatMarkVolume Dirty call
    on a paging file Io that encounters a media error.  It is responsible
    for completing the PagingIo Irp as soon as this is done.

    Note:  this routine (and thus FatMarkVolume()) must be resident as
           the paging file might be damaged at this point.

Arguments:

    Parameter - Points to a dirty volume packet that was allocated from pool

Return Value:

    None.

--*/

{
    PCLEAN_AND_DIRTY_VOLUME_PACKET Packet;
    PVCB Vcb;
    IRP_CONTEXT IrpContext;
    PIRP Irp;

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

    Packet = (PCLEAN_AND_DIRTY_VOLUME_PACKET)Parameter;

    Vcb = Packet->Vcb;
    Irp = Packet->Irp;

    //
    //  Dummy up the IrpContext so we can call our worker routines
    //

    RtlZeroMemory( &IrpContext, sizeof(IRP_CONTEXT));

    SetFlag(IrpContext.Flags, IRP_CONTEXT_FLAG_WAIT);
    IrpContext.OriginatingIrp = Irp;

    //
    //  Make us appear as a top level FSP request so that we will
    //  receive any errors from the operation.
    //

    IoSetTopLevelIrp( (PIRP)FSRTL_FSP_TOP_LEVEL_IRP );

    //
    //  Try to write out the dirty bit.  If something goes wrong, we
    //  tried.
    //

    try {

        SetFlag( Vcb->VcbState, VCB_STATE_FLAG_MOUNTED_DIRTY );

        FatMarkVolume( &IrpContext, Vcb, VolumeDirtyWithSurfaceTest );

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

        NOTHING;
    }

    IoSetTopLevelIrp( NULL );

    //
    //  Now complete the originating Irp or set the synchronous event.
    //

    if (Packet->Event) {
        KeSetEvent( Packet->Event, 0, FALSE );
    } else {
        IoCompleteRequest( Irp, IO_DISK_INCREMENT );
    }

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


VOID
FatCheckDirtyBit (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine looks at the volume dirty bit, and depending on the state of
    VCB_STATE_FLAG_MOUNTED_DIRTY, the appropriate action is taken.

Arguments:

    Vcb - Supplies the Vcb being queried.

Return Value:

    None.

--*/

{
    BOOLEAN Dirty;

    PPACKED_BOOT_SECTOR BootSector;
    PBCB BootSectorBcb;

    UNICODE_STRING VolumeLabel;

    PAGED_CODE();

    //
    //  Look in the boot sector
    //

    FatReadVolumeFile( IrpContext,
                       Vcb,
                       0,
                       sizeof(PACKED_BOOT_SECTOR),
                       &BootSectorBcb,
                       (PVOID *)&BootSector );

    try {

        //
        //  Check if the magic bit is set
        //

        if (IsBpbFat32(&BootSector->PackedBpb)) {
            Dirty = BooleanFlagOn( ((PPACKED_BOOT_SECTOR_EX)BootSector)->CurrentHead,
                                   FAT_BOOT_SECTOR_DIRTY );
        } else {
            Dirty = BooleanFlagOn( BootSector->CurrentHead, FAT_BOOT_SECTOR_DIRTY );
        }

        //
        //  Setup the VolumeLabel string
        //

        VolumeLabel.Length = Vcb->Vpb->VolumeLabelLength;
        VolumeLabel.MaximumLength = MAXIMUM_VOLUME_LABEL_LENGTH;
        VolumeLabel.Buffer = &Vcb->Vpb->VolumeLabel[0];

        if ( Dirty ) {

            //
            //  Do not trigger the mounted dirty bit if this is a verify
            //  and the volume is a boot or paging device.  We know that
            //  a boot or paging device cannot leave the system, and thus
            //  that on its mount we will have figured this out correctly.
            //
            //  This logic is a reasonable change.  Why?
            //  'cause setup cracked a non-exclusive DASD handle near the
            //  end of setup, wrote some data, closed the handle and we
            //  set the verify bit ... came back around and saw that other
            //  arbitrary activity had left the volume in a temporarily dirty
            //  state.
            //
            //  Of course, the real problem is that we don't have a journal.
            //

            if (!(IrpContext->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL &&
                  IrpContext->MinorFunction == IRP_MN_VERIFY_VOLUME &&
                  FlagOn( Vcb->VcbState, VCB_STATE_FLAG_BOOT_OR_PAGING_FILE))) {

                KdPrintEx((DPFLTR_FASTFAT_ID,
                           DPFLTR_INFO_LEVEL,
                           "FASTFAT: WARNING! Mounting Dirty Volume %Z\n",
                           &VolumeLabel));

                SetFlag( Vcb->VcbState, VCB_STATE_FLAG_MOUNTED_DIRTY );
            }

        } else {

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

                KdPrintEx((DPFLTR_FASTFAT_ID,
                           DPFLTR_INFO_LEVEL,
                           "FASTFAT: Volume %Z has been cleaned.\n",
                           &VolumeLabel));

                ClearFlag( Vcb->VcbState, VCB_STATE_FLAG_MOUNTED_DIRTY );

            } else {

                (VOID)FsRtlBalanceReads( Vcb->TargetDeviceObject );
            }
        }

    } finally {

        FatUnpinBcb( IrpContext, BootSectorBcb );
    }
}


VOID
FatVerifyOperationIsLegal (
    IN PIRP_CONTEXT IrpContext
    )

/*++

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.

--*/

{
    PIRP Irp;
    PFILE_OBJECT FileObject;

    PAGED_CODE();

    Irp = IrpContext->OriginatingIrp;

    //
    //  If the Irp is not present, then we got here via close.
    //
    //

    if ( Irp == NULL ) {

        return;
    }

    FileObject = IoGetCurrentIrpStackLocation(Irp)->FileObject;

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

    if ( FileObject == NULL ) {

        return;
    }

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

            FatRaiseStatus( IrpContext, STATUS_FILE_CLOSED );
        }
    }

    return;
}



//
//  Internal support routine
//

VOID
FatResetFcb (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb
    )

/*++

Routine Description:

    This routine is called when an Fcb has been marked as needs to be verified.

    It does the following tasks:

        - Reset Mcb mapping information
        - For directories, reset dirent hints
        - Set allocation size to unknown

Arguments:

    Fcb - Supplies the Fcb to reset

Return Value:

    None.

--*/

{
    LOGICAL IsRealPagingFile;

    PAGED_CODE();
    UNREFERENCED_PARAMETER( IrpContext );

    //
    //  Don't do the two following operations for the Root Dcb
    //  of a non FAT32 volume or paging files.  Paging files!?
    //  Yes, if someone diddles a volume we try to reverify all
    //  of the Fcbs just in case; however, there is no safe way
    //  to chuck and retrieve the mapping pair information for
    //  a real paging file. Lose it and die.
    //
    //  An exception is made for ReadyBoost cache files, which
    //  are created as paging files on removable devices and
    //  require validation after a power transition.
    //

    if (!FlagOn(Fcb->Vcb->VcbState, VCB_STATE_FLAG_REMOVABLE_MEDIA) &&
        FlagOn(Fcb->FcbState, FCB_STATE_PAGING_FILE)) {

        IsRealPagingFile = TRUE;

    } else {

        IsRealPagingFile = FALSE;
    }

    if ( (NodeType(Fcb) != FAT_NTC_ROOT_DCB ||
          FatIsFat32( Fcb->Vcb ))  &&
         !IsRealPagingFile ) {

        //
        //  Reset the mcb mapping.
        //

        FsRtlRemoveLargeMcbEntry( &Fcb->Mcb, 0, 0xFFFFFFFF );

        //
        //  Reset the allocation size to 0 or unknown
        //

        if ( Fcb->FirstClusterOfFile == 0 ) {

            Fcb->Header.AllocationSize.QuadPart = 0;

        } else {

            Fcb->Header.AllocationSize.QuadPart = FCB_LOOKUP_ALLOCATIONSIZE_HINT;
        }
    }

    //
    //  If this is a directory, reset the hints.
    //

    if ( (NodeType(Fcb) == FAT_NTC_DCB) ||
         (NodeType(Fcb) == FAT_NTC_ROOT_DCB) ) {

        //
        //  Force a rescan of the directory
        //

        Fcb->Specific.Dcb.UnusedDirentVbo = 0xffffffff;
        Fcb->Specific.Dcb.DeletedDirentHint = 0xffffffff;
    }
}



BOOLEAN
FatMatchFileSize (
    __in PIRP_CONTEXT IrpContext,
    __in PDIRENT Dirent,
    __in PFCB Fcb
    )
{

    UNREFERENCED_PARAMETER(IrpContext);

    if (NodeType(Fcb) != FAT_NTC_FCB) {
        return TRUE;
    }


        if (Fcb->Header.FileSize.LowPart != Dirent->FileSize) {
            return FALSE;
        }


    return TRUE;
}

//
//  Internal support routine
//

_Requires_lock_held_(_Global_critical_region_)
VOID
FatDetermineAndMarkFcbCondition (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb
    )

/*++

Routine Description:

    This routine checks a specific Fcb to see if it is different from what's
    on the disk.  The following things are checked:

        - File Name
        - File Size (if not directory)
        - First Cluster Of File
        - Dirent Attributes

Arguments:

    Fcb - Supplies the Fcb to examine

Return Value:

    None.

--*/

{
    PDIRENT Dirent;
    PBCB DirentBcb;
    ULONG FirstClusterOfFile;

    OEM_STRING Name;
    CHAR Buffer[16];

    PAGED_CODE();

    //
    //  If this is the Root Dcb, special case it.  That is, we know
    //  by definition that it is good since it is fixed in the volume
    //  structure.
    //

    if ( NodeType(Fcb) == FAT_NTC_ROOT_DCB ) {

        FatMarkFcbCondition( IrpContext, Fcb, FcbGood, FALSE );

        return;
    }

    //  The first thing we need to do to verify ourselves is
    //  locate the dirent on the disk.
    //

    FatGetDirentFromFcbOrDcb( IrpContext,
                              Fcb,
                              TRUE,
                              &Dirent,
                              &DirentBcb );
    //
    //  If we couldn't get the dirent, this fcb must be bad (case of
    //  enclosing directory shrinking during the time it was ejected).
    //

    if (DirentBcb == NULL) {

        FatMarkFcbCondition( IrpContext, Fcb, FcbBad, FALSE );

        return;
    }

    //
    //  We located the dirent for ourselves now make sure it
    //  is really ours by comparing the Name and FatFlags.
    //  Then for a file we also check the file size.
    //
    //  Note that we have to unpin the Bcb before calling FatResetFcb
    //  in order to avoid a deadlock in CcUninitializeCacheMap.
    //

    try {

        Name.MaximumLength = 16;
        Name.Buffer = &Buffer[0];

        Fat8dot3ToString( IrpContext, Dirent, FALSE, &Name );

        //
        //  We need to calculate the first cluster 'cause FAT32 splits
        //  this field across the dirent.
        //

        FirstClusterOfFile = Dirent->FirstClusterOfFile;

        if (FatIsFat32( Fcb->Vcb )) {

            FirstClusterOfFile += Dirent->FirstClusterOfFileHi << 16;
        }

        if (!RtlEqualString( &Name, &Fcb->ShortName.Name.Oem, TRUE )

                ||

             !FatMatchFileSize(IrpContext, Dirent, Fcb )

                ||

             (FirstClusterOfFile != Fcb->FirstClusterOfFile)

                ||

              (Dirent->Attributes != Fcb->DirentFatFlags) ) {

            FatMarkFcbCondition( IrpContext, Fcb, FcbBad, FALSE );

        } else {

            //
            //  We passed.  Get the Fcb ready to use again.
            //

            FatMarkFcbCondition( IrpContext, Fcb, FcbGood, FALSE );
        }

    } finally {

        FatUnpinBcb( IrpContext, DirentBcb );
    }

    return;
}



//
//  Internal support routine
//

VOID
FatQuickVerifyVcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routines just checks the verify bit in the real device and the
    Vcb condition and raises an appropriate exception if so warented.
    It is called when verifying both Fcbs and Vcbs.

Arguments:

    Vcb - Supplies the Vcb to check the condition of.

Return Value:

    None.

--*/

{
    PAGED_CODE();

    //
    //  If the real device needs to be verified we'll set the
    //  DeviceToVerify to be our real device and raise VerifyRequired.
    //

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

        DebugTrace(0, Dbg, "The Vcb needs to be verified\n", 0);

        IoSetHardErrorOrVerifyDevice( IrpContext->OriginatingIrp,
                                      Vcb->Vpb->RealDevice );

        FatRaiseStatus( IrpContext, STATUS_VERIFY_REQUIRED );
    }

    //
    //  Based on the condition of the Vcb we'll either return to our
    //  caller or raise an error condition
    //

    switch (Vcb->VcbCondition) {

    case VcbGood:

        DebugTrace(0, Dbg, "The Vcb is good\n", 0);

        //
        //  Do a check here of an operation that would try to modify a
        //  write protected media.
        //

        if (FlagOn(Vcb->VcbState, VCB_STATE_FLAG_WRITE_PROTECTED) &&
            ((IrpContext->MajorFunction == IRP_MJ_WRITE) ||
             (IrpContext->MajorFunction == IRP_MJ_SET_INFORMATION) ||
             (IrpContext->MajorFunction == IRP_MJ_SET_EA) ||
             (IrpContext->MajorFunction == IRP_MJ_FLUSH_BUFFERS) ||
             (IrpContext->MajorFunction == IRP_MJ_SET_VOLUME_INFORMATION) ||
             (IrpContext->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL &&
              IrpContext->MinorFunction == IRP_MN_USER_FS_REQUEST &&
              IoGetCurrentIrpStackLocation(IrpContext->OriginatingIrp)->Parameters.FileSystemControl.FsControlCode ==
                FSCTL_MARK_VOLUME_DIRTY))) {

            //
            //  Set the real device for the pop-up info, and set the verify
            //  bit in the device object, so that we will force a verify
            //  in case the user put the correct media back in.
            //


            IoSetHardErrorOrVerifyDevice( IrpContext->OriginatingIrp,
                                          Vcb->Vpb->RealDevice );

            FatMarkDevForVerifyIfVcbMounted(Vcb);

            FatRaiseStatus( IrpContext, STATUS_MEDIA_WRITE_PROTECTED );
        }

        break;

    case VcbNotMounted:

        DebugTrace(0, Dbg, "The Vcb is not mounted\n", 0);

        //
        //  Set the real device for the pop-up info, and set the verify
        //  bit in the device object, so that we will force a verify
        //  in case the user put the correct media back in.
        //

        IoSetHardErrorOrVerifyDevice( IrpContext->OriginatingIrp,
                                      Vcb->Vpb->RealDevice );

        FatRaiseStatus( IrpContext, STATUS_WRONG_VOLUME );

        break;

    case VcbBad:

        DebugTrace(0, Dbg, "The Vcb is bad\n", 0);

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

            FatRaiseStatus( IrpContext, STATUS_VOLUME_DISMOUNTED );

        } else {

            FatRaiseStatus( IrpContext, STATUS_FILE_INVALID );
        }
        break;

    default:

        DebugDump("Invalid VcbCondition\n", 0, Vcb);
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )
        FatBugCheck( Vcb->VcbCondition, 0, 0 );
    }
}

_Requires_lock_held_(_Global_critical_region_)
NTSTATUS
FatPerformVerify (
    _In_ PIRP_CONTEXT IrpContext,
    _In_ PIRP Irp,
    _In_ PDEVICE_OBJECT Device
    )

/*++

Routine Description:

    This routines performs an IoVerifyVolume operation and takes the
    appropriate action.  After the Verify is complete the originating
    Irp is sent off to an Ex Worker Thread.  This routine is called
    from the exception handler.

Arguments:

    Irp - The irp to send off after all is well and done.

    Device - The real device needing verification.

Return Value:

    None.

--*/

{
    PVCB Vcb;
    NTSTATUS Status = STATUS_SUCCESS;
    PIO_STACK_LOCATION IrpSp;
    PFILE_OBJECT FileObject = IoGetCurrentIrpStackLocation(Irp)->FileObject;
    BOOLEAN AllowRawMount = FALSE;
    BOOLEAN VcbDeleted = FALSE;

    PAGED_CODE();

    //
    //  Check if this Irp has a status of Verify required and if it does
    //  then call the I/O system to do a verify.
    //
    //  Skip the IoVerifyVolume if this is a mount or verify request
    //  itself.  Trying a recursive mount will cause a deadlock with
    //  the DeviceObject->DeviceLock.
    //

    if ( (IrpContext->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) &&
         ((IrpContext->MinorFunction == IRP_MN_MOUNT_VOLUME) ||
          (IrpContext->MinorFunction == IRP_MN_VERIFY_VOLUME)) ) {

        return FatFsdPostRequest( IrpContext, Irp );
    }

    DebugTrace(0, Dbg, "Verify Required, DeviceObject = %p\n", Device);

    //
    //  Extract a pointer to the Vcb from the VolumeDeviceObject.
    //  Note that since we have specifically excluded mount,
    //  requests, we know that IrpSp->DeviceObject is indeed a
    //  volume device object.
    //

    IrpSp = IoGetCurrentIrpStackLocation(Irp);

    Vcb = &CONTAINING_RECORD( IrpSp->DeviceObject,
                              VOLUME_DEVICE_OBJECT,
                              DeviceObject )->Vcb;

    //
    //  Check if the volume still thinks it needs to be verified,
    //  if it doesn't then we can skip doing a verify because someone
    //  else beat us to it.
    //

    try {

        //
        //  We will allow Raw to mount this volume if we were doing a
        //  a DASD open.
        //

        if ( (IrpContext->MajorFunction == IRP_MJ_CREATE) &&
             (IrpSp->FileObject->FileName.Length == 0) &&
             (IrpSp->FileObject->RelatedFileObject == NULL) ) {

            AllowRawMount = TRUE;
        }

        //
        //  Send down the verify.  This could be going to a different
        //  filesystem.
        //

        Status = IoVerifyVolume( Device, AllowRawMount );

        //
        //  If the verify operation completed it will return
        //  either STATUS_SUCCESS or STATUS_WRONG_VOLUME, exactly.
        //
        //  If FatVerifyVolume encountered an error during
        //  processing, it will return that error.  If we got
        //  STATUS_WRONG_VOLUME from the verfy, and our volume
        //  is now mounted, commute the status to STATUS_SUCCESS.
        //
        //  Acquire the Vcb so we're working with a stable Vcb condition.
        //

        FatAcquireSharedVcb(IrpContext, Vcb);

        if ( (Status == STATUS_WRONG_VOLUME) &&
             (Vcb->VcbCondition == VcbGood) ) {

            Status = STATUS_SUCCESS;
        }
        else if ((STATUS_SUCCESS == Status) && (Vcb->VcbCondition != VcbGood)) {

            Status = STATUS_WRONG_VOLUME;
        }

        //
        //  Do a quick unprotected check here.  The routine will do
        //  a safe check.  After here we can release the resource.
        //  Note that if the volume really went away, we will be taking
        //  the Reparse path.
        //

        if ((VcbGood != Vcb->VcbCondition) &&
            (0 == Vcb->OpenFileCount) ) {

            FatReleaseVcb( IrpContext, Vcb);

#pragma prefast( push )
#pragma prefast( disable: 28137, "prefast wants the wait to be a constant, but that isn't possible for the way fastfat is designed" )
#pragma prefast( disable: 28193 )
            FatAcquireExclusiveGlobal( IrpContext );
#pragma prefast( pop )

            FatAcquireExclusiveVcb( IrpContext,
                                    Vcb );

            VcbDeleted = FatCheckForDismount( IrpContext,
                                              Vcb,
                                              FALSE );

            if (!VcbDeleted) {

                FatReleaseVcb( IrpContext,
                               Vcb );
            }

            FatReleaseGlobal( IrpContext );
        }
        else {

            FatReleaseVcb( IrpContext, Vcb);
        }

        //
        //  If the IopMount in IoVerifyVolume did something, and
        //  this is an absolute open, force a reparse.
        //

        if ((IrpContext->MajorFunction == IRP_MJ_CREATE) &&
            (FileObject->RelatedFileObject == NULL) &&
            ((Status == STATUS_SUCCESS) || (Status == STATUS_WRONG_VOLUME))) {

            Irp->IoStatus.Information = IO_REMOUNT;

            FatCompleteRequest( IrpContext, Irp, STATUS_REPARSE );
            Status = STATUS_REPARSE;
            Irp = NULL;
        }

        if ( (Irp != NULL) && !NT_SUCCESS(Status) ) {

            //
            //  Fill in the device object if required.
            //

            if ( IoIsErrorUserInduced( Status ) ) {

                IoSetHardErrorOrVerifyDevice( Irp, Device );
            }

            NT_ASSERT( STATUS_VERIFY_REQUIRED != Status);

            FatNormalizeAndRaiseStatus( IrpContext, Status );
        }

        //
        //  If there is still an Irp, send it off to an Ex Worker thread.
        //

        if ( Irp != NULL ) {

            Status = FatFsdPostRequest( IrpContext, Irp );
        }

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

        //
        //  We had some trouble trying to perform the verify or raised
        //  an error ourselves.  So we'll abort the I/O request with
        //  the error status that we get back from the execption code.
        //

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

    return Status;
}

//
//  Local support routine
//

NTSTATUS
FatMarkVolumeCompletionRoutine(
    _In_ PDEVICE_OBJECT DeviceObject,
    _In_ PIRP Irp,
    _In_reads_opt_(_Inexpressible_("varies")) 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;
}