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

Copyright (c) 1989-2000 Microsoft Corporation

Module Name:

    StrucSup.c

Abstract:

    This module implements the Fat in-memory data structure manipulation
    routines


--*/

#include "fatprocs.h"

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

#define BugCheckFileId                   (FAT_BUG_CHECK_STRUCSUP)

//
//  The debug trace level
//

#define Dbg                              (DEBUG_TRACE_STRUCSUP)

#define FillMemory(BUF,SIZ,MASK) {                          \
    ULONG i;                                                \
    for (i = 0; i < (((SIZ)/4) - 1); i += 2) {              \
        ((PULONG)(BUF))[i] = (MASK);                        \
        ((PULONG)(BUF))[i+1] = (ULONG)PsGetCurrentThread(); \
    }                                                       \
}

#define IRP_CONTEXT_HEADER (sizeof( IRP_CONTEXT ) * 0x10000 + FAT_NTC_IRP_CONTEXT)

//
//  Local macros.
//
//  Define our lookaside list allocators.  For the time being, and perhaps
//  permanently, the paged structures don't come off of lookasides.  This
//  is due to complications with clean unload as FAT can be in the paging
//  path, making it really hard to find the right time to empty them.
//
//  Fortunately, the hit rates on the Fcb/Ccb lists weren't stunning.
//

#define FAT_FILL_FREE 0

INLINE
PCCB
FatAllocateCcb (
    )
{
    return (PCCB) FsRtlAllocatePoolWithTag( PagedPool, sizeof(CCB), TAG_CCB );
}

INLINE
VOID
FatFreeCcb (
    IN PCCB Ccb
    )
{
#if FAT_FILL_FREE
    RtlFillMemoryUlong(Ccb, sizeof(CCB), FAT_FILL_FREE);
#endif

    ExFreePool( Ccb );
}

INLINE
PFCB
FatAllocateFcb (
    )
{
    return (PFCB) FsRtlAllocatePoolWithTag( PagedPool, sizeof(FCB), TAG_FCB );
}

INLINE
VOID
FatFreeFcb (
    IN PFCB Fcb
    )
{
#if FAT_FILL_FREE
    RtlFillMemoryUlong(Fcb, sizeof(FCB), FAT_FILL_FREE);
#endif

    ExFreePool( Fcb );
}

INLINE
PNON_PAGED_FCB
FatAllocateNonPagedFcb (
    )
{
    return (PNON_PAGED_FCB) ExAllocateFromNPagedLookasideList( &FatNonPagedFcbLookasideList );
}

INLINE
VOID
FatFreeNonPagedFcb (
    PNON_PAGED_FCB NonPagedFcb
    )
{
#if FAT_FILL_FREE
    RtlFillMemoryUlong(NonPagedFcb, sizeof(NON_PAGED_FCB), FAT_FILL_FREE);
#endif

    ExFreeToNPagedLookasideList( &FatNonPagedFcbLookasideList, (PVOID) NonPagedFcb );
}

INLINE
PERESOURCE
FatAllocateResource (
    )
{
    PERESOURCE Resource;

    Resource = (PERESOURCE) ExAllocateFromNPagedLookasideList( &FatEResourceLookasideList );

    ExInitializeResourceLite( Resource );

    return Resource;
}

INLINE
VOID
FatFreeResource (
    IN PERESOURCE Resource
    )
{
    ExDeleteResourceLite( Resource );

#if FAT_FILL_FREE
    RtlFillMemoryUlong(Resource, sizeof(ERESOURCE), FAT_FILL_FREE);
#endif

    ExFreeToNPagedLookasideList( &FatEResourceLookasideList, (PVOID) Resource );
}

INLINE
PIRP_CONTEXT
FatAllocateIrpContext (
    )
{
    return (PIRP_CONTEXT) ExAllocateFromNPagedLookasideList( &FatIrpContextLookasideList );
}

INLINE
VOID
FatFreeIrpContext (
    IN PIRP_CONTEXT IrpContext
    )
{
#if FAT_FILL_FREE
    RtlFillMemoryUlong(IrpContext, sizeof(IRP_CONTEXT), FAT_FILL_FREE);
#endif

    ExFreeToNPagedLookasideList( &FatIrpContextLookasideList, (PVOID) IrpContext );
}

#ifdef ALLOC_PRAGMA
#pragma alloc_text(PAGE, FatInitializeVcb)
#pragma alloc_text(PAGE, FatTearDownVcb)
#pragma alloc_text(PAGE, FatDeleteVcb)
#pragma alloc_text(PAGE, FatCreateRootDcb)
#pragma alloc_text(PAGE, FatCreateFcb)
#pragma alloc_text(PAGE, FatCreateDcb)
#pragma alloc_text(PAGE, FatDeleteFcb)
#pragma alloc_text(PAGE, FatCreateCcb)
#pragma alloc_text(PAGE, FatDeallocateCcbStrings)
#pragma alloc_text(PAGE, FatDeleteCcb)
#pragma alloc_text(PAGE, FatGetNextFcbTopDown)
#pragma alloc_text(PAGE, FatGetNextFcbBottomUp)
#pragma alloc_text(PAGE, FatConstructNamesInFcb)
#pragma alloc_text(PAGE, FatCheckFreeDirentBitmap)
#pragma alloc_text(PAGE, FatCreateIrpContext)
#pragma alloc_text(PAGE, FatDeleteIrpContext_Real)
#pragma alloc_text(PAGE, FatIsHandleCountZero)
#pragma alloc_text(PAGE, FatAllocateCloseContext)
#pragma alloc_text(PAGE, FatPreallocateCloseContext)
#pragma alloc_text(PAGE, FatEnsureStringBufferEnough)
#pragma alloc_text(PAGE, FatFreeStringBuffer)
#pragma alloc_text(PAGE, FatScanForDataTrack)
#endif


_Requires_lock_held_(_Global_critical_region_)
VOID
FatInitializeVcb (
    IN PIRP_CONTEXT IrpContext,
    IN OUT PVCB Vcb,
    IN PDEVICE_OBJECT TargetDeviceObject,
    IN PVPB Vpb,
    IN PDEVICE_OBJECT FsDeviceObject
    )

/*++

Routine Description:

    This routine initializes and inserts a new Vcb record into the in-memory
    data structure.  The Vcb record "hangs" off the end of the Volume device
    object and must be allocated by our caller.

Arguments:

    Vcb - Supplies the address of the Vcb record being initialized.

    TargetDeviceObject - Supplies the address of the target device object to
        associate with the Vcb record.

    Vpb - Supplies the address of the Vpb to associate with the Vcb record.

    FsDeviceObject - The filesystem device object that the mount was directed
                     too.

Return Value:

    None.

--*/

