Loading...
   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
/*
 * Copyright (c) 2000-2003 Apple Computer, Inc. All rights reserved.
 *
 * @APPLE_LICENSE_HEADER_START@
 * 
 * The contents of this file constitute Original Code as defined in and
 * are subject to the Apple Public Source License Version 1.1 (the
 * "License").  You may not use this file except in compliance with the
 * License.  Please obtain a copy of the License at
 * http://www.apple.com/publicsource and read it before using this file.
 * 
 * This Original Code and all software distributed under the License are
 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT.  Please see the
 * License for the specific language governing rights and limitations
 * under the License.
 * 
 * @APPLE_LICENSE_HEADER_END@
 */
/*
	File:		FileExtentMapping.c

	Contains:	xxx put contents here xxx

	Version:	HFS Plus 1.0

	Written by:	Dave Heller, Mark Day

	Copyright:	© 1996-1999 by Apple Computer, Inc., all rights reserved.

	File Ownership:

		DRI:				Mark Day

		Other Contact:		xxx put other contact here xxx

		Technology:			xxx put technology here xxx

	Writers:

		(DSH)	Deric Horn
		(msd)	Mark Day
		(djb)	Don Brady

	Change History (most recent first):
	  <MacOSX>	  9/9/99	djb		Fix fcbModifiedMask flag testing logic.
	  <MacOSX>	 8/25/98	djb		Flush extents b-tree header if dirty (2371088).
	  <MacOSX>	 6/30/98	djb		Add functions NodesAreContiguous and ExtentsAreIntegral (for radar #2249539).
	  <MacOSX>	 6/23/98	djb		Changed DeallocFile to DeleteFile which now deletes the catalog record.
	  								Fixed UpdateExtentRecord to pass correct fcb to Btree routines. Fixed
	  								hfs+ bug in CreateExtentRecord (double dereference).
	  <MacOSX>	 5/20/98	djb		In ExtendFileC don't lie about the peof! (radar #2230094).
	  <MacOSX>	 4/17/98	djb		Add VCB locking.
	  <MacOSX>	  4/2/98	djb		Switch over to real BTree interface (no more BTreeWrapper.c).
	  <MacOSX>	 3/31/98	djb		Sync up with final HFSVolumes.h header file.

	  <CS24>	 1/23/98	msd		Bug 2208024: AllocContig is actually allocating one extent even
									though there is not enough contiguous space.
	  <CS23>	 12/2/97	DSH		GetFCBExtentRecord no longer static so DFA can use it.
	  <CS22>	10/20/97	msd		When allocating more space for a file, do the clump size
									calculations in ExtendFileC, not BlockAllocate. Undo change from
									<CS18>.
	  <CS21>	10/17/97	msd		Conditionalize DebugStrs.
	  <CS20>	10/16/97	msd		Simplify the code path for MapFileBlockC (logical to physical
									block mapping) in the typical case where the file isn't
									fragmented so badly that it has extents in the extents B-tree.
									Simplified some of the calculations for all cases.
	  <CS19>	10/13/97	DSH		FindExtentRecord & DeleteExtentRecord are also being used by DFA
									no longer static.
	  <CS18>	 10/6/97	msd		When extending a file, set the physical EOF to include any extra
									space allocated due to a file's clump size.
	  <CS17>	 9/19/97	msd		Remove the MapLogicalToPhysical SPI. It was never used and is
									not being tested anyway.
	  <CS16>	  9/5/97	msd		In CompareExtentKeys and CompareExtentKeysPlus, use the symbolic
									constants for key length. Don't DebugStr unless DEBUG_BUILD is
									set.
	  <CS15>	 7/24/97	djb		Add instrumentation to MapFileBlockC
	  <CS14>	 7/16/97	DSH		FilesInternal.i renamed FileMgrInternal.i to avoid name
									collision
	  <CS13>	 7/15/97	DSH		AdjEOF() mark the FCB as modified. (1664389)
	  <CS12>	  7/8/97	DSH		Loading PrecompiledHeaders from define passed in on C line
	  <CS11>	  7/3/97	msd		Bug #1663518. Remove DebugStr when setting the FCB extent record
									for a volume control file.
	  <CS10>	 6/27/97	msd		Moved enum kFirstFileRefnum to FilesInternal.
	   <CS9>	 6/24/97	djb		Include "CatalogPrivate.h"
	   <CS8>	 6/16/97	msd		Finish implementation of CreateLargeFile SPI.
	   <CS7>	 6/12/97	msd		Add stub for CreateLargeFile SPI.
	   <CS6>	  6/5/97	msd		Add MapLogicalToPhysical.
	   <CS5>	  6/2/97	msd		In TruncateFileC, don't update the extent record unless it was
									actually changed (prevents extra updates when truncating to the
									end of the extent, and it is the last extent of the file.) Added
									an AdjustEOF routine called by the assembly AdjEOF routine. It
									copies the EOF, physical length, and extent information from one
									FCB to all other FCBs for that fork.
	   <CS4>	 5/20/97	DSH		Removed const declaration in MapFileBlocC, const is benign when
									passing by value, and SC requires it to match prototype.
	   <CS3>	 5/15/97	msd		Change enum kResourceForkType from -1 to 0xFF since it is now
									unsigned. Change all forkType parameters to UInt8.
	   <CS2>	  5/7/97	msd		When checking for an unused extent descriptor, check the length,
									not the starting block.
	   <CS1>	 4/24/97	djb		first checked in
	 <HFS25>	 4/11/97	DSH		use extended VCB fields catalogRefNum, and extentsRefNum.
	 <HFS24>	  4/4/97	djb		Get in sync with volume format changes.
	 <HFS23>	 3/17/97	DSH		Casting to compile with SC.
	 <HFS22>	 2/26/97	msd		Add instrumentation in ExtendFileC and TruncateFileC. In
									CompareExtentKeys and CompareExtentKeysPlus, make sure the key
									lengths are correct.
	 <HFS21>	  2/5/97	msd		The comparison with fsBTStartOfIterationErr didn't work because
									the enum is an unsigned long; it is now casted to an OSErr
									before comparing.
	 <HFS20>	 1/31/97	msd		In FindExtentRecord, turn an fsBTStartOfIterationErr error into
									btNotFound.
	 <HFS19>	 1/28/97	msd		Fixed bug in MapFileBlockC where it returned the wrong number of
									bytes available at the given block number.  This could
									potentially cause programs to read or write over other files.
	 <HFS18>	 1/16/97	djb		Extent key compare procs now return SInt32. Fixed
									UpdateExtentRecord - it was passing a pointer to an ExtentKey
									pointer.
	 <HFS17>	 1/10/97	msd		Change TruncateFileC to call DellocateFork when the new PEOF is
									0. Fixes a fxRangeErr returned when no extents existed.
	 <HFS16>	  1/6/97	msd		Previous change prevents extent records from being removed if
									the files new PEOF is in the local (FCB/catalog) extents.
	 <HFS15>	  1/3/97	djb		Temp fix in TruncateFileC to prevent unwanted calls to
									TruncateExtents.
	 <HFS14>	12/23/96	msd		Previous change to SearchExtentFile didn't set up the outputs
									for hint and key when the FCB extent record wasn't full.
	 <HFS13>	12/20/96	msd		In SearchExtentFile, don't bother searching the extents file if
									the FCB's extent record wasn't full, or if the FCB was for the
									extents file itself. Modified SearchExtentRecord to return a
									Boolean to indicate that the record was not full.
	 <HFS12>	12/19/96	DSH		Changed refs from VCB to ExtendedVCB
	 <HFS11>	12/19/96	djb		Updated for new B-tree Manager interface.
	 <HFS10>	12/12/96	djb		Really use new SPI for GetCatalogNode.
	  <HFS9>	12/12/96	djb		Use new Catalog SPI for GetCatalogNode. Added Mark's changes to
									MapFileBlockC.
	  <HFS8>	12/11/96	msd		TruncateFileC must always release extents, even if PEOF hasn't
									changed (since allocation may have been rounded up due to clump
									size).
	  <HFS7>	12/10/96	msd		Check PRAGMA_LOAD_SUPPORTED before loading precompiled headers.
	  <HFS6>	 12/4/96	DSH		Precompiled headers
	  <HFS5>	11/26/96	msd		Add an exported routine to grow the parallel FCB table to
									accomodate the HFS+ ExtentRecord.
	  <HFS4>	11/26/96	msd		Convert internal routines to use ExtentKey and ExtentRecord
									(instead of the raw HFS structures).
	  <HFS3>	11/21/96	msd		Added CompareExtentKeysPlus().
	  <HFS2>	11/20/96	msd		Finish porting FXM to C.
	  <HFS1>	 11/6/96	DKH		first checked in

*/


#include "../../hfs.h"
#include "../../hfs_format.h"
#include "../../hfs_endian.h"

#include "../headers/FileMgrInternal.h"
#include "../headers/BTreesInternal.h"
#include "../headers/CatalogPrivate.h"		// calling a private catalog routine (LocateCatalogNode)

#include <sys/malloc.h>
 
