|
root / base / usr / src / cmd / fs.d / pcfs / fsck
fsck Plain Text 4133 lines 105.3 KB
   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
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
#
# CDDL HEADER START
#
# The contents of this file are subject to the terms of the
# Common Development and Distribution License (the "License").
# You may not use this file except in compliance with the License.
#
# You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
# or http://www.opensolaris.org/os/licensing.
# See the License for the specific language governing permissions
# and limitations under the License.
#
# When distributing Covered Code, include this CDDL HEADER in each
# file and include the License file at usr/src/OPENSOLARIS.LICENSE.
# If applicable, add the following below this CDDL HEADER, with the
# fields enclosed by brackets "[]" replaced with your own identifying
# information: Portions Copyright [yyyy] [name of copyright owner]
#
# CDDL HEADER END
#
#
# Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
# Copyright 2024 MNX Cloud, Inc.
#

FSTYPE=		pcfs
LIBPROG=	fsck
ATTMK=		$(LIBPROG)

include		../../Makefile.fstype

COMMONOBJS=	pcfs_common.o getresponse.o
COMMONSRCS=	../common/pcfs_common.c $(SRC)/common/util/getresponse.c
FSCKOBJS=	fsck_main.o bpb.o clusters.o fat.o dir.o
FSCKSRCS=	$(FSCKOBJS:%.o=%.c)

#
#  Error injection module for debugging purposes
#
#DEBUGOBJS=	inject.o
#DEBUGSRCS=	$(DEBUGOBJS:%.o=%.c)

OBJS=		$(FSCKOBJS) $(DEBUGOBJS) $(COMMONOBJS)
SRCS=		$(FSCKSRCS) $(DEBUGSRCS) $(COMMONSRCS)

# for messaging catalog
#
POFILES=	$(OBJS:%.o=%.po)
POFILE=		fsck.po

catalog:        $(POFILE)

CPPFLAGS +=	-D_LARGEFILE64_SOURCE
CPPFLAGS +=	-I../common
CPPFLAGS +=	-I$(SRC)/common/util

CERRWARN +=	-Wno-parentheses
CERRWARN +=	-Wno-unused-variable
CERRWARN +=	$(CNOWARN_UNINIT)

$(LIBPROG):	$(OBJS)
		$(LINK.c) -o $@ $(OBJS) $(LDLIBS)
		$(POST_PROCESS)

%.o : ../common/%.c
	$(COMPILE.c) $(OUTPUT_OPTION) $<
	$(POST_PROCESS_O)

%.o : $(SRC)/common/util/%.c
	$(COMPILE.c) $(OUTPUT_OPTION) $<
	$(POST_PROCESS_O)

$(POFILE):
	$(RM) $@
	$(COMPILE.cpp) $(SRCS) > $(POFILE).i
	$(XGETTEXT) $(XGETFLAGS) $(POFILE).i
	sed "/^domain/d" messages.po > $@
	$(RM) $(POFILE).i messages.po

clean:
	$(RM) $(FSCKOBJS) $(DEBUGOBJS) $(COMMONOBJS) $(POFILE).i messages.po
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999,2000 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright (c) 2011 Gary Mills
 * Copyright 2024 MNX Cloud, Inc.
 */

/*
 * fsck_pcfs -- routines for manipulating the BPB (BIOS parameter block)
 * of the file system.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <libintl.h>
#include <sys/types.h>
#include <sys/dktp/fdisk.h>
#include <sys/fs/pc_fs.h>
#include <sys/fs/pc_dir.h>
#include <sys/fs/pc_label.h>
#include "pcfs_common.h"
#include "fsck_pcfs.h"
#include "pcfs_bpb.h"

extern	off64_t	FirstClusterOffset;
extern	off64_t	PartitionOffset;
extern	int32_t	BytesPerCluster;
extern	int32_t	TotalClusters;
extern	int32_t	LastCluster;
extern	int32_t	RootDirSize;
extern	int32_t	FATSize;
extern	short	FATEntrySize;
extern	bpb_t	TheBIOSParameterBlock;
extern	int	IsFAT32;
extern	int	Verbose;

static void
computeFileAreaSize(void)
{
	int32_t	dataSectors;
	int32_t	overhead;

	/*
	 * Compute bytes/cluster for later reference
	 */
	BytesPerCluster =  TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector;

	/*
	 * First we'll find total number of sectors in the file area...
	 */
	if (TheBIOSParameterBlock.bpb.sectors_in_volume > 0)
		dataSectors = TheBIOSParameterBlock.bpb.sectors_in_volume;
	else
		dataSectors =
		    TheBIOSParameterBlock.bpb.sectors_in_logical_volume;

	overhead = TheBIOSParameterBlock.bpb.resv_sectors;

	RootDirSize = TheBIOSParameterBlock.bpb.num_root_entries *
	    sizeof (struct pcdir);
	overhead += RootDirSize / TheBIOSParameterBlock.bpb.bytes_per_sector;

	if (TheBIOSParameterBlock.bpb.sectors_per_fat) {
		/*
		 * Good old FAT12 or FAT16
		 */
		overhead += TheBIOSParameterBlock.bpb.num_fats *
		    TheBIOSParameterBlock.bpb.sectors_per_fat;
		/*
		 * Compute this for later - when we actually pull in a copy
		 * of the FAT
		 */
		FATSize = TheBIOSParameterBlock.bpb.sectors_per_fat *
		    TheBIOSParameterBlock.bpb.bytes_per_sector;
	} else {
		/*
		 *  FAT32
		 *  I'm unsure if this is always going to work.  At one
		 *  point during the creation of this program and mkfs_pcfs
		 *  it seemed that Windows had created an fs where it had
		 *  rounded big_sectors_per_fat up to a cluster boundary.
		 *  Later, though, I encountered a problem where I wasn't
		 *  finding the root directory because I was looking in the
		 *  wrong place by doing that same roundup.  So, for now,
		 *  I'm backing off on the cluster boundary thing and just
		 *  believing what I am told.
		 */
		overhead += TheBIOSParameterBlock.bpb.num_fats *
		    TheBIOSParameterBlock.bpb32.big_sectors_per_fat;
		/*
		 * Compute this for later - when we actually pull in a copy
		 * of the FAT
		 */
		FATSize = TheBIOSParameterBlock.bpb32.big_sectors_per_fat *
		    TheBIOSParameterBlock.bpb.bytes_per_sector;
	}

	/*
	 * Now change sectors to clusters.  The computed value for
	 * TotalClusters is persistent for the remainder of execution.
	 */
	dataSectors -= overhead;
	TotalClusters = dataSectors /
	    TheBIOSParameterBlock.bpb.sectors_per_cluster;

	/*
	 *  Also need to compute last cluster and offset of the first cluster
	 */
	LastCluster = TotalClusters + FIRST_CLUSTER;
	FirstClusterOffset = overhead *
	    TheBIOSParameterBlock.bpb.bytes_per_sector;
	FirstClusterOffset += PartitionOffset;

	/*
	 * XXX this should probably be more sophisticated
	 */
	if (IsFAT32)
		FATEntrySize = 32;
	else {
		if (TotalClusters <= DOS_F12MAXC)
			FATEntrySize = 12;
		else
			FATEntrySize = 16;
	}

	if (Verbose) {
		(void) fprintf(stderr,
		    gettext("Disk has a file area of %d "
		    "allocation units,\neach with %d sectors = %llu "
		    "bytes.\n"), TotalClusters,
		    TheBIOSParameterBlock.bpb.sectors_per_cluster,
		    (uint64_t)TotalClusters *
		    TheBIOSParameterBlock.bpb.sectors_per_cluster *
		    TheBIOSParameterBlock.bpb.bytes_per_sector);
		(void) fprintf(stderr,
		    gettext("File system overhead of %d sectors.\n"), overhead);
		(void) fprintf(stderr,
		    gettext("The last cluster is %d\n"), LastCluster);
	}
}

/*
 *  XXX - right now we aren't attempting to fix anything that looks bad,
 *	instead we just give up.
 */
void
readBPB(int fd)
{
	boot_sector_t ubpb;

	/*
	 *  The BPB is the first sector of the file system
	 */
	if (lseek64(fd, PartitionOffset, SEEK_SET) < 0) {
		mountSanityCheckFails();
		perror(gettext("Cannot seek to start of disk partition"));
		(void) close(fd);
		exit(7);
	}
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Reading BIOS parameter block\n"));
	if (read(fd, ubpb.buf, bpsec) < bpsec) {
		mountSanityCheckFails();
		perror(gettext("Read BIOS parameter block"));
		(void) close(fd);
		exit(2);
	}

	if (ltohs(ubpb.mb.signature) != BOOTSECSIG) {
		mountSanityCheckFails();
		(void) fprintf(stderr,
		    gettext("Bad signature on BPB. Giving up.\n"));
		exit(2);
	}

#ifdef _BIG_ENDIAN
	swap_pack_grabbpb(&TheBIOSParameterBlock, &(ubpb.bs));
#else
	(void) memcpy(&(TheBIOSParameterBlock.bpb), &(ubpb.bs.bs_front.bs_bpb),
	    sizeof (TheBIOSParameterBlock.bpb));
	(void) memcpy(&(TheBIOSParameterBlock.ebpb), &(ubpb.bs.bs_ebpb),
	    sizeof (TheBIOSParameterBlock.ebpb));
#endif
	if (TheBIOSParameterBlock.bpb.bytes_per_sector != 512 &&
	    TheBIOSParameterBlock.bpb.bytes_per_sector != 1024 &&
	    TheBIOSParameterBlock.bpb.bytes_per_sector != 2048 &&
	    TheBIOSParameterBlock.bpb.bytes_per_sector != 4096) {
		mountSanityCheckFails();
		(void) fprintf(stderr,
		    gettext("Bogus bytes per sector value.  Giving up.\n"));
		exit(2);
	}
	if (!(ISP2(TheBIOSParameterBlock.bpb.sectors_per_cluster) &&
	    IN_RANGE(TheBIOSParameterBlock.bpb.sectors_per_cluster,
	    1, 128))) {
		mountSanityCheckFails();
		(void) fprintf(stderr,
		    gettext("Bogus sectors per cluster value.  Giving up.\n"));
		(void) close(fd);
		exit(6);
	}
	if (TheBIOSParameterBlock.bpb.sectors_per_fat == 0) {
#ifdef _BIG_ENDIAN
		swap_pack_grab32bpb(&TheBIOSParameterBlock, &(ubpb.bs));
#else
		(void) memcpy(&(TheBIOSParameterBlock.bpb32),
		    &(ubpb.bs32.bs_bpb32),
		    sizeof (TheBIOSParameterBlock.bpb32));
#endif
		IsFAT32 = 1;
	}
	if (!IsFAT32) {
		if ((TheBIOSParameterBlock.bpb.num_root_entries == 0) ||
		    ((TheBIOSParameterBlock.bpb.num_root_entries *
		    sizeof (struct pcdir)) %
		    TheBIOSParameterBlock.bpb.bytes_per_sector) != 0) {
			mountSanityCheckFails();
			(void) fprintf(stderr,
			    gettext("Bogus number of root entries.  "
			    "Giving up.\n"));
			exit(2);
		}
	} else {
		if (TheBIOSParameterBlock.bpb.num_root_entries != 0) {
			mountSanityCheckFails();
			(void) fprintf(stderr,
			    gettext("Bogus number of root entries.  "
			    "Giving up.\n"));
			exit(2);
		}
	}
	/*
	 * In general, we would expect the number of FATs field to
	 * equal 2.  Our mkfs and Windows have this as a default
	 * value.  I suppose someone could override the default,
	 * though, so we'll sort of arbitrarily accept any number
	 * between 1 and 4 inclusive as reasonable values.
	 *
	 * XXX: Warn, but continue, if value is suspicious? (>2?)
	 */
	if (TheBIOSParameterBlock.bpb.num_fats > 4 ||
	    TheBIOSParameterBlock.bpb.num_fats < 1) {
		mountSanityCheckFails();
		(void) fprintf(stderr,
		    gettext("Bogus number of FATs.  Giving up.\n"));
		exit(2);
	}
	computeFileAreaSize();
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999,2000 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright (c) 2016 by Delphix. All rights reserved.
 * Copyright 2024 MNX Cloud, Inc.
 */

/*
 * fsck_pcfs -- routines for manipulating clusters.
 */
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <libintl.h>
#include <errno.h>
#include <sys/dktp/fdisk.h>
#include <sys/fs/pc_fs.h>
#include <sys/fs/pc_dir.h>
#include <sys/fs/pc_label.h>
#include "getresponse.h"
#include "pcfs_common.h"
#include "fsck_pcfs.h"

extern	ClusterContents	TheRootDir;
extern	off64_t		FirstClusterOffset;
extern	off64_t		PartitionOffset;
extern	int32_t		BytesPerCluster;
extern	int32_t		TotalClusters;
extern	int32_t		LastCluster;
extern	int32_t		RootDirSize;
extern	int32_t		FATSize;
extern	bpb_t		TheBIOSParameterBlock;
extern	short		FATEntrySize;
extern	int		RootDirModified;
extern	int		OkayToRelink;
extern	int		ReadOnly;
extern	int		IsFAT32;
extern	int		Verbose;

static	struct pcdir	BlankPCDIR;
static	CachedCluster	*ClusterCache;
static	ClusterInfo	**InUse;
static	int32_t		ReservedClusterCount;
static	int32_t		AllocedClusterCount;
static	int32_t		FreeClusterCount;
static	int32_t		BadClusterCount;

/*
 * Internal statistics
 */
static	int32_t		CachedClusterCount;

int32_t	HiddenClusterCount;
int32_t	FileClusterCount;
int32_t	DirClusterCount;
int32_t	HiddenFileCount;
int32_t	FileCount;
int32_t	DirCount;

static int32_t orphanSizeLookup(int32_t clusterNum);

static void
freeNameInfo(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;
	if (InUse[clusterNum - FIRST_CLUSTER]->path != NULL) {
		if (InUse[clusterNum - FIRST_CLUSTER]->path->references > 1) {
			InUse[clusterNum - FIRST_CLUSTER]->path->references--;
		} else {
			free(InUse[clusterNum - FIRST_CLUSTER]->path->fullName);
			free(InUse[clusterNum - FIRST_CLUSTER]->path);
		}
		InUse[clusterNum - FIRST_CLUSTER]->path = NULL;
	}
}

static void
printOrphanPath(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;
	if (InUse[clusterNum - FIRST_CLUSTER]->path != NULL) {
		(void) printf(gettext("\nOrphaned allocation units originally "
		    "allocated to:\n"));
		(void) printf("%s\n",
		    InUse[clusterNum - FIRST_CLUSTER]->path->fullName);
		freeNameInfo(clusterNum);
	} else {
		(void) printf(gettext("\nOrphaned allocation units originally "
		    "allocated to an unknown file or directory:\n"));
		(void) printf(gettext("Orphaned chain begins with allocation "
		    "unit %d.\n"), clusterNum);
	}
}

static void
printOrphanSize(int32_t clusterNum)
{
	int32_t size = orphanSizeLookup(clusterNum);

	if (size > 0) {
		(void) printf(gettext("%d bytes in the orphaned chain of "
		    "allocation units.\n"), size);
		if (Verbose) {
			(void) printf(gettext("[Starting at allocation "
			    "unit %d]\n"), clusterNum);
		}
	}
}

static void
printOrphanInfo(int32_t clusterNum)
{
	printOrphanPath(clusterNum);
	printOrphanSize(clusterNum);
}

static bool
askAboutFreeing(int32_t clusterNum)
{
	/*
	 * If it is not OkayToRelink, we haven't already printed the size
	 * of the orphaned chain.
	 */
	if (!OkayToRelink)
		printOrphanInfo(clusterNum);
	/*
	 *  If we are in preen mode, preenBail won't return.
	 */
	preenBail("Need user confirmation to free orphaned chain.\n");

	(void) printf(
	    gettext("Free the allocation units in the orphaned chain ? "
	    "(y/n) "));
	if (AlwaysYes)
		return (true);
	if (AlwaysNo)
		return (false);
	return (yes());
}

static bool
askAboutRelink(int32_t clusterNum)
{
	/*
	 * Display the size of the chain for the user to consider.
	 */
	printOrphanInfo(clusterNum);
	/*
	 *  If we are in preen mode, preenBail won't return.
	 */
	preenBail("Need user confirmation to re-link orphaned chain.\n");

	(void) printf(gettext("Re-link orphaned chain into file system ? "
	    "(y/n) "));

	if (AlwaysYes)
		return (true);
	if (AlwaysNo)
		return (false);
	return (yes());
}

static int
isHidden(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (0);

	if (InUse[clusterNum - FIRST_CLUSTER] == NULL)
		return (0);

	return (InUse[clusterNum - FIRST_CLUSTER]->flags & CLINFO_HIDDEN);
}

static int
isInUse(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (0);

	return ((InUse[clusterNum - FIRST_CLUSTER] != NULL) &&
	    (InUse[clusterNum - FIRST_CLUSTER]->dirent != NULL));
}

/*
 *  Caller's may request that we cache the data from a readCluster.
 *  The xxxClusterxxxCachexxx routines handle looking for cached data
 *  or initially caching the data.
 *
 *  XXX - facilitate releasing cached data for low memory situations.
 */
static CachedCluster *
findClusterCacheEntry(int32_t clusterNum)
{
	CachedCluster *loop = ClusterCache;

	while (loop != NULL) {
		if (loop->clusterNum == clusterNum)
			return (loop);
		loop = loop->next;
	}
	return (NULL);
}

static uchar_t *
findClusterDataInTheCache(int32_t clusterNum)
{
	CachedCluster *loop = ClusterCache;

	while (loop) {
		if (loop->clusterNum == clusterNum)
			return (loop->clusterData.bytes);
		loop = loop->next;
	}
	return (NULL);
}

static uchar_t *
addToCache(int32_t clusterNum, uchar_t *buf, int32_t *datasize)
{
	CachedCluster *new;
	uchar_t *cp;

	if ((new = (CachedCluster *)malloc(sizeof (CachedCluster))) == NULL) {
		perror(gettext("No memory for cached cluster info"));
		return (buf);
	}
	new->clusterNum = clusterNum;
	new->modified = 0;

	if ((cp = (uchar_t *)calloc(1, BytesPerCluster)) == NULL) {
		perror(gettext("No memory for cached copy of cluster"));
		free(new);
		return (buf);
	}
	(void) memcpy(cp, buf, *datasize);
	new->clusterData.bytes = cp;

	if (Verbose) {
		(void) fprintf(stderr,
		    gettext("Allocation unit %d cached.\n"), clusterNum);
	}
	if (ClusterCache == NULL) {
		ClusterCache = new;
		new->next = NULL;
	} else if (new->clusterNum < ClusterCache->clusterNum) {
		new->next = ClusterCache;
		ClusterCache = new;
	} else {
		CachedCluster *loop = ClusterCache;
		CachedCluster *trailer = NULL;

		while (loop && new->clusterNum > loop->clusterNum) {
			trailer = loop;
			loop = loop->next;
		}
		trailer->next = new;
		if (loop) {
			new->next = loop;
		} else {
			new->next = NULL;
		}
	}
	CachedClusterCount++;
	return (new->clusterData.bytes);
}

static int
seekCluster(int fd, int32_t clusterNum)
{
	off64_t seekto;
	int saveError;

	seekto = FirstClusterOffset +
	    ((off64_t)clusterNum - FIRST_CLUSTER) * BytesPerCluster;
	if (lseek64(fd, seekto, SEEK_SET) != seekto) {
		saveError = errno;
		(void) fprintf(stderr,
		    gettext("Seek to Allocation unit #%d failed: "),
		    clusterNum);
		(void) fprintf(stderr, strerror(saveError));
		(void) fprintf(stderr, "\n");
		return (0);
	}
	return (1);
}

/*
 *  getcluster
 *	Get cluster bytes off the disk.  We always read those bytes into
 *	the same static buffer.  If the caller wants its own copy of the
 *	data it'll have to make its own copy.  We'll return all the data
 *	read, even if it's short of a full cluster.  This is for future use
 *	when we might want to relocate any salvagable data from bad clusters.
 */
static int
getCluster(int fd, int32_t clusterNum, uchar_t **data, int32_t *datasize)
{
	static uchar_t *clusterBuffer = NULL;
	int saveError;
	int try;

	*datasize = 0;
	*data = NULL;

	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (RDCLUST_BADINPUT);

	if (clusterBuffer == NULL &&
	    (clusterBuffer = (uchar_t *)malloc(BytesPerCluster)) == NULL) {
		perror(gettext("No memory for a cluster data buffer"));
		return (RDCLUST_MEMERR);
	}

	for (try = 0; try < RDCLUST_MAX_RETRY; try++) {
		if (!seekCluster(fd, clusterNum))
			return (RDCLUST_FAIL);
		if ((*datasize = read(fd, clusterBuffer, BytesPerCluster)) ==
		    BytesPerCluster) {
			*data = clusterBuffer;
			return (RDCLUST_GOOD);
		}
	}
	if (*datasize >= 0) {
		*data = clusterBuffer;
		(void) fprintf(stderr,
		    gettext("Short read of allocation unit #%d\n"), clusterNum);
	} else {
		saveError = errno;
		(void) fprintf(stderr, "Allocation unit %d:", clusterNum);
		(void) fprintf(stderr, strerror(saveError));
		(void) fprintf(stderr, "\n");
	}
	return (RDCLUST_FAIL);
}

static void
writeCachedCluster(int fd, CachedCluster *clustInfo)
{
	ssize_t bytesWritten;

	if (ReadOnly)
		return;

	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Allocation unit %d modified.\n"),
		    clustInfo->clusterNum);

	if (seekCluster(fd, clustInfo->clusterNum) == 0)
		return;

	if ((bytesWritten = write(fd, clustInfo->clusterData.bytes,
	    BytesPerCluster)) != BytesPerCluster) {
		if (bytesWritten < 0) {
			perror(gettext("Failed to write modified "
			    "allocation unit"));
		} else {
			(void) fprintf(stderr,
			    gettext("Short write of allocation unit %d\n"),
			    clustInfo->clusterNum);
		}
		(void) close(fd);
		exit(13);
	}
}