{
    CC_FILE_SIZES FileSizes;
    PDEVICE_OBJECT RealDevice;
    ULONG i;

    STORAGE_HOTPLUG_INFO HotplugInfo;
    STORAGE_DEVICE_NUMBER StorDeviceNumber;
    NTSTATUS Status;

    //
    //  The following variables are used for abnormal unwind
    //

    PLIST_ENTRY UnwindEntryList = NULL;
    PERESOURCE UnwindResource = NULL;
    PERESOURCE UnwindResource2 = NULL;
    PFILE_OBJECT UnwindFileObject = NULL;
    PFILE_OBJECT UnwindCacheMap = NULL;
    BOOLEAN UnwindWeAllocatedMcb = FALSE;
    PFILE_SYSTEM_STATISTICS UnwindStatistics = NULL;
    BOOLEAN UnwindWeAllocatedBadBlockMap = FALSE;
    BOOLEAN CloseContextAllocated = FALSE;
    
    PAGED_CODE();
    UNREFERENCED_PARAMETER( FsDeviceObject );

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

    _SEH2_TRY {

        //
        //  We start by first zeroing out all of the VCB, this will guarantee
        //  that any stale data is wiped clean
        //

        RtlZeroMemory( Vcb, sizeof(VCB) );

        //
        //  Set the proper node type code and node byte size
        //

        Vcb->VolumeFileHeader.NodeTypeCode = FAT_NTC_VCB;
        Vcb->VolumeFileHeader.NodeByteSize = sizeof(VCB);

        //
        //  Initialize the tunneling cache
        //

        FsRtlInitializeTunnelCache(&Vcb->Tunnel);

        //
        //  Insert this Vcb record on the FatData.VcbQueue
        //

        NT_ASSERT( FlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT) );


#ifdef _MSC_VER
#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, "this will always wait" )
#endif

        (VOID)FatAcquireExclusiveGlobal( IrpContext );

#ifdef _MSC_VER
#pragma prefast( pop )
#endif

        InsertTailList( &FatData.VcbQueue, &Vcb->VcbLinks );
        FatReleaseGlobal( IrpContext );
        UnwindEntryList = &Vcb->VcbLinks;

        //
        //  Set the Target Device Object, Vpb, and Vcb State fields
        //


        ObReferenceObject( TargetDeviceObject );
        Vcb->TargetDeviceObject = TargetDeviceObject;
        Vcb->Vpb = Vpb;

        Vcb->CurrentDevice = Vpb->RealDevice;

        //
        //  Set the removable media and defflush flags based on the storage
        //  inquiry and the old characteristic bits.
        //

        Status = FatPerformDevIoCtrl( IrpContext,
                                      IOCTL_STORAGE_GET_HOTPLUG_INFO,
                                      TargetDeviceObject,
                                      NULL,
                                      0,
                                      &HotplugInfo,
                                      sizeof(HotplugInfo),
                                      FALSE,
                                      TRUE,
                                      NULL );

        if (NT_SUCCESS( Status )) {

            if (HotplugInfo.MediaRemovable) {

                SetFlag( Vcb->VcbState, VCB_STATE_FLAG_REMOVABLE_MEDIA );
            }

            //
            //  If the media or device is hot-pluggable, then set this flag.
            //

            if (HotplugInfo.MediaHotplug || HotplugInfo.DeviceHotplug) {

                SetFlag( Vcb->VcbState, VCB_STATE_FLAG_HOTPLUGGABLE );
            }

            if (!HotplugInfo.WriteCacheEnableOverride) {

                //
                //  If the device or media is hotplug and the override is not
                //  set, force defflush behavior for the device.
                //

                if (HotplugInfo.MediaHotplug || HotplugInfo.DeviceHotplug) {

                    NT_ASSERT( FlagOn( Vcb->VcbState, VCB_STATE_FLAG_HOTPLUGGABLE ));

                    SetFlag( Vcb->VcbState, VCB_STATE_FLAG_DEFERRED_FLUSH );

                //
                //  Now, for removables that claim to be lockable, lob a lock
                //  request and see if it works.  There can unfortunately be
                //  transient, media dependent reasons that it can fail.  If
                //  it does not, we must force defflush on.
                //

                } else if (HotplugInfo.MediaRemovable &&
                           !HotplugInfo.MediaHotplug) {

                    Status = FatToggleMediaEjectDisable( IrpContext, Vcb, TRUE );

                    if (!NT_SUCCESS( Status )) {

                        SetFlag( Vcb->VcbState, VCB_STATE_FLAG_DEFERRED_FLUSH );

                    }

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

        if (FlagOn(Vpb->RealDevice->Characteristics, FILE_REMOVABLE_MEDIA)) {

            SetFlag( Vcb->VcbState, VCB_STATE_FLAG_REMOVABLE_MEDIA );
        }

        //
        //  Make sure we turn on deferred flushing for floppies like we always
        //  have.
        //

        if (FlagOn(Vpb->RealDevice->Characteristics, FILE_FLOPPY_DISKETTE)) {

            SetFlag( Vcb->VcbState, VCB_STATE_FLAG_DEFERRED_FLUSH );
        }

        //
        //  Query the storage device number.
        //

        Status = FatPerformDevIoCtrl( IrpContext,
                                      IOCTL_STORAGE_GET_DEVICE_NUMBER,
                                      TargetDeviceObject,
                                      NULL,
                                      0,
                                      &StorDeviceNumber,
                                      sizeof(StorDeviceNumber),
                                      FALSE,
                                      TRUE,
                                      NULL );

        if (NT_SUCCESS( Status )) {

            Vcb->DeviceNumber = StorDeviceNumber.DeviceNumber;

        } else {

            Vcb->DeviceNumber = (ULONG)(-1);
        }

        FatSetVcbCondition( Vcb, VcbGood);

        //
        //  Initialize the resource variable for the Vcb
        //

        ExInitializeResourceLite( &Vcb->Resource );
        UnwindResource = &Vcb->Resource;

        ExInitializeResourceLite( &Vcb->ChangeBitMapResource );
        UnwindResource2 = &Vcb->ChangeBitMapResource;

        //
        //  Initialize the free cluster bitmap mutex.
        //

        ExInitializeFastMutex( &Vcb->FreeClusterBitMapMutex );

        //
        //  Create the special file object for the virtual volume file with a close
        //  context, its pointers back to the Vcb and the section object pointer.
        //
        //  We don't have to unwind the close context.  That will happen in the close
        //  path automatically.
        //

        RealDevice = Vcb->CurrentDevice;

        FatPreallocateCloseContext(Vcb);
        CloseContextAllocated = TRUE;

        Vcb->VirtualVolumeFile = UnwindFileObject = IoCreateStreamFileObject( NULL, RealDevice );

        FatSetFileObject( Vcb->VirtualVolumeFile,
                          VirtualVolumeFile,
                          Vcb,
                          NULL );

        //
        //  Remember this internal, residual open.
        //

        InterlockedIncrement( (LONG*)&(Vcb->InternalOpenCount) );
        InterlockedIncrement( (LONG*)&(Vcb->ResidualOpenCount) );

        Vcb->VirtualVolumeFile->SectionObjectPointer = &Vcb->SectionObjectPointers;

        Vcb->VirtualVolumeFile->ReadAccess = TRUE;
        Vcb->VirtualVolumeFile->WriteAccess = TRUE;
        Vcb->VirtualVolumeFile->DeleteAccess = TRUE;

        //
        //  Initialize the notify structures.
        //

        InitializeListHead( &Vcb->DirNotifyList );

        FsRtlNotifyInitializeSync( &Vcb->NotifySync );

        //
        //  Initialize the Cache Map for the volume file.  The size is
        //  initially set to that of our first read.  It will be extended
        //  when we know how big the Fat is.
        //

        FileSizes.AllocationSize.QuadPart =
        FileSizes.FileSize.QuadPart = sizeof(PACKED_BOOT_SECTOR);
        FileSizes.ValidDataLength = FatMaxLarge;

        FatInitializeCacheMap( Vcb->VirtualVolumeFile,
                               &FileSizes,
                               TRUE,
                               &FatData.CacheManagerNoOpCallbacks,
                               Vcb );

        UnwindCacheMap = Vcb->VirtualVolumeFile;

        //
        //  Initialize the structure that will keep track of dirty fat sectors.
        //  The largest possible Mcb structures are less than 1K, so we use
        //  non paged pool.
        //

        FsRtlInitializeLargeMcb( &Vcb->DirtyFatMcb, PagedPool );

        UnwindWeAllocatedMcb = TRUE;

        //
        //  Initialize the structure that will keep track of bad clusters on the volume.
        //
        //  It will be empty until it is populated by FSCTL_GET_RETRIEVAL_POINTERS with a volume handle.
        //

        FsRtlInitializeLargeMcb( &Vcb->BadBlockMcb, PagedPool );
        UnwindWeAllocatedBadBlockMap = TRUE;

        //
        //  Set the cluster index hint to the first valid cluster of a fat: 2
        //

        Vcb->ClusterHint = 2;

        //
        //  Initialize the directory stream file object creation event.
        //  This event is also "borrowed" for async non-cached writes.
        //

        ExInitializeFastMutex( &Vcb->DirectoryFileCreationMutex );

        //
        //  Initialize the clean volume callback Timer and DPC.
        //

        KeInitializeTimer( &Vcb->CleanVolumeTimer );

        KeInitializeDpc( &Vcb->CleanVolumeDpc, FatCleanVolumeDpc, Vcb );

        //
        //  Initialize the performance counters.
        //

#ifndef __REACTOS__
        Vcb->Statistics = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
#else
        Vcb->Statistics = FsRtlAllocatePoolWithTag( NonPagedPool,
#endif
                                                    sizeof(FILE_SYSTEM_STATISTICS) * FatData.NumberProcessors,
                                                    TAG_VCB_STATS );
        UnwindStatistics = Vcb->Statistics;

        RtlZeroMemory( Vcb->Statistics, sizeof(FILE_SYSTEM_STATISTICS) * FatData.NumberProcessors );

        for (i = 0; i < FatData.NumberProcessors; i += 1) {
            Vcb->Statistics[i].Common.FileSystemType = FILESYSTEM_STATISTICS_TYPE_FAT;
            Vcb->Statistics[i].Common.Version = 1;
            Vcb->Statistics[i].Common.SizeOfCompleteStructure =
                sizeof(FILE_SYSTEM_STATISTICS);
        }

        //
        //  Pick up a VPB right now so we know we can pull this filesystem stack off
        //  of the storage stack on demand.
        //

#ifndef __REACTOS__
        Vcb->SwapVpb = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
#else
        Vcb->SwapVpb = FsRtlAllocatePoolWithTag( NonPagedPool,
#endif
                                                 sizeof( VPB ),
                                                 TAG_VPB );

        RtlZeroMemory( Vcb->SwapVpb, sizeof( VPB ) );

        //
        //  Initialize the close queue listheads.
        //

        InitializeListHead( &Vcb->AsyncCloseList );
        InitializeListHead( &Vcb->DelayedCloseList );

        //
        //  Initialize the Advanced FCB Header
        //

        ExInitializeFastMutex( &Vcb->AdvancedFcbHeaderMutex );
        FsRtlSetupAdvancedHeader( &Vcb->VolumeFileHeader,
                                  &Vcb->AdvancedFcbHeaderMutex );


        //
        //  With the Vcb now set up, set the IrpContext Vcb field.
        //

        IrpContext->Vcb = Vcb;

    } _SEH2_FINALLY {

        DebugUnwind( FatInitializeVcb );

        //
        //  If this is an abnormal termination then undo our work
        //

        if (_SEH2_AbnormalTermination()) {

            if (UnwindCacheMap != NULL) { FatSyncUninitializeCacheMap( IrpContext, UnwindCacheMap ); }
            if (UnwindFileObject != NULL) { ObDereferenceObject( UnwindFileObject ); }
            if (UnwindResource != NULL) { FatDeleteResource( UnwindResource ); }
            if (UnwindResource2 != NULL) { FatDeleteResource( UnwindResource2 ); }
            if (UnwindWeAllocatedMcb) { FsRtlUninitializeLargeMcb( &Vcb->DirtyFatMcb ); }
            if (UnwindWeAllocatedBadBlockMap) { FsRtlUninitializeLargeMcb(&Vcb->BadBlockMcb ); }
            if (UnwindEntryList != NULL) {
#ifdef _MSC_VER
#pragma prefast( suppress: 28137, "prefast wants the wait to be a constant, but that isn't possible for the way fastfat is designed" )          
#endif      
                (VOID)FatAcquireExclusiveGlobal( IrpContext );
                RemoveEntryList( UnwindEntryList );
                FatReleaseGlobal( IrpContext );
            }
            if (UnwindStatistics != NULL) { ExFreePool( UnwindStatistics ); }

            //
            // Cleanup the close context we preallocated above.
            //
            
            if (CloseContextAllocated && (Vcb->VirtualVolumeFile == NULL)) {

                //
                // FatAllocateCloseContext does not allocate memory, it
                // pulls a close context off the preallocated slist queue.
                //
                // Doing this here is necessary to balance out the one we 
                // preallocated for the Vcb earlier in this function, but 
                // only if we failed to create the virtual volume file.
                //
                // If VirtualVolumeFile is not NULL, then this CloseContext
                // will get cleaned up when the close comes in for it during
                // Vcb teardown.
                //
                
                PCLOSE_CONTEXT CloseContext = FatAllocateCloseContext(Vcb);

                ExFreePool( CloseContext );
                CloseContextAllocated = FALSE;
            }
        }

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

    //
    //  and return to our caller
    //

    UNREFERENCED_PARAMETER( IrpContext );

    return;
}


VOID
FatTearDownVcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine tries to remove all internal opens from the volume.

Arguments:

    IrpContext - Supplies the context for the overall request.

    Vcb - Supplies the Vcb to be torn down.

Return Value:

    None

--*/

{
    PFILE_OBJECT DirectoryFileObject;


    PAGED_CODE();

    //
    //  Get rid of the virtual volume file, if we need to.
    //

    if (Vcb->VirtualVolumeFile != NULL) {

        //
        //  Uninitialize the cache
        //

        CcUninitializeCacheMap( Vcb->VirtualVolumeFile,
                                &FatLargeZero,
                                NULL );

        FsRtlTeardownPerStreamContexts( &Vcb->VolumeFileHeader );

        ObDereferenceObject( Vcb->VirtualVolumeFile );

        Vcb->VirtualVolumeFile = NULL;
    }

    //
    //  Close down the EA file.
    //

    FatCloseEaFile( IrpContext, Vcb, FALSE );

    //
    //  Close down the root directory stream..
    //

    if (Vcb->RootDcb != NULL) {

        DirectoryFileObject = Vcb->RootDcb->Specific.Dcb.DirectoryFile;

        if (DirectoryFileObject != NULL) {

            //
            //  Tear down this directory file.
            //

            CcUninitializeCacheMap( DirectoryFileObject,
                                    &FatLargeZero,
                                    NULL );

            Vcb->RootDcb->Specific.Dcb.DirectoryFile = NULL;
            ObDereferenceObject( DirectoryFileObject );
        }
    }

    //
    //  The VCB can no longer be used.
    //

    FatSetVcbCondition( Vcb, VcbBad );
}


VOID
FatDeleteVcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine removes the Vcb record from Fat's in-memory data
    structures.  It also will remove all associated underlings
    (i.e., FCB records).

Arguments:

    Vcb - Supplies the Vcb to be removed

Return Value:

    None

--*/

{
    PFCB Fcb;

    PAGED_CODE();

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

    //
    //  If the IrpContext points to the VCB being deleted NULL out the stail
    //  pointer.
    //

    if (IrpContext->Vcb == Vcb) {

        IrpContext->Vcb = NULL;

    }

    //
    //  Chuck the backpocket Vpb we kept just in case.
    //

    if (Vcb->SwapVpb) {

        ExFreePool( Vcb->SwapVpb );

    }

    //
    //  Free the VPB, if we need to.
    //

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

        //
        //  We swapped the VPB, so we need to free the main one.
        //

        ExFreePool( Vcb->Vpb );
    }

    if (Vcb->VolumeGuidPath.Buffer) {
        ExFreePool( Vcb->VolumeGuidPath.Buffer );
        Vcb->VolumeGuidPath.Buffer = NULL;
    }

    //
    //  Remove this record from the global list of all Vcb records.
    //  Note that the global lock must already be held when calling
    //  this function.
    //

    RemoveEntryList( &(Vcb->VcbLinks) );

    //
    //  Make sure the direct access open count is zero, and the open file count
    //  is also zero.
    //

    if ((Vcb->DirectAccessOpenCount != 0) || (Vcb->OpenFileCount != 0)) {

#ifdef _MSC_VER
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )
#endif
        FatBugCheck( 0, 0, 0 );
    }

    //
    //  Remove the EaFcb and dereference the Fcb for the Ea file if it
    //  exists.
    //

    if (Vcb->EaFcb != NULL) {

        Vcb->EaFcb->OpenCount = 0;
        FatDeleteFcb( IrpContext, &Vcb->EaFcb );
    }

    //
    //  Remove the Root Dcb
    //

    if (Vcb->RootDcb != NULL) {

        //
        //  Rundown stale child Fcbs that may be hanging around.  Yes, this
        //  can happen.  No, the create path isn't perfectly defensive about
        //  tearing down branches built up on creates that don't wind up
        //  succeeding.  Normal system operation usually winds up having
        //  cleaned them out through re-visiting, but ...
        //
        //  Just pick off Fcbs from the bottom of the tree until we run out.
        //  Then we delete the root Dcb.
        //

        while( (Fcb = FatGetNextFcbBottomUp( IrpContext, NULL, Vcb->RootDcb )) != Vcb->RootDcb ) {

            FatDeleteFcb( IrpContext, &Fcb );
        }

        FatDeleteFcb( IrpContext, &Vcb->RootDcb );
    }

    //
    //  Uninitialize the notify sychronization object.
    //

    FsRtlNotifyUninitializeSync( &Vcb->NotifySync );

    //
    //  Uninitialize the resource variable for the Vcb
    //

    FatDeleteResource( &Vcb->Resource );
    FatDeleteResource( &Vcb->ChangeBitMapResource );

    //
    //  If allocation support has been setup, free it.
    //

    if (Vcb->FreeClusterBitMap.Buffer != NULL) {

        FatTearDownAllocationSupport( IrpContext, Vcb );
    }

    //
    //  UnInitialize the Mcb structure that kept track of dirty fat sectors.
    //

    FsRtlUninitializeLargeMcb( &Vcb->DirtyFatMcb );

    //
    //  Uninitialize the Mcb structure that kept track of bad sectors.
    //

    FsRtlUninitializeLargeMcb( &Vcb->BadBlockMcb );

    //
    //  Free the pool for the stached copy of the boot sector
    //

    if ( Vcb->First0x24BytesOfBootSector ) {

        ExFreePool( Vcb->First0x24BytesOfBootSector );
        Vcb->First0x24BytesOfBootSector = NULL;
    }

    //
    //  Cancel the CleanVolume Timer and Dpc
    //

    (VOID)KeCancelTimer( &Vcb->CleanVolumeTimer );

    (VOID)KeRemoveQueueDpc( &Vcb->CleanVolumeDpc );

    //
    //  Free the performance counters memory
    //

    ExFreePool( Vcb->Statistics );

    //
    //  Clean out the tunneling cache
    //

    FsRtlDeleteTunnelCache(&Vcb->Tunnel);

    //
    // Dereference the target device object.
    //

    ObDereferenceObject( Vcb->TargetDeviceObject );

    //
    //  We better have used all the close contexts we allocated. There could be
    //  one remaining if we're doing teardown due to a final close coming in on
    //  a directory file stream object.  It will be freed on the way back up.
    //

    NT_ASSERT( Vcb->CloseContextCount <= 1);

    //
    //  And zero out the Vcb, this will help ensure that any stale data is
    //  wiped clean
    //

    RtlZeroMemory( Vcb, sizeof(VCB) );

    //
    //  return and tell the caller
    //

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

    return;
}


_Requires_lock_held_(_Global_critical_region_)    
VOID
FatCreateRootDcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine allocates, initializes, and inserts a new root DCB record
    into the in memory data structure.

Arguments:

    Vcb - Supplies the Vcb to associate the new DCB under

Return Value:

    None. The Vcb is modified in-place.

--*/

{
    PDCB Dcb = NULL;

    //
    //  The following variables are used for abnormal unwind
    //

    PVOID UnwindStorage[2] = { NULL, NULL };
    PERESOURCE UnwindResource = NULL;
    PERESOURCE UnwindResource2 = NULL;
    PLARGE_MCB UnwindMcb = NULL;
    PFILE_OBJECT UnwindFileObject = NULL;

    PAGED_CODE();

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

    _SEH2_TRY {

        //
        //  Make sure we don't already have a root dcb for this vcb
        //

        if (Vcb->RootDcb != NULL) {

            DebugDump("Error trying to create multiple root dcbs\n", 0, Vcb);
#ifdef _MSC_VER
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )          
#endif  
            FatBugCheck( 0, 0, 0 );
        }

        //
        //  Allocate a new DCB and zero it out, we use Dcb locally so we don't
        //  have to continually reference through the Vcb
        //

#ifndef __REACTOS__
        UnwindStorage[0] = Dcb = Vcb->RootDcb = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
#else
        UnwindStorage[0] = Dcb = Vcb->RootDcb = FsRtlAllocatePoolWithTag( NonPagedPool,
#endif
                                                                          sizeof(DCB),
                                                                          TAG_FCB );

        RtlZeroMemory( Dcb, sizeof(DCB));

        UnwindStorage[1] =
        Dcb->NonPaged = FatAllocateNonPagedFcb();

        RtlZeroMemory( Dcb->NonPaged, sizeof( NON_PAGED_FCB ) );

        //
        //  Set the proper node type code, node byte size, and call backs
        //

        Dcb->Header.NodeTypeCode = FAT_NTC_ROOT_DCB;
        Dcb->Header.NodeByteSize = sizeof(DCB);

        Dcb->FcbCondition = FcbGood;

        //
        //  The parent Dcb, initial state, open count, dirent location
        //  information, and directory change count fields are already zero so
        //  we can skip setting them
        //

        //
        //  Initialize the resource variable
        //

        UnwindResource =
        Dcb->Header.Resource = FatAllocateResource();

        //
        //  Initialize the PagingIo Resource.  We no longer use the FsRtl common
        //  shared pool because this led to a) deadlocks due to cases where files
        //  and their parent directories shared a resource and b) there is no way
        //  to anticipate inter-driver induced deadlock via recursive operation.
        //

        UnwindResource2 =
        Dcb->Header.PagingIoResource = FatAllocateResource();

        //
        //  The root Dcb has an empty parent dcb links field
        //

        InitializeListHead( &Dcb->ParentDcbLinks );

        //
        //  Set the Vcb
        //

        Dcb->Vcb = Vcb;

        //
        //  initialize the parent dcb queue.
        //

        InitializeListHead( &Dcb->Specific.Dcb.ParentDcbQueue );

        //
        //  Set the full file name up.
        //

        Dcb->FullFileName.Buffer = L"\\";
        Dcb->FullFileName.Length = (USHORT)2;
        Dcb->FullFileName.MaximumLength = (USHORT)4;

        Dcb->ShortName.Name.Oem.Buffer = "\\";
        Dcb->ShortName.Name.Oem.Length = (USHORT)1;
        Dcb->ShortName.Name.Oem.MaximumLength = (USHORT)2;

        //
        //  Construct a lie about file properties since we don't
        //  have a proper "." entry to look at.
        //

        Dcb->DirentFatFlags = FILE_ATTRIBUTE_DIRECTORY;

        //
        //  Initialize Advanced FCB Header fields
        //

        ExInitializeFastMutex( &Dcb->NonPaged->AdvancedFcbHeaderMutex );
        FsRtlSetupAdvancedHeader( &Dcb->Header,
                                  &Dcb->NonPaged->AdvancedFcbHeaderMutex );

        //
        //  Initialize the Mcb, and setup its mapping.  Note that the root
        //  directory is a fixed size so we can set it everything up now.
        //

#ifndef __REACTOS__
        FsRtlInitializeLargeMcb( &Dcb->Mcb, NonPagedPoolNx );
#else
        FsRtlInitializeLargeMcb( &Dcb->Mcb, NonPagedPool );
#endif
        UnwindMcb = &Dcb->Mcb;

        if (FatIsFat32(Vcb)) {

            //
            //  The first cluster of fat32 roots comes from the BPB
            //

            Dcb->FirstClusterOfFile = Vcb->Bpb.RootDirFirstCluster;

        } else {

            FatAddMcbEntry( Vcb, &Dcb->Mcb,
                            0,
                            FatRootDirectoryLbo( &Vcb->Bpb ),
                            FatRootDirectorySize( &Vcb->Bpb ));
        }

        if (FatIsFat32(Vcb)) {

            //
            //  Find the size of the fat32 root. As a side-effect, this will create
            //  MCBs for the entire root. In the process of doing this, we may
            //  discover that the FAT chain is bogus and raise corruption.
            //

            Dcb->Header.AllocationSize.LowPart = 0xFFFFFFFF;
            FatLookupFileAllocationSize( IrpContext, Dcb);

            Dcb->Header.FileSize.QuadPart =
                    Dcb->Header.AllocationSize.QuadPart;
        } else {

            //
            //  set the allocation size to real size of the root directory
            //

            Dcb->Header.FileSize.QuadPart =
            Dcb->Header.AllocationSize.QuadPart = FatRootDirectorySize( &Vcb->Bpb );

        }

        //
        //  Set our two create dirent aids to represent that we have yet to
        //  enumerate the directory for never used or deleted dirents.
        //

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

        //
        //  Setup the free dirent bitmap buffer.
        //

        RtlInitializeBitMap( &Dcb->Specific.Dcb.FreeDirentBitmap,
                             NULL,
                             0 );

        FatCheckFreeDirentBitmap( IrpContext, Dcb );

#if (NTDDI_VERSION >= NTDDI_WIN8)
        //
        //  Initialize the oplock structure.
        //
        
        FsRtlInitializeOplock( FatGetFcbOplock(Dcb) );
#endif

    } _SEH2_FINALLY {

        DebugUnwind( FatCreateRootDcb );

        //
        //  If this is an abnormal termination then undo our work
        //

        if (_SEH2_AbnormalTermination()) {

            ULONG i;

            if (UnwindFileObject != NULL) { ObDereferenceObject( UnwindFileObject ); }
            if (UnwindMcb != NULL) { FsRtlUninitializeLargeMcb( UnwindMcb ); }
            if (UnwindResource != NULL) { FatFreeResource( UnwindResource ); }
            if (UnwindResource2 != NULL) { FatFreeResource( UnwindResource2 ); }

            for (i = 0; i < sizeof(UnwindStorage)/sizeof(PVOID); i += 1) {
                if (UnwindStorage[i] != NULL) { ExFreePool( UnwindStorage[i] ); }
            }

            //
            //  Re-zero the entry in the Vcb.
            //

            Vcb->RootDcb = NULL;
        }

        DebugTrace(-1, Dbg, "FatCreateRootDcb -> %p\n", Dcb);
    } _SEH2_END;

    return;
}