/*
============================================================
Public (Exported) Routines:
============================================================
	DeAllocFile		Deallocate all disk space allocated to a specified file.
					Both forks are deallocated.

	ExtendFileC		Allocate more space to a given file.

	CompareExtentKeys
					Compare two extents file keys (a search key and a trial
					key).  Used by the BTree manager when searching for,
					adding, or deleting keys in the extents file of an HFS
					volume.
					
	CompareExtentKeysPlus
					Compare two extents file keys (a search key and a trial
					key).  Used by the BTree manager when searching for,
					adding, or deleting keys in the extents file of an HFS+
					volume.
					
	MapFileBlockC	Convert (map) an offset within a given file into a
					physical disk address.
					
	TruncateFileC	Truncates the disk space allocated to a file.  The file
					space is truncated to a specified new physical EOF, rounded
					up to the next allocation block boundry.  There is an option
					to truncate to the end of the extent containing the new EOF.
	
	FlushExtentFile
					Flush the extents file for a given volume.

	GrowParallelFCBs
					Make sure the parallel FCB entries are big enough to support
					the HFS+ ExtentRecord.  If not, the array is grown and the
					pre-existing data copied over.

	AdjustEOF
					Copy EOF, physical length, and extent records from one FCB
					to all other FCBs for that fork.  This is used when a file is
					grown or shrunk as the result of a Write, SetEOF, or Allocate.

	MapLogicalToPhysical
					Map some position in a file to a volume block number.  Also
					returns the number of contiguous bytes that are mapped there.
					This is a queued HFSDispatch call that does the equivalent of
					MapFileBlockC, using a parameter block.

============================================================
Internal Routines:
============================================================
	FindExtentRecord
					Search the extents BTree for a particular extent record.
	SearchExtentFile
					Search the FCB and extents file for an extent record that
					contains a given file position (in bytes).
	SearchExtentRecord
					Search a given extent record to see if it contains a given
					file position (in bytes).  Used by SearchExtentFile.
	ReleaseExtents
					Deallocate all allocation blocks in all extents of an extent
					data record.
	TruncateExtents
					Deallocate blocks and delete extent records for all allocation
					blocks beyond a certain point in a file.  The starting point
					must be the first file allocation block for some extent record
					for the file.
	DeallocateFork
					Deallocate all allocation blocks belonging to a given fork.
	UpdateExtentRecord
					If the extent record came from the extents file, write out
					the updated record; otherwise, copy the updated record into
					the FCB resident extent record.  If the record has no extents,
					and was in the extents file, then delete the record instead.
*/

static const SInt64 kTwoGigabytes = 0x80000000LL;

enum
{
	kDataForkType			= 0,
	kResourceForkType		= 0xFF,
	
	kPreviousRecord			= -1
};


static OSErr HFSPlusToHFSExtents(
	const HFSPlusExtentRecord	oldExtents,
	HFSExtentRecord				newExtents);

static OSErr FindExtentRecord(
	const ExtendedVCB		*vcb,
	UInt8					forkType,
	UInt32					fileID,
	UInt32					startBlock,
	Boolean					allowPrevious,
	HFSPlusExtentKey		*foundKey,
	HFSPlusExtentRecord		foundData,
	UInt32					*foundHint);

static OSErr DeleteExtentRecord(
	const ExtendedVCB		*vcb,
	UInt8					forkType,
	UInt32					fileID,
	UInt32					startBlock);

static OSErr CreateExtentRecord(
	const ExtendedVCB		*vcb,
	HFSPlusExtentKey		*key,
	HFSPlusExtentRecord		extents,
	UInt32					*hint);


static OSErr GetFCBExtentRecord(
	const FCB				*fcb,
	HFSPlusExtentRecord		extents);

static OSErr SearchExtentFile(
	const ExtendedVCB		*vcb,
	const FCB	 			*fcb,
	SInt64 					filePosition,
	HFSPlusExtentKey		*foundExtentKey,
	HFSPlusExtentRecord		foundExtentData,
	UInt32					*foundExtentDataIndex,
	UInt32					*extentBTreeHint,
	UInt32					*endingFABNPlusOne );

static OSErr SearchExtentRecord(
	const ExtendedVCB		*vcb,
	UInt32					searchFABN,
	const HFSPlusExtentRecord	extentData,
	UInt32					extentDataStartFABN,
	UInt32					*foundExtentDataOffset,
	UInt32					*endingFABNPlusOne,
	Boolean					*noMoreExtents);

static OSErr ReleaseExtents(
	ExtendedVCB				*vcb,
	const HFSPlusExtentRecord	extentRecord,
	UInt32					*numReleasedAllocationBlocks,
	Boolean 				*releasedLastExtent);

static OSErr DeallocateFork(
	ExtendedVCB 		*vcb,
	HFSCatalogNodeID	fileID,
	UInt8			forkType,
	HFSPlusExtentRecord	catalogExtents,
	Boolean *		recordDeleted);

static OSErr TruncateExtents(
	ExtendedVCB			*vcb,
	UInt8				forkType,
	UInt32				fileID,
	UInt32				startBlock,
	Boolean *			recordDeleted);

static OSErr UpdateExtentRecord (
	const ExtendedVCB		*vcb,
	FCB						*fcb,
	const HFSPlusExtentKey	*extentFileKey,
	const HFSPlusExtentRecord	extentData,
	UInt32					extentBTreeHint);

static Boolean ExtentsAreIntegral(
	const HFSPlusExtentRecord extentRecord,
	UInt32		mask,
	UInt32		*blocksChecked,
	Boolean		*checkedLastExtent);

//_________________________________________________________________________________
//
//	Routine:	FindExtentRecord
//
//	Purpose:	Search the extents BTree for an extent record matching the given
//				FileID, fork, and starting file allocation block number.
//
//	Inputs:
//		vcb				Volume to search
//		forkType		0 = data fork, -1 = resource fork
//		fileID			File's FileID (CatalogNodeID)
//		startBlock		Starting file allocation block number
//		allowPrevious	If the desired record isn't found and this flag is set,
//						then see if the previous record belongs to the same fork.
//						If so, then return it.
//
//	Outputs:
//		foundKey	The key data for the record actually found
//		foundData	The extent record actually found (NOTE: on an HFS volume, the
//					fourth entry will be zeroes.
//		foundHint	The BTree hint to find the node again
//_________________________________________________________________________________
static OSErr FindExtentRecord(
	const ExtendedVCB	*vcb,
	UInt8				forkType,
	UInt32				fileID,
	UInt32				startBlock,
	Boolean				allowPrevious,
	HFSPlusExtentKey	*foundKey,
	HFSPlusExtentRecord	foundData,
	UInt32				*foundHint)
{
	FCB *				fcb;
	BTreeIterator		*btIterator;
	FSBufferDescriptor	btRecord;
	OSErr				err;
	UInt16				btRecordSize;
	
	err = noErr;
	if (foundHint)
		*foundHint = 0;
	fcb = GetFileControlBlock(vcb->extentsRefNum);
	
	MALLOC(btIterator, BTreeIterator *, sizeof(*btIterator), M_TEMP, M_WAITOK);
	bzero(btIterator, sizeof(*btIterator));

	if (vcb->vcbSigWord == kHFSSigWord) {
		HFSExtentKey *		extentKeyPtr;
		HFSExtentRecord		extentData;

		extentKeyPtr = (HFSExtentKey*) &btIterator->key;
		extentKeyPtr->keyLength	= kHFSExtentKeyMaximumLength;
		extentKeyPtr->forkType = forkType;
		extentKeyPtr->fileID = fileID;
		extentKeyPtr->startBlock = startBlock;
		
		btRecord.bufferAddress = &extentData;
		btRecord.itemSize = sizeof(HFSExtentRecord);
		btRecord.itemCount = 1;

		err = BTSearchRecord(fcb, btIterator, &btRecord, &btRecordSize, btIterator);

		if (err == btNotFound && allowPrevious) {
			err = BTIterateRecord(fcb, kBTreePrevRecord, btIterator, &btRecord, &btRecordSize);

			//	A previous record may not exist, so just return btNotFound (like we would if
			//	it was for the wrong file/fork).
			if (err == (OSErr) fsBTStartOfIterationErr)		//¥¥ fsBTStartOfIterationErr is type unsigned long
				err = btNotFound;

			if (err == noErr) {
				//	Found a previous record.  Does it belong to the same fork of the same file?
				if (extentKeyPtr->fileID != fileID || extentKeyPtr->forkType != forkType)
					err = btNotFound;
			}
		}

		if (err == noErr) {
			UInt16	i;
			
			// Copy the found key back for the caller
			if (foundKey) {
				foundKey->keyLength  = kHFSPlusExtentKeyMaximumLength;
				foundKey->forkType   = extentKeyPtr->forkType;
				foundKey->pad        = 0;
				foundKey->fileID     = extentKeyPtr->fileID;
				foundKey->startBlock = extentKeyPtr->startBlock;
			}
			// Copy the found data back for the caller
			foundData[0].startBlock = extentData[0].startBlock;
			foundData[0].blockCount = extentData[0].blockCount;
			foundData[1].startBlock = extentData[1].startBlock;
			foundData[1].blockCount = extentData[1].blockCount;
			foundData[2].startBlock = extentData[2].startBlock;
			foundData[2].blockCount = extentData[2].blockCount;
			
			for (i = 3; i < kHFSPlusExtentDensity; ++i)
			{
				foundData[i].startBlock = 0;
				foundData[i].blockCount = 0;
			}
		}
	}
	else {		// HFS Plus volume
		HFSPlusExtentKey *	extentKeyPtr;
		HFSPlusExtentRecord	extentData;

		extentKeyPtr = (HFSPlusExtentKey*) &btIterator->key;
		extentKeyPtr->keyLength	 = kHFSPlusExtentKeyMaximumLength;
		extentKeyPtr->forkType	 = forkType;
		extentKeyPtr->pad		 = 0;
		extentKeyPtr->fileID	 = fileID;
		extentKeyPtr->startBlock = startBlock;
		
		btRecord.bufferAddress = &extentData;
		btRecord.itemSize = sizeof(HFSPlusExtentRecord);
		btRecord.itemCount = 1;

		err = BTSearchRecord(fcb, btIterator, &btRecord, &btRecordSize, btIterator);

		if (err == btNotFound && allowPrevious) {
			err = BTIterateRecord(fcb, kBTreePrevRecord, btIterator, &btRecord, &btRecordSize);

			//	A previous record may not exist, so just return btNotFound (like we would if
			//	it was for the wrong file/fork).
			if (err == (OSErr) fsBTStartOfIterationErr)		//¥¥ fsBTStartOfIterationErr is type unsigned long
				err = btNotFound;

			if (err == noErr) {
				//	Found a previous record.  Does it belong to the same fork of the same file?
				if (extentKeyPtr->fileID != fileID || extentKeyPtr->forkType != forkType)
					err = btNotFound;
			}
		}

		if (err == noErr) {
			// Copy the found key back for the caller
			if (foundKey)
				BlockMoveData(extentKeyPtr, foundKey, sizeof(HFSPlusExtentKey));
			// Copy the found data back for the caller
			BlockMoveData(&extentData, foundData, sizeof(HFSPlusExtentRecord));
		}
	}

	if (foundHint)
		*foundHint = btIterator->hint.nodeNum;
	FREE(btIterator, M_TEMP);	
	return err;
}