/*
 * It's cheaper to allocate a lot at a time; malloc overhead pushes
 * you over the brink much more quickly if you don't.
 * This numbers seems to be a fair trade-off between reduced malloc overhead
 * and additional overhead by over-allocating.
 */

#define	CHUNKSIZE	1024

static ClusterInfo *pool;

static ClusterInfo *
newClusterInfo(void)
{

	ClusterInfo *ret;

	if (pool == NULL) {
		int i;

		pool = (ClusterInfo *)malloc(sizeof (ClusterInfo) * CHUNKSIZE);

		if (pool == NULL) {
			perror(
			    gettext("Out of memory for cluster information"));
			exit(9);
		}

		for (i = 0; i < CHUNKSIZE - 1; i++)
			pool[i].nextfree = &pool[i+1];

		pool[CHUNKSIZE-1].nextfree = NULL;
	}
	ret = pool;
	pool = pool->nextfree;

	memset(ret, 0, sizeof (*ret));

	return (ret);
}

/* Should be called with verified arguments */

static ClusterInfo *
cloneClusterInfo(int32_t clusterNum)
{
	ClusterInfo *cl = InUse[clusterNum - FIRST_CLUSTER];

	if (cl->refcnt > 1) {
		ClusterInfo *newCl = newClusterInfo();
		cl->refcnt--;
		*newCl = *cl;
		newCl->refcnt = 1;
		if (newCl->path)
			newCl->path->references++;
		InUse[clusterNum - FIRST_CLUSTER] = newCl;
	}
	return (InUse[clusterNum - FIRST_CLUSTER]);
}

static void
updateFlags(int32_t clusterNum, int newflags)
{
	ClusterInfo *cl = InUse[clusterNum - FIRST_CLUSTER];

	if (cl->flags != newflags && cl->refcnt > 1)
		cl = cloneClusterInfo(clusterNum);

	cl->flags = newflags;
}

static void
freeClusterInfo(ClusterInfo *old)
{
	if (--old->refcnt <= 0) {
		if (old->path && --old->path->references <= 0) {
			free(old->path->fullName);
			free(old->path);
		}
		old->nextfree = pool;
		pool = old;
	}
}

/*
 * Allocate entries in our sparse array of cluster information.
 * Returns non-zero if the structure already has been allocated
 * (for those keeping score at home).
 *
 * The template parameter, if non-NULL, is used to facilitate sharing
 * the ClusterInfo nodes for the clusters belonging to the same file.
 * The first call to allocInUse for a new file should have *template
 * set to 0; on return, *template then points to the newly allocated
 * ClusterInfo.  Second and further calls keep the same value
 * in *template and that ClusterInfo ndoe is then used for all
 * entries in the file.  Code that modifies the ClusterInfo nodes
 * should take care proper sharing semantics are maintained (i.e.,
 * copy-on-write using cloneClusterInfo())
 *
 * The ClusterInfo used in the template is guaranted to be in use in
 * at least one other cluster as we never return a value if we didn't
 * set it first.  So we can overwrite it without the possibility of a leak.
 */
static int
allocInUse(int32_t clusterNum, ClusterInfo **template)
{
	ClusterInfo *newCl;

	if (InUse[clusterNum - FIRST_CLUSTER] != NULL)
		return (CLINFO_PREVIOUSLY_ALLOCED);

	if (template != NULL && *template != NULL)
		newCl = *template;
	else {
		newCl = newClusterInfo();
		if (template)
			*template = newCl;
	}

	InUse[clusterNum - FIRST_CLUSTER] = newCl;
	newCl->refcnt++;

	return (CLINFO_NEWLY_ALLOCED);
}

static void
markFree(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;

	if (InUse[clusterNum - FIRST_CLUSTER]) {
		if (InUse[clusterNum - FIRST_CLUSTER]->saved)
			free(InUse[clusterNum - FIRST_CLUSTER]->saved);
		freeClusterInfo(InUse[clusterNum - FIRST_CLUSTER]);
		InUse[clusterNum - FIRST_CLUSTER] = NULL;
	}
}

static void
markOrphan(int fd, int32_t clusterNum, struct pcdir *dp)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;

	(void) markInUse(fd, clusterNum, dp, NULL, 0, VISIBLE, NULL);
	if (InUse[clusterNum - FIRST_CLUSTER] != NULL)
		updateFlags(clusterNum,
		    InUse[clusterNum - FIRST_CLUSTER]->flags | CLINFO_ORPHAN);
}

static void
markBad(int32_t clusterNum, uchar_t *recovered, int32_t recoveredLen)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;

	(void) allocInUse(clusterNum, NULL);

	if (recoveredLen) {
		(void) cloneClusterInfo(clusterNum);
		InUse[clusterNum - FIRST_CLUSTER]->saved = recovered;
	}
	updateFlags(clusterNum,
	    InUse[clusterNum - FIRST_CLUSTER]->flags | CLINFO_BAD);

	BadClusterCount++;
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Allocation unit %d marked bad.\n"), clusterNum);
}

static void
clearOrphan(int32_t c)
{
	/* silent failure for bogus clusters */
	if (c < FIRST_CLUSTER || c > LastCluster)
		return;
	if (InUse[c - FIRST_CLUSTER] != NULL)
		updateFlags(c,
		    InUse[c - FIRST_CLUSTER]->flags & ~CLINFO_ORPHAN);
}

static void
clearInUse(int32_t c)
{
	ClusterInfo **clp;

	/* silent failure for bogus clusters */
	if (c < FIRST_CLUSTER || c > LastCluster)
		return;

	clp = &InUse[c - FIRST_CLUSTER];
	if (*clp != NULL) {
		freeClusterInfo(*clp);
		*clp = NULL;
	}
}

static void
clearAllClusters_InUse()
{
	int32_t cc;
	for (cc = FIRST_CLUSTER; cc < LastCluster; cc++) {
		clearInUse(cc);
	}
}

static void
makeUseTable(void)
{
	if (InUse != NULL) {
		clearAllClusters_InUse();
		return;
	}
	if ((InUse = (ClusterInfo **)
	    calloc(TotalClusters, sizeof (ClusterInfo *))) == NULL) {
		perror(gettext("No memory for internal table"));
		exit(9);
	}
}

static void
countClusters(void)
{
	int32_t c;

	BadClusterCount = HiddenClusterCount =
	    AllocedClusterCount = FreeClusterCount = 0;

	for (c = FIRST_CLUSTER; c < LastCluster; c++) {
		if (badInFAT(c)) {
			BadClusterCount++;
		} else if (isMarkedBad(c)) {
			/*
			 * This catches the bad sectors found
			 * during thorough verify that have never been
			 * allocated to a file.  Without this check, we
			 * count these guys as free.
			 */
			BadClusterCount++;
			markBadInFAT(c);
		} else if (isHidden(c)) {
			HiddenClusterCount++;
		} else if (isInUse(c)) {
			AllocedClusterCount++;
		} else {
			FreeClusterCount++;
		}
	}
}

/*
 * summarizeFAT
 *	Mark orphans without directory entries as allocated.
 *	XXX - these chains should be reclaimed!
 *	XXX - merge this routine with countClusters (same loop, duh.)
 */
static void
summarizeFAT(int fd)
{
	int32_t c;
	ClusterInfo *tmpl = NULL;

	for (c = FIRST_CLUSTER; c < LastCluster; c++) {
		if (!freeInFAT(c) && !badInFAT(c) && !reservedInFAT(c) &&
		    !isInUse(c)) {
			(void) markInUse(fd, c, &BlankPCDIR, NULL, 0, VISIBLE,
			    &tmpl);
		}
	}
}

static void
getReadyToSearch(int fd)
{
	getFAT(fd);
	if (!IsFAT32)
		getRootDirectory(fd);
}


static char PathName[MAXPATHLEN];