PFCB
FatCreateFcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN PDCB ParentDcb,
    IN ULONG LfnOffsetWithinDirectory,
    IN ULONG DirentOffsetWithinDirectory,
    IN PDIRENT Dirent,
    IN PUNICODE_STRING Lfn OPTIONAL,
    IN PUNICODE_STRING OrigLfn OPTIONAL,    
    IN BOOLEAN IsPagingFile,
    IN BOOLEAN SingleResource
    )

/*++

Routine Description:

    This routine allocates, initializes, and inserts a new Fcb record into
    the in-memory data structures.

Arguments:

    Vcb - Supplies the Vcb to associate the new FCB under.

    ParentDcb - Supplies the parent dcb that the new FCB is under.

    LfnOffsetWithinDirectory - Supplies the offset of the LFN.  If there is
        no LFN associated with this file then this value is same as
        DirentOffsetWithinDirectory.

    DirentOffsetWithinDirectory - Supplies the offset, in bytes from the
        start of the directory file where the dirent for the fcb is located

    Dirent - Supplies the dirent for the fcb being created

    Lfn - Supplies a long UNICODE name associated with this file.

    IsPagingFile - Indicates if we are creating an FCB for a paging file
        or some other type of file.

    SingleResource - Indicates if this Fcb should share a single resource
        as both main and paging.

Return Value:

    PFCB - Returns a pointer to the newly allocated FCB

--*/