static OSErr CreateExtentRecord(
	const ExtendedVCB	*vcb,
	HFSPlusExtentKey	*key,
	HFSPlusExtentRecord	extents,
	UInt32				*hint)
{
	BTreeIterator * btIterator;
	FSBufferDescriptor	btRecord;
	UInt16				btRecordSize;
	OSErr				err;
	
	err = noErr;
	*hint = 0;

	MALLOC(btIterator, BTreeIterator *, sizeof(*btIterator), M_TEMP, M_WAITOK);
	bzero(btIterator, sizeof(*btIterator));
	
	if (vcb->vcbSigWord == kHFSSigWord) {
		HFSExtentKey *		keyPtr;
		HFSExtentRecord		data;
		
		btRecordSize = sizeof(HFSExtentRecord);
		btRecord.bufferAddress = &data;
		btRecord.itemSize = btRecordSize;
		btRecord.itemCount = 1;

		keyPtr = (HFSExtentKey*) &btIterator->key;
		keyPtr->keyLength	= kHFSExtentKeyMaximumLength;
		keyPtr->forkType	= key->forkType;
		keyPtr->fileID		= key->fileID;
		keyPtr->startBlock	= key->startBlock;
		
		err = HFSPlusToHFSExtents(extents, data);
	}
	else {		// HFS Plus volume
		btRecordSize = sizeof(HFSPlusExtentRecord);
		btRecord.bufferAddress = extents;
		btRecord.itemSize = btRecordSize;
		btRecord.itemCount = 1;

		BlockMoveData(key, &btIterator->key, sizeof(HFSPlusExtentKey));
	}

	if (err == noErr)
		err = BTInsertRecord(GetFileControlBlock(vcb->extentsRefNum), btIterator, &btRecord, btRecordSize);

	if (err == noErr)
		*hint = btIterator->hint.nodeNum;

	(void) BTFlushPath(GetFileControlBlock(vcb->extentsRefNum));
	
	FREE(btIterator, M_TEMP);	
	return err;
}


static OSErr DeleteExtentRecord(
	const ExtendedVCB	*vcb,
	UInt8				forkType,
	UInt32				fileID,
	UInt32				startBlock)
{
	BTreeIterator * btIterator;
	OSErr				err;
	
	err = noErr;

	MALLOC(btIterator, BTreeIterator *, sizeof(*btIterator), M_TEMP, M_WAITOK);
	bzero(btIterator, sizeof(*btIterator));
	
	if (vcb->vcbSigWord == kHFSSigWord) {
		HFSExtentKey *	keyPtr;

		keyPtr = (HFSExtentKey*) &btIterator->key;
		keyPtr->keyLength	= kHFSExtentKeyMaximumLength;
		keyPtr->forkType	= forkType;
		keyPtr->fileID		= fileID;
		keyPtr->startBlock	= startBlock;
	}
	else {		//	HFS Plus volume
		HFSPlusExtentKey *	keyPtr;

		keyPtr = (HFSPlusExtentKey*) &btIterator->key;
		keyPtr->keyLength	= kHFSPlusExtentKeyMaximumLength;
		keyPtr->forkType	= forkType;
		keyPtr->pad			= 0;
		keyPtr->fileID		= fileID;
		keyPtr->startBlock	= startBlock;
	}

	err = BTDeleteRecord(GetFileControlBlock(vcb->extentsRefNum), btIterator);
	(void) BTFlushPath(GetFileControlBlock(vcb->extentsRefNum));
	
	FREE(btIterator, M_TEMP);	
	return err;
}



//_________________________________________________________________________________
//
// Routine:		MapFileBlock
//
// Function: 	Maps a file position into a physical disk address.
//
// Input:		A2.L  -  VCB pointer
//				(A1,D1.W)  -  FCB pointer
//				D4.L  -  number of bytes desired
//				D5.L  -  file position (byte address)
//
// Output:		D3.L  -  physical start block
//				D6.L  -  number of contiguous bytes available (up to D4 bytes)
//				D0.L  -  result code												<01Oct85>
//						   0 = ok
//						   FXRangeErr = file position beyond mapped range			<17Oct85>
//						   FXOvFlErr = extents file overflow						<17Oct85>
//						   other = error											<17Oct85>
//
// Called By:	Log2Phys (read/write in place), Cache (map a file block).
//_________________________________________________________________________________

__private_extern__
OSErr MapFileBlockC (
	ExtendedVCB		*vcb,				// volume that file resides on
	FCB				*fcb,				// FCB of file
	size_t			numberOfBytes,		// number of contiguous bytes desired
	off_t			offset,				// starting offset within file (in bytes)
	daddr_t			*startSector,		// first sector (NOT an allocation block)
	size_t			*availableBytes)	// number of contiguous bytes (up to numberOfBytes)
{
	OSErr				err;
	UInt32				allocBlockSize;			//	Size of the volume's allocation block
	UInt32			sectorSize;
	HFSPlusExtentKey	foundKey;
	HFSPlusExtentRecord	foundData;
	UInt32				foundIndex;
	UInt32				hint;
	UInt32				firstFABN;				// file allocation block of first block in found extent
	UInt32				nextFABN;				// file allocation block of block after end of found extent
	off_t				dataEnd;				// (offset) end of range that is contiguous
	UInt32				sectorsPerBlock;		// Number of sectors per allocation block
	UInt32				startBlock;				// volume allocation block corresponding to firstFABN
	daddr_t				temp;
	off_t				tmpOff;

	allocBlockSize = vcb->blockSize;
	sectorSize = VCBTOHFS(vcb)->hfs_phys_block_size;
	
	err = SearchExtentFile(vcb, fcb, offset, &foundKey, foundData, &foundIndex, &hint, &nextFABN);
	if (err == noErr) {
		startBlock = foundData[foundIndex].startBlock;
		firstFABN = nextFABN - foundData[foundIndex].blockCount;
	}
	
	if (err != noErr)
	{
		return err;
	}

	//
	//	Determine the end of the available space.  It will either be the end of the extent,
	//	or the file's PEOF, whichever is smaller.
	//
	dataEnd = (off_t)((off_t)(nextFABN) * (off_t)(allocBlockSize));   // Assume valid data through end of this extent
	if (((off_t)fcb->ff_blocks * (off_t)allocBlockSize) < dataEnd)    // Is PEOF shorter?
		dataEnd = (off_t)fcb->ff_blocks * (off_t)allocBlockSize;  // Yes, so only map up to PEOF
	
	//	Compute the number of sectors in an allocation block
	sectorsPerBlock = allocBlockSize / sectorSize;	// sectors per allocation block
	
	//
	//	Compute the absolute sector number that contains the offset of the given file
	//	offset in sectors from start of the extent +
	//      offset in sectors from start of allocation block space
	//
	temp = (daddr_t)((offset - (off_t)((off_t)(firstFABN) * (off_t)(allocBlockSize)))/sectorSize);
	temp += startBlock * sectorsPerBlock;

	/* Add in any volume offsets */
	if (vcb->vcbSigWord == kHFSPlusSigWord)
		temp += vcb->hfsPlusIOPosOffset / sectorSize;
	else
		temp += vcb->vcbAlBlSt;
	
	//	Return the desired sector for file position "offset"
	*startSector = temp;
	
	//
	//	Determine the number of contiguous bytes until the end of the extent
	//	(or the amount they asked for, whichever comes first).
	//
	if (availableBytes)
	{
		tmpOff = dataEnd - offset;
		if (tmpOff > (off_t)(numberOfBytes))
			*availableBytes = numberOfBytes;  // more there than they asked for, so pin the output
		else
			*availableBytes = tmpOff;
	}
	return noErr;
}


//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	ReleaseExtents
//
//	Function: 	Release the extents of a single extent data record.
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr ReleaseExtents(
	ExtendedVCB 			*vcb,
	const HFSPlusExtentRecord	extentRecord,
	UInt32					*numReleasedAllocationBlocks,
	Boolean 				*releasedLastExtent)
{
	UInt32	extentIndex;
	UInt32	numberOfExtents;
	OSErr	err = noErr;
	
	*numReleasedAllocationBlocks = 0;
	*releasedLastExtent = false;
	
	if (vcb->vcbSigWord == kHFSPlusSigWord)
		numberOfExtents = kHFSPlusExtentDensity;
	else
		numberOfExtents = kHFSExtentDensity;

	for( extentIndex = 0; extentIndex < numberOfExtents; extentIndex++)
	{
		UInt32	numAllocationBlocks;
		
		// Loop over the extent record and release the blocks associated with each extent.
		
		numAllocationBlocks = extentRecord[extentIndex].blockCount;
		if ( numAllocationBlocks == 0 )
		{
			*releasedLastExtent = true;
			break;
		}

		err = BlockDeallocate( vcb, extentRecord[extentIndex].startBlock, numAllocationBlocks );
		if ( err != noErr )
			break;
					
		*numReleasedAllocationBlocks += numAllocationBlocks;		//	bump FABN to beg of next extent
	}

	return( err );
}