static void
summarize(int fd, int includeFAT)
{
	struct pcdir *ignorep1, *ignorep2 = NULL;
	int32_t ignore32;
	char ignore;
	int pathlen;

	ReservedClusterCount = 0;
	AllocedClusterCount = 0;
	HiddenClusterCount = 0;
	FileClusterCount = 0;
	FreeClusterCount = 0;
	DirClusterCount = 0;
	BadClusterCount = 0;
	HiddenFileCount = 0;
	FileCount = 0;
	DirCount = 0;
	ignorep1 = ignorep2 = NULL;
	ignore = '\0';

	PathName[0] = '\0';
	pathlen = 0;

	getReadyToSearch(fd);
	/*
	 *  Traverse the full meta-data tree to talley what clusters
	 * are in use.  The root directory is an area outside of the
	 * file space on FAT12 and FAT16 file systems.  On FAT32 file
	 * systems, the root directory is in a file area cluster just
	 * like any other directory.
	 */
	if (!IsFAT32) {
		traverseFromRoot(fd, 0, PCFS_VISIT_SUBDIRS, PCFS_TRAVERSE_ALL,
		    ignore, &ignorep1, &ignore32, &ignorep2, PathName,
		    &pathlen);
	} else {
		DirCount++;
		traverseDir(fd, TheBIOSParameterBlock.bpb32.root_dir_clust,
		    0, PCFS_VISIT_SUBDIRS, PCFS_TRAVERSE_ALL, ignore,
		    &ignorep1, &ignore32, &ignorep2, PathName, &pathlen);
	}

	if (includeFAT)
		summarizeFAT(fd);
	countClusters();
}

int
isMarkedBad(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (0);

	if (InUse[clusterNum - FIRST_CLUSTER] == NULL)
		return (0);

	return (InUse[clusterNum - FIRST_CLUSTER]->flags & CLINFO_BAD);
}

static int
isMarkedOrphan(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (0);

	if (InUse[clusterNum - FIRST_CLUSTER] == NULL)
		return (0);

	return (InUse[clusterNum - FIRST_CLUSTER]->flags & CLINFO_ORPHAN);
}

static void
orphanChain(int fd, int32_t c, struct pcdir *ndp)
{
	ClusterInfo *tmpl = NULL;

	/* silent failure for bogus clusters */
	if (c < FIRST_CLUSTER || c > LastCluster)
		return;
	clearInUse(c);
	markOrphan(fd, c, ndp);
	c = nextInChain(c);
	while (c != 0) {
		clearInUse(c);
		clearOrphan(c);
		(void) markInUse(fd, c, ndp, NULL, 0, VISIBLE, &tmpl);
		c = nextInChain(c);
	}
}

static int32_t
findAFreeCluster(int32_t startAt)
{
	int32_t look = startAt;

	for (;;) {
		if (freeInFAT(look)) {
			break;
		}
		if (look == LastCluster)
			look = FIRST_CLUSTER;
		else
			look++;
		if (look == startAt)
			break;
	}
	if (look != startAt)
		return (look);
	else
		return (0);
}

static void
setEndOfDirectory(struct pcdir *dp)
{
	dp->pcd_filename[0] = PCD_UNUSED;
}

static void
emergencyEndOfDirectory(int fd, int32_t secondToLast)
{
	ClusterContents dirdata;
	int32_t dirdatasize = 0;

	if (readCluster(fd, secondToLast, &(dirdata.bytes), &dirdatasize,
	    RDCLUST_DO_CACHE) != RDCLUST_GOOD) {
		(void) fprintf(stderr,
		    gettext("Unable to read allocation unit %d.\n"),
		    secondToLast);
		(void) fprintf(stderr,
		    gettext("Cannot allocate a new allocation unit to hold an"
		    " end-of-directory marker.\nCannot access allocation unit"
		    " to overwrite existing directory entry with\nthe marker."
		    "  Needed directory truncation has failed.  Giving up.\n"));
		(void) close(fd);
		exit(11);
	}
	setEndOfDirectory(dirdata.dirp);
	markClusterModified(secondToLast);
}

static void
makeNewEndOfDirectory(struct pcdir *entry, int32_t secondToLast,
    int32_t newCluster, ClusterContents *newData)
{
	setEndOfDirectory(newData->dirp);
	markClusterModified(newCluster);
	/*
	 *  There are two scenarios.  One is that we truncated the
	 *  directory in the very beginning.  The other is that we
	 *  truncated it in the middle or at the end.  In the first
	 *  scenario, the secondToLast argument is not a valid cluster
	 *  (it's zero), and so we actually need to change the start
	 *  cluster for the directory to this new start cluster.  In
	 *  the second scenario, the secondToLast cluster we received
	 *  as an argument needs to be pointed at the new end of
	 *  directory.
	 */
	if (secondToLast == 0) {
		updateDirEnt_Start(entry, newCluster);
	} else {
		writeFATEntry(secondToLast, newCluster);
	}
	markLastInFAT(newCluster);
}

static void
createNewEndOfDirectory(int fd, struct pcdir *entry, int32_t secondToLast)
{
	ClusterContents dirdata;
	int32_t dirdatasize = 0;
	int32_t freeCluster;

	if (((freeCluster = findAFreeCluster(secondToLast)) != 0)) {
		if (readCluster(fd, freeCluster, &(dirdata.bytes),
		    &dirdatasize, RDCLUST_DO_CACHE) == RDCLUST_GOOD) {
			if (Verbose) {
				(void) fprintf(stderr,
				    gettext("Grabbed allocation unit #%d "
				    "for truncated\ndirectory's new end "
				    "of directory.\n"), freeCluster);
			}
			makeNewEndOfDirectory(entry, secondToLast,
			    freeCluster, &dirdata);
			return;
		}
	}
	if (secondToLast == 0) {
		if (freeCluster == 0) {
			(void) fprintf(stderr, gettext("File system full.\n"));
		} else {
			(void) fprintf(stderr,
			    gettext("Unable to read allocation unit %d.\n"),
			    freeCluster);
		}
		(void) fprintf(stderr,
		    gettext("Cannot allocate a new allocation unit to hold "
		    "an end-of-directory marker.\nNo existing directory "
		    "entries can be overwritten with the marker,\n"
		    "the only unit allocated to the directory is "
		    "inaccessible.\nNeeded directory truncation has failed.  "
		    "Giving up.\n"));
		(void) close(fd);
		exit(11);
	}
	emergencyEndOfDirectory(fd, secondToLast);
}

/*
 * truncAtCluster
 *	Given a directory entry and a cluster number, search through
 *	the cluster chain for the entry and make the cluster previous
 *	to the given cluster in the chain the last cluster in the file.
 *	The number of orphaned bytes is returned.  For a chain that's
 *	a directory we need to do some special handling, since we'll be
 *	getting rid of the end of directory notice by truncating.
 */
static int64_t
truncAtCluster(int fd, struct pcdir *entry, int32_t cluster)
{
	uint32_t oldSize, newSize;
	int32_t prev, count, follow;
	int dir = (entry->pcd_attr & PCA_DIR);

	prev = 0; count = 0;
	follow = extractStartCluster(entry);
	while (follow != cluster && follow >= FIRST_CLUSTER &&
	    follow <= LastCluster) {
		prev = follow;
		count++;
		follow = nextInChain(follow);
	}
	if (follow != cluster) {
		/*
		 *  We didn't find the cluster they wanted to trunc at
		 *  anywhere in the entry's chain.  So we'll leave the
		 *  entry alone, and return a negative value so they
		 *  can know something is wrong.
		 */
		return (-1);
	}
	if (Verbose) {
		(void) fprintf(stderr,
		    gettext("Chain truncation at unit #%d\n"), cluster);
	}
	if (!dir) {
		oldSize = extractSize(entry);
		newSize = count *
		    TheBIOSParameterBlock.bpb.sectors_per_cluster *
		    TheBIOSParameterBlock.bpb.bytes_per_sector;
		if (newSize == 0)
			updateDirEnt_Start(entry, 0);
	} else {
		newSize = 0;
	}
	updateDirEnt_Size(entry, newSize);
	if (dir) {
		createNewEndOfDirectory(fd, entry, prev);
	} else if (prev != 0) {
		markLastInFAT(prev);
	}
	if (dir) {
		/*
		 * We don't really know what the size of a directory is
		 * but it is important for us to know if this truncation
		 * results in an orphan with any size.  The value we
		 * return from this routine for a normal file is the
		 * number of bytes left in the chain.  For a directory
		 * we can't be exact, and the caller doesn't really
		 * expect us to be.  For a directory the caller only
		 * cares if there are zero bytes left or more than
		 * zero bytes left.  We'll return 1 to indicate
		 * more than zero.
		 */
		if ((follow = nextInChain(follow)) != 0)
			return (1);
		else
			return (0);
	}
	/*
	 * newSize should always be smaller than the old one, since
	 * we are decreasing the number of clusters allocated to the file.
	 */
	return ((int64_t)oldSize - (int64_t)newSize);
}

static struct pcdir *
updateOrphanedChainMetadata(int fd, struct pcdir *dp, int32_t endCluster,
    int isBad)
{
	struct pcdir *ndp = NULL;
	int64_t remainder;
	char *newName = NULL;
	int chosenName;
	int dir = (dp->pcd_attr & PCA_DIR);

	/*
	 *  If the truncation fails, (which ought not to happen),
	 *  there's no need to go any further, we just return
	 *  a null value for the new directory entry pointer.
	 */
	remainder = truncAtCluster(fd, dp, endCluster);
	if (remainder < 0)
		return (ndp);
	if (!dir && isBad) {
		/*
		 *  Subtract out the bad cluster from the remaining size
		 *  We always assume the cluster being deleted from the
		 *  file is full size, but that might not be the case
		 *  for the last cluster of the file, so that is why
		 *  we check for negative remainder value.
		 */
		remainder -= TheBIOSParameterBlock.bpb.sectors_per_cluster *
		    TheBIOSParameterBlock.bpb.bytes_per_sector;
		if (remainder < 0)
			remainder = 0;
	}
	/*
	 * Build a new directory entry for the rest of the chain.
	 * Later, if the user okays it, we'll link this entry into the
	 * root directory.  The new entry will start out as a
	 * copy of the truncated entry.
	 */
	if ((remainder != 0) &&
	    ((newName = nextAvailableCHKName(&chosenName)) != NULL) &&
	    ((ndp = newDirEnt(dp)) != NULL)) {
		if (Verbose) {
			if (dir)
				(void) fprintf(stderr,
				    gettext("Orphaned directory chain.\n"));
			else
				(void) fprintf(stderr,
				    gettext("Orphaned chain, %u bytes.\n"),
				    (uint32_t)remainder);
		}
		if (!dir)
			updateDirEnt_Size(ndp, (uint32_t)remainder);
		if (isBad)
			updateDirEnt_Start(ndp, nextInChain(endCluster));
		else
			updateDirEnt_Start(ndp, endCluster);
		updateDirEnt_Name(ndp, newName);
		addEntryToCHKList(chosenName);
	}
	return (ndp);
}

/*
 *  splitChain()
 *
 *	split a cluster allocation chain into two cluster chains
 *	around a given cluster (problemCluster).  This results in two
 *	separate directory entries; the original (dp), and one we hope
 *	to create and return a pointer to to the caller (*newdp).
 *	This second entry is the orphan chain, and it may end up in
 *	the root directory as a FILEnnnn.CHK file.  We also return the
 *	starting cluster of the orphan chain to the caller (*orphanStart).
 */
void
splitChain(int fd, struct pcdir *dp, int32_t problemCluster,
    struct pcdir **newdp, int32_t *orphanStart)
{
	struct pcdir *ndp = NULL;
	int isBad = isMarkedBad(problemCluster);

	ndp = updateOrphanedChainMetadata(fd, dp, problemCluster, isBad);
	*newdp = ndp;
	clearInUse(problemCluster);
	if (isBad) {
		clearOrphan(problemCluster);
		*orphanStart = nextInChain(problemCluster);
		orphanChain(fd, *orphanStart, ndp);
		markBadInFAT(problemCluster);
	} else {
		*orphanStart = problemCluster;
		orphanChain(fd, problemCluster, ndp);
	}
}

/*
 *  freeOrphan
 *
 *  User has requested that an orphaned cluster chain be freed back
 *  into the file area.
 */
static void
freeOrphan(int32_t c)
{
	int32_t n;

	/*
	 * Free the directory entry we explicitly created for
	 * the orphaned clusters.
	 */
	if (InUse[c - FIRST_CLUSTER]->dirent != NULL)
		free(InUse[c - FIRST_CLUSTER]->dirent);
	/*
	 * Then mark the clusters themselves as available.
	 */
	do {
		n = nextInChain(c);
		markFreeInFAT(c);
		markFree(c);
		c = n;
	} while (c != 0);
}

/*
 *  Rewrite the InUse field for a cluster chain.  Can be used on a partial
 *  chain if provided with a stopAtCluster.
 */
static void
redoInUse(int fd, int32_t c, struct pcdir *ndp, int32_t stopAtCluster)
{
	while (c && c != stopAtCluster) {
		clearInUse(c);
		(void) markInUse(fd, c, ndp, NULL, 0, VISIBLE, NULL);
		c = nextInChain(c);
	}
}

static struct pcdir *
orphanDirEntLookup(int32_t clusterNum)
{
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (NULL);

	if (isInUse(clusterNum)) {
		return (InUse[clusterNum - FIRST_CLUSTER]->dirent);
	} else {
		return (NULL);
	}
}

static int32_t
orphanSizeLookup(int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (-1);

	if (isInUse(clusterNum)) {
		return (extractSize(InUse[clusterNum - FIRST_CLUSTER]->dirent));
	} else {
		return (-1);
	}
}

/*
 *  linkOrphan
 *
 *  User has requested that an orphaned cluster chain be brought back
 *  into the file system.  So we have to make a new directory entry
 *  in the root directory and point it at the cluster chain.
 */
static void
linkOrphan(int fd, int32_t start)
{
	struct pcdir *newEnt = NULL;
	struct pcdir *dp;

	if ((dp = orphanDirEntLookup(start)) != NULL) {
		newEnt = addRootDirEnt(fd, dp);
	} else {
		(void) printf(gettext("Re-link of orphaned chain failed."
		    "  Allocation units will remain orphaned.\n"));
	}
	/*
	 *  A cluster isn't really InUse() unless it is referenced,
	 *  so if newEnt is NULL here, we are in effect using markInUse()
	 *  to note that the cluster is NOT in use.
	 */
	redoInUse(fd, start, newEnt, 0);
}

/*
 *  relinkCreatedOrphans
 *
 *  While marking clusters as bad, we can create orphan cluster
 *  chains.  Since we were the ones doing the marking, we were able to
 *  keep track of the orphans we created.  Now we want to go through
 *  all those chains and either get them back into the file system or
 *  free them depending on the user's input.
 */
static void
relinkCreatedOrphans(int fd)
{
	int32_t c;

	for (c = FIRST_CLUSTER; c < LastCluster; c++) {
		if (isMarkedOrphan(c)) {
			if (OkayToRelink && askAboutRelink(c)) {
				linkOrphan(fd, c);
			} else if (askAboutFreeing(c)) {
				freeOrphan(c);
			}
			clearOrphan(c);
		}
	}
}

/*
 *  relinkFATOrphans
 *
 *  We want to find orphans not represented in the meta-data.
 *  These are chains marked in the FAT as being in use but
 *  not referenced anywhere by any directory entries.
 *  We'll go through the whole FAT and mark the first cluster
 *  in any such chain as an orphan.  Then we can just use
 *  the relinkCreatedOrphans routine to get them back into the
 *  file system or free'ed depending on the user's input.
 */