{
    PFCB Fcb = NULL;
    POOL_TYPE PoolType;

    //
    //  The following variables are used for abnormal unwind
    //

    PVOID UnwindStorage[2] = { NULL, NULL };
    PERESOURCE UnwindResource = NULL;
    PERESOURCE UnwindResource2 = NULL;
    PLIST_ENTRY UnwindEntryList = NULL;
    PLARGE_MCB UnwindMcb = NULL;
    PFILE_LOCK UnwindFileLock = NULL;
    POPLOCK UnwindOplock = NULL;

    PAGED_CODE();

    UNREFERENCED_PARAMETER( OrigLfn );
    
    DebugTrace(+1, Dbg, "FatCreateFcb\n", 0);

    _SEH2_TRY {

        //
        //  Determine the pool type we should be using for the fcb and the
        //  mcb structure
        //

        if (IsPagingFile) {

#ifndef __REACTOS__
            PoolType = NonPagedPoolNx;
            Fcb = UnwindStorage[0] = FsRtlAllocatePoolWithTag( NonPagedPoolNx,
#else
            PoolType = NonPagedPool;
            Fcb = UnwindStorage[0] = FsRtlAllocatePoolWithTag( NonPagedPool,
#endif
                                                               sizeof(FCB),
                                                               TAG_FCB );
        } else {

            PoolType = PagedPool;
            Fcb = UnwindStorage[0] = FatAllocateFcb();

        }

        //
        //  ... and zero it out
        //

        RtlZeroMemory( Fcb, sizeof(FCB) );

        UnwindStorage[1] =
        Fcb->NonPaged = FatAllocateNonPagedFcb();

        RtlZeroMemory( Fcb->NonPaged, sizeof( NON_PAGED_FCB ) );

        //
        //  Set the proper node type code, node byte size, and call backs
        //

        Fcb->Header.NodeTypeCode = FAT_NTC_FCB;
        Fcb->Header.NodeByteSize = sizeof(FCB);

        Fcb->FcbCondition = FcbGood;

        //
        //  Check to see if we need to set the Fcb state to indicate that this
        //  is a paging/system file.  This will prevent it from being opened
        //  again.
        //

        if (IsPagingFile) {

            SetFlag( Fcb->FcbState, FCB_STATE_PAGING_FILE | FCB_STATE_SYSTEM_FILE );
        }

        //
        //  The initial state, open count, and segment objects fields are already
        //  zero so we can skip setting them
        //

        //
        //  Initialize the resource variable
        //


        UnwindResource =
        Fcb->Header.Resource = FatAllocateResource();

        //
        //  Initialize the PagingIo Resource.  We no longer use the FsRtl common
        //  shared pool because this led to a) deadlocks due to cases where files
        //  and their parent directories shared a resource and b) there is no way
        //  to anticipate inter-driver induced deadlock via recursive operation.
        //

        if (SingleResource) {

            Fcb->Header.PagingIoResource = Fcb->Header.Resource;

        } else {

            UnwindResource2 =
            Fcb->Header.PagingIoResource = FatAllocateResource();
        }

        //
        //  Insert this fcb into our parent dcb's queue.
        //
        //  There is a deep reason why this goes on the tail, to allow us
        //  to easily enumerate all child directories before child files.
        //  This is important to let us maintain whole-volume lockorder
        //  via BottomUp enumeration.
        //
            
        InsertTailList( &ParentDcb->Specific.Dcb.ParentDcbQueue,
                        &Fcb->ParentDcbLinks );
        UnwindEntryList = &Fcb->ParentDcbLinks;
        
        //
        //  Point back to our parent dcb
        //

        Fcb->ParentDcb = ParentDcb;

        //
        //  Set the Vcb
        //

        Fcb->Vcb = Vcb;

        //
        //  Set the dirent offset within the directory
        //

        Fcb->LfnOffsetWithinDirectory = LfnOffsetWithinDirectory;
        Fcb->DirentOffsetWithinDirectory = DirentOffsetWithinDirectory;

        //
        //  Set the DirentFatFlags and LastWriteTime
        //

        Fcb->DirentFatFlags = Dirent->Attributes;

        Fcb->LastWriteTime = FatFatTimeToNtTime( IrpContext,
                                                 Dirent->LastWriteTime,
                                                 0 );

        //
        //  These fields are only non-zero when in Chicago mode.
        //

        if (FatData.ChicagoMode) {

#ifndef __REACTOS__
            LARGE_INTEGER FatSystemJanOne1980 = {0};
#else
            LARGE_INTEGER FatSystemJanOne1980 = {{0}};
#endif

            //
            //  If either date is possibly zero, get the system
            //  version of 1/1/80.
            //

            if ((((PUSHORT)Dirent)[9] & ((PUSHORT)Dirent)[8]) == 0) {

                ExLocalTimeToSystemTime( &FatJanOne1980,
                                         &FatSystemJanOne1980 );
            }

            //
            //  Only do the really hard work if this field is non-zero.
            //

            if (((PUSHORT)Dirent)[9] != 0) {

                Fcb->LastAccessTime =
                    FatFatDateToNtTime( IrpContext,
                                        Dirent->LastAccessDate );

            } else {

                Fcb->LastAccessTime = FatSystemJanOne1980;
            }

            //
            //  Only do the really hard work if this field is non-zero.
            //

            if (((PUSHORT)Dirent)[8] != 0) {

                Fcb->CreationTime =
                    FatFatTimeToNtTime( IrpContext,
                                        Dirent->CreationTime,
                                        Dirent->CreationMSec );

            } else {

                Fcb->CreationTime = FatSystemJanOne1980;
            }
        }

        //
        //  Initialize Advanced FCB Header fields
        //

        ExInitializeFastMutex( &Fcb->NonPaged->AdvancedFcbHeaderMutex );
        FsRtlSetupAdvancedHeader( &Fcb->Header,
                                  &Fcb->NonPaged->AdvancedFcbHeaderMutex );

        //
        //  To make FAT match the present functionality of NTFS, disable
        //  stream contexts on paging files
        //

        if (IsPagingFile) {

            SetFlag( Fcb->Header.Flags2, FSRTL_FLAG2_IS_PAGING_FILE );
            ClearFlag( Fcb->Header.Flags2, FSRTL_FLAG2_SUPPORTS_FILTER_CONTEXTS );
        }

        //
        //  Initialize the Mcb
        //

        FsRtlInitializeLargeMcb( &Fcb->Mcb, PoolType );
        UnwindMcb = &Fcb->Mcb;

        //
        //  Set the file size, valid data length, first cluster of file,
        //  and allocation size based on the information stored in the dirent
        //

        Fcb->Header.FileSize.LowPart = Dirent->FileSize;

        Fcb->Header.ValidDataLength.LowPart = Dirent->FileSize;

        Fcb->ValidDataToDisk = Dirent->FileSize;

        Fcb->FirstClusterOfFile = (ULONG)Dirent->FirstClusterOfFile;

        if ( FatIsFat32(Vcb) ) {

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

        if ( Fcb->FirstClusterOfFile == 0 ) {

            Fcb->Header.AllocationSize.QuadPart = 0;

        } else {

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


        //
        //  Initialize the Fcb's file lock record
        //

        FsRtlInitializeFileLock( &Fcb->Specific.Fcb.FileLock, NULL, NULL );
        UnwindFileLock = &Fcb->Specific.Fcb.FileLock;

        //
        //  Initialize the oplock structure.
        //

        FsRtlInitializeOplock( FatGetFcbOplock(Fcb) );
        UnwindOplock = FatGetFcbOplock(Fcb);

        //
        //  Indicate that Fast I/O is possible
        //

        Fcb->Header.IsFastIoPossible = TRUE;

        //
        //  Set the file names.  This must be the last thing we do.
        //

        FatConstructNamesInFcb( IrpContext,
                                Fcb,
                                Dirent,
                                Lfn );

        //
        //  Drop the shortname hint so prefix searches can figure out
        //  what they found
        //

        Fcb->ShortName.FileNameDos = TRUE;

    } _SEH2_FINALLY {

        DebugUnwind( FatCreateFcb );

        //
        //  If this is an abnormal termination then undo our work
        //

        if (_SEH2_AbnormalTermination()) {

            ULONG i;

            if (UnwindOplock != NULL) { FsRtlUninitializeOplock( UnwindOplock ); }
            if (UnwindFileLock != NULL) { FsRtlUninitializeFileLock( UnwindFileLock ); }
            if (UnwindMcb != NULL) { FsRtlUninitializeLargeMcb( UnwindMcb ); }
            if (UnwindEntryList != NULL) { RemoveEntryList( UnwindEntryList ); }
            if (UnwindResource != NULL) { FatFreeResource( UnwindResource ); }
            if (UnwindResource2 != NULL) { FatFreeResource( UnwindResource2 ); }

            for (i = 0; i < sizeof(UnwindStorage)/sizeof(PVOID); i += 1) {
                if (UnwindStorage[i] != NULL) { ExFreePool( UnwindStorage[i] ); }
            }
        }

        DebugTrace(-1, Dbg, "FatCreateFcb -> %p\n", Fcb);
    } _SEH2_END;

    //
    //  return and tell the caller
    //

    return Fcb;
}


PDCB
FatCreateDcb (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb,
    IN PDCB ParentDcb,
    IN ULONG LfnOffsetWithinDirectory,
    IN ULONG DirentOffsetWithinDirectory,
    IN PDIRENT Dirent,
    IN PUNICODE_STRING Lfn OPTIONAL
    )

/*++

Routine Description:

    This routine allocates, initializes, and inserts a new Dcb record into
    the in memory data structures.

Arguments:

    Vcb - Supplies the Vcb to associate the new DCB under.

    ParentDcb - Supplies the parent dcb that the new DCB is under.

    LfnOffsetWithinDirectory - Supplies the offset of the LFN.  If there is
        no LFN associated with this file then this value is same as
        DirentOffsetWithinDirectory.

    DirentOffsetWithinDirectory - Supplies the offset, in bytes from the
        start of the directory file where the dirent for the fcb is located

    Dirent - Supplies the dirent for the dcb being created

    FileName - Supplies the file name of the file relative to the directory
        it's in (e.g., the file \config.sys is called "CONFIG.SYS" without
        the preceding backslash).

    Lfn - Supplies a long UNICODE name associated with this directory.

Return Value:

    PDCB - Returns a pointer to the newly allocated DCB

--*/

{
    PDCB Dcb = NULL;

    //
    //  The following variables are used for abnormal unwind
    //

    PVOID UnwindStorage[2] = { NULL, NULL  };
    PERESOURCE UnwindResource = NULL;
    PERESOURCE UnwindResource2 = NULL;
    PLIST_ENTRY UnwindEntryList = NULL;
    PLARGE_MCB UnwindMcb = NULL;
    POPLOCK UnwindOplock = NULL;

    PAGED_CODE();

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

    _SEH2_TRY {

        //
        //  assert that the only time we are called is if wait is true
        //

        NT_ASSERT( FlagOn(IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT) );

        //
        //  Allocate a new DCB, and zero it out
        //

        UnwindStorage[0] = Dcb = FatAllocateFcb();

        RtlZeroMemory( Dcb, sizeof(DCB) );

        UnwindStorage[1] =
        Dcb->NonPaged = FatAllocateNonPagedFcb();

        RtlZeroMemory( Dcb->NonPaged, sizeof( NON_PAGED_FCB ) );

        //
        //  Set the proper node type code, node byte size and call backs
        //

        Dcb->Header.NodeTypeCode = FAT_NTC_DCB;
        Dcb->Header.NodeByteSize = sizeof(DCB);

        Dcb->FcbCondition = FcbGood;

        //
        //  The initial state, open count, and directory change count fields are
        //  already zero so we can skip setting them
        //

        //
        //  Initialize the resource variable
        //


        UnwindResource =
        Dcb->Header.Resource = FatAllocateResource();

        //
        //  Initialize the PagingIo Resource.  We no longer use the FsRtl common
        //  shared pool because this led to a) deadlocks due to cases where files
        //  and their parent directories shared a resource and b) there is no way
        //  to anticipate inter-driver induced deadlock via recursive operation.
        //

        UnwindResource2 =
        Dcb->Header.PagingIoResource = FatAllocateResource();

        //
        //  Insert this Dcb into our parent dcb's queue
        //
        //  There is a deep reason why this goes on the head, to allow us
        //  to easily enumerate all child directories before child files.
        //  This is important to let us maintain whole-volume lockorder
        //  via BottomUp enumeration.
        //

        InsertHeadList( &ParentDcb->Specific.Dcb.ParentDcbQueue,
                        &Dcb->ParentDcbLinks );
        UnwindEntryList = &Dcb->ParentDcbLinks;

        //
        //  Point back to our parent dcb
        //

        Dcb->ParentDcb = ParentDcb;

        //
        //  Set the Vcb
        //

        Dcb->Vcb = Vcb;

        //
        //  Set the dirent offset within the directory
        //

        Dcb->LfnOffsetWithinDirectory = LfnOffsetWithinDirectory;
        Dcb->DirentOffsetWithinDirectory = DirentOffsetWithinDirectory;

        //
        //  Set the DirentFatFlags and LastWriteTime
        //

        Dcb->DirentFatFlags = Dirent->Attributes;

        Dcb->LastWriteTime = FatFatTimeToNtTime( IrpContext,
                                                 Dirent->LastWriteTime,
                                                 0 );

        //
        //  These fields are only non-zero when in Chicago mode.
        //

        if (FatData.ChicagoMode) {

#ifndef __REACTOS__
            LARGE_INTEGER FatSystemJanOne1980 = {0};
#else
            LARGE_INTEGER FatSystemJanOne1980 = {{0}};
#endif

            //
            //  If either date is possibly zero, get the system
            //  version of 1/1/80.
            //

            if ((((PUSHORT)Dirent)[9] & ((PUSHORT)Dirent)[8]) == 0) {

                ExLocalTimeToSystemTime( &FatJanOne1980,
                                         &FatSystemJanOne1980 );
            }

            //
            //  Only do the really hard work if this field is non-zero.
            //

            if (((PUSHORT)Dirent)[9] != 0) {

                Dcb->LastAccessTime =
                    FatFatDateToNtTime( IrpContext,
                                        Dirent->LastAccessDate );

            } else {

                Dcb->LastAccessTime = FatSystemJanOne1980;
            }

            //
            //  Only do the really hard work if this field is non-zero.
            //

            if (((PUSHORT)Dirent)[8] != 0) {

                Dcb->CreationTime =
                    FatFatTimeToNtTime( IrpContext,
                                        Dirent->CreationTime,
                                        Dirent->CreationMSec );

            } else {

                Dcb->CreationTime = FatSystemJanOne1980;
            }
        }

        //
        //  Initialize Advanced FCB Header fields
        //

        ExInitializeFastMutex( &Dcb->NonPaged->AdvancedFcbHeaderMutex );
        FsRtlSetupAdvancedHeader( &Dcb->Header,
                                  &Dcb->NonPaged->AdvancedFcbHeaderMutex );

        //
        //  Initialize the Mcb
        //

        FsRtlInitializeLargeMcb( &Dcb->Mcb, PagedPool );
        UnwindMcb = &Dcb->Mcb;

        //
        //  Set the file size, first cluster of file, and allocation size
        //  based on the information stored in the dirent
        //

        Dcb->FirstClusterOfFile = (ULONG)Dirent->FirstClusterOfFile;

        if ( FatIsFat32(Dcb->Vcb) ) {

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

        if ( Dcb->FirstClusterOfFile == 0 ) {

            Dcb->Header.AllocationSize.QuadPart = 0;

        } else {

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


        //  initialize the notify queues, and the parent dcb queue.
        //

        InitializeListHead( &Dcb->Specific.Dcb.ParentDcbQueue );

        //
        //  Setup the free dirent bitmap buffer.  Since we don't know the
        //  size of the directory, leave it zero for now.
        //

        RtlInitializeBitMap( &Dcb->Specific.Dcb.FreeDirentBitmap,
                             NULL,
                             0 );

        //
        //  Set our two create dirent aids to represent that we have yet to
        //  enumerate the directory for never used or deleted dirents.
        //

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

#if (NTDDI_VERSION >= NTDDI_WIN8)
        //
        //  Initialize the oplock structure.
        //

        FsRtlInitializeOplock( FatGetFcbOplock(Dcb) );
        UnwindOplock = FatGetFcbOplock(Dcb);
#endif

        //
        //  Postpone initializing the cache map until we need to do a read/write
        //  of the directory file.


        //
        //  set the file names.  This must be the last thing we do.
        //

        FatConstructNamesInFcb( IrpContext,
                                Dcb,
                                Dirent,
                                Lfn );

        Dcb->ShortName.FileNameDos = TRUE;

    } _SEH2_FINALLY {

        DebugUnwind( FatCreateDcb );

        //
        //  If this is an abnormal termination then undo our work
        //

        if (_SEH2_AbnormalTermination()) {

            ULONG i;

            if (UnwindOplock != NULL) { FsRtlUninitializeOplock( UnwindOplock ); }
            if (UnwindMcb != NULL) { FsRtlUninitializeLargeMcb( UnwindMcb ); }
            if (UnwindEntryList != NULL) { RemoveEntryList( UnwindEntryList ); }
            if (UnwindResource != NULL) { FatFreeResource( UnwindResource ); }
            if (UnwindResource2 != NULL) { FatFreeResource( UnwindResource2 ); }

            for (i = 0; i < sizeof(UnwindStorage)/sizeof(PVOID); i += 1) {
                if (UnwindStorage[i] != NULL) { ExFreePool( UnwindStorage[i] ); }
            }
        }

        DebugTrace(-1, Dbg, "FatCreateDcb -> %p\n", Dcb);
    } _SEH2_END;

    //
    //  return and tell the caller
    //

    DebugTrace(-1, Dbg, "FatCreateDcb -> %p\n", Dcb);

    return Dcb;
}


VOID
FatDeleteFcb (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB *FcbPtr
    )

/*++

Routine Description:

    This routine deallocates and removes an FCB, DCB, or ROOT DCB record
    from Fat's in-memory data structures.  It also will remove all
    associated underlings (i.e., Notify irps, and child FCB/DCB records).

Arguments:

    Fcb - Supplies the FCB/DCB/ROOT DCB to be removed

Return Value:

    None

--*/

{
    PFCB Fcb = *FcbPtr;

    PAGED_CODE();

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

    //
    //  We can only delete this record if the open count is zero.
    //

    if (Fcb->OpenCount != 0) {

        DebugDump("Error deleting Fcb, Still Open\n", 0, Fcb);
#ifdef _MSC_VER
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )        
#endif
        FatBugCheck( 0, 0, 0 );
    }

    //
    //  Better be an FCB/DCB.
    //

    if ((Fcb->Header.NodeTypeCode != FAT_NTC_DCB) &&
        (Fcb->Header.NodeTypeCode != FAT_NTC_ROOT_DCB) &&
        (Fcb->Header.NodeTypeCode != FAT_NTC_FCB)) {

#ifdef _MSC_VER
#pragma prefast( suppress:28159, "things are seriously wrong if we get here" )
#endif
        FatBugCheck( 0, 0, 0 );
    }

    //
    //  If this is a DCB then remove every Notify record from the two
    //  notify queues
    //

    if ((Fcb->Header.NodeTypeCode == FAT_NTC_DCB) ||
        (Fcb->Header.NodeTypeCode == FAT_NTC_ROOT_DCB)) {

        //
        //  If we allocated a free dirent bitmap buffer, free it.
        //

        if ((Fcb->Specific.Dcb.FreeDirentBitmap.Buffer != NULL) &&
            (Fcb->Specific.Dcb.FreeDirentBitmap.Buffer !=
             &Fcb->Specific.Dcb.FreeDirentBitmapBuffer[0])) {

            ExFreePool(Fcb->Specific.Dcb.FreeDirentBitmap.Buffer);
        }

#if (NTDDI_VERSION >= NTDDI_WIN8)
        //
        //  Uninitialize the oplock.
        //
        
        FsRtlUninitializeOplock( FatGetFcbOplock(Fcb) );
#endif

        NT_ASSERT( Fcb->Specific.Dcb.DirectoryFileOpenCount == 0 );
        NT_ASSERT( IsListEmpty(&Fcb->Specific.Dcb.ParentDcbQueue) );
        NT_ASSERT( NULL == Fcb->Specific.Dcb.DirectoryFile);

    } else {

        //
        //  Uninitialize the byte range file locks and opportunistic locks
        //

        FsRtlUninitializeFileLock( &Fcb->Specific.Fcb.FileLock );
        FsRtlUninitializeOplock( FatGetFcbOplock(Fcb) );
    }


    //
    //  Release any Filter Context structures associated with this FCB
    //

    FsRtlTeardownPerStreamContexts( &Fcb->Header );

    //
    //  Uninitialize the Mcb
    //

    FsRtlUninitializeLargeMcb( &Fcb->Mcb );

    //
    //  If this is not the root dcb then we need to remove ourselves from
    //  our parents Dcb queue
    //

    if (Fcb->Header.NodeTypeCode != FAT_NTC_ROOT_DCB) {

        RemoveEntryList( &(Fcb->ParentDcbLinks) );
    }

    //
    //  Remove the entry from the splay table if there is still is one.
    //

    if (FlagOn( Fcb->FcbState, FCB_STATE_NAMES_IN_SPLAY_TREE )) {

        FatRemoveNames( IrpContext, Fcb );
    }

    //
    //  Free the file name pool if allocated.
    //

    if (Fcb->Header.NodeTypeCode != FAT_NTC_ROOT_DCB) {

        //
        //  If we blew up at inconvenient times, the shortname
        //  could be null even though you will *never* see this
        //  normally.  Rename is a good example of this case.
        //

        if (Fcb->ShortName.Name.Oem.Buffer) {

            ExFreePool( Fcb->ShortName.Name.Oem.Buffer );
        }

        if (Fcb->FullFileName.Buffer) {

            ExFreePool( Fcb->FullFileName.Buffer );
        }
    }

    if (Fcb->ExactCaseLongName.Buffer) {

        ExFreePool(Fcb->ExactCaseLongName.Buffer);
    }

#ifdef SYSCACHE_COMPILE

    if (Fcb->WriteMask) {

        ExFreePool( Fcb->WriteMask );
    }

#endif

    //
    //  Finally deallocate the Fcb and non-paged fcb records
    //

    FatFreeResource( Fcb->Header.Resource );

    if (Fcb->Header.PagingIoResource != Fcb->Header.Resource) {

        FatFreeResource( Fcb->Header.PagingIoResource );
    }

    //
    //  If an Event was allocated, get rid of it.
    //

    if (Fcb->NonPaged->OutstandingAsyncEvent) {

        ExFreePool( Fcb->NonPaged->OutstandingAsyncEvent );
    }

    FatFreeNonPagedFcb( Fcb->NonPaged );

    Fcb->Header.NodeTypeCode = NTC_UNDEFINED;

    FatFreeFcb( Fcb );
    *FcbPtr = NULL;

    //
    //  and return to our caller
    //

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


PCCB
FatCreateCcb (
    IN PIRP_CONTEXT IrpContext
    )

/*++

Routine Description:

    This routine creates a new CCB record

Arguments:

Return Value:

    CCB - returns a pointer to the newly allocate CCB

--*/

{
    PCCB Ccb;

    PAGED_CODE();

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

    //
    //  Allocate a new CCB Record
    //

    Ccb = FatAllocateCcb();

    RtlZeroMemory( Ccb, sizeof(CCB) );

    //
    //  Set the proper node type code and node byte size
    //

    Ccb->NodeTypeCode = FAT_NTC_CCB;
    Ccb->NodeByteSize = sizeof(CCB);

    //
    //  return and tell the caller
    //

    DebugTrace(-1, Dbg, "FatCreateCcb -> %p\n", Ccb);

    UNREFERENCED_PARAMETER( IrpContext );

    return Ccb;
}



VOID
FatDeallocateCcbStrings(
    IN PCCB Ccb
    )
/*++

Routine Description:

    This routine deallocates CCB query templates

Arguments:

    Ccb - Supplies the CCB

Return Value:

    None

--*/
{
    PAGED_CODE();

    //
    //  If we allocated query template buffers, deallocate them now.
    //

    if (FlagOn(Ccb->Flags, CCB_FLAG_FREE_UNICODE)) {

        NT_ASSERT( Ccb->UnicodeQueryTemplate.Buffer);
        NT_ASSERT( !FlagOn( Ccb->Flags, CCB_FLAG_CLOSE_CONTEXT));
        RtlFreeUnicodeString( &Ccb->UnicodeQueryTemplate );
    }

    if (FlagOn(Ccb->Flags, CCB_FLAG_FREE_OEM_BEST_FIT)) {

        NT_ASSERT( Ccb->OemQueryTemplate.Wild.Buffer );
        NT_ASSERT( !FlagOn( Ccb->Flags, CCB_FLAG_CLOSE_CONTEXT));
        RtlFreeOemString( &Ccb->OemQueryTemplate.Wild );
    }

    ClearFlag( Ccb->Flags, CCB_FLAG_FREE_OEM_BEST_FIT | CCB_FLAG_FREE_UNICODE);
}



VOID
FatDeleteCcb (
    IN PIRP_CONTEXT IrpContext,
    IN PCCB *Ccb
    )

/*++

Routine Description:

    This routine deallocates and removes the specified CCB record
    from the Fat in memory data structures

Arguments:

    Ccb - Supplies the CCB to remove

Return Value:

    None

--*/

{
    PAGED_CODE();

    DebugTrace(+1, Dbg, "FatDeleteCcb, Ccb = %p\n", *Ccb);

    FatDeallocateCcbStrings( *Ccb);

    //
    //  Deallocate the Ccb record
    //

    FatFreeCcb( *Ccb );
    *Ccb = NULL;

    //
    //  return and tell the caller
    //

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

    UNREFERENCED_PARAMETER( IrpContext );
}


PIRP_CONTEXT
FatCreateIrpContext (
    IN PIRP Irp,
    IN BOOLEAN Wait
    )

/*++

Routine Description:

    This routine creates a new IRP_CONTEXT record

Arguments:

    Irp - Supplies the originating Irp.

    Wait - Supplies the wait value to store in the context

Return Value:

    PIRP_CONTEXT - returns a pointer to the newly allocate IRP_CONTEXT Record

--*/

{
    PIRP_CONTEXT IrpContext;
    PIO_STACK_LOCATION IrpSp;

    PAGED_CODE();

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

    IrpSp = IoGetCurrentIrpStackLocation( Irp );

    //
    //  The only operations a filesystem device object should ever receive
    //  are create/teardown of fsdo handles and operations which do not
    //  occur in the context of fileobjects (i.e., mount).
    //

    if (FatDeviceIsFatFsdo( IrpSp->DeviceObject))  {

        if (IrpSp->FileObject != NULL &&
            IrpSp->MajorFunction != IRP_MJ_CREATE &&
            IrpSp->MajorFunction != IRP_MJ_CLEANUP &&
            IrpSp->MajorFunction != IRP_MJ_CLOSE) {

            ExRaiseStatus( STATUS_INVALID_DEVICE_REQUEST );
        }

        NT_ASSERT( IrpSp->FileObject != NULL ||

                (IrpSp->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL &&
                 IrpSp->MinorFunction == IRP_MN_USER_FS_REQUEST &&
                 IrpSp->Parameters.FileSystemControl.FsControlCode == FSCTL_INVALIDATE_VOLUMES) ||

                (IrpSp->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL &&
                 IrpSp->MinorFunction == IRP_MN_MOUNT_VOLUME ) ||

                IrpSp->MajorFunction == IRP_MJ_SHUTDOWN );
    }

    //
    //  Attemtp to allocate from the region first and failing that allocate
    //  from pool.
    //

    DebugDoit( FatFsdEntryCount += 1);

    IrpContext = FatAllocateIrpContext();

    //
    //  Zero out the irp context.
    //

    RtlZeroMemory( IrpContext, sizeof(IRP_CONTEXT) );

    //
    //  Set the proper node type code and node byte size
    //

    IrpContext->NodeTypeCode = FAT_NTC_IRP_CONTEXT;
    IrpContext->NodeByteSize = sizeof(IRP_CONTEXT);

    //
    //  Set the originating Irp field
    //

    IrpContext->OriginatingIrp = Irp;

    //
    //  Major/Minor Function codes
    //

    IrpContext->MajorFunction = IrpSp->MajorFunction;
    IrpContext->MinorFunction = IrpSp->MinorFunction;

    //
    //  Copy RealDevice for workque algorithms, and also set Write Through
    //  and Removable Media if there is a file object.  Only file system
    //  control Irps won't have a file object, and they should all have
    //  a Vpb as the first IrpSp location.
    //

    if (IrpSp->FileObject != NULL) {

        PFILE_OBJECT FileObject = IrpSp->FileObject;

        IrpContext->RealDevice = FileObject->DeviceObject;
        IrpContext->Vcb = &((PVOLUME_DEVICE_OBJECT)(IrpSp->DeviceObject))->Vcb;

        //
        //  See if the request is Write Through. Look for both FileObjects opened
        //  as write through, and non-cached requests with the SL_WRITE_THROUGH flag set.
        //
        //  The latter can only originate from kernel components. (Note - NtWriteFile()
        //  does redundantly set the SL_W_T flag for all requests it issues on write
        //  through file objects)
        //

        if (IsFileWriteThrough( FileObject, IrpContext->Vcb ) ||
            ( (IrpSp->MajorFunction == IRP_MJ_WRITE) &&
              BooleanFlagOn( Irp->Flags, IRP_NOCACHE) &&
              BooleanFlagOn( IrpSp->Flags, SL_WRITE_THROUGH))) {

            SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_WRITE_THROUGH);
        }
    } else if (IrpContext->MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL) {

        IrpContext->RealDevice = IrpSp->Parameters.MountVolume.Vpb->RealDevice;
    }

    //
    //  Set the wait parameter
    //

    if (Wait) { SetFlag( IrpContext->Flags, IRP_CONTEXT_FLAG_WAIT); }

    //
    //  Set the recursive file system call parameter.  We set it true if
    //  the TopLevelIrp field in the thread local storage is not the current
    //  irp, otherwise we leave it as FALSE.
    //

    if ( IoGetTopLevelIrp() != Irp) {

        SetFlag(IrpContext->Flags, IRP_CONTEXT_FLAG_RECURSIVE_CALL);
    }

    //
    //  return and tell the caller
    //

    DebugTrace(-1, Dbg, "FatCreateIrpContext -> %p\n", IrpContext);

    return IrpContext;
}



VOID
FatDeleteIrpContext_Real (
    IN PIRP_CONTEXT IrpContext
    )

/*++

Routine Description:

    This routine deallocates and removes the specified IRP_CONTEXT record
    from the Fat in memory data structures.  It should only be called
    by FatCompleteRequest.

Arguments:

    IrpContext - Supplies the IRP_CONTEXT to remove

Return Value:

    None

--*/

{
    PAGED_CODE();

    DebugTrace(+1, Dbg, "FatDeleteIrpContext, IrpContext = %p\n", IrpContext);

    NT_ASSERT( IrpContext->NodeTypeCode == FAT_NTC_IRP_CONTEXT );
    NT_ASSERT( IrpContext->PinCount == 0 );


    //
    //  If there is a FatIoContext that was allocated, free it.
    //

    if (IrpContext->FatIoContext != NULL) {

        if (!FlagOn(IrpContext->Flags, IRP_CONTEXT_STACK_IO_CONTEXT)) {

            if (IrpContext->FatIoContext->ZeroMdl) {
                IoFreeMdl( IrpContext->FatIoContext->ZeroMdl );
            }

            ExFreePool( IrpContext->FatIoContext );
        }
    }

    //
    //  Drop the IrpContext.
    //

    FatFreeIrpContext( IrpContext );

    //
    //  return and tell the caller
    //

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

    return;
}


PFCB
FatGetNextFcbBottomUp (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb OPTIONAL,
    IN PFCB TerminationFcb
    )

/*++

Routine Description:

    This routine is used to iterate through Fcbs in a tree.  In order to match
    the lockorder for getting multiple Fcbs (so this can be used for acquiring
    all Fcbs), this version does a bottom-up enumeration.

    This is different than the old one, now called TopDown. The problem with
    lockorder was very well hidden.

    The transition rule is still pretty simple:

        A) If you have an adjacent sibling, go to it
            1) Descend to its leftmost child
        B) Else go to your parent

    If this routine is called with in invalid TerminationFcb it will fail,
    badly.

    The TerminationFcb is the last Fcb returned in the enumeration.

    This method is incompatible with the possibility that ancestors may vanish
    based on operations done on the last returned node.  For instance,
    FatPurgeReferencedFileObjects cannot use BottomUp enumeration.

Arguments:

    Fcb - Supplies the current Fcb.  This is NULL if enumeration is starting.

    TerminationFcb - The root Fcb of the tree in which the enumeration starts
        and at which it inclusively stops.

Return Value:

    The next Fcb in the enumeration, or NULL if Fcb was the final one.

--*/

{
    PFCB NextFcb;

    PAGED_CODE();
    UNREFERENCED_PARAMETER( IrpContext );

    NT_ASSERT( FatVcbAcquiredExclusive( IrpContext, TerminationFcb->Vcb ) ||
            FlagOn( TerminationFcb->Vcb->VcbState, VCB_STATE_FLAG_LOCKED ) );

    //
    //  Do we need to begin the enumeration?
    //

    if (Fcb != NULL) {

        //
        //  Did we complete?
        //

        if (Fcb == TerminationFcb) {

            return NULL;
        }

        //
        //  Do we have a sibling to return?
        //

        NextFcb = FatGetNextSibling( Fcb );

        //
        //  If not, return our parent.  We are done with this branch.
        //

        if (NextFcb == NULL) {

            return Fcb->ParentDcb;
        }

    } else {

        NextFcb = TerminationFcb;
    }

    //
    //  Decend to its furthest child (if it exists) and return it.
    //

    for (;
         NodeType( NextFcb ) != FAT_NTC_FCB && FatGetFirstChild( NextFcb ) != NULL;
         NextFcb = FatGetFirstChild( NextFcb )) {
    }

    return NextFcb;
}

PFCB
FatGetNextFcbTopDown (
    IN PIRP_CONTEXT IrpContext,
    IN PFCB Fcb,
    IN PFCB TerminationFcb
    )

/*++

Routine Description:

    This routine is used to iterate through Fcbs in a tree, from the top down.

    The rule is very simple:

        A) If you have a child, go to it, else
        B) If you have an older sibling, go to it, else
        C) Go to your parent's older sibling.

    If this routine is called with in invalid TerminationFcb it will fail,
    badly.

    The Termination Fcb is never returned.  If it is the root of the tree you
    are traversing, visit it first.

    This routine never returns direct ancestors of Fcb, and thus is useful when
    making Fcb's go away (which may tear up the tree).

Arguments:

    Fcb - Supplies the current Fcb

    TerminationFcb - The Fcb at which the enumeration should (non-inclusivly)
        stop.  Assumed to be a directory.

Return Value:

    The next Fcb in the enumeration, or NULL if Fcb was the final one.

--*/

{
    PFCB Sibling;

    PAGED_CODE();
    UNREFERENCED_PARAMETER( IrpContext );

    NT_ASSERT( FatVcbAcquiredExclusive( IrpContext, Fcb->Vcb ) ||
            FlagOn( Fcb->Vcb->VcbState, VCB_STATE_FLAG_LOCKED ) );

    //
    //  If this was a directory (ie. not a file), get the child.  If
    //  there aren't any children and this is our termination Fcb,
    //  return NULL.
    //

    if ( ((NodeType(Fcb) == FAT_NTC_DCB) ||
          (NodeType(Fcb) == FAT_NTC_ROOT_DCB)) &&
         !IsListEmpty(&Fcb->Specific.Dcb.ParentDcbQueue) ) {

        return FatGetFirstChild( Fcb );
    }

    //
    //  Were we only meant to do one iteration?
    //

    if ( Fcb == TerminationFcb ) {

        return NULL;
    }

    Sibling = FatGetNextSibling(Fcb);

    while (TRUE) {

        //
        //  Do we still have an "older" sibling in this directory who is
        //  not the termination Fcb?
        //

        if ( Sibling != NULL ) {

            return (Sibling != TerminationFcb) ? Sibling : NULL;
        }

        //
        //  OK, let's move on to out parent and see if he is the termination
        //  node or has any older siblings.
        //

        if ( Fcb->ParentDcb == TerminationFcb ) {

            return NULL;
        }

        Fcb = Fcb->ParentDcb;

        Sibling = FatGetNextSibling(Fcb);
    }
}


BOOLEAN
FatSwapVpb (
    IN PIRP_CONTEXT IrpContext,
    PVCB Vcb
    )

/*++

Routine Description:

    This routine swaps the VPB for this VCB if it has not been done already.
    This means the device object will get our spare VPB and we will cleanup
    the one used while the volume was mounted.

Arguments:

    IrpContext - Supplies the context for the overall request.

    Vcb - Supplies the VCB to swap the VPB on.

Return Value:

    TRUE - If the VPB was actually swapped.

    FALSE - If the VPB was already swapped.

--*/

{
    BOOLEAN Result = FALSE;
    PVPB OldVpb;
    PIO_STACK_LOCATION IrpSp;


    //
    //  Make sure we have not already swapped it.
    //

    OldVpb = Vcb->Vpb;

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

    if (!FlagOn( Vcb->VcbState, VCB_STATE_FLAG_VPB_MUST_BE_FREED ) && OldVpb->RealDevice->Vpb == OldVpb) {

        //
        //  If not the final reference and we are forcing the disconnect,
        //  then swap out the Vpb.  We must preserve the REMOVE_PENDING flag
        //  so that the device is not remounted in the middle of a PnP remove
        //  operation.
        //

        NT_ASSERT( Vcb->SwapVpb != NULL );

        Vcb->SwapVpb->Type = IO_TYPE_VPB;
        Vcb->SwapVpb->Size = sizeof( VPB );
        Vcb->SwapVpb->RealDevice = OldVpb->RealDevice;

        Vcb->SwapVpb->RealDevice->Vpb = Vcb->SwapVpb;

        Vcb->SwapVpb->Flags = FlagOn( OldVpb->Flags, VPB_REMOVE_PENDING );

        //
        //  If we are working on a mount request, we need to make sure we update
        //  the VPB in the IRP, since the one it points to may no longer be valid.
        //

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

            //
            //  Get the IRP stack.
            //

            IrpSp = IoGetCurrentIrpStackLocation( IrpContext->OriginatingIrp );

            NT_ASSERT( IrpSp->FileObject == NULL );

            //
            //  Check the VPB in the IRP to see if it is the one we are swapping.
            //

            if (IrpSp->Parameters.MountVolume.Vpb == OldVpb) {

                //
                //  Change the IRP to point to the swap VPB.
                //

                IrpSp->Parameters.MountVolume.Vpb = Vcb->SwapVpb;
            }
        }

#ifdef _MSC_VER
#pragma prefast( pop )
#endif

        //
        //  We place the volume in the Bad state (as opposed to NotMounted) so
        //  that it is not eligible for a remount.  Also indicate we used up
        //  the swap.
        //

        Vcb->SwapVpb = NULL;
        FatSetVcbCondition( Vcb, VcbBad);
        SetFlag( Vcb->VcbState, VCB_STATE_FLAG_VPB_MUST_BE_FREED );

        Result = TRUE;
    }

    return Result;
}


_Requires_lock_held_(_Global_critical_region_)    
BOOLEAN
FatCheckForDismount (
    IN PIRP_CONTEXT IrpContext,
    PVCB Vcb,
    IN BOOLEAN Force
    )

/*++

Routine Description:

    This routine determines if a volume is ready for deletion.  It
    correctly synchronizes with creates en-route to the file system.

Arguments:

    Vcb - Supplies the volume to examine

    Force - Specifies whether we want this Vcb forcibly disconnected
        from the driver stack if it will not be deleted (a new vpb will
        be installed if neccesary).  Caller is responsible for making
        sure that the volume has been marked in such a way that attempts
        to operate through the realdevice are blocked (i.e., move the vcb
        out of the mounted state).

Return Value:

    BOOLEAN - TRUE if the volume was deleted, FALSE otherwise.

--*/

{
    KIRQL SavedIrql;
    BOOLEAN VcbDeleted = FALSE;


    //
    //  If the VCB condition is good and we are not forcing, just return.
    //

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

        return FALSE;
    }

    //
    //  Now check for a zero Vpb count on an unmounted volume.  These
    //  volumes will be deleted as they now have no file objects and
    //  there are no creates en route to this volume.
    //

    IoAcquireVpbSpinLock( &SavedIrql );

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

        PVPB Vpb = Vcb->Vpb;

#if DBG
        UNICODE_STRING VolumeLabel;

        //
        //  Setup the VolumeLabel string
        //

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

        KdPrintEx((DPFLTR_FASTFAT_ID,
                   DPFLTR_INFO_LEVEL,
                   "FASTFAT: Dismounting Volume %Z\n",
                   &VolumeLabel));
#endif // DBG

        //
        //  Swap this VCB's VPB.
        //

        FatSwapVpb( IrpContext,
                    Vcb );

        //
        //  Clear the VPB_MOUNTED bit.  New opens should not come in due
        //  to the swapped VPB, but having the flag cleared helps debugging.
        //  Note that we must leave the Vpb->DeviceObject field set until
        //  after the FatTearDownVcb call as closes will have to make their
        //  way back to us.
        //

        ClearFlag( Vpb->Flags, VPB_MOUNTED );

        //
        //  If this Vpb was locked, clear this flag now.
        //

        ClearFlag( Vpb->Flags, (VPB_LOCKED | VPB_DIRECT_WRITES_ALLOWED) );

        IoReleaseVpbSpinLock( SavedIrql );

        //
        //  We are going to attempt the dismount, so mark the VCB as having
        //  a dismount in progress.
        //

        NT_ASSERT( !FlagOn( Vcb->VcbState, VCB_STATE_FLAG_DISMOUNT_IN_PROGRESS ) );
        SetFlag( Vcb->VcbState, VCB_STATE_FLAG_DISMOUNT_IN_PROGRESS );

        //
        //  Close down our internal opens.
        //

        FatTearDownVcb( IrpContext,
                        Vcb );

        //
        //  Process any delayed closes.
        //

        FatFspClose( Vcb );

        //
        //  Grab the VPB lock again so that we can recheck our counts.
        //

        IoAcquireVpbSpinLock( &SavedIrql );

        //
        //  See if we can delete this VCB.
        //

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

            Vpb->DeviceObject = NULL;

            IoReleaseVpbSpinLock( SavedIrql );

            FatDeleteVcb( IrpContext, Vcb );

            IoDeleteDevice( (PDEVICE_OBJECT)
                            CONTAINING_RECORD( Vcb,
                                               VOLUME_DEVICE_OBJECT,
                                               Vcb ) );

            VcbDeleted = TRUE;

        } else {

            IoReleaseVpbSpinLock( SavedIrql );

            NT_ASSERT( FlagOn( Vcb->VcbState, VCB_STATE_FLAG_DISMOUNT_IN_PROGRESS ) );
            ClearFlag( Vcb->VcbState, VCB_STATE_FLAG_DISMOUNT_IN_PROGRESS );
        }

    } else if (Force) {

        //
        //  The requester is forcing the issue.  We need to swap the VPB with our spare.
        //

        FatSwapVpb( IrpContext,
                    Vcb );

        IoReleaseVpbSpinLock( SavedIrql );

    } else {

        //
        //  Just drop the Vpb spinlock.
        //

        IoReleaseVpbSpinLock( SavedIrql );
    }

    return VcbDeleted;
}