//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	TruncateExtents
//
//	Purpose:	Delete extent records whose starting file allocation block number
//				is greater than or equal to a given starting block number.  The
//				allocation blocks represented by the extents are deallocated.
//
//	Inputs:
//		vcb			Volume to operate on
//		fileID		Which file to operate on
//		startBlock	Starting file allocation block number for first extent
//					record to delete.
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr TruncateExtents(
	ExtendedVCB		*vcb,
	UInt8			forkType,
	UInt32			fileID,
	UInt32			startBlock,
	Boolean *		recordDeleted)
{
	OSErr				err;
	UInt32				numberExtentsReleased;
	Boolean				releasedLastExtent;
	UInt32				hint;
	HFSPlusExtentKey	key;
	HFSPlusExtentRecord	extents;

	while (true) {
		err = FindExtentRecord(vcb, forkType, fileID, startBlock, false, &key, extents, &hint);
		if (err != noErr) {
			if (err == btNotFound)
				err = noErr;
			break;
		}
		
		err = ReleaseExtents( vcb, extents, &numberExtentsReleased, &releasedLastExtent );
		if (err != noErr) break;
		
		err = DeleteExtentRecord(vcb, forkType, fileID, startBlock);
		if (err != noErr) break;

		*recordDeleted = true;
		startBlock += numberExtentsReleased;
	}
	
	return err;
}



//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	DeallocateFork
//
//	Function: 	De-allocates all disk space allocated to a specified fork.
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr DeallocateFork(
	ExtendedVCB 		*vcb,
	HFSCatalogNodeID	fileID,
	UInt8			forkType,
	HFSPlusExtentRecord	catalogExtents,
	Boolean *		recordDeleted) /* true if a record was deleted */
{
	OSErr				err;
	UInt32				numReleasedAllocationBlocks;
	Boolean				releasedLastExtent;
	
	//	Release the catalog extents
	err = ReleaseExtents( vcb, catalogExtents, &numReleasedAllocationBlocks, &releasedLastExtent );
	// Release the extra extents, if present
	if (err == noErr && !releasedLastExtent)
		err = TruncateExtents(vcb, forkType, fileID, numReleasedAllocationBlocks, recordDeleted);

	return( err );
}

//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	FlushExtentFile
//
//	Function: 	Flushes the extent file for a specified volume
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

__private_extern__
OSErr FlushExtentFile( ExtendedVCB *vcb )
{
	FCB *	fcb;
	OSErr	err;
	
	fcb = GetFileControlBlock(vcb->extentsRefNum);
	err = BTFlushPath(fcb);
	if ( err == noErr )
	{
		// If the FCB for the extent "file" is dirty, mark the VCB as dirty.
		
        if (FTOC(fcb)->c_flag & C_MODIFIED)
		{
			MarkVCBDirty( vcb );
		//	err = FlushVolumeControlBlock( vcb );
		}
	}
	
	return( err );
}


//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	CompareExtentKeys
//
//	Function: 	Compares two extent file keys (a search key and a trial key) for
//				an HFS volume.
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

__private_extern__
SInt32 CompareExtentKeys( const HFSExtentKey *searchKey, const HFSExtentKey *trialKey )
{
	SInt32	result;		//	± 1
	
	#if DEBUG_BUILD
		if (searchKey->keyLength != kHFSExtentKeyMaximumLength)
			DebugStr("\pHFS: search Key is wrong length");
		if (trialKey->keyLength != kHFSExtentKeyMaximumLength)
			DebugStr("\pHFS: trial Key is wrong length");
	#endif
	
	result = -1;		//	assume searchKey < trialKey
	
	if (searchKey->fileID == trialKey->fileID) {
		//
		//	FileNum's are equal; compare fork types
		//
		if (searchKey->forkType == trialKey->forkType) {
			//
			//	Fork types are equal; compare allocation block number
			//
			if (searchKey->startBlock == trialKey->startBlock) {
				//
				//	Everything is equal
				//
				result = 0;
			}
			else {
				//
				//	Allocation block numbers differ; determine sign
				//
				if (searchKey->startBlock > trialKey->startBlock)
					result = 1;
			}
		}
		else {
			//
			//	Fork types differ; determine sign
			//
			if (searchKey->forkType > trialKey->forkType)
				result = 1;
		}
	}
	else {
		//
		//	FileNums differ; determine sign
		//
		if (searchKey->fileID > trialKey->fileID)
			result = 1;
	}
	
	return( result );
}



//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	CompareExtentKeysPlus
//
//	Function: 	Compares two extent file keys (a search key and a trial key) for
//				an HFS volume.
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

__private_extern__
SInt32 CompareExtentKeysPlus( const HFSPlusExtentKey *searchKey, const HFSPlusExtentKey *trialKey )
{
	SInt32	result;		//	± 1
	
	#if DEBUG_BUILD
		if (searchKey->keyLength != kHFSPlusExtentKeyMaximumLength)
			DebugStr("\pHFS: search Key is wrong length");
		if (trialKey->keyLength != kHFSPlusExtentKeyMaximumLength)
			DebugStr("\pHFS: trial Key is wrong length");
	#endif
	
	result = -1;		//	assume searchKey < trialKey
	
	if (searchKey->fileID == trialKey->fileID) {
		//
		//	FileNum's are equal; compare fork types
		//
		if (searchKey->forkType == trialKey->forkType) {
			//
			//	Fork types are equal; compare allocation block number
			//
			if (searchKey->startBlock == trialKey->startBlock) {
				//
				//	Everything is equal
				//
				result = 0;
			}
			else {
				//
				//	Allocation block numbers differ; determine sign
				//
				if (searchKey->startBlock > trialKey->startBlock)
					result = 1;
			}
		}
		else {
			//
			//	Fork types differ; determine sign
			//
			if (searchKey->forkType > trialKey->forkType)
				result = 1;
		}
	}
	else {
		//
		//	FileNums differ; determine sign
		//
		if (searchKey->fileID > trialKey->fileID)
			result = 1;
	}
	
	return( result );
}

/*
 * Add a file extent to a file.
 *
 * Used by hfs_extendfs to extend the volume allocation bitmap file.
 *
 */
__private_extern__
int
AddFileExtent(ExtendedVCB *vcb, FCB *fcb, UInt32 startBlock, UInt32 blockCount)
{
	HFSPlusExtentKey foundKey;
	HFSPlusExtentRecord foundData;
	UInt32 foundIndex;
	UInt32 hint;
	UInt32 nextBlock;
	SInt64 peof;
	int i;
	int error;

	peof = (SInt64)(fcb->ff_blocks + blockCount) * (SInt64)vcb->blockSize;

	error = SearchExtentFile(vcb, fcb, peof-1, &foundKey, foundData, &foundIndex, &hint, &nextBlock);
	if (error != fxRangeErr)
		return (EBUSY);

	/*
	 * Add new extent.  See if there is room in the current record.
	 */
	if (foundData[foundIndex].blockCount != 0)
		++foundIndex;
	if (foundIndex == kHFSPlusExtentDensity) {
		/*
		 * Existing record is full so create a new one.
		 */
		foundKey.keyLength = kHFSPlusExtentKeyMaximumLength;
		foundKey.forkType = kDataForkType;
		foundKey.pad = 0;
		foundKey.fileID = FTOC(fcb)->c_fileid;
		foundKey.startBlock = nextBlock;
		
		foundData[0].startBlock = startBlock;
		foundData[0].blockCount = blockCount;
		
		/* zero out remaining extents. */
		for (i = 1; i < kHFSPlusExtentDensity; ++i) {
			foundData[i].startBlock = 0;
			foundData[i].blockCount = 0;
		}

		foundIndex = 0;

		error = CreateExtentRecord(vcb, &foundKey, foundData, &hint);
		if (error == fxOvFlErr)
			error = dskFulErr;
	} else {
		/* 
		 * Add a new extent into existing record.
		 */
		foundData[foundIndex].startBlock = startBlock;
		foundData[foundIndex].blockCount = blockCount;
		error = UpdateExtentRecord(vcb, fcb, &foundKey, foundData, hint);
	}
	(void) FlushExtentFile(vcb);

	return (error);
}


//_________________________________________________________________________________
//
// Routine:		Extendfile
//
// Function: 	Extends the disk space allocated to a file.
//
// Input:		A2.L  -  VCB pointer
//				A1.L  -  pointer to FCB array
//				D1.W  -  file refnum
//				D3.B  -  option flags
//							kEFContigMask - force contiguous allocation
//							kEFAllMask - allocate all requested bytes or none
//							NOTE: You may not set both options.
//				D4.L  -  number of additional bytes to allocate
//
// Output:		D0.W  -  result code
//							 0 = ok
//							 -n = IO error
//				D6.L  -  number of bytes allocated
//
// Called by:	FileAloc,FileWrite,SetEof
//
// Note: 		ExtendFile updates the PEOF in the FCB.
//_________________________________________________________________________________