static void
relinkFATOrphans(int fd)
{
	struct pcdir *ndp = NULL;
	int32_t cc, c, n;
	int32_t bpc, newSize;
	char *newName;
	int chosenName;

	for (c = FIRST_CLUSTER; c < LastCluster; c++) {
		if (freeInFAT(c) || badInFAT(c) ||
		    reservedInFAT(c) || isInUse(c))
			continue;
		cc = 1;
		n = c;
		while (n = nextInChain(n))
			cc++;
		bpc = TheBIOSParameterBlock.bpb.sectors_per_cluster *
		    TheBIOSParameterBlock.bpb.bytes_per_sector;
		newSize = cc * bpc;
		if (((newName = nextAvailableCHKName(&chosenName)) != NULL) &&
		    ((ndp = newDirEnt(NULL)) != NULL)) {
			updateDirEnt_Size(ndp, newSize);
			updateDirEnt_Start(ndp, c);
			updateDirEnt_Name(ndp, newName);
			addEntryToCHKList(chosenName);
		}
		orphanChain(fd, c, ndp);
	}
	relinkCreatedOrphans(fd);
}

static void
relinkOrphans(int fd)
{
	relinkCreatedOrphans(fd);
	relinkFATOrphans(fd);
}

static void
checkForFATLoop(int32_t clusterNum)
{
	int32_t prev = clusterNum;
	int32_t follow;

	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;

	follow = nextInChain(clusterNum);
	while (follow != clusterNum && follow >= FIRST_CLUSTER &&
	    follow <= LastCluster) {
		prev = follow;
		follow = nextInChain(follow);
	}
	if (follow == clusterNum) {
		/*
		 * We found a loop.  Eradicate it by changing
		 * the last cluster in the loop to be last
		 * in the chain instead instead of pointing
		 * back to the first cluster.
		 */
		markLastInFAT(prev);
	}
}

static void
sharedChainError(int fd, int32_t clusterNum, struct pcdir *badEntry)
{
	/*
	 * If we have shared clusters, it is either because the
	 * cluster somehow got assigned to multiple files and/or
	 * because of a loop in the cluster chain.  In either
	 * case we want to truncate the offending file at the
	 * cluster of contention.  Then, we will want to run
	 * through the remainder of the chain. If we find ourselves
	 * back at the top, we will know there is a loop in the
	 * FAT we need to remove.
	 */
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Truncating chain due to duplicate allocation of "
		    "unit %d.\n"), clusterNum);
	/*
	 * Note that we don't orphan anything here, because the duplicate
	 * part of the chain may be part of another valid chain.
	 */
	(void) truncAtCluster(fd, badEntry, clusterNum);
	checkForFATLoop(clusterNum);
}

void
truncChainWithBadCluster(int fd, struct pcdir *dp, int32_t startCluster)
{
	struct pcdir *orphanEntry;
	int32_t orphanStartCluster;
	int32_t c = startCluster;

	while (c != 0) {
		if (isMarkedBad(c)) {
			/*
			 *  splitChain() truncates the current guy and
			 *  then makes an orphan chain out of the remaining
			 *  clusters.  When we come back from the split
			 *  we'll want to continue looking for bad clusters
			 *  in the orphan chain.
			 */
			splitChain(fd, dp, c,
			    &orphanEntry, &orphanStartCluster);
			/*
			 *  There is a chance that we weren't able or weren't
			 *  required to make a directory entry for the
			 *  remaining clusters.  In that case we won't go
			 *  on, because we couldn't make any more splits
			 *  anyway.
			 */
			if (orphanEntry == NULL)
				break;
			c = orphanStartCluster;
			dp = orphanEntry;
			continue;
		}
		c = nextInChain(c);
	}
}

int32_t
nextInChain(int32_t currentCluster)
{
	int32_t nextCluster;

	/* silent failure for bogus clusters */
	if (currentCluster < FIRST_CLUSTER || currentCluster > LastCluster)
		return (0);

	/*
	 * Look up FAT entry of next link in cluster chain,
	 * if this one is the last one return 0 as the next link.
	 */
	nextCluster = readFATEntry(currentCluster);
	if (nextCluster < FIRST_CLUSTER || nextCluster > LastCluster)
		return (0);

	return (nextCluster);
}

/*
 * findImpactedCluster
 *
 *	Called when someone modifies what they believe might be a cached
 *	cluster entry, but when	they only have a directory entry pointer
 *	and not the cluster number.  We have to go dig up what cluster
 *	they are modifying.
 */
int32_t
findImpactedCluster(struct pcdir *modified)
{
	CachedCluster *loop;
	/*
	 * Check to see if it's in the root directory first
	 */
	if (!IsFAT32 && ((uchar_t *)modified >= TheRootDir.bytes) &&
	    ((uchar_t *)modified < TheRootDir.bytes + RootDirSize))
		return (FAKE_ROOTDIR_CLUST);

	loop = ClusterCache;
	while (loop) {
		if (((uchar_t *)modified >= loop->clusterData.bytes) &&
		    ((uchar_t *)modified <
		    (loop->clusterData.bytes + BytesPerCluster))) {
			return (loop->clusterNum);
		}
		loop = loop->next;
	}
	/*
	 *  Guess it wasn't cached after all...
	 */
	return (0);
}

void
writeClusterMods(int fd)
{
	CachedCluster *loop = ClusterCache;

	while (loop) {
		if (loop->modified)
			writeCachedCluster(fd, loop);
		loop = loop->next;
	}
}

void
squirrelPath(struct nameinfo *pathInfo, int32_t clusterNum)
{
	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;
	if (InUse[clusterNum - FIRST_CLUSTER] == NULL)
		return;
	InUse[clusterNum - FIRST_CLUSTER]->path = pathInfo;
}

int
markInUse(int fd, int32_t clusterNum, struct pcdir *referencer, struct
    pcdir *longRef, int32_t longStartCluster, int isHiddenFile,
    ClusterInfo **template)
{
	int alreadyMarked;
	ClusterInfo *cl;

	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return (CLINFO_NEWLY_ALLOCED);

	alreadyMarked = allocInUse(clusterNum, template);
	if ((alreadyMarked == CLINFO_PREVIOUSLY_ALLOCED) &&
	    (isInUse(clusterNum))) {
		sharedChainError(fd, clusterNum, referencer);
		return (CLINFO_PREVIOUSLY_ALLOCED);
	}
	cl = InUse[clusterNum - FIRST_CLUSTER];
	/*
	 * If Cl is newly allocated (refcnt <= 1) we must fill in the fields.
	 * If Cl has different fields, we must clone it.
	 */

	if (cl->refcnt <= 1 || cl->dirent != referencer ||
	    cl->longent != longRef ||
	    cl->longEntStartClust != longStartCluster) {
		if (cl->refcnt > 1)
			cl = cloneClusterInfo(clusterNum);
		cl->dirent = referencer;
		cl->longent = longRef;
		cl->longEntStartClust = longStartCluster;
		if (isHiddenFile)
			cl->flags |= CLINFO_HIDDEN;

		/*
		 * Return cl as the template to use for other clusters in
		 * this file
		 */
		if (template)
			*template = cl;
	}
	return (CLINFO_NEWLY_ALLOCED);
}

void
markClusterModified(int32_t clusterNum)
{
	CachedCluster *c;

	if (clusterNum == FAKE_ROOTDIR_CLUST) {
		RootDirModified = 1;
		return;
	}

	/* silent failure for bogus clusters */
	if (clusterNum < FIRST_CLUSTER || clusterNum > LastCluster)
		return;

	if (c = findClusterCacheEntry(clusterNum)) {
		c->modified = 1;
	} else {
		(void) fprintf(stderr,
		    gettext("Unexpected internal error: "
		    "Missing cache entry [%d]\n"), clusterNum);
		exit(10);
	}
}

/*
 *  readCluster
 *	caller wants to read cluster clusterNum.  We should return
 *	a pointer to the read data in "data", and fill in the number
 *	of bytes read in "datasize".  If shouldCache is non-zero
 *	we should allocate cache space to the cluster, otherwise we
 *	just return a pointer to a buffer we re-use whenever cacheing
 *	is not requested.
 */
int
readCluster(int fd, int32_t clusterNum, uchar_t **data, int32_t *datasize,
    int shouldCache)
{
	uchar_t *newBuf;
	int rv;

	*data = NULL;
	if ((*data = findClusterDataInTheCache(clusterNum)) != NULL) {
		*datasize = BytesPerCluster;
		return (RDCLUST_GOOD);
	}

	rv = getCluster(fd, clusterNum, &newBuf, datasize);
	if (rv != RDCLUST_GOOD)
		return (rv);

	/*
	 * Caller requested we NOT cache the data from this read.
	 * So, we just return a pointer to the common data buffer.
	 */
	if (shouldCache == 0) {
		*data = newBuf;
		return (rv);
	}

	/*
	 * Caller requested we cache the data from this read.
	 * So, if we have some data, add it to the cache by
	 * copying it out of the common buffer into new storage.
	 */
	if (*datasize > 0)
		*data = addToCache(clusterNum, newBuf, datasize);
	return (rv);
}

void
findBadClusters(int fd)
{
	int32_t clusterCount;
	int32_t datasize;
	uchar_t *data;

	BadClusterCount = 0;
	makeUseTable();
	(void) printf(gettext("** Scanning allocation units\n"));
	for (clusterCount = FIRST_CLUSTER;
	    clusterCount < LastCluster; clusterCount++) {
		if (readCluster(fd, clusterCount,
		    &data, &datasize, RDCLUST_DONT_CACHE) < 0) {
			if (Verbose)
				(void) fprintf(stderr,
				    gettext(
				    "\nUnreadable allocation unit %d.\n"),
				    clusterCount);
			markBad(clusterCount, data, datasize);
		}
		/*
		 *  Progress meter, display a '.' for every 1000 clusters
		 *  processed.  We don't want to display this when
		 *  we are in verbose mode; verbose mode progress is
		 *  shown by displaying each file name as it is found.
		 */
		if (!Verbose && clusterCount % 1000 == 0)
			(void) printf(".");
	}
	(void) printf(gettext("..done\n"));
}

void
scanAndFixMetadata(int fd)
{
	/*
	 * First we initialize a few things.
	 */
	makeUseTable();
	getReadyToSearch(fd);
	createCHKNameList(fd);

	/*
	 * Make initial scan, taking into account any effect that
	 * the bad clusters we may have already discovered have
	 * on meta-data.  We may break up some cluster chains
	 * during this period.  The relinkCreatedOrphans() call
	 * will then give the user the chance to recover stuff
	 * we've created.
	 */
	(void) printf(gettext("** Scanning file system meta-data\n"));
	summarize(fd, NO_FAT_IN_SUMMARY);
	if (Verbose)
		printSummary(stderr);
	(void) printf(gettext("** Correcting any meta-data discrepancies\n"));
	relinkCreatedOrphans(fd);

	/*
	 * Clear our usage table and go back over everything, this
	 * time including looking for clusters floating free in the FAT.
	 * This may include clusters the user chose to free during the
	 * relink phase.
	 */
	makeUseTable();
	summarize(fd, INCLUDE_FAT_IN_SUMMARY);
	relinkOrphans(fd);
}