VOID
FatConstructNamesInFcb (
    IN PIRP_CONTEXT IrpContext,
    PFCB Fcb,
    PDIRENT Dirent,
    PUNICODE_STRING Lfn OPTIONAL
    )

/*++

Routine Description:

    This routine places the short name in the dirent in the first set of
    STRINGs in the Fcb.  If a long file name (Lfn) was specified, then
    we must decide whether we will store its Oem equivolent in the same
    prefix table as the short name, or rather just save the upcased
    version of the UNICODE string in the FCB.

    For looking up Fcbs, the first approach will be faster, so we want to
    do this as much as possible.  Here are the rules that I have thought
    through extensively to determine when it is safe to store only Oem
    version of the UNICODE name.

    - If the UNICODE name contains no extended characters (>0x80), use Oem.

    - Let U be the upcased version of the UNICODE name.
      Let Up(x) be the function that upcases a UNICODE string.
      Let Down(x) be the function that upcases a UNICODE string.
      Let OemToUni(x) be the function that converts an Oem string to Unicode.
      Let UniToOem(x) be the function that converts a Unicode string to Oem.
      Let BestOemFit(x) be the function that creates the Best uppercase Oem
        fit for the UNICODE string x.

      BestOemFit(x) = UniToOem(Up(OemToUni(UniToOem(x))))   <1>

      if (BestOemFit(U) == BestOemFit(Down(U))              <2>

          then I know that there exists no UNICODE string Y such that:

              Up(Y) == Up(U)                                <3>

              AND

              BestOemFit(U) != BestOemFit(Y)                <4>

      Consider string U as a collection of one character strings.  The
      conjecture is clearly true for each sub-string, thus it is true
      for the entire string.

      Equation <1> is what we use to convert an incoming unicode name in
      FatCommonCreate() to Oem.  The double conversion is done to provide
      better visual best fitting for characters in the Ansi code page but
      not in the Oem code page.  A single Nls routine is provided to do
      this conversion efficiently.

      The idea is that with U, I only have to worry about a case varient Y
      matching it in a unicode compare, and I have shown that any case varient
      of U (the set Y defined in equation <3>), when filtered through <1>
      (as in create), will match the Oem string defined in <1>.

      Thus I do not have to worry about another UNICODE string missing in
      the prefix lookup, but matching when comparing LFNs in the directory.

Arguments:

    Fcb - The Fcb we are supposed to fill in.  Note that ParentDcb must
        already be filled in.

    Dirent - The gives up the short name.

    Lfn - If provided, this gives us the long name.

Return Value:

    None

--*/