__private_extern__
OSErr ExtendFileC (
	ExtendedVCB		*vcb,				// volume that file resides on
	FCB				*fcb,				// FCB of file to truncate
	SInt64			bytesToAdd,			// number of bytes to allocate
	UInt32			blockHint,			// desired starting allocation block
	UInt32			flags,				// EFContig and/or EFAll
	SInt64			*actualBytesAdded)	// number of bytes actually allocated
{
	OSErr				err;
	UInt32				volumeBlockSize;
	SInt64				blocksToAdd;
	SInt64				bytesThisExtent;
	HFSPlusExtentKey	foundKey;
	HFSPlusExtentRecord	foundData;
	UInt32				foundIndex;
	UInt32				hint;
	UInt32				nextBlock;
	UInt32				startBlock;
	Boolean				allOrNothing;
	Boolean				forceContig;
	Boolean				wantContig;
	Boolean				useMetaZone;
	Boolean				needsFlush;
	UInt32				actualStartBlock;
	UInt32				actualNumBlocks;
	UInt32				numExtentsPerRecord;
	SInt64				maximumBytes;
	SInt64				peof;
	UInt32				prevblocks;
	

	needsFlush = false;
	*actualBytesAdded = 0;
	volumeBlockSize = vcb->blockSize;
	allOrNothing = ((flags & kEFAllMask) != 0);
	forceContig = ((flags & kEFContigMask) != 0);
	prevblocks = fcb->ff_blocks;

	if (vcb->vcbSigWord == kHFSPlusSigWord)
		numExtentsPerRecord = kHFSPlusExtentDensity;
	else
		numExtentsPerRecord = kHFSExtentDensity;

	//
	//	Make sure the request and new PEOF are less than 2GB if HFS.
	//
	if (vcb->vcbSigWord == kHFSSigWord) {
		if (bytesToAdd >=  kTwoGigabytes)
			goto Overflow;
		if ((((SInt64)fcb->ff_blocks * (SInt64)volumeBlockSize) + bytesToAdd) >= kTwoGigabytes)
			goto Overflow;
	}
	//
	//	Determine how many blocks need to be allocated.
	//	Round up the number of desired bytes to add.
	//
	blocksToAdd = howmany(bytesToAdd, volumeBlockSize);
	bytesToAdd = (SInt64)((SInt64)blocksToAdd * (SInt64)volumeBlockSize);

	/*
	 * For deferred allocations just reserve the blocks.
	 */
	if ((flags & kEFDeferMask)
	&&  (vcb->vcbSigWord == kHFSPlusSigWord)
	&&  (bytesToAdd < (SInt64)HFS_MAX_DEFERED_ALLOC)
	&&  (blocksToAdd < hfs_freeblks(VCBTOHFS(vcb), 1))) {
		fcb->ff_unallocblocks += blocksToAdd;
		vcb->loanedBlocks     += blocksToAdd;
		FTOC(fcb)->c_blocks   += blocksToAdd;
		fcb->ff_blocks        += blocksToAdd;

		FTOC(fcb)->c_flag |= C_MODIFIED | C_FORCEUPDATE;
		*actualBytesAdded = bytesToAdd;
		return (0);
	}
	/* 
	 * Give back any unallocated blocks before doing real allocations.
	 */
	if (fcb->ff_unallocblocks > 0) {
		blocksToAdd += fcb->ff_unallocblocks;
		bytesToAdd = (SInt64)blocksToAdd * (SInt64)volumeBlockSize;

		vcb->loanedBlocks     -= fcb->ff_unallocblocks;
		FTOC(fcb)->c_blocks   -= fcb->ff_unallocblocks;
		fcb->ff_blocks        -= fcb->ff_unallocblocks;
		fcb->ff_unallocblocks  = 0;
	}

	//
	//	If the file's clump size is larger than the allocation block size,
	//	then set the maximum number of bytes to the requested number of bytes
	//	rounded up to a multiple of the clump size.
	//
	if ((vcb->vcbClpSiz > volumeBlockSize)
	&&  (bytesToAdd < (SInt64)HFS_MAX_DEFERED_ALLOC)
	&&  (flags & kEFNoClumpMask) == 0) {
		maximumBytes = (SInt64)howmany(bytesToAdd, vcb->vcbClpSiz);
		maximumBytes *= vcb->vcbClpSiz;
	} else {
		maximumBytes = bytesToAdd;
	}
	
	//
	//	Compute new physical EOF, rounded up to a multiple of a block.
	//
	if ((vcb->vcbSigWord == kHFSSigWord) && ((((SInt64)fcb->ff_blocks * (SInt64)volumeBlockSize) + bytesToAdd) >= kTwoGigabytes))	//	Too big?
		if (allOrNothing)					// Yes, must they have it all?
			goto Overflow;						// Yes, can't have it
		else {
			--blocksToAdd;						// No, give give 'em one block less
			bytesToAdd -= volumeBlockSize;
		}

	//
	//	If allocation is all-or-nothing, make sure there are
	//	enough free blocks on the volume (quick test).
	//
	if (allOrNothing &&
	    (blocksToAdd > hfs_freeblks(VCBTOHFS(vcb), flags & kEFReserveMask))) {
		err = dskFulErr;
		goto ErrorExit;
	}
	
	//
	//	See if there are already enough blocks allocated to the file.
	//
	peof = ((SInt64)fcb->ff_blocks * (SInt64)volumeBlockSize) + bytesToAdd;  // potential new PEOF
	err = SearchExtentFile(vcb, fcb, peof-1, &foundKey, foundData, &foundIndex, &hint, &nextBlock);
	if (err == noErr) {
		//	Enough blocks are already allocated.  Just update the FCB to reflect the new length.
		fcb->ff_blocks = peof / volumeBlockSize;
		FTOC(fcb)->c_blocks += (bytesToAdd / volumeBlockSize);
		FTOC(fcb)->c_flag |= C_MODIFIED | C_FORCEUPDATE;
		goto Exit;
	}
	if (err != fxRangeErr)		// Any real error?
		goto ErrorExit;				// Yes, so exit immediately

	//
	//	Adjust the PEOF to the end of the last extent.
	//
	peof = (SInt64)((SInt64)nextBlock * (SInt64)volumeBlockSize);			// currently allocated PEOF
	bytesThisExtent = (SInt64)(nextBlock - fcb->ff_blocks) * (SInt64)volumeBlockSize;
	if (bytesThisExtent != 0) {
		fcb->ff_blocks = nextBlock;
		FTOC(fcb)->c_blocks += (bytesThisExtent / volumeBlockSize);
		FTOC(fcb)->c_flag |= C_MODIFIED;
		bytesToAdd -= bytesThisExtent;
	}
	
	//
	//	Allocate some more space.
	//
	//	First try a contiguous allocation (of the whole amount).
	//	If that fails, get whatever we can.
	//		If forceContig, then take whatever we got
	//		else, keep getting bits and pieces (non-contig)
	err = noErr;
	wantContig = true;
	useMetaZone = flags & kEFMetadataMask;
	vcb->vcbFreeExtCnt = 0;	/* For now, force rebuild of free extent list */
	do {
		if (blockHint != 0)
			startBlock = blockHint;
		else
			startBlock = foundData[foundIndex].startBlock + foundData[foundIndex].blockCount;

		/* Force reserve checking if requested. */
		if (flags & kEFReserveMask) {
			SInt64 availbytes;

			actualNumBlocks = 0;
			actualStartBlock = 0;
			
			availbytes = (SInt64)hfs_freeblks(VCBTOHFS(vcb), 1) *
			             (SInt64)volumeBlockSize;
			if (availbytes <= 0) {
				err = dskFulErr;
			} else {
				if (wantContig && (availbytes < bytesToAdd))
					err = dskFulErr;
				else {
					err = BlockAllocate(
						  vcb,
						  startBlock,
						  howmany(MIN(bytesToAdd, availbytes), volumeBlockSize),
						  howmany(MIN(maximumBytes, availbytes), volumeBlockSize),
						  wantContig,
						  useMetaZone,
						  &actualStartBlock,
						  &actualNumBlocks);
				}
			}
		} else {
			err = BlockAllocate(vcb, startBlock, howmany(bytesToAdd, volumeBlockSize),
			                    howmany(maximumBytes, volumeBlockSize), wantContig, useMetaZone,
			                    &actualStartBlock, &actualNumBlocks);
		}
		if (err == dskFulErr) {
			if (forceContig)
				break;			// AllocContig failed because not enough contiguous space
			if (wantContig) {
				//	Couldn't get one big chunk, so get whatever we can.
				err = noErr;
				wantContig = false;
				continue;
			}
			if (actualNumBlocks != 0)
				err = noErr;
			if (useMetaZone == 0) {
				/* Couldn't get anything so dip into metadat zone */
				err = noErr;
				useMetaZone = 1;
				continue;
			}
		}
		if (err == noErr) {
		    if (actualNumBlocks != 0) {
				// this catalog entry *must* get forced to disk when
				// hfs_update() is called
				FTOC(fcb)->c_flag |= C_FORCEUPDATE;
			}

			//	Add the new extent to the existing extent record, or create a new one.
			if ((actualStartBlock == startBlock) && (blockHint == 0)) {
				//	We grew the file's last extent, so just adjust the number of blocks.
				foundData[foundIndex].blockCount += actualNumBlocks;
				err = UpdateExtentRecord(vcb, fcb, &foundKey, foundData, hint);
				if (err != noErr) break;
			}
			else {
				UInt16	i;

				//	Need to add a new extent.  See if there is room in the current record.
				if (foundData[foundIndex].blockCount != 0)	//	Is current extent free to use?
					++foundIndex;							// 	No, so use the next one.
				if (foundIndex == numExtentsPerRecord) {
					//	This record is full.  Need to create a new one.
					if (FTOC(fcb)->c_fileid == kHFSExtentsFileID) {
						(void) BlockDeallocate(vcb, actualStartBlock, actualNumBlocks);
						err = dskFulErr;		// Oops.  Can't extend extents file past first record.
						break;
					}
					
					foundKey.keyLength = kHFSPlusExtentKeyMaximumLength;
					if (FORK_IS_RSRC(fcb))
						foundKey.forkType = kResourceForkType;
					else
						foundKey.forkType = kDataForkType;
					foundKey.pad = 0;
					foundKey.fileID = FTOC(fcb)->c_fileid;
					foundKey.startBlock = nextBlock;
					
					foundData[0].startBlock = actualStartBlock;
					foundData[0].blockCount = actualNumBlocks;
					
					// zero out remaining extents...
					for (i = 1; i < kHFSPlusExtentDensity; ++i)
					{
						foundData[i].startBlock = 0;
						foundData[i].blockCount = 0;
					}

					foundIndex = 0;
					
					err = CreateExtentRecord(vcb, &foundKey, foundData, &hint);
					if (err == fxOvFlErr) {
						//	We couldn't create an extent record because extents B-tree
						//	couldn't grow.  Dellocate the extent just allocated and
						//	return a disk full error.
						(void) BlockDeallocate(vcb, actualStartBlock, actualNumBlocks);
						err = dskFulErr;
					}
					if (err != noErr) break;

					needsFlush = true;		//	We need to update the B-tree header
				}
				else {
					//	Add a new extent into this record and update.
					foundData[foundIndex].startBlock = actualStartBlock;
					foundData[foundIndex].blockCount = actualNumBlocks;
					err = UpdateExtentRecord(vcb, fcb, &foundKey, foundData, hint);
					if (err != noErr) break;
				}
			}
			
			// Figure out how many bytes were actually allocated.
			// NOTE: BlockAllocate could have allocated more than we asked for.
			// Don't set the PEOF beyond what our client asked for.
			nextBlock += actualNumBlocks;
			bytesThisExtent = (SInt64)((SInt64)actualNumBlocks * (SInt64)volumeBlockSize);
			if (bytesThisExtent > bytesToAdd) {
				bytesToAdd = 0;
			}
			else {
				bytesToAdd -= bytesThisExtent;
				maximumBytes -= bytesThisExtent;
			}
			fcb->ff_blocks += (bytesThisExtent / volumeBlockSize);
			FTOC(fcb)->c_blocks += (bytesThisExtent / volumeBlockSize);
			FTOC(fcb)->c_flag |= C_MODIFIED | C_FORCEUPDATE;

			//	If contiguous allocation was requested, then we've already got one contiguous
			//	chunk.  If we didn't get all we wanted, then adjust the error to disk full.
			if (forceContig) {
				if (bytesToAdd != 0)
					err = dskFulErr;
				break;			//	We've already got everything that's contiguous
			}
		}
	} while (err == noErr && bytesToAdd);

ErrorExit:
Exit:
	if (VCBTOHFS(vcb)->hfs_flags & HFS_METADATA_ZONE) {
		/* Keep the roving allocator out of the metadata zone. */
		if (vcb->nextAllocation >= VCBTOHFS(vcb)->hfs_metazone_start &&
		    vcb->nextAllocation <= VCBTOHFS(vcb)->hfs_metazone_end) {
			vcb->nextAllocation = VCBTOHFS(vcb)->hfs_metazone_end + 1;
		}
	}
	*actualBytesAdded = (SInt64)(fcb->ff_blocks - prevblocks) * (SInt64)volumeBlockSize;

	if (needsFlush)
		(void) FlushExtentFile(vcb);

	return err;

Overflow:
	err = fileBoundsErr;
	goto ErrorExit;
}