void
printSummary(FILE *outDest)
{
	(void) fprintf(outDest,
	    gettext("%llu bytes.\n"),
	    (uint64_t)
	    TotalClusters * TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector);
	(void) fprintf(outDest,
	    gettext("%llu bytes in bad sectors.\n"),
	    (uint64_t)
	    BadClusterCount * TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector);
	(void) fprintf(outDest,
	    gettext("%llu bytes in %d directories.\n"),
	    (uint64_t)
	    DirClusterCount * TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector, DirCount);
	if (HiddenClusterCount) {
		(void) fprintf(outDest,
		    gettext("%llu bytes in %d hidden files.\n"),
		    (uint64_t)HiddenClusterCount *
		    TheBIOSParameterBlock.bpb.sectors_per_cluster *
		    TheBIOSParameterBlock.bpb.bytes_per_sector,
		    HiddenFileCount);
	}
	(void) fprintf(outDest,
	    gettext("%llu bytes in %d files.\n"),
	    (uint64_t)
	    FileClusterCount * TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector, FileCount);
	(void) fprintf(outDest,
	    gettext("%llu bytes free.\n"), (uint64_t)FreeClusterCount *
	    TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector);
	(void) fprintf(outDest,
	    gettext("%d bytes per allocation unit.\n"),
	    TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector);
	(void) fprintf(outDest,
	    gettext("%d total allocation units.\n"), TotalClusters);
	if (ReservedClusterCount)
		(void) fprintf(outDest,
		    gettext("%d reserved allocation units.\n"),
		    ReservedClusterCount);
	(void) fprintf(outDest,
	    gettext("%d available allocation units.\n"), FreeClusterCount);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License (the "License").
 * You may not use this file except in compliance with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

/*
 * fsck_pcfs -- routines for manipulating directories.
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <libintl.h>
#include <ctype.h>
#include <time.h>
#include <sys/param.h>
#include <sys/time.h>
#include <sys/byteorder.h>
#include <sys/dktp/fdisk.h>
#include <sys/fs/pc_fs.h>
#include <sys/fs/pc_dir.h>
#include <sys/fs/pc_label.h>
#include "pcfs_common.h"
#include "fsck_pcfs.h"

extern	int32_t	HiddenClusterCount;
extern	int32_t	FileClusterCount;
extern	int32_t	DirClusterCount;
extern	int32_t	HiddenFileCount;
extern	int32_t	LastCluster;
extern	int32_t	FileCount;
extern	int32_t	BadCount;
extern	int32_t	DirCount;
extern	int32_t	FATSize;
extern	off64_t	PartitionOffset;
extern	bpb_t	TheBIOSParameterBlock;
extern	int	ReadOnly;
extern	int	IsFAT32;
extern	int	Verbose;

static uchar_t *CHKsList = NULL;

ClusterContents	TheRootDir;
int32_t	RootDirSize;
int	RootDirModified;
int	OkayToRelink = 1;

/*
 * We have a bunch of routines for handling CHK names.  A CHK name is
 * simply a file name of the form "FILEnnnn.CHK", where the n's are the
 * digits in the numbers from 1 to 9999.  There are always four digits
 * used, leading zeros are added as necessary.
 *
 * We use CHK names to link orphaned cluster chains back into the file
 * system's root directory under an auspicious name so that the user
 * may be able to recover some of their data.
 *
 * We use these routines to ensure CHK names we use don't conflict
 * with any already present in the file system.
 */
static int
hasCHKName(struct pcdir *dp)
{
	return (dp->pcd_filename[CHKNAME_F] == 'F' &&
	    dp->pcd_filename[CHKNAME_I] == 'I' &&
	    dp->pcd_filename[CHKNAME_L] == 'L' &&
	    dp->pcd_filename[CHKNAME_E] == 'E' &&
	    isdigit(dp->pcd_filename[CHKNAME_THOUSANDS]) &&
	    isdigit(dp->pcd_filename[CHKNAME_HUNDREDS]) &&
	    isdigit(dp->pcd_filename[CHKNAME_TENS]) &&
	    isdigit(dp->pcd_filename[CHKNAME_ONES]) &&
	    dp->pcd_ext[CHKNAME_C] == 'C' &&
	    dp->pcd_ext[CHKNAME_H] == 'H' &&
	    dp->pcd_ext[CHKNAME_K] == 'K');
}

void
addEntryToCHKList(int chkNumber)
{
	/* silent failure on bogus value */
	if (chkNumber < 0 || chkNumber > MAXCHKVAL)
		return;
	CHKsList[chkNumber / NBBY] |= (1 << (chkNumber % NBBY));
}

static void
addToCHKList(struct pcdir *dp)
{
	int chknum;

	chknum = 1000 * (dp->pcd_filename[CHKNAME_THOUSANDS] - '0');
	chknum += 100 * (dp->pcd_filename[CHKNAME_HUNDREDS] - '0');
	chknum += 10 * (dp->pcd_filename[CHKNAME_TENS] - '0');
	chknum += (dp->pcd_filename[CHKNAME_ONES] - '0');
	addEntryToCHKList(chknum);
}

static int
inUseCHKName(int chkNumber)
{
	return (CHKsList[chkNumber / NBBY] & (1 << (chkNumber % NBBY)));
}

static void
appendToPath(struct pcdir *dp, char *thePath, int *theLen)
{
	int i = 0;

	/*
	 * Sometimes caller doesn't care about keeping track of the path
	 */
	if (thePath == NULL)
		return;

	/*
	 *  Prepend /
	 */
	if (*theLen < MAXPATHLEN)
		*(thePath + (*theLen)++) = '/';
	/*
	 *  Print out the file name part, but only up to the first
	 *  space.
	 */
	while (*theLen < MAXPATHLEN && i < PCFNAMESIZE) {
		/*
		 *  When we start seeing spaces we assume that's the
		 *  end of the interesting characters in the name.
		 */
		if ((dp->pcd_filename[i] == ' ') ||
		    !(pc_validchar(dp->pcd_filename[i])))
			break;
		*(thePath + (*theLen)++) = dp->pcd_filename[i++];
	}
	/*
	 *  Leave now, if we don't have an extension (or room for one)
	 */
	if ((dp->pcd_ext[i] == ' ') || ((*theLen) >= MAXPATHLEN) ||
	    (!(pc_validchar(dp->pcd_ext[i]))))
		return;
	/*
	 *  Tack on the extension
	 */
	*(thePath + (*theLen)++) = '.';
	i = 0;
	while ((*theLen < MAXPATHLEN) && (i < PCFEXTSIZE)) {
		if ((dp->pcd_ext[i] == ' ') || !(pc_validchar(dp->pcd_ext[i])))
			break;
		*(thePath + (*theLen)++) = dp->pcd_ext[i++];
	}
}

static void
printName(FILE *outDest, struct pcdir *dp)
{
	int i;
	for (i = 0; i < PCFNAMESIZE; i++) {
		if ((dp->pcd_filename[i] == ' ') ||
		    !(pc_validchar(dp->pcd_filename[i])))
			break;
		(void) fprintf(outDest, "%c", dp->pcd_filename[i]);
	}
	(void) fprintf(outDest, ".");
	for (i = 0; i < PCFEXTSIZE; i++) {
		if (!(pc_validchar(dp->pcd_ext[i])))
			break;
		(void) fprintf(outDest, "%c", dp->pcd_ext[i]);
	}
}

/*
 *  sanityCheckSize
 *	Make sure the size in the directory entry matches what is
 *	actually allocated.  If there is a mismatch, orphan all
 *	the allocated clusters.  Returns SIZE_MATCHED if everything matches
 *	up, TRUNCATED to indicate truncation was necessary.
 */
static int
sanityCheckSize(int fd, struct pcdir *dp, int32_t actualClusterCount,
    int isDir, int32_t startCluster, struct nameinfo *fullPathName,
    struct pcdir **orphanEntry)
{
	uint32_t sizeFromDir;
	int32_t ignorei = 0;
	int64_t bpc;

	bpc = TheBIOSParameterBlock.bpb.sectors_per_cluster *
	    TheBIOSParameterBlock.bpb.bytes_per_sector;
	sizeFromDir = extractSize(dp);
	if (isDir) {
		if (sizeFromDir == 0)
			return (SIZE_MATCHED);
	} else {
		if ((sizeFromDir > ((actualClusterCount - 1) * bpc)) &&
		    (sizeFromDir <= (actualClusterCount * bpc)))
			return (SIZE_MATCHED);
	}
	if (fullPathName != NULL) {
		fullPathName->references++;
		(void) fprintf(stderr, "%s\n", fullPathName->fullName);
	}
	squirrelPath(fullPathName, startCluster);
	(void) fprintf(stderr,
	    gettext("Truncating chain due to incorrect size "
	    "in directory.  Size from directory = %u bytes,\n"), sizeFromDir);
	if (actualClusterCount == 0) {
		(void) fprintf(stderr,
		    gettext("Zero bytes are allocated to the file.\n"));
	} else {
		(void) fprintf(stderr,
		    gettext("Allocated size in range %llu - %llu bytes.\n"),
		    ((actualClusterCount - 1) * bpc) + 1,
		    (actualClusterCount * bpc));
	}
	/*
	 * Use splitChain() to make an orphan that is the entire allocation
	 * chain.
	 */
	splitChain(fd, dp, startCluster, orphanEntry, &ignorei);
	return (TRUNCATED);
}

static int
noteUsage(int fd, int32_t startAt, struct pcdir *dp, struct pcdir *lp,
    int32_t longEntryStartCluster, int isHidden, int isDir,
    struct nameinfo *fullPathName)
{
	struct pcdir *orphanEntry;
	int32_t chain = startAt;
	int32_t count = 0;
	int savePathNextIteration = 0;
	int haveBad = 0;
	ClusterInfo *tmpl = NULL;

	while ((chain >= FIRST_CLUSTER) && (chain <= LastCluster)) {
		if ((markInUse(fd, chain, dp, lp, longEntryStartCluster,
		    isHidden ? HIDDEN : VISIBLE, &tmpl))
			!= CLINFO_NEWLY_ALLOCED)
			break;
		count++;
		if (savePathNextIteration == 1) {
			savePathNextIteration = 0;
			if (fullPathName != NULL)
				fullPathName->references++;
			squirrelPath(fullPathName, chain);
		}
		if (isMarkedBad(chain)) {
			haveBad = 1;
			savePathNextIteration = 1;
		}
		if (isHidden)
			HiddenClusterCount++;
		else if (isDir)
			DirClusterCount++;
		else
			FileClusterCount++;
		chain = nextInChain(chain);
	}
	/*
	 * Do a sanity check on the file size in the directory entry.
	 * This may create an orphaned cluster chain.
	 */
	if (sanityCheckSize(fd, dp, count, isDir, startAt,
	    fullPathName, &orphanEntry) == TRUNCATED) {
		/*
		 * The pre-existing directory entry has been truncated,
		 * so the chain associated with it no longer has any
		 * bad clusters.  Instead, the new orphan has them.
		 */
		if (haveBad > 0) {
			truncChainWithBadCluster(fd, orphanEntry, startAt);
		}
		haveBad = 0;
	}
	return (haveBad);
}

static void
storeInfoAboutEntry(int fd, struct pcdir *dp, struct pcdir *ldp, int depth,
    int32_t longEntryStartCluster, char *fullPath, int *fullLen)
{
	struct nameinfo *pathCopy;
	int32_t start;
	int haveBad;
	int hidden = (dp->pcd_attr & PCA_HIDDEN || dp->pcd_attr & PCA_SYSTEM);
	int dir = (dp->pcd_attr & PCA_DIR);
	int i;

	if (hidden)
		HiddenFileCount++;
	else if (dir)
		DirCount++;
	else
		FileCount++;
	appendToPath(dp, fullPath, fullLen);

	/*
	 * Make a copy of the name at this point.  We may want it to
	 * note the original source of an orphaned cluster.
	 */
	if ((pathCopy =
	    (struct nameinfo *)malloc(sizeof (struct nameinfo))) != NULL) {
		if ((pathCopy->fullName =
		    (char *)malloc(*fullLen + 1)) != NULL) {
			pathCopy->references = 0;
			(void) strncpy(pathCopy->fullName, fullPath, *fullLen);
			pathCopy->fullName[*fullLen] = '\0';
		} else {
			free(pathCopy);
			pathCopy = NULL;
		}
	}
	if (Verbose) {
		for (i = 0; i < depth; i++)
			(void) fprintf(stderr, "  ");
		if (hidden)
			(void) fprintf(stderr, "[");
		else if (dir)
			(void) fprintf(stderr, "|_");
		else
			(void) fprintf(stderr, gettext("(%06d) "), FileCount);
		printName(stderr, dp);
		if (hidden)
			(void) fprintf(stderr, "]");
		(void) fprintf(stderr,
		    gettext(", %u bytes, start cluster %d"),
		    extractSize(dp), extractStartCluster(dp));
		(void) fprintf(stderr, "\n");
	}
	start = extractStartCluster(dp);
	haveBad = noteUsage(fd, start, dp, ldp, longEntryStartCluster,
	    hidden, dir, pathCopy);
	if (haveBad > 0) {
		if (dir && pathCopy->fullName != NULL) {
			(void) fprintf(stderr,
			    gettext("Adjusting for bad allocation units in "
			    "the meta-data of:\n  "));
			(void) fprintf(stderr, pathCopy->fullName);
			(void) fprintf(stderr, "\n");
		}
		truncChainWithBadCluster(fd, dp, start);
	}
	if ((pathCopy != NULL) && (pathCopy->references == 0)) {
		free(pathCopy->fullName);
		free(pathCopy);
	}
}

static void
storeInfoAboutLabel(struct pcdir *dp)
{
	/*
	 * XXX eventually depth should be passed to this routine just
	 * as it is with storeInfoAboutEntry().  If it isn't zero, then
	 * we've got a bogus directory entry.
	 */
	if (Verbose) {
		(void) fprintf(stderr, gettext("** "));
		printName(stderr, dp);
		(void) fprintf(stderr, gettext(" **\n"));
	}
}

static void
searchChecks(struct pcdir *dp, int operation, char matchRequired,
    struct pcdir **found)
{
	/*
	 *  We support these searching operations:
	 *
	 *  PCFS_FIND_ATTR
	 *	look for the first file with a certain attribute
	 *	(e.g, find all hidden files)
	 *  PCFS_FIND_STATUS
	 *	look for the first file with a certain status
	 *	(e.g., the file has been marked deleted; making
	 *	its directory entry reusable)
	 *  PCFS_FIND_CHKS
	 *	look for all files with short names of the form
	 *	FILENNNN.CHK.  These are the file names we give
	 *	to chains of orphaned clusters we relink into the
	 *	file system.  This find facility allows us to seek
	 *	out all existing files of this naming form so that
	 *	we may create unique file names for new orphans.
	 */
	if (operation == PCFS_FIND_ATTR && dp->pcd_attr == matchRequired) {
		*found = dp;
	} else if (operation == PCFS_FIND_STATUS &&
	    dp->pcd_filename[0] == matchRequired) {
		*found = dp;
	} else if (operation == PCFS_FIND_CHKS && hasCHKName(dp)) {
		addToCHKList(dp);
	}
}

static void
catalogEntry(int fd, struct pcdir *dp, struct pcdir *longdp,
    int32_t currentCluster, int depth, char *recordPath, int *pathLen)
{
	if (dp->pcd_attr & PCA_LABEL) {
		storeInfoAboutLabel(dp);
	} else {
		storeInfoAboutEntry(fd, dp, longdp, depth, currentCluster,
		    recordPath, pathLen);
	}
}

/*
 * visitNodes()
 *
 * This is the main workhouse routine for traversing pcfs metadata.
 * There isn't a lot to the metadata.  Basically there is a root
 * directory somewhere (either in its own special place outside the
 * data area or in a data cluster).  The root directory (and all other
 * directories) are filled with a number of fixed size entries.  An
 * entry has the filename and extension, the file's attributes, the
 * file's size, and the starting data cluster of the storage allocated
 * to the file.  To determine which clusters are assigned to the file,
 * you start at the starting cluster entry in the FAT, and follow the
 * chain of entries in the FAT.
 *
 *	Arguments are:
 *	fd
 *		descriptor for accessing the raw file system data
 *	currentCluster
 *		original caller supplies the initial starting cluster,
 *		subsequent recursive calls are made with updated
 *		cluster numbers for the sub-directories.
 *	dirData
 *		pointer to the directory data bytes
 *	dirDataLen
 *		size of the whole buffer of data bytes (usually it is
 *		the size of a cluster, but the root directory on
 *		FAT12/16 is not necessarily the same size as a cluster).
 *	depth
 *		original caller should set it to zero (assuming they are
 *		starting from the root directory).  This number is used to
 *		change the indentation of file names presented as debug info.
 *	descend
 *		boolean indicates if we should descend into subdirectories.
 *	operation
 *		what, if any, matching should be performed.
 *		The PCFS_TRAVERSE_ALL operation is a depth first traversal
 *		of all nodes in the metadata tree, that tracks all the
 *		clusters in use (according to the meta-data, at least)
 *	matchRequired
 *		value to be matched (if any)
 *	found
 *		output parameter
 *		used to return pointer to a directory entry that matches
 *		the search requirement
 *		original caller should pass in a pointer to a NULL pointer.
 *	lastDirCluster
 *		output parameter
 *		if no match found, last cluster num of starting directory
 *	dirEnd
 *		output parameter
 *		if no match found, return parameter stores pointer to where
 *		new directory entry could be appended to existing directory
 *	recordPath
 *		output parameter
 *		as files are discovered, and directories traversed, this
 *		buffer is used to store the current full path name.
 *	pathLen
 *		output parameter
 *		this is in the integer length of the current full path name.
 */
static void
visitNodes(int fd, int32_t currentCluster, ClusterContents *dirData,
    int32_t dirDataLen, int depth, int descend, int operation,
    char matchRequired,  struct pcdir **found, int32_t *lastDirCluster,
    struct pcdir **dirEnd, char *recordPath, int *pathLen)
{
	struct pcdir *longdp = NULL;
	struct pcdir *dp;
	int32_t longStart;
	int withinLongName = 0;
	int saveLen = *pathLen;

	dp = dirData->dirp;

	/*
	 *  A directory entry where the first character of the name is
	 *  PCD_UNUSED indicates the end of the directory.
	 */
	while ((uchar_t *)dp < dirData->bytes + dirDataLen &&
	    dp->pcd_filename[0] != PCD_UNUSED) {
		/*
		 *  Handle the special case find operations.
		 */
		searchChecks(dp, operation, matchRequired, found);
		if (*found)
			break;
		/*
		 * Are we looking at part of a long file name entry?
		 * If so, we may need to note the start of the name.
		 * We don't do any further processing of long file
		 * name entries.
		 *
		 * We also skip deleted entries and the '.' and '..'
		 * entries.
		 */
		if ((dp->pcd_attr & PCDL_LFN_BITS) == PCDL_LFN_BITS) {
			if (!withinLongName) {
				withinLongName++;
				longStart = currentCluster;
				longdp = dp;
			}
			dp++;
			continue;
		} else if ((dp->pcd_filename[0] == PCD_ERASED) ||
		    (dp->pcd_filename[0] == '.')) {
			/*
			 * XXX - if we were within a long name, then
			 * its existence is bogus, because it is not
			 * attached to any real file.
			 */
			withinLongName = 0;
			dp++;
			continue;
		}
		withinLongName = 0;
		if (operation == PCFS_TRAVERSE_ALL)
			catalogEntry(fd, dp, longdp, longStart, depth,
			    recordPath, pathLen);
		longdp = NULL;
		longStart = 0;
		if (dp->pcd_attr & PCA_DIR && descend == PCFS_VISIT_SUBDIRS) {
			traverseDir(fd, extractStartCluster(dp), depth + 1,
			    descend, operation, matchRequired, found,
			    lastDirCluster, dirEnd, recordPath, pathLen);
			if (*found)
				break;
		}
		dp++;
		*pathLen = saveLen;
	}
	if (*found)
		return;
	if ((uchar_t *)dp < dirData->bytes + dirDataLen) {
		/*
		 * We reached the end of directory before the end of
		 * our provided data (a cluster).  That means this cluster
		 * is the last one in this directory's chain.  It also
		 * means we've just looked at the last directory entry.
		 */
		*lastDirCluster = currentCluster;
		*dirEnd = dp;
		return;
	}
	/*
	 * If there is more to the directory we'll go get it otherwise we
	 * are done traversing this directory.
	 */
	if ((currentCluster == FAKE_ROOTDIR_CLUST) ||
	    (lastInFAT(currentCluster))) {
		*lastDirCluster = currentCluster;
		return;
	} else {
		traverseDir(fd, nextInChain(currentCluster),
		    depth, descend, operation, matchRequired,
		    found, lastDirCluster, dirEnd, recordPath, pathLen);
		*pathLen = saveLen;
	}
}

/*
 *  traverseFromRoot()
 *	For use with 12 and 16 bit FATs that have a root directory outside
 *	of the file system.  This is a general purpose routine that
 *	can be used simply to visit all of the nodes in the metadata or
 *	to find the first instance of something, e.g., the first directory
 *	entry where the file is marked deleted.
 *
 *	Inputs are described in the commentary for visitNodes() above.
 */
void
traverseFromRoot(int fd, int depth, int descend, int operation,
    char matchRequired,  struct pcdir **found, int32_t *lastDirCluster,
    struct pcdir **dirEnd, char *recordPath, int *pathLen)
{
	visitNodes(fd, FAKE_ROOTDIR_CLUST, &TheRootDir, RootDirSize, depth,
	    descend, operation, matchRequired, found, lastDirCluster, dirEnd,
	    recordPath, pathLen);
}

/*
 *  traverseDir()
 *	For use with all FATs outside of the initial root directory on
 *	12 and 16 bit FAT file systems.  This is a general purpose routine
 *	that can be used simply to visit all of the nodes in the metadata or
 *	to find the first instance of something, e.g., the first directory
 *	entry where the file is marked deleted.
 *
 *	Unique Input is:
 *	startAt
 *		starting cluster of the directory
 *
 *	This is the cluster that is the first one in this directory.
 *	We read it right away, so we can provide it as data to visitNodes().
 *	Note that we cache this cluster as we read it, because it is
 *	metadata and we cache all metadata.  By doing so, we can
 *	keep pointers to directory entries for quickly moving around and
 *	fixing up any problems we find.  Of course if we get a big
 *	filesystem with a huge amount of metadata we may be hosed, as
 *	we'll likely run out of memory.
 *
 *	I believe in the future this will have to be addressed.  It
 *	may be possible to do more of the processing of problems
 *	within directories as they are cached, so that when memory
 *	runs short we can free cached directories we are already
 *	finished visiting.
 *
 *	The remainder of inputs are described in visitNodes() comments.
 */
void
traverseDir(int fd, int32_t startAt, int depth, int descend, int operation,
    char matchRequired,  struct pcdir **found, int32_t *lastDirCluster,
    struct pcdir **dirEnd, char *recordPath, int *pathLen)
{
	ClusterContents dirdata;
	int32_t dirdatasize = 0;

	if (startAt < FIRST_CLUSTER || startAt > LastCluster)
		return;

	if (readCluster(fd, startAt, &(dirdata.bytes), &dirdatasize,
	    RDCLUST_DO_CACHE) != RDCLUST_GOOD) {
		(void) fprintf(stderr,
		    gettext("Unable to get more directory entries!\n"));
		return;
	}

	if (operation == PCFS_TRAVERSE_ALL) {
		if (Verbose)
			(void) fprintf(stderr,
			    gettext("Directory traversal enters "
			    "allocation unit %d.\n"), startAt);
	}
	visitNodes(fd, startAt, &dirdata, dirdatasize, depth, descend,
	    operation, matchRequired, found, lastDirCluster, dirEnd,
	    recordPath, pathLen);
}

void
createCHKNameList(int fd)
{
	struct pcdir *ignorep1, *ignorep2;
	int32_t ignore32;
	char *ignorecp = NULL;
	char ignore = '\0';
	int ignoreint = 0;

	ignorep1 = ignorep2 = NULL;
	if (!OkayToRelink || CHKsList != NULL)
		return;

	/*
	 *  Allocate an array to keep a bit map of the integer
	 *  values used in CHK names.
	 */
	if ((CHKsList =
	    (uchar_t *)calloc(1, idivceil(MAXCHKVAL, NBBY))) == NULL) {
		OkayToRelink = 0;
		return;
	}

	/*
	 *  Search the root directory for all the files with names of
	 *  the form FILEXXXX.CHK.  The root directory is an area
	 *  outside of the file space on FAT12 and FAT16 file systems.
	 *  On FAT32 file systems, the root directory is in a file
	 *  area cluster just like any other directory.
	 */
	if (!IsFAT32) {
		traverseFromRoot(fd, 0, PCFS_NO_SUBDIRS, PCFS_FIND_CHKS,
		    ignore, &ignorep1, &ignore32, &ignorep2, ignorecp,
		    &ignoreint);
	} else {
		DirCount++;
		traverseDir(fd, TheBIOSParameterBlock.bpb32.root_dir_clust,
		    0, PCFS_NO_SUBDIRS, PCFS_FIND_CHKS, ignore,
		    &ignorep1, &ignore32, &ignorep2, ignorecp, &ignoreint);
	}
}


char *
nextAvailableCHKName(int *chosen)
{
	static char nameBuf[PCFNAMESIZE];
	int i;

	if (!OkayToRelink)
		return (NULL);

	nameBuf[CHKNAME_F] = 'F';
	nameBuf[CHKNAME_I] = 'I';
	nameBuf[CHKNAME_L] = 'L';
	nameBuf[CHKNAME_E] = 'E';

	for (i = 1; i <= MAXCHKVAL; i++) {
		if (!inUseCHKName(i))
			break;
	}
	if (i <= MAXCHKVAL) {
		nameBuf[CHKNAME_THOUSANDS] = '0' + (i / 1000);
		nameBuf[CHKNAME_HUNDREDS] = '0' + ((i % 1000) / 100);
		nameBuf[CHKNAME_TENS] = '0' + ((i % 100) / 10);
		nameBuf[CHKNAME_ONES] = '0' + (i % 10);
		*chosen = i;
		return (nameBuf);
	} else {
		(void) fprintf(stderr,
		    gettext("Sorry, no names available for "
		    "relinking orphan chains!\n"));
		OkayToRelink = 0;
		return (NULL);
	}
}

uint32_t
extractSize(struct pcdir *dp)
{
	uint32_t returnMe;

	read_32_bits((uchar_t *)&(dp->pcd_size), &returnMe);
	return (returnMe);
}

int32_t
extractStartCluster(struct pcdir *dp)
{
	uint32_t lo, hi;

	if (IsFAT32) {
		read_16_bits((uchar_t *)&(dp->un.pcd_scluster_hi), &hi);
		read_16_bits((uchar_t *)&(dp->pcd_scluster_lo), &lo);
		return ((int32_t)((hi << 16) | lo));
	} else {
		read_16_bits((uchar_t *)&(dp->pcd_scluster_lo), &lo);
		return ((int32_t)lo);
	}
}

static struct pcdir *
findAvailableRootDirEntSlot(int fd, int32_t *clusterWithSlot)
{
	struct pcdir *deletedEntry = NULL;
	struct pcdir *appendPoint = NULL;
	char *ignorecp = NULL;
	int ignore = 0;

	*clusterWithSlot = 0;

	/*
	 *  First off, try to find an erased entry in the root
	 *  directory.  The root directory is an area outside of the
	 *  file space on FAT12 and FAT16 file systems.  On FAT32 file
	 *  systems, the root directory is in a file area cluster just
	 *  like any other directory.
	 */
	if (!IsFAT32) {
		traverseFromRoot(fd, 0, PCFS_NO_SUBDIRS, PCFS_FIND_STATUS,
		    PCD_ERASED, &deletedEntry, clusterWithSlot,
		    &appendPoint, ignorecp, &ignore);
	} else {
		DirCount++;
		traverseDir(fd, TheBIOSParameterBlock.bpb32.root_dir_clust,
		    0, PCFS_NO_SUBDIRS, PCFS_FIND_STATUS, PCD_ERASED,
		    &deletedEntry, clusterWithSlot, &appendPoint, ignorecp,
		    &ignore);
	}
	/*
	 *  If we found a deleted file in the directory we'll overwrite
	 *  that entry.
	 */
	if (deletedEntry)
		return (deletedEntry);
	/*
	 *  If there is room at the end of the existing directory, we
	 *  should place the new entry there.
	 */
	if (appendPoint)
		return (appendPoint);
	/*
	 *  XXX need to grow the directory
	 */
	return (NULL);
}

static void
insertDirEnt(struct pcdir *slot, struct pcdir *entry, int32_t clusterWithSlot)
{
	(void) memcpy(slot, entry, sizeof (struct pcdir));
	markClusterModified(clusterWithSlot);
}

/*
 *  Convert current UNIX time into a PCFS timestamp (which is in local time).
 *
 *  Since the "seconds" field of that is only accurate to 2sec precision,
 *  we allow for the optional (used only for creation times on FAT) "msec"
 *  parameter that takes the fractional part.
 */
static void
getNow(struct pctime *pctp, uchar_t *msec)
{
	time_t		now;
	struct tm	tm;
	ushort_t	tim, dat;

	/*
	 * Disable daylight savings corrections - Solaris PCFS doesn't
	 * support such conversions yet. Save timestamps in local time.
	 */
	daylight = 0;

	(void) time(&now);
	(void) localtime_r(&now, &tm);

	dat = (tm.tm_year - 80) << YEARSHIFT;
	dat |= tm.tm_mon << MONSHIFT;
	dat |= tm.tm_mday << DAYSHIFT;
	tim = tm.tm_hour << HOURSHIFT;
	tim |= tm.tm_min << MINSHIFT;
	tim |= (tm.tm_sec / 2) << SECSHIFT;

	/*
	 * Sanity check. If we overflow the PCFS timestamp range
	 * we set the time to 01/01/1980, 00:00:00
	 */
	if (dat < 80 || dat > 227)
		dat = tim = 0;

	pctp->pct_date = LE_16(dat);
	pctp->pct_time = LE_16(tim);
	if (msec)
		*msec = (tm.tm_sec & 1) ? 100 : 0;
}

/*
 *  FAT file systems store the following time information in a directory
 *  entry:
 *		timestamp		member of "struct pcdir"
 * ======================================================================
 *		creation time		pcd_crtime.pct_time
 *		creation date		pcd_crtime.pct_date
 *		last access date	pcd_ladate
 *		last modify time	pcd_mtime.pct_time
 *		last modify date	pcd_mtime.pct_date
 *
 *  No access time is kept.
 */
static void
updateDirEnt_CreatTime(struct pcdir *dp)
{
	getNow(&dp->pcd_crtime, &dp->pcd_crtime_msec);
	markClusterModified(findImpactedCluster(dp));
}

static void
updateDirEnt_ModTimes(struct pcdir *dp)
{
	timestruc_t	ts;

	getNow(&dp->pcd_mtime, NULL);
	dp->pcd_ladate = dp->pcd_mtime.pct_date;
	dp->pcd_attr |= PCA_ARCH;
	markClusterModified(findImpactedCluster(dp));
}

struct pcdir *
addRootDirEnt(int fd, struct pcdir *new)
{
	struct pcdir *added;
	int32_t inCluster;

	if ((added = findAvailableRootDirEntSlot(fd, &inCluster)) != NULL) {
		insertDirEnt(added, new, inCluster);
		return (added);
	}
	return (NULL);
}

/*
 *  FAT12 and FAT16 have a root directory outside the normal file space,
 *  so we have separate routines for finding and reading the root directory.
 */
static off64_t
seekRootDirectory(int fd)
{
	off64_t seekto;

	/*
	 *  The RootDir immediately follows the FATs, which in
	 *  turn immediately follow the reserved sectors.
	 */
	seekto = (off64_t)TheBIOSParameterBlock.bpb.resv_sectors *
		    TheBIOSParameterBlock.bpb.bytes_per_sector +
		    (off64_t)FATSize * TheBIOSParameterBlock.bpb.num_fats +
		    (off64_t)PartitionOffset;
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Seeking root directory @%lld.\n"), seekto);
	return (lseek64(fd, seekto, SEEK_SET));
}

void
getRootDirectory(int fd)
{
	ssize_t bytesRead;

	if (TheRootDir.bytes != NULL)
		return;
	else if ((TheRootDir.bytes = (uchar_t *)malloc(RootDirSize)) == NULL) {
		mountSanityCheckFails();
		perror(gettext("No memory for a copy of the root directory"));
		(void) close(fd);
		exit(8);
	}

	if (seekRootDirectory(fd) < 0) {
		mountSanityCheckFails();
		perror(gettext("Cannot seek to RootDir"));
		(void) close(fd);
		exit(8);
	}

	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Reading root directory.\n"));
	if ((bytesRead = read(fd, TheRootDir.bytes, RootDirSize)) !=
	    RootDirSize) {
		mountSanityCheckFails();
		if (bytesRead < 0) {
			perror(gettext("Cannot read a RootDir"));
		} else {
			(void) fprintf(stderr,
			    gettext("Short read of RootDir\n"));
		}
		(void) close(fd);
		exit(8);
	}
	if (Verbose) {
		(void) fprintf(stderr,
		    gettext("Dump of root dir's first 256 bytes.\n"));
		header_for_dump();
		dump_bytes(TheRootDir.bytes, 256);
	}
}

void
writeRootDirMods(int fd)
{
	ssize_t bytesWritten;

	if (!TheRootDir.bytes) {
		(void) fprintf(stderr,
		    gettext("Internal error: No Root directory to write\n"));
		(void) close(fd);
		exit(12);
	}
	if (!RootDirModified) {
		if (Verbose) {
			(void) fprintf(stderr,
			    gettext("No root directory changes need to "
			    "be written.\n"));
		}
		return;
	}
	if (ReadOnly)
		return;
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Writing root directory.\n"));
	if (seekRootDirectory(fd) < 0) {
		perror(gettext("Cannot write the RootDir (seek failed)"));
		(void) close(fd);
		exit(12);
	}
	if ((bytesWritten = write(fd, TheRootDir.bytes, RootDirSize)) !=
	    RootDirSize) {
		if (bytesWritten < 0) {
			perror(gettext("Cannot write the RootDir"));
		} else {
			(void) fprintf(stderr,
			    gettext("Short write of root directory\n"));
		}
		(void) close(fd);
		exit(12);
	}
	RootDirModified = 0;
}

struct pcdir *
newDirEnt(struct pcdir *copyme)
{
	struct pcdir *ndp;

	if ((ndp = (struct pcdir *)calloc(1, sizeof (struct pcdir))) == NULL) {
		(void) fprintf(stderr, gettext("Out of memory to create a "
		    "new directory entry!\n"));
		return (ndp);
	}
	if (copyme)
		(void) memcpy(ndp, copyme, sizeof (struct pcdir));
	ndp->pcd_ext[CHKNAME_C] = 'C';
	ndp->pcd_ext[CHKNAME_H] = 'H';
	ndp->pcd_ext[CHKNAME_K] = 'K';
	updateDirEnt_CreatTime(ndp);
	updateDirEnt_ModTimes(ndp);
	return (ndp);
}

void
updateDirEnt_Size(struct pcdir *dp, uint32_t newSize)
{
	uchar_t *p = (uchar_t *)&(dp->pcd_size);
	store_32_bits(&p, newSize);
	markClusterModified(findImpactedCluster(dp));
}

void
updateDirEnt_Start(struct pcdir *dp, int32_t newStart)
{
	uchar_t *p = (uchar_t *)&(dp->pcd_scluster_lo);
	store_16_bits(&p, newStart & 0xffff);
	if (IsFAT32) {
		p = (uchar_t *)&(dp->un.pcd_scluster_hi);
		store_16_bits(&p, newStart >> 16);
	}
	markClusterModified(findImpactedCluster(dp));
}

void
updateDirEnt_Name(struct pcdir *dp, char *newName)
{
	int i;

	for (i = 0; i < PCFNAMESIZE; i++) {
		if (*newName)
			dp->pcd_filename[i] = *newName++;
		else
			dp->pcd_filename[i] = ' ';
	}
	markClusterModified(findImpactedCluster(dp));
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 * All rights reserved.
 */

/*
 * fsck_pcfs -- routines for manipulating the FAT.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <libintl.h>
#include <sys/dktp/fdisk.h>
#include <sys/fs/pc_fs.h>
#include <sys/fs/pc_dir.h>
#include <sys/fs/pc_label.h>
#include "pcfs_common.h"
#include "fsck_pcfs.h"

extern	int32_t	BytesPerCluster;
extern	int32_t	TotalClusters;
extern	int32_t	LastCluster;
extern	off64_t	FirstClusterOffset;
extern	off64_t	PartitionOffset;
extern	bpb_t	TheBIOSParameterBlock;
extern	int	ReadOnly;
extern	int	IsFAT32;
extern	int	Verbose;

static	uchar_t	*TheFAT;
static	int	FATRewriteNeeded = 0;

int32_t		FATSize;
short		FATEntrySize;

static off64_t
seekFAT(int fd)
{
	off64_t seekto;
	/*
	 *  The FAT(s) immediately follows the reserved sectors.
	 */
	seekto = TheBIOSParameterBlock.bpb.resv_sectors *
		TheBIOSParameterBlock.bpb.bytes_per_sector + PartitionOffset;
	return (lseek64(fd, seekto, SEEK_SET));
}

void
getFAT(int fd)
{
	ssize_t bytesRead;

	if (TheFAT != NULL) {
		return;
	} else if ((TheFAT = (uchar_t *)malloc(FATSize)) == NULL) {
		mountSanityCheckFails();
		perror(gettext("No memory for a copy of the FAT"));
		(void) close(fd);
		exit(7);
	}
	if (seekFAT(fd) < 0) {
		mountSanityCheckFails();
		perror(gettext("Cannot seek to FAT"));
		(void) close(fd);
		exit(7);
	}
	if (Verbose)
		(void) fprintf(stderr,
		    gettext("Reading FAT\n"));
	if ((bytesRead = read(fd, TheFAT, FATSize)) != FATSize) {
		mountSanityCheckFails();
		if (bytesRead < 0) {
			perror(gettext("Cannot read a FAT"));
		} else {
			(void) fprintf(stderr,
			    gettext("Short read of FAT."));
		}
		(void) close(fd);
		exit(7);
	}
	/*
	 * XXX - might want to read the other copies of the FAT
	 * for comparison and/or to use if the first one seems hosed.
	 */
	if (Verbose) {
		(void) fprintf(stderr,
		    gettext("Dump of FAT's first 32 bytes.\n"));
		header_for_dump();
		dump_bytes(TheFAT, 32);
	}
}

void
writeFATMods(int fd)
{
	ssize_t bytesWritten;

	if (TheFAT == NULL) {
		(void) fprintf(stderr,
		    gettext("Internal error: No FAT to write\n"));
		(void) close(fd);
		exit(11);
	}
	if (!FATRewriteNeeded) {
		if (Verbose) {
			(void) fprintf(stderr,
			    gettext("No FAT changes need to be written.\n"));
		}
		return;
	}
	if (ReadOnly)
		return;
	if (Verbose)
		(void) fprintf(stderr, gettext("Writing FAT\n"));
	if (seekFAT(fd) < 0) {
		perror(gettext("Cannot seek to FAT"));
		(void) close(fd);
		exit(11);
	}
	if ((bytesWritten = write(fd, TheFAT, FATSize)) != FATSize) {
		if (bytesWritten < 0) {
			perror(gettext("Cannot write FAT"));
		} else {
			(void) fprintf(stderr,
			    gettext("Short write of FAT."));
		}
		(void) close(fd);
		exit(11);
	}
	FATRewriteNeeded = 0;
}

/*
 *  checkFAT32CleanBit()
 *	Return non-zero if the bit indicating proper Windows shutdown has
 *	been set.
 */
int
checkFAT32CleanBit(int fd)
{
	getFAT(fd);
	return (TheFAT[WIN_SHUTDOWN_STATUS_BYTE] & WIN_SHUTDOWN_BIT_MASK);
}

static uchar_t *
findClusterEntryInFAT(int32_t currentCluster)
{
	int32_t idx;
	if (FATEntrySize == 32) {
		idx = currentCluster * 4;
	} else if (FATEntrySize == 16) {
		idx = currentCluster * 2;
	} else {
		idx = currentCluster + currentCluster/2;
	}
	return (TheFAT + idx);
}

/*
 *  {read,write}FATentry
 *	For the 16 and 32 bit FATs these routines are relatively easy
 *	to follow.
 *
 *	12 bit FATs are kind of strange, though.  The magic index for
 *	12 bit FATS computed below, 1.5 * clusterNum, is a
 *	simplification that there are 8 bits in a byte, so you need
 *	1.5 bytes per entry.
 *
 *	It's easiest to think about FAT12 entries in pairs:
 *
 *	---------------------------------------------
 *	| mid1 | low1 | low2 | high1 | high2 | mid2 |
 *	---------------------------------------------
 *
 *	Each box in the diagram represents a nibble (4 bits) of a FAT
 *	entry.  A FAT entry is made up of three nibbles.  So if you
 *	look closely, you'll see that first byte of the pair of
 *	entries contains the low and middle nibbles of the first
 *	entry.  The second byte has the low nibble of the second entry
 *	and the high nibble of the first entry.  Those two bytes alone
 *	are enough to read the first entry.  The second FAT entry is
 *	finished out by the last nibble pair.
 */
int32_t
readFATEntry(int32_t currentCluster)
{
	int32_t value;
	uchar_t *ep;

	ep = findClusterEntryInFAT(currentCluster);
	if (FATEntrySize == 32) {
		read_32_bits(ep, (uint32_t *)&value);
	} else if (FATEntrySize == 16) {
		read_16_bits(ep, (uint32_t *)&value);
		/*
		 *  Convert 16 bit entry to 32 bit if we are
		 *  into the reserved or higher values.
		 */
		if (value >= PCF_RESCLUSTER)
			value |= 0xFFF0000;
	} else {
		value = 0;
		if (currentCluster & 1) {
			/*
			 * Odd numbered cluster
			 */
			value = (((unsigned int)*ep++ & 0xf0) >> 4);
			value += (*ep << 4);
		} else {
			value = *ep++;
			value += ((*ep & 0x0f) << 8);
		}
		/*
		 *  Convert 12 bit entry to 32 bit if we are
		 *  into the reserved or higher values.
		 */
		if (value >= PCF_12BCLUSTER)
			value |= 0xFFFF000;
	}
	return (value);
}

void
writeFATEntry(int32_t currentCluster, int32_t value)
{
	uchar_t *ep;

	FATRewriteNeeded = 1;
	ep = findClusterEntryInFAT(currentCluster);
	if (FATEntrySize == 32) {
		store_32_bits(&ep, value);
	} else if (FATEntrySize == 16) {
		store_16_bits(&ep, value);
	} else {
		if (currentCluster & 1) {
			/*
			 * Odd numbered cluster
			 */
			*ep = (*ep & 0x0f) | ((value << 4) & 0xf0);
			ep++;
			*ep = (value >> 4) & 0xff;
		} else {
			*ep++ = value & 0xff;
			*ep = (*ep & 0xf0) | ((value >> 8) & 0x0f);
		}
	}
}

/*
 * reservedInFAT - Is this cluster marked in the reserved range?
 *	The range from PCF_RESCLUSTER32 to PCF_BADCLUSTER32 - 1,
 *	have been reserved by Microsoft.  No cluster should be
 *	marked with these; they are effectively invalid cluster values.
 */
int
reservedInFAT(int32_t clusterNum)
{
	int32_t e;

	e = readFATEntry(clusterNum);
	return (e >= PCF_RESCLUSTER32 && e < PCF_BADCLUSTER32);
}

/*
 *  badInFAT - Is this cluster marked as bad?  I.e., is it inaccessible?
 */
int
badInFAT(int32_t clusterNum)
{
	return (readFATEntry(clusterNum) == PCF_BADCLUSTER32);
}

/*
 *  lastInFAT - Is this cluster marked as free?  I.e., is it available
 *	for use?
 */
int
freeInFAT(int32_t clusterNum)
{
	return (readFATEntry(clusterNum) == PCF_FREECLUSTER);
}

/*
 *  lastInFAT - Is this cluster the last in its cluster chain?
 */
int
lastInFAT(int32_t clusterNum)
{
	return (readFATEntry(clusterNum) == PCF_LASTCLUSTER32);
}

/*
 *  markLastInFAT - Mark this cluster as the last in its cluster chain.
 */
void
markLastInFAT(int32_t clusterNum)
{
	writeFATEntry(clusterNum, PCF_LASTCLUSTER32);
}

void
markFreeInFAT(int32_t clusterNum)
{
	writeFATEntry(clusterNum, PCF_FREECLUSTER);
}

void
markBadInFAT(int32_t clusterNum)
{
	writeFATEntry(clusterNum, PCF_BADCLUSTER32);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999,2001 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright 2024 MNX Cloud, Inc.
 */

/*
 * fsck_pcfs -- main routines.
 */

#include <stdio.h>
#include <errno.h>
#include <err.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <strings.h>
#include <libintl.h>
#include <locale.h>
#include <unistd.h>
#include <stropts.h>
#include <sys/fcntl.h>
#include <sys/dktp/fdisk.h>
#include "getresponse.h"
#include "pcfs_common.h"
#include "fsck_pcfs.h"
#include "pcfs_bpb.h"

size_t bpsec = MINBPS;
int32_t BytesPerCluster;
int32_t TotalClusters;
int32_t LastCluster;
off64_t	FirstClusterOffset;
off64_t	PartitionOffset;
bpb_t	TheBIOSParameterBlock;

/*
 * {Output,Input}Image are the file names where we should write the
 * checked fs image and from which we should read the initial fs.
 * The image capability is designed for debugging purposes.
 */
static char	*OutputImage = NULL;
static char	*InputImage = NULL;
static int	WritableOnly = 0; /* -o w, check writable fs' only */
static int	Mflag = 0;	  /* -m, sanity check if fs is mountable */
static int	Preen = 0;	  /* -o p, preen; non-interactive */
/*
 * By default be quick; skip verify reads.
 * If the user wants more exhaustive checking,
 * they should run with the -o v option.
 */
static int	Quick = 1;

int	ReadOnly = 0;
int	IsFAT32 = 0;
int	Verbose = 0;

bool	AlwaysYes = false; /* -y or -Y, assume a yes answer to all questions */
bool	AlwaysNo = false; /* -n or -N, assume a no answer to all questions */

extern	ClusterContents	TheRootDir;

/*
 * Function definitions
 */

static void
passOne(int fd)
{
	if (!Quick)
		findBadClusters(fd);
	scanAndFixMetadata(fd);
}

static void
writeBackChanges(int fd)
{
	writeFATMods(fd);
	if (!IsFAT32)
		writeRootDirMods(fd);
	writeClusterMods(fd);
}

static void
tryOpen(int *fd, char *openMe, int oflag, int exitOnFailure)
{
	int saveError;

	if ((*fd = open(openMe, oflag)) < 0) {
		if (exitOnFailure == RETURN_ON_OPEN_FAILURE)
			return;
		saveError = errno;
		mountSanityCheckFails();
		(void) fprintf(stderr, "%s: ", openMe);
		(void) fprintf(stderr, strerror(saveError));
		(void) fprintf(stderr, "\n");
		exit(1);
	}
}

static void
doOpen(int *inFD, int *outFD, char *name, char *outName)
{
	if (ReadOnly) {
		tryOpen(inFD, name, O_RDONLY, EXIT_ON_OPEN_FAILURE);
		*outFD = -1;
	} else {
		tryOpen(inFD, name, O_RDWR, RETURN_ON_OPEN_FAILURE);
		if (*inFD < 0) {
			if (errno != EACCES || WritableOnly) {
				int saveError = errno;
				mountSanityCheckFails();
				(void) fprintf(stderr,
				    gettext("%s: "), name);
				(void) fprintf(stderr, strerror(saveError));
				(void) fprintf(stderr, "\n");
				exit(2);
			} else {
				tryOpen(inFD, name, O_RDONLY,
				    EXIT_ON_OPEN_FAILURE);
				AlwaysYes = false;
				AlwaysNo = true;
				ReadOnly = 1;
				*outFD = -1;
			}
		} else {
			*outFD = *inFD;
		}
	}

	if (outName != NULL) {
		tryOpen(outFD, outName, (O_RDWR | O_CREAT),
		    EXIT_ON_OPEN_FAILURE);
	}

	(void) printf("** %s %s\n", name,
	    ReadOnly ? gettext("(NO WRITE)") : "");
}

static void
openFS(char *special, int *inFD, int *outFD)
{
	struct stat dinfo;
	char *actualDisk = NULL;
	char *suffix = NULL;
	int rv;

	if (Verbose)
		(void) fprintf(stderr, gettext("Opening file system.\n"));

	if (InputImage == NULL) {
		actualDisk = stat_actual_disk(special, &dinfo, &suffix);
		/*
		 *  Destination exists, now find more about it.
		 */
		if (!(S_ISCHR(dinfo.st_mode))) {
			mountSanityCheckFails();
			(void) fprintf(stderr,
			    gettext("\n%s: device name must be a "
			    "character special device.\n"), actualDisk);
			exit(2);
		}
	} else {
		actualDisk = InputImage;
	}
	doOpen(inFD, outFD, actualDisk, OutputImage);
	rv = get_media_sector_size(*inFD, &bpsec);
	if (rv != 0) {
		(void) fprintf(stderr,
		    gettext("error detecting device sector size: %s\n"),
		    strerror(rv));
		exit(2);
	}
	if (!is_sector_size_valid(bpsec)) {
		(void) fprintf(stderr,
		    gettext("unsupported sector size: %zu\n"), bpsec);
		exit(2);
	}

	if (suffix) {
		if ((PartitionOffset =
		    findPartitionOffset(*inFD, bpsec, suffix)) < 0) {
			mountSanityCheckFails();
			(void) fprintf(stderr,
			    gettext("Unable to find logical drive %s\n"),
			    suffix);
			exit(2);
		} else if (Verbose) {
			(void) fprintf(stderr,
			    gettext("Partition starts at offset %lld\n"),
			    PartitionOffset);
		}
	} else {
		PartitionOffset = 0;
	}
}

void
usage(void)
{
	(void) fprintf(stderr,
	    gettext("pcfs Usage: fsck -F pcfs [-o v|p|w] special-file\n"));
	exit(1);
}

static
char *LegalOpts[] = {
#define	VFLAG 0
	"v",
#define	PFLAG 1
	"p",
#define	WFLAG 2
	"w",
#define	DFLAG 3
	"d",
#define	IFLAG 4
	"i",
#define	OFLAG 5
	"o",
	NULL
};

static void
parseSubOptions(char *optsstr)
{
	char *value;
	int c;

	while (*optsstr != '\0') {
		switch (c = getsubopt(&optsstr, LegalOpts, &value)) {
		case VFLAG:
			Quick = 0;
			break;
		case PFLAG:
			Preen++;
			break;
		case WFLAG:
			WritableOnly++;
			break;
		case DFLAG:
			Verbose++;
			break;
		case IFLAG:
			if (value == NULL) {
				missing_arg(LegalOpts[c]);
			} else {
				InputImage = value;
			}
			break;
		case OFLAG:
			if (value == NULL) {
				missing_arg(LegalOpts[c]);
			} else {
				OutputImage = value;
			}
			break;
		default:
			bad_arg(value);
			break;
		}
	}
}

static void
sanityCheckOpts(void)
{
	if (WritableOnly && ReadOnly) {
		(void) fprintf(stderr,
		    gettext("-w option may not be used with the -n "
		    "or -m options\n"));
		exit(4);
	}
}

static void
confirmMountable(char *special, int fd)
{
	char *printName;
	int okayToMount = 1;

	printName = InputImage ? InputImage : special;

	if (!IsFAT32) {
		/* make sure we can at least read the root directory */
		getRootDirectory(fd);
		if (TheRootDir.bytes == NULL)
			okayToMount = 0;
	} else {
		/* check the bit designed into FAT32 for this purpose */
		okayToMount = checkFAT32CleanBit(fd);
	}
	if (okayToMount) {
		(void) fprintf(stderr,
		    gettext("pcfs fsck: sanity check: %s okay\n"), printName);
		exit(0);
	} else {
		(void) fprintf(stderr,
		    gettext("pcfs fsck: sanity check: %s needs checking\n"),
		    printName);
		exit(32);
	}
}

void
mountSanityCheckFails(void)
{
	if (Mflag) {
		(void) fprintf(stderr,
		    gettext("pcfs fsck: sanity check failed: "));
	}
}

/*
 * preenBail
 *	Routine that other routines can call if they would go into a
 *	state where they need user input.  They can send an optional
 *	message string to be printed before the exit.  Caller should
 *	send a NULL string if they don't have an exit message.
 */
void
preenBail(char *outString)
{
	/*
	 *  If we are running in the 'preen' mode, we got here because
	 *  we reached a situation that would require user intervention.
	 *  We have no choice but to bail at this point.
	 */
	if (Preen) {
		if (outString)
			(void) printf("%s", outString);
		(void) printf(gettext("FILE SYSTEM FIX REQUIRES USER "
		    "INTERVENTION; RUN fsck MANUALLY.\n"));
		exit(36);
	}
}

int
main(int argc, char *argv[])
{
	char *string;
	int  ifd, ofd;
	int  c;

	(void) setlocale(LC_ALL, "");

#if !defined(TEXT_DOMAIN)
#define	TEXT_DOMAIN "SYS_TEST"
#endif
	(void) textdomain(TEXT_DOMAIN);
	if (init_yes() < 0)
		errx(2, gettext(ERR_MSG_INIT_YES), strerror(errno));

	if (argc < 2)
		usage();

	while ((c = getopt(argc, argv, "F:VYNynmo:")) != EOF) {
		switch (c) {
		case 'F':
			string = optarg;
			if (strcmp(string, "pcfs") != 0)
				usage();
			break;
		case 'V': {
				char	*opt_text;
				int	opt_count;

				(void) printf(gettext("fsck -F pcfs "));
				for (opt_count = 1; opt_count < argc;
				    opt_count++) {
					opt_text = argv[opt_count];
					if (opt_text)
						(void) printf(" %s ",
						    opt_text);
				}
				(void) printf("\n");
				fini_yes();
				exit(0);
			}
			break;
		case 'N':
		case 'n':
			AlwaysYes = false;
			AlwaysNo = true;
			ReadOnly = 1;
			break;
		case 'Y':
		case 'y':
			AlwaysYes = true;
			AlwaysNo = false;
			break;
		case 'm':
			Mflag++;
			ReadOnly = 1;
			break;
		case 'o':
			string = optarg;
			parseSubOptions(string);
			break;
		}
	}

	sanityCheckOpts();
	if (InputImage == NULL && (optind < 0 || optind >= argc))
		usage();

	openFS(argv[optind], &ifd, &ofd);
	readBPB(ifd);

	/*
	 * -m mountable fs check.  This call will not return.
	 */
	if (Mflag)
		confirmMountable(argv[optind], ifd);

	/*
	 *  Pass 1: Find any bad clusters and adjust the FAT and directory
	 *	entries accordingly
	 */
	passOne(ifd);

	/*
	 *  XXX - future passes?
	 *	Ideas:
	 *	    Data relocation for bad clusters with partial read success?
	 *	    Syncing backup FAT copies with main copy?
	 *	    Syncing backup root sector for FAT32?
	 */

	/*
	 *  No problems if we made it this far.
	 */
	printSummary(stdout);
	writeBackChanges(ofd);
	fini_yes();
	return (0);
}
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999,2000 by Sun Microsystems, Inc.
 * All rights reserved.
 * Copyright 2024 MNX Cloud, Inc.
 */

#ifndef _FSCK_PCFS_H
#define	_FSCK_PCFS_H

/*
 * Structures used by the pcfs file system checker.
 */

#ifdef __cplusplus
extern "C" {
#endif

#include <sys/types.h>

/*
 *  The root directory of FAT12/16 file systems doesn't sit in
 *  a cluster.
 */
#define	FAKE_ROOTDIR_CLUST	-1

/*
 *  The first available cluster number for a FAT fs is always the same, 2.
 */
#define	FIRST_CLUSTER		2

#define	RETURN_ON_OPEN_FAILURE	0
#define	EXIT_ON_OPEN_FAILURE	1

#define	NO_FAT_IN_SUMMARY	0
#define	INCLUDE_FAT_IN_SUMMARY	1

#define	RDCLUST_DONT_CACHE	0
#define	RDCLUST_DO_CACHE	1

/*
 *  Return values for sanityCheckSize()
 */
#define	SIZE_MATCHED	0
#define	TRUNCATED	1

#define	RDCLUST_MAX_RETRY 3
#define	RDCLUST_GOOD 0
#define	RDCLUST_FAIL -1
#define	RDCLUST_MEMERR -2
#define	RDCLUST_BADINPUT -3

typedef union clustDataTypes {
    struct pcdir	*dirp;
    uchar_t		*bytes;
} ClusterContents;

struct cached {
    int32_t	clusterNum;
    ClusterContents clusterData;
    short	modified;
    struct cached *next;
};

typedef struct cached CachedCluster;

struct nameinfo {
	char *fullName;
	int references;
};

/*
 * This structure is shared between all structures belonging to
 * a single file.  The refcnt is a 24 bit integer, that should be
 * sufficient for 4GB files, even when someone uses 256 byte clusters
 * (4K is the typical cluster size, 512 bytes is probably the minimum)
 * The inefficiency of using a bit field is compensated by the memory
 * savings and prevented paging on large filesystems.
 */
struct clinfo {
	struct pcdir	*dirent;
	union {
	    struct clinfo	*_nextfree;
	    struct pcdir	*_longent;
	}		_unionelem;
	int32_t		longEntStartClust;
	int		refcnt:24;
	uint_t		flags:8;
	uchar_t		*saved;
	struct nameinfo	*path;
};

/*
 * #define dirent conflicts with other dirent uses, so we used the
 * second element instead of the first one one as union for the free
 * list
 */
#define	longent		_unionelem._longent
#define	nextfree	_unionelem._nextfree

typedef struct clinfo ClusterInfo;

/*
 *  Return values for allocInUse
 */
#define	CLINFO_PREVIOUSLY_ALLOCED	1
#define	CLINFO_NEWLY_ALLOCED		0

#define	CLINFO_BAD	0x1
#define	CLINFO_ORPHAN	0x2
#define	CLINFO_HIDDEN	0x4

/*
 *	Traversal operations for wandering the file system metadata
 */
#define	PCFS_NO_SUBDIRS		0
#define	PCFS_VISIT_SUBDIRS	1

#define	PCFS_TRAVERSE_ALL	1	/* visit all nodes */
#define	PCFS_FIND_ATTR		2	/* search for matching attribute */
#define	PCFS_FIND_STATUS	3	/* search for same status */
#define	PCFS_FIND_CHKS		4	/* find FILENNNN.CHK files */

/*
 *  Booleans for markInUse, whether or not file is marked hidden.
 */
#define	VISIBLE 0
#define	HIDDEN  1

/*
 * Indices for various parts of the FILEnnnn.CHK name
 */
#define	CHKNAME_F	0
#define	CHKNAME_I	1
#define	CHKNAME_L	2
#define	CHKNAME_E	3
#define	CHKNAME_THOUSANDS	4
#define	CHKNAME_HUNDREDS	5
#define	CHKNAME_TENS	6
#define	CHKNAME_ONES	7
#define	CHKNAME_C	0
#define	CHKNAME_H	1
#define	CHKNAME_K	2

/*
 *  Largest value that will fit into our lost+found naming scheme of
 *  FILEnnnn.CHK.
 */
#define	MAXCHKVAL	9999

extern size_t bpsec;
extern bool AlwaysYes;	/* assume a yes answer to all questions */
extern bool AlwaysNo;	/* assume a no answer to all questions */

/*
 * Function prototypes
 */
extern struct pcdir *addRootDirEnt(int fd, struct pcdir *copyme);
extern struct pcdir *newDirEnt(struct pcdir *copyme);
extern int32_t extractStartCluster(struct pcdir *dp);
extern int32_t findImpactedCluster(struct pcdir *modified);
extern int32_t readFATEntry(int32_t currentCluster);
extern uint32_t extractSize(struct pcdir *dp);
extern int32_t nextInChain(int32_t currentCluster);
extern char *nextAvailableCHKName(int *chosen);
extern void truncChainWithBadCluster(int fd, struct pcdir *dp,
    int32_t startCluster);
extern void mountSanityCheckFails(void);
extern void markClusterModified(int32_t clusterNum);
extern void scanAndFixMetadata(int fd);
extern void updateDirEnt_Start(struct pcdir *dp, int32_t newStart);
extern void addEntryToCHKList(int chkNumber);
extern void createCHKNameList(int fd);
extern void updateDirEnt_Name(struct pcdir *dp, char *newName);
extern void updateDirEnt_Size(struct pcdir *dp, uint32_t newSize);
extern void getRootDirectory(int fd);
extern void writeClusterMods(int fd);
extern void writeRootDirMods(int fd);
extern void traverseFromRoot(int fd, int depth, int descend, int operation,
    char matchRequired,  struct pcdir **found, int32_t *lastDirCluster,
    struct pcdir **dirEnd, char *recordPath, int *pathLen);
extern void findBadClusters(int fd);
extern void markFreeInFAT(int32_t clusterNum);
extern void markLastInFAT(int32_t clusterNum);
extern void writeFATEntry(int32_t currentCluster, int32_t value);
extern void markBadInFAT(int32_t clusterNum);
extern void printSummary(FILE *outDest);
extern void squirrelPath(struct nameinfo *pathInfo, int32_t clusterNum);
extern void usingCHKName(void *nameCookie);
extern void writeFATMods(int fd);
extern void traverseDir(int fd, int32_t startAt, int depth, int descend,
    int operation, char matchRequired,  struct pcdir **found,
    int32_t *lastDirCluster, struct pcdir **dirEnd, char *recordPath,
    int *pathLen);
extern void splitChain(int fd, struct pcdir *dp, int32_t problemCluster,
    struct pcdir **newdp, int32_t *orphanStart);
extern void preenBail(char *outString);
extern void readBPB(int fd);
extern void getFAT(int fd);
extern int checkFAT32CleanBit(int fd);
extern int reservedInFAT(int32_t clusterNum);
extern int isMarkedBad(int32_t clusterNum);
extern int readCluster(int fd, int32_t clusterNum, uchar_t **data,
    int32_t *datasize, int shouldCache);
extern int freeInFAT(int32_t clusterNum);
extern int lastInFAT(int32_t clusterNum);
extern int markInUse(int fd, int32_t clusterNum, struct pcdir *referencer,
    struct pcdir *longRef, int32_t longStartCluster, int isHidden,
    ClusterInfo **template);
extern int badInFAT(int32_t clusterNum);

#ifdef __cplusplus
}
#endif

#endif /* _FSCK_PCFS_H */
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright (c) 1999 by Sun Microsystems, Inc.
 * All rights reserved.
 */

/*
 * fsck_pcfs -- inject.c
 *	Debugging routine that will insert random errors into the reads,
 *	so that you'll actually end up with some bad clusters.
 */

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>

extern ssize_t _read(int fildes, void *buf, size_t nbyte);

ssize_t
read(int fildes, void *buf, size_t nbyte)
{
	static int count = 0;

	if ((count++ >= 263 && count <= 267) ||
	    (count >= 381 && count <= 385) ||
	    (count >= 1014 && count <= 1019) ||
	    (count >= 1119 && count <= 1123) ||
	    (count >= 1888 && count <= 1892)) {
		errno = EIO;
		return (-1);
	}
	return (_read(fildes, buf, nbyte));
}