{
#ifndef __REACTOS__
    NTSTATUS Status;
#endif
    ULONG i;

#ifndef __REACTOS__
    OEM_STRING OemA;
    OEM_STRING OemB;
#endif
    UNICODE_STRING Unicode;
    POEM_STRING ShortName;
    POEM_STRING LongOemName;
    PUNICODE_STRING LongUniName;

    PAGED_CODE();

    ShortName = &Fcb->ShortName.Name.Oem;

    NT_ASSERT( ShortName->Buffer == NULL );

    _SEH2_TRY {

        //
        //  First do the short name.
        //

        //
        //  Copy over the case flags for the short name of the file
        //

        if (FlagOn(Dirent->NtByte, FAT_DIRENT_NT_BYTE_8_LOWER_CASE)) {

            SetFlag(Fcb->FcbState, FCB_STATE_8_LOWER_CASE);

        } else {

            ClearFlag(Fcb->FcbState, FCB_STATE_8_LOWER_CASE);
        }

        if (FlagOn(Dirent->NtByte, FAT_DIRENT_NT_BYTE_3_LOWER_CASE)) {

            SetFlag(Fcb->FcbState, FCB_STATE_3_LOWER_CASE);

        } else {

            ClearFlag(Fcb->FcbState, FCB_STATE_3_LOWER_CASE);
        }

        ShortName->MaximumLength = 16;
        ShortName->Buffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                      16,
                                                      TAG_FILENAME_BUFFER );

        Fat8dot3ToString( IrpContext, Dirent, FALSE, ShortName );

        Fcb->ShortName.FileNameDos = TRUE;

        //
        //  If no Lfn was specified, we are done.  In either case, set the
        //  final name length.
        //

        NT_ASSERT( Fcb->ExactCaseLongName.Buffer == NULL );

        if (!ARGUMENT_PRESENT(Lfn) || (Lfn->Length == 0)) {

            Fcb->FinalNameLength = (USHORT) RtlOemStringToCountedUnicodeSize( ShortName );
            Fcb->ExactCaseLongName.Length = Fcb->ExactCaseLongName.MaximumLength = 0;

            try_return( NOTHING );
        }

        //
        //  If we already set up the full filename, we could be in trouble.  If the fast
        //  path for doing it already fired, FatSetFullFileNameInFcb, it will have missed
        //  this and could have built the full filename out of the shortname of the file.
        //
        //  At that point, disaster could be inevitable since the final name length will not
        //  match.  We use this to tell the notify package what to do - FatNotifyReportChange.
        //

        NT_ASSERT( Fcb->FullFileName.Buffer == NULL );

        //
        //  We know now we have an Lfn, save away a copy.
        //

        Fcb->FinalNameLength = Lfn->Length;

        Fcb->ExactCaseLongName.Length = Fcb->ExactCaseLongName.MaximumLength = Lfn->Length;
        Fcb->ExactCaseLongName.Buffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                                  Lfn->Length,
                                                                  TAG_FILENAME_BUFFER );
        RtlCopyMemory(Fcb->ExactCaseLongName.Buffer, Lfn->Buffer, Lfn->Length);

        //
        //  First check for no extended characters.
        //

        for (i=0; i < Lfn->Length/sizeof(WCHAR); i++) {

            if (Lfn->Buffer[i] >= 0x80) {

                break;
            }
        }

        if (i == Lfn->Length/sizeof(WCHAR)) {

            //
            //  Cool, I can go with the Oem, upcase it fast by hand.
            //

            LongOemName = &Fcb->LongName.Oem.Name.Oem;


            LongOemName->Buffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                            Lfn->Length/sizeof(WCHAR),
                                                            TAG_FILENAME_BUFFER );
            LongOemName->Length =
            LongOemName->MaximumLength = Lfn->Length/sizeof(WCHAR);

            for (i=0; i < Lfn->Length/sizeof(WCHAR); i++) {

                WCHAR c;

                c = Lfn->Buffer[i];

#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable:4244 )
#endif
                LongOemName->Buffer[i] = c < 'a' ?
                                         (UCHAR)c :
                                         c <= 'z' ?
                                         c - (UCHAR)('a'-'A') :
                                         (UCHAR)c;
#ifdef _MSC_VER
#pragma warning( pop )
#endif
            }

            //
            //  If this name happens to be exactly the same as the short
            //  name, don't add it to the splay table.
            //

            if (FatAreNamesEqual(IrpContext, *ShortName, *LongOemName) ||
                (FatFindFcb( IrpContext,
                             &Fcb->ParentDcb->Specific.Dcb.RootOemNode,
                             LongOemName,
                             NULL) != NULL)) {

                ExFreePool( LongOemName->Buffer );

                LongOemName->Buffer = NULL;
                LongOemName->Length =
                LongOemName->MaximumLength = 0;

            } else {

                SetFlag( Fcb->FcbState, FCB_STATE_HAS_OEM_LONG_NAME );
            }

            try_return( NOTHING );
        }

        //
        //  Now we have the fun part.  Make a copy of the Lfn.
        //