//_________________________________________________________________________________
//
// Routine:		TruncateFileC
//
// Function: 	Truncates the disk space allocated to a file.  The file space is
//				truncated to a specified new PEOF rounded up to the next allocation
//				block boundry.  If the 'TFTrunExt' option is specified, the file is
//				truncated to the end of the extent containing the new PEOF.
//
// Input:		A2.L  -  VCB pointer
//				A1.L  -  pointer to FCB array
//				D1.W  -  file refnum
//				D2.B  -  option flags
//						   TFTrunExt - truncate to the extent containing new PEOF
//				D3.L  -  new PEOF
//
// Output:		D0.W  -  result code
//							 0 = ok
//							 -n = IO error
//
// Note: 		TruncateFile updates the PEOF in the FCB.
//_________________________________________________________________________________

__private_extern__
OSErr TruncateFileC (
	ExtendedVCB		*vcb,				// volume that file resides on
	FCB				*fcb,				// FCB of file to truncate
	SInt64			peof,				// new physical size for file
	Boolean			truncateToExtent)	// if true, truncate to end of extent containing newPEOF
{
	OSErr				err;
	UInt32				nextBlock;		//	next file allocation block to consider
	UInt32				startBlock;		//	Physical (volume) allocation block number of start of a range
	UInt32				physNumBlocks;	//	Number of allocation blocks in file (according to PEOF)
	UInt32				numBlocks;
	HFSPlusExtentKey	key;			//	key for current extent record; key->keyLength == 0 if FCB's extent record
	UInt32				hint;			//	BTree hint corresponding to key
	HFSPlusExtentRecord	extentRecord;
	UInt32				extentIndex;
	UInt32				extentNextBlock;
	UInt32				numExtentsPerRecord;
	SInt64                          temp64;
	UInt8				forkType;
	Boolean				extentChanged;	// true if we actually changed an extent
	Boolean				recordDeleted;	// true if an extent record got deleted
	

	recordDeleted = false;
	
	if (vcb->vcbSigWord == kHFSPlusSigWord)
		numExtentsPerRecord = kHFSPlusExtentDensity;
	else
		numExtentsPerRecord = kHFSExtentDensity;

	if (FORK_IS_RSRC(fcb))
		forkType = kResourceForkType;
	else
		forkType = kDataForkType;

	temp64 = fcb->ff_blocks;
	physNumBlocks = (UInt32)temp64;

	//
	//	Round newPEOF up to a multiple of the allocation block size.  If new size is
	//	two gigabytes or more, then round down by one allocation block (??? really?
	//	shouldn't that be an error?).
	//
	nextBlock = howmany(peof, vcb->blockSize);	// number of allocation blocks to remain in file
	peof = (SInt64)((SInt64)nextBlock * (SInt64)vcb->blockSize);					// number of bytes in those blocks
	if ((vcb->vcbSigWord == kHFSSigWord) && (peof >= kTwoGigabytes)) {
		#if DEBUG_BUILD
			DebugStr("\pHFS: Trying to truncate a file to 2GB or more");
		#endif
		err = fileBoundsErr;
		goto ErrorExit;
	}

	//
	//	Update FCB's length
	//
	/*
	 * XXX Any errors could cause ff_blocks and c_blocks to get out of sync...
	 */
	numBlocks = peof / vcb->blockSize;
	FTOC(fcb)->c_blocks -= (fcb->ff_blocks - numBlocks);
	fcb->ff_blocks = numBlocks;

	// this catalog entry is modified and *must* get forced 
	// to disk when hfs_update() is called
	FTOC(fcb)->c_flag |= C_MODIFIED | C_FORCEUPDATE;
	
	//
	//	If the new PEOF is 0, then truncateToExtent has no meaning (we should always deallocate
	//	all storage).
	//
	if (peof == 0) {
		int i;
		
		//	Deallocate all the extents for this fork
		err = DeallocateFork(vcb, FTOC(fcb)->c_fileid, forkType, fcb->fcbExtents, &recordDeleted);
		if (err != noErr) goto ErrorExit;	//	got some error, so return it
		
		//	Update the catalog extent record (making sure it's zeroed out)
		if (err == noErr) {
			for (i=0; i < kHFSPlusExtentDensity; i++) {
				fcb->fcbExtents[i].startBlock = 0;
				fcb->fcbExtents[i].blockCount = 0;
			}
		}
		goto Done;
	}
	
	//
	//	Find the extent containing byte (peof-1).  This is the last extent we'll keep.
	//	(If truncateToExtent is true, we'll keep the whole extent; otherwise, we'll only
	//	keep up through peof).  The search will tell us how many allocation blocks exist
	//	in the found extent plus all previous extents.
	//
	err = SearchExtentFile(vcb, fcb, peof-1, &key, extentRecord, &extentIndex, &hint, &extentNextBlock);
	if (err != noErr) goto ErrorExit;

	extentChanged = false;		//	haven't changed the extent yet
	
	if (!truncateToExtent) {
		//
		//	Shorten this extent.  It may be the case that the entire extent gets
		//	freed here.
		//
		numBlocks = extentNextBlock - nextBlock;	//	How many blocks in this extent to free up
		if (numBlocks != 0) {
			//	Compute first volume allocation block to free
			startBlock = extentRecord[extentIndex].startBlock + extentRecord[extentIndex].blockCount - numBlocks;
			//	Free the blocks in bitmap
			err = BlockDeallocate(vcb, startBlock, numBlocks);
			if (err != noErr) goto ErrorExit;
			//	Adjust length of this extent
			extentRecord[extentIndex].blockCount -= numBlocks;
			//	If extent is empty, set start block to 0
			if (extentRecord[extentIndex].blockCount == 0)
				extentRecord[extentIndex].startBlock = 0;
			//	Remember that we changed the extent record
			extentChanged = true;
		}
	}
	
	//
	//	Now move to the next extent in the record, and set up the file allocation block number
	//
	nextBlock = extentNextBlock;		//	Next file allocation block to free
	++extentIndex;						//	Its index within the extent record
	
	//
	//	Release all following extents in this extent record.  Update the record.
	//
	while (extentIndex < numExtentsPerRecord && extentRecord[extentIndex].blockCount != 0) {
		numBlocks = extentRecord[extentIndex].blockCount;
		//	Deallocate this extent
		err = BlockDeallocate(vcb, extentRecord[extentIndex].startBlock, numBlocks);
		if (err != noErr) goto ErrorExit;
		//	Update next file allocation block number
		nextBlock += numBlocks;
		//	Zero out start and length of this extent to delete it from record
		extentRecord[extentIndex].startBlock = 0;
		extentRecord[extentIndex].blockCount = 0;
		//	Remember that we changed an extent
		extentChanged = true;
		//	Move to next extent in record
		++extentIndex;
	}
	
	//
	//	If any of the extents in the current record were changed, then update that
	//	record (in the FCB, or extents file).
	//
	if (extentChanged) {
		err = UpdateExtentRecord(vcb, fcb, &key, extentRecord, hint);
		if (err != noErr) goto ErrorExit;
	}
	
	//
	//	If there are any following allocation blocks, then we need
	//	to seach for their extent records and delete those allocation
	//	blocks.
	//
	if (nextBlock < physNumBlocks)
		err = TruncateExtents(vcb, forkType, FTOC(fcb)->c_fileid, nextBlock, &recordDeleted);

Done:
ErrorExit:

	if (recordDeleted)
		(void) FlushExtentFile(vcb);

	return err;
}