#ifndef __REACTOS__
        OemA.Buffer = NULL;
        OemB.Buffer = NULL;
#endif
        Unicode.Buffer = NULL;

        Unicode.Length =
        Unicode.MaximumLength = Lfn->Length;
        Unicode.Buffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                   Lfn->Length,
                                                   TAG_FILENAME_BUFFER );

        RtlCopyMemory( Unicode.Buffer, Lfn->Buffer, Lfn->Length );

#ifndef __REACTOS__
        Status = STATUS_SUCCESS;<--- Status is assigned
#endif

#if TRUE
        //
        //  Unfortunately, this next block of code breaks down when you have
        //  two long Unicode filenames that both map to the same Oem (and are,
        //  well, long, i.e. are not the short names). In this case, with one
        //  in the prefix table first, the other will hit the common Oem
        //  representation.  This leads to several forms of user astonishment.
        //
        //  It isn't worth it, or probably even possible, to try to figure out
        //  when this is really safe to go through.  Simply omit the attempt.
        //
        //  Ex: ANSI 0x82 and 0x84 in the 1252 ANSI->UNI and 437 UNI->OEM codepages.
        //
        //      0x82 => 0x201a => 0x2c
        //      0x84 => 0x201e => 0x2c
        //
        //  0x2c is comma, so is FAT Oem illegal and forces shortname generation.
        //  Since it is otherwise well-formed by the rules articulated previously,
        //  we would have put 0x2c in the Oem prefix tree.  In terms of the
        //  argument given above, even though there exist no Y and U s.t.
        //
        //  Up(Y) == Up(U) && BestOemFit(U) != BestOemFit(Y)
        //
        //  there most certainly exist Y and U s.t.
        //
        //  Up(Y) != Up(U) && BestOemFit(U) == BestOemFit(Y)
        //
        //  and that is enough to keep us from doing this.  Note that the < 0x80
        //  case is OK since we know that the mapping in the OEM codepages are
        //  the identity in that range.
        //
        //  We still need to monocase it, though.  Do this through a full down/up
        //  transition.
        //

        (VOID)RtlDowncaseUnicodeString( &Unicode, &Unicode, FALSE );
        (VOID)RtlUpcaseUnicodeString( &Unicode, &Unicode, FALSE );
#else
        //
        //  Downcase and convert to upcased Oem.  Only continue if we can
        //  convert without error.  Any error other than UNMAPPABLE_CHAR
        //  is a fatal error and we raise.
        //
        //  Note that even if the conversion fails, we must leave Unicode
        //  in an upcased state.
        //
        //  NB: The Rtl doesn't NULL .Buffer on error.
        //

        (VOID)RtlDowncaseUnicodeString( &Unicode, &Unicode, FALSE );
        Status = RtlUpcaseUnicodeStringToCountedOemString( &OemA, &Unicode, TRUE );<--- Status is overwritten
        (VOID)RtlUpcaseUnicodeString( &Unicode, &Unicode, FALSE );

        if (!NT_SUCCESS(Status)) {

            if (Status != STATUS_UNMAPPABLE_CHARACTER) {

                NT_ASSERT( Status == STATUS_NO_MEMORY );
                ExFreePool(Unicode.Buffer);
                FatNormalizeAndRaiseStatus( IrpContext, Status );
            }

        } else {

            //
            //  The same as above except upcase.
            //

            Status = RtlUpcaseUnicodeStringToCountedOemString( &OemB, &Unicode, TRUE );

            if (!NT_SUCCESS(Status)) {

                RtlFreeOemString( &OemA );

                if (Status != STATUS_UNMAPPABLE_CHARACTER) {

                    NT_ASSERT( Status == STATUS_NO_MEMORY );
                    ExFreePool(Unicode.Buffer);
                    FatNormalizeAndRaiseStatus( IrpContext, Status );
                }
            }
        }

        //
        //  If the final OemNames are equal, I can use save only the Oem
        //  name.  If the name did not map, then I have to go with the UNICODE
        //  name because I could get a case varient that didn't convert
        //  in create, but did match the LFN.
        //

        if (NT_SUCCESS(Status) && FatAreNamesEqual( IrpContext, OemA, OemB )) {

            //
            //  Cool, I can go with the Oem.  If we didn't convert correctly,
            //  get a fresh convert from the original LFN.
            //

            ExFreePool(Unicode.Buffer);

            RtlFreeOemString( &OemB );

            Fcb->LongName.Oem.Name.Oem = OemA;

            //
            //  If this name happens to be exactly the same as the short
            //  name, or a similar short name already exists don't add it
            //  to the splay table (note the final condition implies a
            //  corrupt disk.
            //

            if (FatAreNamesEqual(IrpContext, *ShortName, OemA) ||
                (FatFindFcb( IrpContext,
                             &Fcb->ParentDcb->Specific.Dcb.RootOemNode,
                             &OemA,
                             NULL) != NULL)) {

                RtlFreeOemString( &OemA );

            } else {

                SetFlag( Fcb->FcbState, FCB_STATE_HAS_OEM_LONG_NAME );
            }

            try_return( NOTHING );
        }

        //
        //  The long name must be left in UNICODE.  Free the two Oem strings
        //  if we got here just because they weren't equal.
        //

        if (NT_SUCCESS(Status)) {

            RtlFreeOemString( &OemA );
            RtlFreeOemString( &OemB );
        }