/*
 * HFS Plus only
 *
 */
__private_extern__
OSErr HeadTruncateFile (
	ExtendedVCB  *vcb,
	FCB  *fcb,
	UInt32  headblks)
{
	HFSPlusExtentRecord  extents;
	HFSPlusExtentRecord  tailExtents;
	HFSCatalogNodeID  fileID;
	UInt8  forkType;
	UInt32  blkcnt;
	UInt32  startblk;
	UInt32  blksfreed;
	int  i, j;
	int  error;


	if (vcb->vcbSigWord != kHFSPlusSigWord)
		return (-1);

	forkType = FORK_IS_RSRC(fcb) ? kResourceForkType : kDataForkType;
	fileID = FTOC(fcb)->c_fileid;
	bzero(tailExtents, sizeof(tailExtents));

	blksfreed = 0;
	startblk = 0;

	/*
	 * Process catalog resident extents
	 */
	for (i = 0, j = 0; i < kHFSPlusExtentDensity; ++i) {
		blkcnt = fcb->fcbExtents[i].blockCount;
		if (blkcnt == 0)
			break;  /* end of extents */

		if (blksfreed < headblks) {
			error = BlockDeallocate(vcb, fcb->fcbExtents[i].startBlock, blkcnt);
			/*
			 * Any errors after the first BlockDeallocate
			 * must be ignored so we can put the file in
			 * a known state.
			 */
			if (error ) {
				if (i == 0)
					goto ErrorExit;  /* uh oh */
				else {
					error = 0;
					printf("HeadTruncateFile: problems deallocating %s (%d)\n",
					       FTOC(fcb)->c_desc.cd_nameptr ? FTOC(fcb)->c_desc.cd_nameptr : "", error);
				}
			}

			blksfreed += blkcnt;
			fcb->fcbExtents[i].startBlock = 0;
			fcb->fcbExtents[i].blockCount = 0;
		} else {
			tailExtents[j].startBlock = fcb->fcbExtents[i].startBlock;
			tailExtents[j].blockCount = blkcnt;
			++j;
		}
		startblk += blkcnt;	
	}
	
	if (blkcnt == 0)
		goto CopyExtents;

	/* 
	 * Process overflow extents
	 */
	for (;;) {
		UInt32  extblks;

		error = FindExtentRecord(vcb, forkType, fileID, startblk, false, NULL, extents, NULL);
		if (error) {
			/*
			 * Any errors after the first BlockDeallocate
			 * must be ignored so we can put the file in
			 * a known state.
			 */
			if (error != btNotFound)
				printf("HeadTruncateFile: problems finding extents %s (%d)\n",
				       FTOC(fcb)->c_desc.cd_nameptr ? FTOC(fcb)->c_desc.cd_nameptr : "", error);
			error = 0;
			break;
		}

		for(i = 0, extblks = 0; i < kHFSPlusExtentDensity; ++i) {
			blkcnt = extents[i].blockCount;
			if (blkcnt == 0)
				break;  /* end of extents */

			if (blksfreed < headblks) {
				error = BlockDeallocate(vcb, extents[i].startBlock, blkcnt);
				if (error) {
					printf("HeadTruncateFile: problems deallocating %s (%d)\n",
					       FTOC(fcb)->c_desc.cd_nameptr ? FTOC(fcb)->c_desc.cd_nameptr : "", error);
					error = 0;
				}
				blksfreed += blkcnt;
			} else {
				tailExtents[j].startBlock = extents[i].startBlock;
				tailExtents[j].blockCount = blkcnt;
				++j;
			}
			extblks += blkcnt;		
		}
		
		error = DeleteExtentRecord(vcb, forkType, fileID, startblk);
		if (error) {
			printf("HeadTruncateFile: problems deallocating %s (%d)\n",
				FTOC(fcb)->c_desc.cd_nameptr ? FTOC(fcb)->c_desc.cd_nameptr : "", error);
			error = 0;
		}
		
		if (blkcnt == 0)
			break;  /* all done */

		startblk += extblks;
	}

CopyExtents:
	if (blksfreed) {
		bcopy(tailExtents, fcb->fcbExtents, sizeof(tailExtents));
		blkcnt = fcb->ff_blocks - headblks;
		FTOC(fcb)->c_blocks -= blkcnt;
		fcb->ff_blocks = blkcnt;

		FTOC(fcb)->c_flag |= C_CHANGE | C_FORCEUPDATE;

		(void) FlushExtentFile(vcb);
	}

ErrorExit:	
	return MacToVFSError(error);
}



//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	SearchExtentRecord (was XRSearch)
//
//	Function: 	Searches extent record for the extent mapping a given file
//				allocation block number (FABN).
//
//	Input:		searchFABN  			-  desired FABN
//				extentData  			-  pointer to extent data record (xdr)
//				extentDataStartFABN  	-  beginning FABN for extent record
//
//	Output:		foundExtentDataOffset  -  offset to extent entry within xdr
//							result = noErr, offset to extent mapping desired FABN
//							result = FXRangeErr, offset to last extent in record
//				endingFABNPlusOne	-  ending FABN +1
//				noMoreExtents		- True if the extent was not found, and the
//									  extent record was not full (so don't bother
//									  looking in subsequent records); false otherwise.
//
//	Result:		noErr = ok
//				FXRangeErr = desired FABN > last mapped FABN in record
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr SearchExtentRecord(
	const ExtendedVCB		*vcb,
	UInt32					searchFABN,
	const HFSPlusExtentRecord	extentData,
	UInt32					extentDataStartFABN,
	UInt32					*foundExtentIndex,
	UInt32					*endingFABNPlusOne,
	Boolean					*noMoreExtents)
{
	OSErr	err = noErr;
	UInt32	extentIndex;
	UInt32	numberOfExtents;
	UInt32	numAllocationBlocks;
	Boolean	foundExtent;
	
	*endingFABNPlusOne 	= extentDataStartFABN;
	*noMoreExtents		= false;
	foundExtent			= false;

	if (vcb->vcbSigWord == kHFSPlusSigWord)
		numberOfExtents = kHFSPlusExtentDensity;
	else
		numberOfExtents = kHFSExtentDensity;
	
	for( extentIndex = 0; extentIndex < numberOfExtents; ++extentIndex )
	{
		
		// Loop over the extent record and find the search FABN.
		
		numAllocationBlocks = extentData[extentIndex].blockCount;
		if ( numAllocationBlocks == 0 )
		{
			break;
		}

		*endingFABNPlusOne += numAllocationBlocks;
		
		if( searchFABN < *endingFABNPlusOne )
		{
			// Found the extent.
			foundExtent = true;
			break;
		}
	}
	
	if( foundExtent )
	{
		// Found the extent. Note the extent offset
		*foundExtentIndex = extentIndex;
	}
	else
	{
		// Did not find the extent. Set foundExtentDataOffset accordingly
		if( extentIndex > 0 )
		{
			*foundExtentIndex = extentIndex - 1;
		}
		else
		{
			*foundExtentIndex = 0;
		}
		
		// If we found an empty extent, then set noMoreExtents.
		if (extentIndex < numberOfExtents)
			*noMoreExtents = true;

		// Finally, return an error to the caller
		err = fxRangeErr;
	}

	return( err );
}