#endif

        LongUniName = &Fcb->LongName.Unicode.Name.Unicode;

        LongUniName->Length =
        LongUniName->MaximumLength = Unicode.Length;
        LongUniName->Buffer = Unicode.Buffer;

        SetFlag(Fcb->FcbState, FCB_STATE_HAS_UNICODE_LONG_NAME);

    try_exit: NOTHING;
    } _SEH2_FINALLY {

        if (_SEH2_AbnormalTermination()) {

            if (ShortName->Buffer != NULL) {

                ExFreePool( ShortName->Buffer );
                ShortName->Buffer = NULL;
            }

        } else {

            //
            //  Creating all the names worked, so add all the names
            //  to the splay tree.
            //

            FatInsertName( IrpContext,
                           &Fcb->ParentDcb->Specific.Dcb.RootOemNode,
                           &Fcb->ShortName );

            Fcb->ShortName.Fcb = Fcb;

            if (FlagOn(Fcb->FcbState, FCB_STATE_HAS_OEM_LONG_NAME)) {

                FatInsertName( IrpContext,
                               &Fcb->ParentDcb->Specific.Dcb.RootOemNode,
                               &Fcb->LongName.Oem );

                Fcb->LongName.Oem.Fcb = Fcb;
            }

            if (FlagOn(Fcb->FcbState, FCB_STATE_HAS_UNICODE_LONG_NAME)) {

                FatInsertName( IrpContext,
                               &Fcb->ParentDcb->Specific.Dcb.RootUnicodeNode,
                               &Fcb->LongName.Unicode );

                Fcb->LongName.Unicode.Fcb = Fcb;
            }

            SetFlag(Fcb->FcbState, FCB_STATE_NAMES_IN_SPLAY_TREE);
        }
    } _SEH2_END;

    return;
}


_Requires_lock_held_(_Global_critical_region_)    
VOID
FatCheckFreeDirentBitmap (
    IN PIRP_CONTEXT IrpContext,
    IN PDCB Dcb
    )

/*++

Routine Description:

    This routine checks if the size of the free dirent bitmap is
    sufficient to for the current directory size.  It is called
    whenever we grow a directory.

Arguments:

    Dcb -  Supplies the directory in question.

Return Value:

    None

--*/

{
    ULONG OldNumberOfDirents;
    ULONG NewNumberOfDirents;

    PAGED_CODE();
    UNREFERENCED_PARAMETER( IrpContext );

    //
    //  Setup the Bitmap buffer if it is not big enough already
    //

    NT_ASSERT( Dcb->Header.AllocationSize.QuadPart != FCB_LOOKUP_ALLOCATIONSIZE_HINT );

    OldNumberOfDirents = Dcb->Specific.Dcb.FreeDirentBitmap.SizeOfBitMap;
    NewNumberOfDirents = Dcb->Header.AllocationSize.LowPart / sizeof(DIRENT);

    //
    //  Do the usual unsync/sync check.
    //

    if (NewNumberOfDirents > OldNumberOfDirents) {

        FatAcquireDirectoryFileMutex( Dcb->Vcb );

        _SEH2_TRY {

            PULONG OldBitmapBuffer;
            PULONG BitmapBuffer;

            ULONG BytesInBitmapBuffer;
            ULONG BytesInOldBitmapBuffer;

            OldNumberOfDirents = Dcb->Specific.Dcb.FreeDirentBitmap.SizeOfBitMap;
            NewNumberOfDirents = Dcb->Header.AllocationSize.LowPart / sizeof(DIRENT);

            if (NewNumberOfDirents > OldNumberOfDirents) {

                //
                //  Remember the old bitmap
                //

                OldBitmapBuffer = Dcb->Specific.Dcb.FreeDirentBitmap.Buffer;

                //
                //  Now make a new bitmap bufffer
                //

                BytesInBitmapBuffer = NewNumberOfDirents / 8;

                BytesInOldBitmapBuffer = OldNumberOfDirents / 8;

                if (DCB_UNION_SLACK_SPACE >= BytesInBitmapBuffer) {

                    BitmapBuffer = &Dcb->Specific.Dcb.FreeDirentBitmapBuffer[0];

                } else {

                    BitmapBuffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                             BytesInBitmapBuffer,
                                                             TAG_DIRENT_BITMAP );
                }

                //
                //  Copy the old buffer to the new buffer, free the old one, and zero
                //  the rest of the new one.  Only do the first two steps though if
                //  we moved out of the initial buffer.
                //

                if ((OldNumberOfDirents != 0) &&
                    (BitmapBuffer != &Dcb->Specific.Dcb.FreeDirentBitmapBuffer[0])) {

                    RtlCopyMemory( BitmapBuffer,
                                   OldBitmapBuffer,
                                   BytesInOldBitmapBuffer );

                    if (OldBitmapBuffer != &Dcb->Specific.Dcb.FreeDirentBitmapBuffer[0]) {

                        ExFreePool( OldBitmapBuffer );
                    }
                }

                NT_ASSERT( BytesInBitmapBuffer > BytesInOldBitmapBuffer );

                RtlZeroMemory( (PUCHAR)BitmapBuffer + BytesInOldBitmapBuffer,
                               BytesInBitmapBuffer - BytesInOldBitmapBuffer );

                //
                //  Now initialize the new bitmap.
                //

                RtlInitializeBitMap( &Dcb->Specific.Dcb.FreeDirentBitmap,
                                     BitmapBuffer,
                                     NewNumberOfDirents );
            }

        } _SEH2_FINALLY {

            FatReleaseDirectoryFileMutex( Dcb->Vcb );
        } _SEH2_END;
    }
}


BOOLEAN
FatIsHandleCountZero (
    IN PIRP_CONTEXT IrpContext,
    IN PVCB Vcb
    )

/*++

Routine Description:

    This routine decides if the handle count on the volume is zero.

Arguments:

    Vcb - The volume in question

Return Value:

    BOOLEAN - TRUE if there are no open handles on the volume, FALSE
              otherwise.

--*/

{
    PFCB Fcb;

    PAGED_CODE();

    Fcb = Vcb->RootDcb;

    while (Fcb != NULL) {

        if (Fcb->UncleanCount != 0) {

            return FALSE;
        }

        Fcb = FatGetNextFcbTopDown(IrpContext, Fcb, Vcb->RootDcb);
    }

    return TRUE;
}


PCLOSE_CONTEXT

FatAllocateCloseContext(
    OPTIONAL PVCB Vcb
    )
/*++

Routine Description:

    This routine preallocates a close context, presumeably on behalf
    of a fileobject which does not have a structure we can embed one
    in.

Arguments:

    None.

Return Value:

    None.

--*/
{
    PAGED_CODE();
    UNREFERENCED_PARAMETER( Vcb );

#if DBG
    if (ARGUMENT_PRESENT(Vcb)) {

        NT_ASSERT( 0 != Vcb->CloseContextCount);
        InterlockedDecrement( (LONG*)&Vcb->CloseContextCount);
    }
#endif
    return (PCLOSE_CONTEXT)ExInterlockedPopEntrySList( &FatCloseContextSList,
                                                       &FatData.GeneralSpinLock );
}


VOID
FatPreallocateCloseContext (
    PVCB Vcb
    )

/*++

Routine Description:

    This routine preallocates a close context, presumeably on behalf
    of a fileobject which does not have a structure we can embed one
    in.

Arguments:

    None.

Return Value:

    None.

--*/

{
    PCLOSE_CONTEXT CloseContext;

    PAGED_CODE();

    UNREFERENCED_PARAMETER( Vcb );

    CloseContext = FsRtlAllocatePoolWithTag( PagedPool,
                                             sizeof(CLOSE_CONTEXT),
                                             TAG_FAT_CLOSE_CONTEXT );

    ExInterlockedPushEntrySList( &FatCloseContextSList,
                                 (PSLIST_ENTRY) CloseContext,
                                 &FatData.GeneralSpinLock );

    DbgDoit( InterlockedIncrement( (LONG*)&Vcb->CloseContextCount));
}



VOID
FatEnsureStringBufferEnough (
    _Inout_ PVOID String,
    _In_ USHORT DesiredBufferSize
    )

/*++

Routine Description:

    Ensures that a string string (STRING, UNICODE_STRING, ANSI_STRING, OEM_STRING)
    has a buffer >= DesiredBufferSize,  allocating from pool if neccessary.  Any
    existing pool buffer will be freed if a new one is allocated.

    NOTE: No copy of old buffer contents is performed on reallocation.

    Will raise on allocation failure.

Arguments:

    String - pointer to string structure

    DesiredBufferSize - (bytes) minimum required buffer size

--*/

{
    PSTRING LocalString = String;

    PAGED_CODE();

    if (LocalString->MaximumLength < DesiredBufferSize)  {

        FatFreeStringBuffer( LocalString);

        LocalString->Buffer = FsRtlAllocatePoolWithTag( PagedPool,
                                                        DesiredBufferSize,
                                                        TAG_DYNAMIC_NAME_BUFFER);
        NT_ASSERT( LocalString->Buffer);

        LocalString->MaximumLength = DesiredBufferSize;
    }
}


VOID
FatFreeStringBuffer (
    _Inout_ PVOID String
    )

/*++

Routine Description:

    Frees the buffer of an string (STRING, UNICODE_STRING, ANSI_STRING, OEM_STRING)
    structure if it is not within the current thread's stack limits.

    Regardless of action performed,  on exit String->Buffer will be set to NULL and
    String->MaximumLength to zero.

Arguments:

    String - pointer to string structure

--*/

{
    ULONG_PTR High, Low;
    PSTRING LocalString = String;

    PAGED_CODE();

    if (NULL != LocalString->Buffer)  {

        IoGetStackLimits( &Low, &High );

        if (((ULONG_PTR)(LocalString->Buffer) < Low) ||
            ((ULONG_PTR)(LocalString->Buffer) > High))  {

            ExFreePool( LocalString->Buffer);
        }

        LocalString->Buffer = NULL;
    }

    LocalString->MaximumLength = LocalString->Length = 0;
}


BOOLEAN
FatScanForDataTrack(
    IN PIRP_CONTEXT IrpContext,
    IN PDEVICE_OBJECT TargetDeviceObject
    )

/*++

Routine Description:

    This routine is called to verify and process the TOC for this disk.

    FAT queries for the TOC to avoid trying to mount on CD-DA/CD-E media,  Doing data reads on
    audio/leadin of that media sends a lot of drives into what could charitably be called
    "conniptions" which take a couple seconds to clear and would also convince FAT that the
    device was busted, and fail the mount (not letting CDFS get its crack).

    There is special handling of PD media.  These things fail the TOC read, but return
    a special error code so FAT knows to continue to try the mount anyway.

Arguments:

    TargetDeviceObject - Device object to send TOC request to.

Return Value:

    BOOLEAN - TRUE if we found a TOC with a single data track.

--*/

{
    NTSTATUS Status;
    IO_STATUS_BLOCK Iosb;

    ULONG LocalTrackCount;
    ULONG LocalTocLength;

    PCDROM_TOC CdromToc;
    BOOLEAN Result = FALSE;

    PAGED_CODE();

    CdromToc = FsRtlAllocatePoolWithTag( PagedPool,
                                         sizeof( CDROM_TOC ),
                                         TAG_IO_BUFFER );

    RtlZeroMemory( CdromToc, sizeof( CDROM_TOC ));

    _SEH2_TRY {

        //
        //  Go ahead and read the table of contents
        //

        Status = FatPerformDevIoCtrl( IrpContext,
                                     IOCTL_CDROM_READ_TOC,
                                     TargetDeviceObject,
                                     NULL,
                                     0,
                                     CdromToc,
                                     sizeof( CDROM_TOC ),
                                     FALSE,
                                     TRUE,
                                     &Iosb );

        //
        //  Nothing to process if this request fails.
        //

        if (Status != STATUS_SUCCESS) {

            //
            //  If we get the special error indicating a failed TOC read on PD media just
            //  plow ahead with the mount (see comments above).
            //

            if ((Status == STATUS_IO_DEVICE_ERROR) || (Status == STATUS_INVALID_DEVICE_REQUEST)) {

                Result = TRUE;<--- Result is assigned

            }

            try_leave( NOTHING );
        }

        //
        //  Get the number of tracks and stated size of this structure.
        //

        LocalTrackCount = CdromToc->LastTrack - CdromToc->FirstTrack + 1;
        LocalTocLength = PtrOffset( CdromToc, &CdromToc->TrackData[LocalTrackCount + 1] );

        //
        //  Get out if there is an immediate problem with the TOC,  or more than
        //  one track.
        //

        if ((LocalTocLength > Iosb.Information) ||
            (CdromToc->FirstTrack > CdromToc->LastTrack) ||
            (LocalTrackCount != 1)) {

            try_leave( NOTHING);
        }

        //
        //  Is it a data track?  DVD-RAM reports single,  data,  track.
        //

        Result = BooleanFlagOn( CdromToc->TrackData[ 0].Control, 0x04 );<--- Result is overwritten
    }
    _SEH2_FINALLY {

        ExFreePool( CdromToc);
    } _SEH2_END;

    return Result;
}