//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	SearchExtentFile (was XFSearch)
//
//	Function: 	Searches extent file (including the FCB resident extent record)
//				for the extent mapping a given file position.
//
//	Input:		vcb  			-  VCB pointer
//				fcb  			-  FCB pointer
//				filePosition  	-  file position (byte address)
//
// Output:		foundExtentKey  		-  extent key record (xkr)
//							If extent was found in the FCB's resident extent record,
//							then foundExtentKey->keyLength will be set to 0.
//				foundExtentData			-  extent data record(xdr)
//				foundExtentIndex  	-  index to extent entry in xdr
//							result =  0, offset to extent mapping desired FABN
//							result = FXRangeErr, offset to last extent in record
//									 (i.e., kNumExtentsPerRecord-1)
//				extentBTreeHint  		-  BTree hint for extent record
//							kNoHint = Resident extent record
//				endingFABNPlusOne  		-  ending FABN +1
//
//	Result:
//		noErr			Found an extent that contains the given file position
//		FXRangeErr		Given position is beyond the last allocated extent
//		(other)			(some other internal I/O error)
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr SearchExtentFile(
	const ExtendedVCB 	*vcb,
	const FCB	 		*fcb,
	SInt64 				filePosition,
	HFSPlusExtentKey	*foundExtentKey,
	HFSPlusExtentRecord	foundExtentData,
	UInt32				*foundExtentIndex,
	UInt32				*extentBTreeHint,
	UInt32				*endingFABNPlusOne )
{
	OSErr				err;
	UInt32				filePositionBlock;
	SInt64                          temp64;
	Boolean				noMoreExtents;
	
	temp64 = filePosition / (SInt64)vcb->blockSize;
	filePositionBlock = (UInt32)temp64;

    bcopy ( fcb->fcbExtents, foundExtentData, sizeof(HFSPlusExtentRecord));
	
	//	Search the resident FCB first.
    err = SearchExtentRecord( vcb, filePositionBlock, foundExtentData, 0,
									foundExtentIndex, endingFABNPlusOne, &noMoreExtents );

	if( err == noErr ) {
		// Found the extent. Set results accordingly
		*extentBTreeHint = kNoHint;			// no hint, because not in the BTree
		foundExtentKey->keyLength = 0;		// 0 = the FCB itself
		
		goto Exit;
	}
	
	//	Didn't find extent in FCB.  If FCB's extent record wasn't full, there's no point
	//	in searching the extents file.  Note that SearchExtentRecord left us pointing at
	//	the last valid extent (or the first one, if none were valid).  This means we need
	//	to fill in the hint and key outputs, just like the "if" statement above.
	if ( noMoreExtents ) {
		*extentBTreeHint = kNoHint;			// no hint, because not in the BTree
		foundExtentKey->keyLength = 0;		// 0 = the FCB itself
		err = fxRangeErr;		// There are no more extents, so must be beyond PEOF
		goto Exit;
	}
	
	//
	//	Find the desired record, or the previous record if it is the same fork
	//
	err = FindExtentRecord(vcb, FORK_IS_RSRC(fcb) ? kResourceForkType : kDataForkType,
						   FTOC(fcb)->c_fileid, filePositionBlock, true, foundExtentKey, foundExtentData, extentBTreeHint);

	if (err == btNotFound) {
		//
		//	If we get here, the desired position is beyond the extents in the FCB, and there are no extents
		//	in the extents file.  Return the FCB's extents and a range error.
		//
		*extentBTreeHint = kNoHint;
		foundExtentKey->keyLength = 0;
		err = GetFCBExtentRecord(fcb, foundExtentData);
		//	Note: foundExtentIndex and endingFABNPlusOne have already been set as a result of the very
		//	first SearchExtentRecord call in this function (when searching in the FCB's extents, and
		//	we got a range error).
		
		return fxRangeErr;
	}
	
	//
	//	If we get here, there was either a BTree error, or we found an appropriate record.
	//	If we found a record, then search it for the correct index into the extents.
	//
	if (err == noErr) {
		//	Find appropriate index into extent record
		err = SearchExtentRecord(vcb, filePositionBlock, foundExtentData, foundExtentKey->startBlock,
								 foundExtentIndex, endingFABNPlusOne, &noMoreExtents);
	}

Exit:
	return err;
}



//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹
//	Routine:	UpdateExtentRecord
//
//	Function: 	Write new extent data to an existing extent record with a given key.
//				If all of the extents are empty, and the extent record is in the
//				extents file, then the record is deleted.
//
//	Input:		vcb			  			-	the volume containing the extents
//				fcb						-	the file that owns the extents
//				extentFileKey  			-	pointer to extent key record (xkr)
//						If the key length is 0, then the extents are actually part
//						of the catalog record, stored in the FCB.
//				extentData  			-	pointer to extent data record (xdr)
//				extentBTreeHint			-	hint for given key, or kNoHint
//
//	Result:		noErr = ok
//				(other) = error from BTree
//‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹‹

static OSErr UpdateExtentRecord (
	const ExtendedVCB		*vcb,
	FCB						*fcb,
	const HFSPlusExtentKey	*extentFileKey,
	const HFSPlusExtentRecord	extentData,
	UInt32					extentBTreeHint)
{
    OSErr err = noErr;
	
	if (extentFileKey->keyLength == 0) {	// keyLength == 0 means the FCB's extent record
		BlockMoveData(extentData, fcb->fcbExtents, sizeof(HFSPlusExtentRecord));
		FTOC(fcb)->c_flag |= C_MODIFIED;
	}
	else {
		BTreeIterator * btIterator;
		FSBufferDescriptor btRecord;
		UInt16 btRecordSize;
		FCB * btFCB;

		//
		//	Need to find and change a record in Extents BTree
		//
		btFCB = GetFileControlBlock(vcb->extentsRefNum);

		MALLOC(btIterator, BTreeIterator *, sizeof(*btIterator), M_TEMP, M_WAITOK);
		bzero(btIterator, sizeof(*btIterator));

		if (vcb->vcbSigWord == kHFSSigWord) {
			HFSExtentKey *	key;				// Actual extent key used on disk in HFS
			HFSExtentRecord	foundData;			// The extent data actually found

			key = (HFSExtentKey*) &btIterator->key;
			key->keyLength	= kHFSExtentKeyMaximumLength;
			key->forkType	= extentFileKey->forkType;
			key->fileID		= extentFileKey->fileID;
			key->startBlock	= extentFileKey->startBlock;

			btIterator->hint.index = 0;
			btIterator->hint.nodeNum = extentBTreeHint;

			btRecord.bufferAddress = &foundData;
			btRecord.itemSize = sizeof(HFSExtentRecord);
			btRecord.itemCount = 1;

			err = BTSearchRecord(btFCB, btIterator, &btRecord, &btRecordSize, btIterator);
			
			if (err == noErr)
				err = HFSPlusToHFSExtents(extentData, (HFSExtentDescriptor *)&foundData);

			if (err == noErr)
				err = BTReplaceRecord(btFCB, btIterator, &btRecord, btRecordSize);
			(void) BTFlushPath(btFCB);
		}
		else {		//	HFS Plus volume
			HFSPlusExtentRecord	foundData;		// The extent data actually found

			BlockMoveData(extentFileKey, &btIterator->key, sizeof(HFSPlusExtentKey));

			btIterator->hint.index = 0;
			btIterator->hint.nodeNum = extentBTreeHint;

			btRecord.bufferAddress = &foundData;
			btRecord.itemSize = sizeof(HFSPlusExtentRecord);
			btRecord.itemCount = 1;

			err = BTSearchRecord(btFCB, btIterator, &btRecord, &btRecordSize, btIterator);
	
			if (err == noErr) {
				BlockMoveData(extentData, &foundData, sizeof(HFSPlusExtentRecord));
				err = BTReplaceRecord(btFCB, btIterator, &btRecord, btRecordSize);
			}
			(void) BTFlushPath(btFCB);
		}
		FREE(btIterator, M_TEMP);	
	}
	
	return err;
}




static OSErr HFSPlusToHFSExtents(
	const HFSPlusExtentRecord	oldExtents,
	HFSExtentRecord		newExtents)
{
	OSErr	err;
	
	err = noErr;

	// copy the first 3 extents
	newExtents[0].startBlock = oldExtents[0].startBlock;
	newExtents[0].blockCount = oldExtents[0].blockCount;
	newExtents[1].startBlock = oldExtents[1].startBlock;
	newExtents[1].blockCount = oldExtents[1].blockCount;
	newExtents[2].startBlock = oldExtents[2].startBlock;
	newExtents[2].blockCount = oldExtents[2].blockCount;

	#if DEBUG_BUILD
		if (oldExtents[3].startBlock || oldExtents[3].blockCount) {
			DebugStr("\pExtentRecord with > 3 extents is invalid for HFS");
			err = fsDSIntErr;
		}
	#endif
	
	return err;
}




static OSErr GetFCBExtentRecord(
	const FCB			*fcb,
	HFSPlusExtentRecord	extents)
{
	
	BlockMoveData(fcb->fcbExtents, extents, sizeof(HFSPlusExtentRecord));
	
	return noErr;
}


//_________________________________________________________________________________
//
// Routine:		ExtentsAreIntegral
//
// Purpose:		Ensure that each extent can hold an integral number of nodes
//				Called by the NodesAreContiguous function
//_________________________________________________________________________________

static Boolean ExtentsAreIntegral(
	const HFSPlusExtentRecord extentRecord,
	UInt32		mask,
	UInt32		*blocksChecked,
	Boolean		*checkedLastExtent)
{
	UInt32		blocks;
	UInt32		extentIndex;

	*blocksChecked = 0;
	*checkedLastExtent = false;
	
	for(extentIndex = 0; extentIndex < kHFSPlusExtentDensity; extentIndex++)
	{		
		blocks = extentRecord[extentIndex].blockCount;
		
		if ( blocks == 0 )
		{
			*checkedLastExtent = true;
			break;
		}

		*blocksChecked += blocks;

		if (blocks & mask)
			return false;
	}
	
	return true;
}


//_________________________________________________________________________________
//
// Routine:		NodesAreContiguous
//
// Purpose:		Ensure that all b-tree nodes are contiguous on disk
//				Called by BTOpenPath during volume mount
//_________________________________________________________________________________

__private_extern__
Boolean NodesAreContiguous(
	ExtendedVCB	*vcb,
	FCB			*fcb,
	UInt32		nodeSize)
{
	UInt32				mask;
	UInt32				startBlock;
	UInt32				blocksChecked;
	UInt32				hint;
	HFSPlusExtentKey	key;
	HFSPlusExtentRecord	extents;
	OSErr				result;
	Boolean				lastExtentReached;
	

	if (vcb->blockSize >= nodeSize)
		return TRUE;

	mask = (nodeSize / vcb->blockSize) - 1;

	// check the local extents
	(void) GetFCBExtentRecord(fcb, extents);
	if ( !ExtentsAreIntegral(extents, mask, &blocksChecked, &lastExtentReached) )
		return FALSE;

	if (lastExtentReached || (SInt64)((SInt64)blocksChecked * (SInt64)vcb->blockSize) >= fcb->ff_size)
		return TRUE;

	startBlock = blocksChecked;

	// check the overflow extents (if any)
	while ( !lastExtentReached )
	{
		result = FindExtentRecord(vcb, kDataForkType, fcb->ff_cp->c_fileid, startBlock, FALSE, &key, extents, &hint);
		if (result) break;

		if ( !ExtentsAreIntegral(extents, mask, &blocksChecked, &lastExtentReached) )
			return FALSE;

		startBlock += blocksChecked;
	}

	return TRUE;
}