2 * Copyright (c) 2013-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
28 #include <sys/systm.h>
29 #include <sys/kauth.h>
32 #include "hfs_journal.h"
33 #include <miscfs/specfs/specdev.h>
36 #include "hfs_catalog.h"
37 #include "hfs_cnode.h"
38 #include "hfs_endian.h"
39 #include "hfs_btreeio.h"
40 #include "hfs_cprotect.h"
42 /* Enable/disable debugging code for live volume resizing */
43 int hfs_resize_debug
= 0;
45 static errno_t
hfs_file_extent_overlaps(struct hfsmount
*hfsmp
, u_int32_t allocLimit
,
46 struct HFSPlusCatalogFile
*filerec
, bool *overlaps
);
47 static int hfs_reclaimspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, u_int32_t reclaimblks
, vfs_context_t context
);
48 static int hfs_extend_journal(struct hfsmount
*hfsmp
, u_int32_t sector_size
, u_int64_t sector_count
, vfs_context_t context
);
51 * Extend a file system.
54 hfs_extendfs(struct hfsmount
*hfsmp
, u_int64_t newsize
, vfs_context_t context
)
56 struct proc
*p
= vfs_context_proc(context
);
57 kauth_cred_t cred
= vfs_context_ucred(context
);
58 struct vnode
*vp
= NULL
;
61 struct filefork
*fp
= NULL
;
63 struct cat_fork forkdata
;
66 u_int64_t prev_phys_block_count
;
68 u_int64_t sector_count
;
69 u_int32_t sector_size
;
70 u_int32_t phys_sector_size
;
71 u_int32_t overage_blocks
;
72 daddr64_t prev_fs_alt_sector
;
76 int64_t oldBitmapSize
;
78 Boolean usedExtendFileC
= false;
79 int transaction_begun
= 0;
81 devvp
= hfsmp
->hfs_devvp
;
82 vcb
= HFSTOVCB(hfsmp
);
85 * - HFS Plus file systems only.
86 * - Journaling must be enabled.
87 * - No embedded volumes.
89 if ((vcb
->vcbSigWord
== kHFSSigWord
) ||
90 (hfsmp
->jnl
== NULL
) ||
91 (vcb
->hfsPlusIOPosOffset
!= 0)) {
95 * If extending file system by non-root, then verify
96 * ownership and check permissions.
98 if (suser(cred
, NULL
)) {
99 error
= hfs_vget(hfsmp
, kHFSRootFolderID
, &vp
, 0, 0);
103 error
= hfs_owner_rights(hfsmp
, VTOC(vp
)->c_uid
, cred
, p
, 0);
105 error
= hfs_write_access(vp
, cred
, p
, false);
107 hfs_unlock(VTOC(vp
));
112 error
= vnode_authorize(devvp
, NULL
, KAUTH_VNODE_READ_DATA
| KAUTH_VNODE_WRITE_DATA
, context
);
116 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKSIZE
, (caddr_t
)§or_size
, 0, context
)) {
119 if (sector_size
!= hfsmp
->hfs_logical_block_size
) {
122 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)§or_count
, 0, context
)) {
125 /* Check if partition size is correct for new file system size */
126 if ((sector_size
* sector_count
) < newsize
) {
127 printf("hfs_extendfs: not enough space on device (vol=%s)\n", hfsmp
->vcbVN
);
130 error
= VNOP_IOCTL(devvp
, DKIOCGETPHYSICALBLOCKSIZE
, (caddr_t
)&phys_sector_size
, 0, context
);
132 if ((error
!= ENOTSUP
) && (error
!= ENOTTY
)) {
135 /* If ioctl is not supported, force physical and logical sector size to be same */
136 phys_sector_size
= sector_size
;
138 oldsize
= (u_int64_t
)hfsmp
->totalBlocks
* (u_int64_t
)hfsmp
->blockSize
;
143 if ((newsize
<= oldsize
) || (newsize
% sector_size
) || (newsize
% phys_sector_size
)) {
144 printf("hfs_extendfs: invalid size (newsize=%qu, oldsize=%qu)\n", newsize
, oldsize
);
147 uint64_t cnt
= newsize
/ vcb
->blockSize
;
148 if (cnt
> 0xFFFFFFFF) {
149 printf ("hfs_extendfs: current blockSize=%u too small for newsize=%qu\n", hfsmp
->blockSize
, newsize
);
153 newblkcnt
= (uint32_t)cnt
;
155 addblks
= newblkcnt
- vcb
->totalBlocks
;
157 if (hfs_resize_debug
) {
158 printf ("hfs_extendfs: old: size=%qu, blkcnt=%u\n", oldsize
, hfsmp
->totalBlocks
);
159 printf ("hfs_extendfs: new: size=%qu, blkcnt=%u, addblks=%u\n", newsize
, newblkcnt
, addblks
);
161 printf("hfs_extendfs: will extend \"%s\" by %d blocks\n", vcb
->vcbVN
, addblks
);
163 hfs_lock_mount (hfsmp
);
164 if (hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) {
165 hfs_unlock_mount(hfsmp
);
169 hfsmp
->hfs_flags
|= HFS_RESIZE_IN_PROGRESS
;
170 hfs_unlock_mount (hfsmp
);
172 /* Start with a clean journal. */
173 hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
176 * Enclose changes inside a transaction.
178 if (hfs_start_transaction(hfsmp
) != 0) {
182 transaction_begun
= 1;
185 /* Update the hfsmp fields for the physical information about the device */
186 prev_phys_block_count
= hfsmp
->hfs_logical_block_count
;
187 prev_fs_alt_sector
= hfsmp
->hfs_fs_avh_sector
;
189 hfsmp
->hfs_logical_block_count
= sector_count
;
190 hfsmp
->hfs_logical_bytes
= (uint64_t) sector_count
* (uint64_t) sector_size
;
193 * It is possible that the new file system is smaller than the partition size.
194 * Therefore, update offsets for AVH accordingly.
196 if (hfs_resize_debug
) {
197 printf ("hfs_extendfs: old: partition_avh_sector=%qu, fs_avh_sector=%qu\n",
198 hfsmp
->hfs_partition_avh_sector
, hfsmp
->hfs_fs_avh_sector
);
200 hfsmp
->hfs_partition_avh_sector
= (hfsmp
->hfsPlusIOPosOffset
/ sector_size
) +
201 HFS_ALT_SECTOR(sector_size
, hfsmp
->hfs_logical_block_count
);
203 hfsmp
->hfs_fs_avh_sector
= (hfsmp
->hfsPlusIOPosOffset
/ sector_size
) +
204 HFS_ALT_SECTOR(sector_size
, (newsize
/hfsmp
->hfs_logical_block_size
));
205 if (hfs_resize_debug
) {
206 printf ("hfs_extendfs: new: partition_avh_sector=%qu, fs_avh_sector=%qu\n",
207 hfsmp
->hfs_partition_avh_sector
, hfsmp
->hfs_fs_avh_sector
);
211 * Note: we take the attributes lock in case we have an attribute data vnode
212 * which needs to change size.
214 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
| SFL_EXTENTS
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
215 vp
= vcb
->allocationsRefNum
;
217 bcopy(&fp
->ff_data
, &forkdata
, sizeof(forkdata
));
220 * Calculate additional space required (if any) by allocation bitmap.
222 oldBitmapSize
= fp
->ff_size
;
223 bitmapblks
= roundup((newblkcnt
+7) / 8, vcb
->vcbVBMIOSize
) / vcb
->blockSize
;
224 if (bitmapblks
> (daddr_t
)fp
->ff_blocks
)
225 bitmapblks
-= fp
->ff_blocks
;
230 * The allocation bitmap can contain unused bits that are beyond end of
231 * current volume's allocation blocks. Usually they are supposed to be
232 * zero'ed out but there can be cases where they might be marked as used.
233 * After extending the file system, those bits can represent valid
234 * allocation blocks, so we mark all the bits from the end of current
235 * volume to end of allocation bitmap as "free".
237 * Figure out the number of overage blocks before proceeding though,
238 * so we don't add more bytes to our I/O than necessary.
239 * First figure out the total number of blocks representable by the
240 * end of the bitmap file vs. the total number of blocks in the new FS.
241 * Then subtract away the number of blocks in the current FS. This is how much
242 * we can mark as free right now without having to grow the bitmap file.
244 overage_blocks
= fp
->ff_blocks
* vcb
->blockSize
* 8;
245 overage_blocks
= MIN (overage_blocks
, newblkcnt
);
246 overage_blocks
-= vcb
->totalBlocks
;
248 BlockMarkFreeUnused(vcb
, vcb
->totalBlocks
, overage_blocks
);
250 if (bitmapblks
> 0) {
256 * Get the bitmap's current size (in allocation blocks) so we know
257 * where to start zero filling once the new space is added. We've
258 * got to do this before the bitmap is grown.
260 blkno
= (daddr64_t
)fp
->ff_blocks
;
263 * Try to grow the allocation file in the normal way, using allocation
264 * blocks already existing in the file system. This way, we might be
265 * able to grow the bitmap contiguously, or at least in the metadata
268 error
= ExtendFileC(vcb
, fp
, bitmapblks
* vcb
->blockSize
, 0,
269 kEFAllMask
| kEFNoClumpMask
| kEFReserveMask
270 | kEFMetadataMask
| kEFContigMask
, &bytesAdded
);
273 usedExtendFileC
= true;
276 * If the above allocation failed, fall back to allocating the new
277 * extent of the bitmap from the space we're going to add. Since those
278 * blocks don't yet belong to the file system, we have to update the
279 * extent list directly, and manually adjust the file size.
282 error
= AddFileExtent(vcb
, fp
, vcb
->totalBlocks
, bitmapblks
);
284 printf("hfs_extendfs: error %d adding extents\n", error
);
287 fp
->ff_blocks
+= bitmapblks
;
288 VTOC(vp
)->c_blocks
= fp
->ff_blocks
;
289 VTOC(vp
)->c_flag
|= C_MODIFIED
;
293 * Update the allocation file's size to include the newly allocated
294 * blocks. Note that ExtendFileC doesn't do this, which is why this
295 * statement is outside the above "if" statement.
297 fp
->ff_size
+= (u_int64_t
)bitmapblks
* (u_int64_t
)vcb
->blockSize
;
300 * Zero out the new bitmap blocks.
307 error
= (int)buf_meta_bread(vp
, blkno
, vcb
->blockSize
, NOCRED
, &bp
);
314 bzero((char *)buf_dataptr(bp
), vcb
->blockSize
);
316 error
= (int)buf_bwrite(bp
);
324 printf("hfs_extendfs: error %d clearing blocks\n", error
);
328 * Mark the new bitmap space as allocated.
330 * Note that ExtendFileC will have marked any blocks it allocated, so
331 * this is only needed if we used AddFileExtent. Also note that this
332 * has to come *after* the zero filling of new blocks in the case where
333 * we used AddFileExtent (since the part of the bitmap we're touching
334 * is in those newly allocated blocks).
336 if (!usedExtendFileC
) {
337 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
, bitmapblks
);
339 printf("hfs_extendfs: error %d setting bitmap\n", error
);
342 vcb
->freeBlocks
-= bitmapblks
;
347 * Mark the new alternate VH as allocated.
349 if (vcb
->blockSize
== 512)
350 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
+ addblks
- 2, 2);
352 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
+ addblks
- 1, 1);
354 printf("hfs_extendfs: error %d setting bitmap (VH)\n", error
);
359 * Mark the old alternate VH as free.
361 if (vcb
->blockSize
== 512)
362 (void) BlockMarkFree(vcb
, vcb
->totalBlocks
- 2, 2);
364 (void) BlockMarkFree(vcb
, vcb
->totalBlocks
- 1, 1);
367 * Adjust file system variables for new space.
369 vcb
->totalBlocks
+= addblks
;
370 vcb
->freeBlocks
+= addblks
;
372 error
= hfs_flushvolumeheader(hfsmp
, HFS_FVH_WAIT
| HFS_FVH_WRITE_ALT
);
374 printf("hfs_extendfs: couldn't flush volume headers (%d)", error
);
376 * Restore to old state.
378 if (usedExtendFileC
) {
379 (void) TruncateFileC(vcb
, fp
, oldBitmapSize
, 0, FORK_IS_RSRC(fp
),
380 FTOC(fp
)->c_fileid
, false);
382 fp
->ff_blocks
-= bitmapblks
;
383 fp
->ff_size
-= (u_int64_t
)bitmapblks
* (u_int64_t
)vcb
->blockSize
;
385 * No need to mark the excess blocks free since those bitmap blocks
386 * are no longer part of the bitmap. But we do need to undo the
387 * effect of the "vcb->freeBlocks -= bitmapblks" above.
389 vcb
->freeBlocks
+= bitmapblks
;
391 vcb
->totalBlocks
-= addblks
;
392 vcb
->freeBlocks
-= addblks
;
393 hfsmp
->hfs_logical_block_count
= prev_phys_block_count
;
394 hfsmp
->hfs_fs_avh_sector
= prev_fs_alt_sector
;
395 /* Do not revert hfs_partition_avh_sector because the
396 * partition size is larger than file system size
399 if (vcb
->blockSize
== 512) {
400 if (BlockMarkAllocated(vcb
, vcb
->totalBlocks
- 2, 2)) {
401 hfs_mark_inconsistent(hfsmp
, HFS_ROLLBACK_FAILED
);
404 if (BlockMarkAllocated(vcb
, vcb
->totalBlocks
- 1, 1)) {
405 hfs_mark_inconsistent(hfsmp
, HFS_ROLLBACK_FAILED
);
411 * Invalidate the old alternate volume header. We are growing the filesystem so
412 * this sector must be returned to the FS as free space.
415 if (prev_fs_alt_sector
) {
416 if (buf_meta_bread(hfsmp
->hfs_devvp
,
417 HFS_PHYSBLK_ROUNDDOWN(prev_fs_alt_sector
, hfsmp
->hfs_log_per_phys
),
418 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
) == 0) {
419 journal_modify_block_start(hfsmp
->jnl
, bp
);
421 bzero((char *)buf_dataptr(bp
) + HFS_ALT_OFFSET(hfsmp
->hfs_physical_block_size
), kMDBSize
);
423 journal_modify_block_end(hfsmp
->jnl
, bp
, NULL
, NULL
);
430 * Update the metadata zone size based on current volume size
432 hfs_metadatazone_init(hfsmp
, false);
435 * Adjust the size of hfsmp->hfs_attrdata_vp
437 if (hfsmp
->hfs_attrdata_vp
) {
438 struct cnode
*attr_cp
;
439 struct filefork
*attr_fp
;
441 if (vnode_get(hfsmp
->hfs_attrdata_vp
) == 0) {
442 attr_cp
= VTOC(hfsmp
->hfs_attrdata_vp
);
443 attr_fp
= VTOF(hfsmp
->hfs_attrdata_vp
);
445 attr_cp
->c_blocks
= newblkcnt
;
446 attr_fp
->ff_blocks
= newblkcnt
;
447 attr_fp
->ff_extents
[0].blockCount
= newblkcnt
;
448 attr_fp
->ff_size
= (off_t
) newblkcnt
* hfsmp
->blockSize
;
449 ubc_setsize(hfsmp
->hfs_attrdata_vp
, attr_fp
->ff_size
);
450 vnode_put(hfsmp
->hfs_attrdata_vp
);
455 * We only update hfsmp->allocLimit if totalBlocks actually increased.
458 UpdateAllocLimit(hfsmp
, hfsmp
->totalBlocks
);
461 /* Release all locks and sync up journal content before
462 * checking and extending, if required, the journal
465 hfs_systemfile_unlock(hfsmp
, lockflags
);
468 if (transaction_begun
) {
469 hfs_end_transaction(hfsmp
);
470 hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
471 transaction_begun
= 0;
474 /* Increase the journal size, if required. */
475 error
= hfs_extend_journal(hfsmp
, sector_size
, sector_count
, context
);
477 printf ("hfs_extendfs: Could not extend journal size\n");
481 /* Log successful extending */
482 printf("hfs_extendfs: extended \"%s\" to %d blocks (was %d blocks)\n",
483 hfsmp
->vcbVN
, hfsmp
->totalBlocks
, (u_int32_t
)(oldsize
/hfsmp
->blockSize
));
487 /* Restore allocation fork. */
488 bcopy(&forkdata
, &fp
->ff_data
, sizeof(forkdata
));
489 VTOC(vp
)->c_blocks
= fp
->ff_blocks
;
494 hfs_lock_mount (hfsmp
);
495 hfsmp
->hfs_flags
&= ~HFS_RESIZE_IN_PROGRESS
;
496 hfs_unlock_mount (hfsmp
);
498 hfs_systemfile_unlock(hfsmp
, lockflags
);
500 if (transaction_begun
) {
501 hfs_end_transaction(hfsmp
);
502 /* Just to be sure, sync all data to the disk */
503 int flush_error
= hfs_flush(hfsmp
, HFS_FLUSH_FULL
);
504 if (flush_error
&& !error
)
508 printf ("hfs_extentfs: failed error=%d on vol=%s\n", MacToVFSError(error
), hfsmp
->vcbVN
);
511 return MacToVFSError(error
);
514 #define HFS_MIN_SIZE (32LL * 1024LL * 1024LL)
517 * Truncate a file system (while still mounted).
520 hfs_truncatefs(struct hfsmount
*hfsmp
, u_int64_t newsize
, vfs_context_t context
)
524 u_int32_t reclaimblks
= 0;
526 int transaction_begun
= 0;
527 Boolean updateFreeBlocks
= false;
528 Boolean disable_sparse
= false;
531 hfs_lock_mount (hfsmp
);
532 if (hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) {
533 hfs_unlock_mount (hfsmp
);
536 hfsmp
->hfs_flags
|= HFS_RESIZE_IN_PROGRESS
;
537 hfsmp
->hfs_resize_blocksmoved
= 0;
538 hfsmp
->hfs_resize_totalblocks
= 0;
539 hfsmp
->hfs_resize_progress
= 0;
540 hfs_unlock_mount (hfsmp
);
543 * - Journaled HFS Plus volumes only.
544 * - No embedded volumes.
546 if ((hfsmp
->jnl
== NULL
) ||
547 (hfsmp
->hfsPlusIOPosOffset
!= 0)) {
551 oldsize
= (u_int64_t
)hfsmp
->totalBlocks
* (u_int64_t
)hfsmp
->blockSize
;
552 newblkcnt
= newsize
/ hfsmp
->blockSize
;
553 reclaimblks
= hfsmp
->totalBlocks
- newblkcnt
;
555 if (hfs_resize_debug
) {
556 printf ("hfs_truncatefs: old: size=%qu, blkcnt=%u, freeblks=%u\n", oldsize
, hfsmp
->totalBlocks
, hfs_freeblks(hfsmp
, 1));
557 printf ("hfs_truncatefs: new: size=%qu, blkcnt=%u, reclaimblks=%u\n", newsize
, newblkcnt
, reclaimblks
);
560 /* Make sure new size is valid. */
561 if ((newsize
< HFS_MIN_SIZE
) ||
562 (newsize
>= oldsize
) ||
563 (newsize
% hfsmp
->hfs_logical_block_size
) ||
564 (newsize
% hfsmp
->hfs_physical_block_size
)) {
565 printf ("hfs_truncatefs: invalid size (newsize=%qu, oldsize=%qu)\n", newsize
, oldsize
);
571 * Make sure that the file system has enough free blocks reclaim.
573 * Before resize, the disk is divided into four zones -
574 * A. Allocated_Stationary - These are allocated blocks that exist
575 * before the new end of disk. These blocks will not be
576 * relocated or modified during resize.
577 * B. Free_Stationary - These are free blocks that exist before the
578 * new end of disk. These blocks can be used for any new
579 * allocations during resize, including allocation for relocating
580 * data from the area of disk being reclaimed.
581 * C. Allocated_To-Reclaim - These are allocated blocks that exist
582 * beyond the new end of disk. These blocks need to be reclaimed
583 * during resize by allocating equal number of blocks in Free
584 * Stationary zone and copying the data.
585 * D. Free_To-Reclaim - These are free blocks that exist beyond the
586 * new end of disk. Nothing special needs to be done to reclaim
589 * Total number of blocks on the disk before resize:
590 * ------------------------------------------------
591 * Total Blocks = Allocated_Stationary + Free_Stationary +
592 * Allocated_To-Reclaim + Free_To-Reclaim
594 * Total number of blocks that need to be reclaimed:
595 * ------------------------------------------------
596 * Blocks to Reclaim = Allocated_To-Reclaim + Free_To-Reclaim
598 * Note that the check below also makes sure that we have enough space
599 * to relocate data from Allocated_To-Reclaim to Free_Stationary.
600 * Therefore we do not need to check total number of blocks to relocate
603 * The condition below gets converted to:
605 * Allocated To-Reclaim + Free To-Reclaim >= Free Stationary + Free To-Reclaim
607 * which is equivalent to:
609 * Allocated To-Reclaim >= Free Stationary
611 if (reclaimblks
>= hfs_freeblks(hfsmp
, 1)) {
612 printf("hfs_truncatefs: insufficient space (need %u blocks; have %u free blocks)\n", reclaimblks
, hfs_freeblks(hfsmp
, 1));
617 /* Start with a clean journal. */
618 hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
620 if (hfs_start_transaction(hfsmp
) != 0) {
624 transaction_begun
= 1;
626 /* Take the bitmap lock to update the alloc limit field */
627 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
630 * Prevent new allocations from using the part we're trying to truncate.
632 * NOTE: allocLimit is set to the allocation block number where the new
633 * alternate volume header will be. That way there will be no files to
634 * interfere with allocating the new alternate volume header, and no files
635 * in the allocation blocks beyond (i.e. the blocks we're trying to
638 if (hfsmp
->blockSize
== 512) {
639 error
= UpdateAllocLimit (hfsmp
, newblkcnt
- 2);
642 error
= UpdateAllocLimit (hfsmp
, newblkcnt
- 1);
645 /* Sparse devices use first fit allocation which is not ideal
646 * for volume resize which requires best fit allocation. If a
647 * sparse device is being truncated, disable the sparse device
648 * property temporarily for the duration of resize. Also reset
649 * the free extent cache so that it is rebuilt as sorted by
650 * totalBlocks instead of startBlock.
652 * Note that this will affect all allocations on the volume and
653 * ideal fix would be just to modify resize-related allocations,
654 * but it will result in complexity like handling of two free
655 * extent caches sorted differently, etc. So we stick to this
658 hfs_lock_mount (hfsmp
);
659 if (hfsmp
->hfs_flags
& HFS_HAS_SPARSE_DEVICE
) {
660 hfsmp
->hfs_flags
&= ~HFS_HAS_SPARSE_DEVICE
;
661 ResetVCBFreeExtCache(hfsmp
);
662 disable_sparse
= true;
666 * Update the volume free block count to reflect the total number
667 * of free blocks that will exist after a successful resize.
668 * Relocation of extents will result in no net change in the total
669 * free space on the disk. Therefore the code that allocates
670 * space for new extent and deallocates the old extent explicitly
671 * prevents updating the volume free block count. It will also
672 * prevent false disk full error when the number of blocks in
673 * an extent being relocated is more than the free blocks that
674 * will exist after the volume is resized.
676 hfsmp
->reclaimBlocks
= reclaimblks
;
677 hfsmp
->freeBlocks
-= reclaimblks
;
678 updateFreeBlocks
= true;
679 hfs_unlock_mount(hfsmp
);
682 hfs_systemfile_unlock(hfsmp
, lockflags
);
687 * Update the metadata zone size to match the new volume size,
688 * and if it too less, metadata zone might be disabled.
690 hfs_metadatazone_init(hfsmp
, false);
693 * If some files have blocks at or beyond the location of the
694 * new alternate volume header, recalculate free blocks and
695 * reclaim blocks. Otherwise just update free blocks count.
697 * The current allocLimit is set to the location of new alternate
698 * volume header, and reclaimblks are the total number of blocks
699 * that need to be reclaimed. So the check below is really
700 * ignoring the blocks allocated for old alternate volume header.
702 if (hfs_isallocated(hfsmp
, hfsmp
->allocLimit
, reclaimblks
)) {
704 * hfs_reclaimspace will use separate transactions when
705 * relocating files (so we don't overwhelm the journal).
707 hfs_end_transaction(hfsmp
);
708 transaction_begun
= 0;
710 /* Attempt to reclaim some space. */
711 error
= hfs_reclaimspace(hfsmp
, hfsmp
->allocLimit
, reclaimblks
, context
);
713 printf("hfs_truncatefs: couldn't reclaim space on %s (error=%d)\n", hfsmp
->vcbVN
, error
);
718 if (hfs_start_transaction(hfsmp
) != 0) {
722 transaction_begun
= 1;
724 /* Check if we're clear now. */
725 error
= hfs_isallocated(hfsmp
, hfsmp
->allocLimit
, reclaimblks
);
727 printf("hfs_truncatefs: didn't reclaim enough space on %s (error=%d)\n", hfsmp
->vcbVN
, error
);
728 error
= EAGAIN
; /* tell client to try again */
734 * Note: we take the attributes lock in case we have an attribute data vnode
735 * which needs to change size.
737 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
| SFL_EXTENTS
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
740 * Allocate last 1KB for alternate volume header.
742 error
= BlockMarkAllocated(hfsmp
, hfsmp
->allocLimit
, (hfsmp
->blockSize
== 512) ? 2 : 1);
744 printf("hfs_truncatefs: Error %d allocating new alternate volume header\n", error
);
749 * Mark the old alternate volume header as free.
750 * We don't bother shrinking allocation bitmap file.
752 if (hfsmp
->blockSize
== 512)
753 (void) BlockMarkFree(hfsmp
, hfsmp
->totalBlocks
- 2, 2);
755 (void) BlockMarkFree(hfsmp
, hfsmp
->totalBlocks
- 1, 1);
757 /* Don't invalidate the old AltVH yet. It is still valid until the partition size is updated ! */
759 /* Log successful shrinking. */
760 printf("hfs_truncatefs: shrank \"%s\" to %d blocks (was %d blocks)\n",
761 hfsmp
->vcbVN
, newblkcnt
, hfsmp
->totalBlocks
);
764 * Adjust file system variables and flush them to disk.
766 * Note that although the logical block size is updated here, it is only
767 * done for the benefit/convenience of the partition management software. The
768 * logical block count change has not yet actually been propagated to
769 * the disk device yet (and we won't get any notification when it does).
771 hfsmp
->totalBlocks
= newblkcnt
;
772 hfsmp
->hfs_logical_block_count
= newsize
/ hfsmp
->hfs_logical_block_size
;
773 hfsmp
->hfs_logical_bytes
= (uint64_t) hfsmp
->hfs_logical_block_count
* (uint64_t) hfsmp
->hfs_logical_block_size
;
774 hfsmp
->reclaimBlocks
= 0;
777 * At this point, a smaller HFS file system exists in a larger volume.
778 * As per volume format, the alternate volume header is located 1024 bytes
779 * before end of the partition. So, until the partition is also resized,
780 * a valid alternate volume header will need to be updated at 1024 bytes
781 * before end of the volume. Under normal circumstances, a file system
782 * resize is always followed by a volume resize, so we also need to
783 * write a copy of the new alternate volume header at 1024 bytes before
784 * end of the new file system.
786 if (hfs_resize_debug
) {
787 printf ("hfs_truncatefs: old: partition_avh_sector=%qu, fs_avh_sector=%qu\n",
788 hfsmp
->hfs_partition_avh_sector
, hfsmp
->hfs_fs_avh_sector
);
790 hfsmp
->hfs_fs_avh_sector
= HFS_ALT_SECTOR(hfsmp
->hfs_logical_block_size
, hfsmp
->hfs_logical_block_count
);
791 /* Note hfs_partition_avh_sector stays unchanged! partition size has not yet been modified */
792 if (hfs_resize_debug
) {
793 printf ("hfs_truncatefs: new: partition_avh_sector=%qu, fs_avh_sector=%qu\n",
794 hfsmp
->hfs_partition_avh_sector
, hfsmp
->hfs_fs_avh_sector
);
798 error
= hfs_flushvolumeheader(hfsmp
, HFS_FVH_WAIT
| HFS_FVH_WRITE_ALT
);
800 panic("hfs_truncatefs: unexpected error flushing volume header (%d)\n", error
);
804 * Adjust the size of hfsmp->hfs_attrdata_vp
806 if (hfsmp
->hfs_attrdata_vp
) {
810 if (vnode_get(hfsmp
->hfs_attrdata_vp
) == 0) {
811 cp
= VTOC(hfsmp
->hfs_attrdata_vp
);
812 fp
= VTOF(hfsmp
->hfs_attrdata_vp
);
814 cp
->c_blocks
= newblkcnt
;
815 fp
->ff_blocks
= newblkcnt
;
816 fp
->ff_extents
[0].blockCount
= newblkcnt
;
817 fp
->ff_size
= (off_t
) newblkcnt
* hfsmp
->blockSize
;
818 ubc_setsize(hfsmp
->hfs_attrdata_vp
, fp
->ff_size
);
819 vnode_put(hfsmp
->hfs_attrdata_vp
);
825 * Update the allocLimit to acknowledge the last one or two blocks now.
826 * Add it to the tree as well if necessary.
828 UpdateAllocLimit (hfsmp
, hfsmp
->totalBlocks
);
830 hfs_lock_mount (hfsmp
);
831 if (disable_sparse
== true) {
832 /* Now that resize is completed, set the volume to be sparse
833 * device again so that all further allocations will be first
834 * fit instead of best fit. Reset free extent cache so that
837 hfsmp
->hfs_flags
|= HFS_HAS_SPARSE_DEVICE
;
838 ResetVCBFreeExtCache(hfsmp
);
841 if (error
&& (updateFreeBlocks
== true)) {
842 hfsmp
->freeBlocks
+= reclaimblks
;
844 hfsmp
->reclaimBlocks
= 0;
846 if (hfsmp
->nextAllocation
>= hfsmp
->allocLimit
) {
847 hfsmp
->nextAllocation
= hfsmp
->hfs_metazone_end
+ 1;
849 hfsmp
->hfs_flags
&= ~HFS_RESIZE_IN_PROGRESS
;
850 hfs_unlock_mount (hfsmp
);
852 /* On error, reset the metadata zone for original volume size */
853 if (error
&& (updateFreeBlocks
== true)) {
854 hfs_metadatazone_init(hfsmp
, false);
858 hfs_systemfile_unlock(hfsmp
, lockflags
);
860 if (transaction_begun
) {
861 hfs_end_transaction(hfsmp
);
862 /* Just to be sure, sync all data to the disk */
863 int flush_error
= hfs_flush(hfsmp
, HFS_FLUSH_FULL
);
864 if (flush_error
&& !error
)
869 printf ("hfs_truncatefs: failed error=%d on vol=%s\n", MacToVFSError(error
), hfsmp
->vcbVN
);
872 return MacToVFSError(error
);
877 * Invalidate the physical block numbers associated with buffer cache blocks
878 * in the given extent of the given vnode.
880 struct hfs_inval_blk_no
{
881 daddr64_t sectorStart
;
882 daddr64_t sectorCount
;
885 hfs_invalidate_block_numbers_callback(buf_t bp
, void *args_in
)
888 struct hfs_inval_blk_no
*args
;
890 blkno
= buf_blkno(bp
);
893 if (blkno
>= args
->sectorStart
&& blkno
< args
->sectorStart
+args
->sectorCount
)
894 buf_setblkno(bp
, buf_lblkno(bp
));
899 hfs_invalidate_sectors(struct vnode
*vp
, daddr64_t sectorStart
, daddr64_t sectorCount
)
901 struct hfs_inval_blk_no args
;
902 args
.sectorStart
= sectorStart
;
903 args
.sectorCount
= sectorCount
;
905 buf_iterate(vp
, hfs_invalidate_block_numbers_callback
, BUF_SCAN_DIRTY
|BUF_SCAN_CLEAN
, &args
);
910 * Copy the contents of an extent to a new location. Also invalidates the
911 * physical block number of any buffer cache block in the copied extent
912 * (so that if the block is written, it will go through VNOP_BLOCKMAP to
913 * determine the new physical block number).
915 * At this point, for regular files, we hold the truncate lock exclusive
916 * and the cnode lock exclusive.
920 struct hfsmount
*hfsmp
,
921 struct vnode
*vp
, /* The file whose extent is being copied. */
922 u_int32_t oldStart
, /* The start of the source extent. */
923 u_int32_t newStart
, /* The start of the destination extent. */
924 u_int32_t blockCount
, /* The number of allocation blocks to copy. */
925 __unused vfs_context_t context
)
930 struct vfsioattr ioattr
;
934 u_int32_t ioSizeSectors
; /* Device sectors in this I/O */
935 daddr64_t srcSector
, destSector
;
936 u_int32_t sectorsPerBlock
= hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
942 * Sanity check that we have locked the vnode of the file we're copying.
944 * But since hfs_systemfile_lock() doesn't actually take the lock on
945 * the allocation file if a journal is active, ignore the check if the
946 * file being copied is the allocation file.
948 struct cnode
*cp
= VTOC(vp
);
949 if (cp
!= hfsmp
->hfs_allocation_cp
&& cp
->c_lockowner
!= current_thread())
950 panic("hfs_copy_extent: vp=%p (cp=%p) not owned?\n", vp
, cp
);
954 * Prepare the CP blob and get it ready for use, if necessary.
956 * Note that we specifically *exclude* system vnodes (catalog, bitmap, extents, EAs),
957 * because they are implicitly protected via the media key on iOS. As such, they
958 * must not be relocated except with the media key. So it is OK to not pass down
959 * a special cpentry to the IOMedia/LwVM code for handling.
961 if (!vnode_issystem (vp
) && vnode_isreg(vp
) && cp_fs_protected (hfsmp
->hfs_mp
)) {
967 * Determine the I/O size to use
969 * NOTE: Many external drives will result in an ioSize of 128KB.
970 * TODO: Should we use a larger buffer, doing several consecutive
971 * reads, then several consecutive writes?
973 vfs_ioattr(hfsmp
->hfs_mp
, &ioattr
);
974 bufferSize
= MIN(ioattr
.io_maxreadcnt
, ioattr
.io_maxwritecnt
);
975 buffer
= hfs_malloc(bufferSize
);
977 /* Get a buffer for doing the I/O */
978 bp
= buf_alloc(hfsmp
->hfs_devvp
);
979 buf_setdataptr(bp
, (uintptr_t)buffer
);
981 resid
= (off_t
) blockCount
* (off_t
) hfsmp
->blockSize
;
982 srcSector
= (daddr64_t
) oldStart
* hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
983 destSector
= (daddr64_t
) newStart
* hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
985 ioSize
= MIN(bufferSize
, (size_t) resid
);
986 ioSizeSectors
= ioSize
/ hfsmp
->hfs_logical_block_size
;
988 /* Prepare the buffer for reading */
989 buf_reset(bp
, B_READ
);
990 buf_setsize(bp
, ioSize
);
991 buf_setcount(bp
, ioSize
);
992 buf_setblkno(bp
, srcSector
);
993 buf_setlblkno(bp
, srcSector
);
996 * Note that because this is an I/O to the device vp
997 * it is correct to have lblkno and blkno both point to the
998 * start sector being read from. If it were being issued against the
999 * underlying file then that would be different.
1002 /* Attach the new CP blob to the buffer if needed */
1005 /* attach the RELOCATION_INFLIGHT flag for the underlying call to VNOP_STRATEGY */
1006 cp
->c_cpentry
->cp_flags
|= CP_RELOCATION_INFLIGHT
;
1007 bufattr_setcpx(buf_attr(bp
), hfsmp
->hfs_resize_cpx
);
1009 /* Initialize the content protection file offset to start at 0 */
1010 bufattr_setcpoff(buf_attr(bp
), 0);
1015 err
= VNOP_STRATEGY(bp
);
1017 err
= buf_biowait(bp
);
1020 /* Turn the flag off in error cases. */
1022 cp
->c_cpentry
->cp_flags
&= ~CP_RELOCATION_INFLIGHT
;
1025 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (read)\n", err
);
1029 /* Prepare the buffer for writing */
1030 buf_reset(bp
, B_WRITE
);
1031 buf_setsize(bp
, ioSize
);
1032 buf_setcount(bp
, ioSize
);
1033 buf_setblkno(bp
, destSector
);
1034 buf_setlblkno(bp
, destSector
);
1035 if (vnode_issystem(vp
) && journal_uses_fua(hfsmp
->jnl
))
1039 /* Attach the CP to the buffer if needed */
1041 bufattr_setcpx(buf_attr(bp
), hfsmp
->hfs_resize_cpx
);
1043 * The last STRATEGY call may have updated the cp file offset behind our
1044 * back, so we cannot trust it. Re-initialize the content protection
1045 * file offset back to 0 before initiating the write portion of this I/O.
1047 bufattr_setcpoff(buf_attr(bp
), 0);
1052 vnode_startwrite(hfsmp
->hfs_devvp
);
1053 err
= VNOP_STRATEGY(bp
);
1055 err
= buf_biowait(bp
);
1058 /* Turn the flag off regardless once the strategy call finishes. */
1060 cp
->c_cpentry
->cp_flags
&= ~CP_RELOCATION_INFLIGHT
;
1064 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (write)\n", err
);
1069 srcSector
+= ioSizeSectors
;
1070 destSector
+= ioSizeSectors
;
1074 hfs_free(buffer
, bufferSize
);
1076 /* Make sure all writes have been flushed to disk. */
1077 if (vnode_issystem(vp
) && !journal_uses_fua(hfsmp
->jnl
)) {
1079 err
= hfs_flush(hfsmp
, HFS_FLUSH_CACHE
);
1081 printf("hfs_copy_extent: hfs_flush failed (%d)\n", err
);
1082 err
= 0; /* Don't fail the copy. */
1087 hfs_invalidate_sectors(vp
, (daddr64_t
)oldStart
*sectorsPerBlock
, (daddr64_t
)blockCount
*sectorsPerBlock
);
1093 /* Structure to store state of reclaiming extents from a
1094 * given file. hfs_reclaim_file()/hfs_reclaim_xattr()
1095 * initializes the values in this structure which are then
1096 * used by code that reclaims and splits the extents.
1098 struct hfs_reclaim_extent_info
{
1102 u_int8_t is_dirlink
; /* Extent belongs to directory hard link */
1103 u_int8_t is_sysfile
; /* Extent belongs to system file */
1104 u_int8_t is_xattr
; /* Extent belongs to extent-based xattr */
1105 u_int8_t extent_index
;
1106 int lockflags
; /* Locks that reclaim and split code should grab before modifying the extent record */
1107 u_int32_t blocks_relocated
; /* Total blocks relocated for this file till now */
1108 u_int32_t recStartBlock
; /* File allocation block number (FABN) for current extent record */
1109 u_int32_t cur_blockCount
; /* Number of allocation blocks that have been checked for reclaim */
1110 struct filefork
*catalog_fp
; /* If non-NULL, extent is from catalog record */
1112 HFSPlusExtentRecord overflow
;/* Extent record from overflow extents btree */
1113 HFSPlusAttrRecord xattr
; /* Attribute record for large EAs */
1115 HFSPlusExtentDescriptor
*extents
; /* Pointer to current extent record being processed.
1116 * For catalog extent record, points to the correct
1117 * extent information in filefork. For overflow extent
1118 * record, or xattr record, points to extent record
1119 * in the structure above
1121 struct cat_desc
*dirlink_desc
;
1122 struct cat_attr
*dirlink_attr
;
1123 struct filefork
*dirlink_fork
; /* For directory hard links, fp points actually to this */
1124 struct BTreeIterator
*iterator
; /* Shared read/write iterator, hfs_reclaim_file/xattr()
1125 * use it for reading and hfs_reclaim_extent()/hfs_split_extent()
1126 * use it for writing updated extent record
1128 struct FSBufferDescriptor btdata
; /* Shared btdata for reading/writing extent record, same as iterator above */
1129 u_int16_t recordlen
;
1130 int overflow_count
; /* For debugging, counter for overflow extent record */
1131 FCB
*fcb
; /* Pointer to the current btree being traversed */
1135 * Split the current extent into two extents, with first extent
1136 * to contain given number of allocation blocks. Splitting of
1137 * extent creates one new extent entry which can result in
1138 * shifting of many entries through all the extent records of a
1139 * file, and/or creating a new extent record in the overflow
1143 * The diagram below represents two consecutive extent records,
1144 * for simplicity, lets call them record X and X+1 respectively.
1145 * Interesting extent entries have been denoted by letters.
1146 * If the letter is unchanged before and after split, it means
1147 * that the extent entry was not modified during the split.
1148 * A '.' means that the entry remains unchanged after the split
1149 * and is not relevant for our example. A '0' means that the
1150 * extent entry is empty.
1152 * If there isn't sufficient contiguous free space to relocate
1153 * an extent (extent "C" below), we will have to break the one
1154 * extent into multiple smaller extents, and relocate each of
1155 * the smaller extents individually. The way we do this is by
1156 * finding the largest contiguous free space that is currently
1157 * available (N allocation blocks), and then convert extent "C"
1158 * into two extents, C1 and C2, that occupy exactly the same
1159 * allocation blocks as extent C. Extent C1 is the first
1160 * N allocation blocks of extent C, and extent C2 is the remainder
1161 * of extent C. Then we can relocate extent C1 since we know
1162 * we have enough contiguous free space to relocate it in its
1163 * entirety. We then repeat the process starting with extent C2.
1165 * In record X, only the entries following entry C are shifted, and
1166 * the original entry C is replaced with two entries C1 and C2 which
1167 * are actually two extent entries for contiguous allocation blocks.
1169 * Note that the entry E from record X is shifted into record X+1 as
1170 * the new first entry. Since the first entry of record X+1 is updated,
1171 * the FABN will also get updated with the blockCount of entry E.
1172 * This also results in shifting of all extent entries in record X+1.
1173 * Note that the number of empty entries after the split has been
1174 * changed from 3 to 2.
1177 * record X record X+1
1178 * ---------------------===--------- ---------------------------------
1179 * | A | . | . | . | B | C | D | E | | F | . | . | . | G | 0 | 0 | 0 |
1180 * ---------------------===--------- ---------------------------------
1183 * ---------------------=======----- ---------------------------------
1184 * | A | . | . | . | B | C1| C2| D | | E | F | . | . | . | G | 0 | 0 |
1185 * ---------------------=======----- ---------------------------------
1187 * C1.startBlock = C.startBlock
1190 * C2.startBlock = C.startBlock + N
1191 * C2.blockCount = C.blockCount - N
1193 * FABN = old FABN - E.blockCount
1196 * extent_info - This is the structure that contains state about
1197 * the current file, extent, and extent record that
1198 * is being relocated. This structure is shared
1199 * among code that traverses through all the extents
1200 * of the file, code that relocates extents, and
1201 * code that splits the extent.
1202 * newBlockCount - The blockCount of the extent to be split after
1203 * successfully split operation.
1205 * Zero on success, non-zero on failure.
1208 hfs_split_extent(struct hfs_reclaim_extent_info
*extent_info
, uint32_t newBlockCount
)
1211 int index
= extent_info
->extent_index
;
1213 HFSPlusExtentDescriptor shift_extent
; /* Extent entry that should be shifted into next extent record */
1214 HFSPlusExtentDescriptor last_extent
;
1215 HFSPlusExtentDescriptor
*extents
; /* Pointer to current extent record being manipulated */
1216 HFSPlusExtentRecord
*extents_rec
= NULL
;
1217 HFSPlusExtentKey
*extents_key
= NULL
;
1218 HFSPlusAttrRecord
*xattr_rec
= NULL
;
1219 HFSPlusAttrKey
*xattr_key
= NULL
;
1220 struct BTreeIterator iterator
;
1221 struct FSBufferDescriptor btdata
;
1223 uint32_t read_recStartBlock
; /* Starting allocation block number to read old extent record */
1224 uint32_t write_recStartBlock
; /* Starting allocation block number to insert newly updated extent record */
1225 Boolean create_record
= false;
1229 is_xattr
= extent_info
->is_xattr
;
1230 extents
= extent_info
->extents
;
1231 cp
= VTOC(extent_info
->vp
);
1233 if (newBlockCount
== 0) {
1234 if (hfs_resize_debug
) {
1235 printf ("hfs_split_extent: No splitting required for newBlockCount=0\n");
1240 if (hfs_resize_debug
) {
1241 printf ("hfs_split_extent: Split record:%u recStartBlock=%u %u:(%u,%u) for %u blocks\n", extent_info
->overflow_count
, extent_info
->recStartBlock
, index
, extents
[index
].startBlock
, extents
[index
].blockCount
, newBlockCount
);
1244 /* Extents overflow btree can not have more than 8 extents.
1245 * No split allowed if the 8th extent is already used.
1247 if ((extent_info
->fileID
== kHFSExtentsFileID
) && (extents
[kHFSPlusExtentDensity
- 1].blockCount
!= 0)) {
1248 printf ("hfs_split_extent: Maximum 8 extents allowed for extents overflow btree, cannot split further.\n");
1253 /* Determine the starting allocation block number for the following
1254 * overflow extent record, if any, before the current record
1257 read_recStartBlock
= extent_info
->recStartBlock
;
1258 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
1259 if (extents
[i
].blockCount
== 0) {
1262 read_recStartBlock
+= extents
[i
].blockCount
;
1265 /* Shift and split */
1266 if (index
== kHFSPlusExtentDensity
-1) {
1267 /* The new extent created after split will go into following overflow extent record */
1268 shift_extent
.startBlock
= extents
[index
].startBlock
+ newBlockCount
;
1269 shift_extent
.blockCount
= extents
[index
].blockCount
- newBlockCount
;
1271 /* Last extent in the record will be split, so nothing to shift */
1273 /* Splitting of extents can result in at most of one
1274 * extent entry to be shifted into following overflow extent
1275 * record. So, store the last extent entry for later.
1277 shift_extent
= extents
[kHFSPlusExtentDensity
-1];
1278 if ((hfs_resize_debug
) && (shift_extent
.blockCount
!= 0)) {
1279 printf ("hfs_split_extent: Save 7:(%u,%u) to shift into overflow record\n", shift_extent
.startBlock
, shift_extent
.blockCount
);
1282 /* Start shifting extent information from the end of the extent
1283 * record to the index where we want to insert the new extent.
1284 * Note that kHFSPlusExtentDensity-1 is already saved above, and
1285 * does not need to be shifted. The extent entry that is being
1286 * split does not get shifted.
1288 for (i
= kHFSPlusExtentDensity
-2; i
> index
; i
--) {
1289 if (hfs_resize_debug
) {
1290 if (extents
[i
].blockCount
) {
1291 printf ("hfs_split_extent: Shift %u:(%u,%u) to %u:(%u,%u)\n", i
, extents
[i
].startBlock
, extents
[i
].blockCount
, i
+1, extents
[i
].startBlock
, extents
[i
].blockCount
);
1294 extents
[i
+1] = extents
[i
];
1298 if (index
== kHFSPlusExtentDensity
-1) {
1299 /* The second half of the extent being split will be the overflow
1300 * entry that will go into following overflow extent record. The
1301 * value has been stored in 'shift_extent' above, so there is
1302 * nothing to be done here.
1305 /* Update the values in the second half of the extent being split
1306 * before updating the first half of the split. Note that the
1307 * extent to split or first half of the split is at index 'index'
1308 * and a new extent or second half of the split will be inserted at
1309 * 'index+1' or into following overflow extent record.
1311 extents
[index
+1].startBlock
= extents
[index
].startBlock
+ newBlockCount
;
1312 extents
[index
+1].blockCount
= extents
[index
].blockCount
- newBlockCount
;
1314 /* Update the extent being split, only the block count will change */
1315 extents
[index
].blockCount
= newBlockCount
;
1317 if (hfs_resize_debug
) {
1318 printf ("hfs_split_extent: Split %u:(%u,%u) and ", index
, extents
[index
].startBlock
, extents
[index
].blockCount
);
1319 if (index
!= kHFSPlusExtentDensity
-1) {
1320 printf ("%u:(%u,%u)\n", index
+1, extents
[index
+1].startBlock
, extents
[index
+1].blockCount
);
1322 printf ("overflow:(%u,%u)\n", shift_extent
.startBlock
, shift_extent
.blockCount
);
1326 /* Write out information about the newly split extent to the disk */
1327 if (extent_info
->catalog_fp
) {
1328 /* (extent_info->catalog_fp != NULL) means the newly split
1329 * extent exists in the catalog record. This means that
1330 * the cnode was updated. Therefore, to write out the changes,
1331 * mark the cnode as modified. We cannot call hfs_update()
1332 * in this function because the caller hfs_reclaim_extent()
1333 * is holding the catalog lock currently.
1335 cp
->c_flag
|= C_MODIFIED
;
1337 /* The newly split extent is for large EAs or is in overflow
1338 * extent record, so update it directly in the btree using the
1339 * iterator information from the shared extent_info structure
1341 error
= BTReplaceRecord(extent_info
->fcb
, extent_info
->iterator
,
1342 &(extent_info
->btdata
), extent_info
->recordlen
);
1344 printf ("hfs_split_extent: fileID=%u BTReplaceRecord returned error=%d\n", extent_info
->fileID
, error
);
1349 /* No extent entry to be shifted into another extent overflow record */
1350 if (shift_extent
.blockCount
== 0) {
1351 if (hfs_resize_debug
) {
1352 printf ("hfs_split_extent: No extent entry to be shifted into overflow records\n");
1358 /* The overflow extent entry has to be shifted into an extent
1359 * overflow record. This means that we might have to shift
1360 * extent entries from all subsequent overflow records by one.
1361 * We start iteration from the first record to the last record,
1362 * and shift the extent entry from one record to another.
1363 * We might have to create a new extent record for the last
1364 * extent entry for the file.
1367 /* Initialize iterator to search the next record */
1368 bzero(&iterator
, sizeof(iterator
));
1370 /* Copy the key from the iterator that was used to update the modified attribute record. */
1371 xattr_key
= (HFSPlusAttrKey
*)&(iterator
.key
);
1372 bcopy((HFSPlusAttrKey
*)&(extent_info
->iterator
->key
), xattr_key
, sizeof(HFSPlusAttrKey
));
1373 /* Note: xattr_key->startBlock will be initialized later in the iteration loop */
1375 xattr_rec
= hfs_malloc(sizeof(*xattr_rec
));
1377 btdata
.bufferAddress
= xattr_rec
;
1378 btdata
.itemSize
= sizeof(HFSPlusAttrRecord
);
1379 btdata
.itemCount
= 1;
1380 extents
= xattr_rec
->overflowExtents
.extents
;
1382 /* Initialize the extent key for the current file */
1383 extents_key
= (HFSPlusExtentKey
*) &(iterator
.key
);
1384 extents_key
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
1385 extents_key
->forkType
= extent_info
->forkType
;
1386 extents_key
->fileID
= extent_info
->fileID
;
1387 /* Note: extents_key->startBlock will be initialized later in the iteration loop */
1389 extents_rec
= hfs_malloc(sizeof(*extents_rec
));
1391 btdata
.bufferAddress
= extents_rec
;
1392 btdata
.itemSize
= sizeof(HFSPlusExtentRecord
);
1393 btdata
.itemCount
= 1;
1394 extents
= extents_rec
[0];
1397 /* The overflow extent entry has to be shifted into an extent
1398 * overflow record. This means that we might have to shift
1399 * extent entries from all subsequent overflow records by one.
1400 * We start iteration from the first record to the last record,
1401 * examine one extent record in each iteration and shift one
1402 * extent entry from one record to another. We might have to
1403 * create a new extent record for the last extent entry for the
1406 * If shift_extent.blockCount is non-zero, it means that there is
1407 * an extent entry that needs to be shifted into the next
1408 * overflow extent record. We keep on going till there are no such
1409 * entries left to be shifted. This will also change the starting
1410 * allocation block number of the extent record which is part of
1411 * the key for the extent record in each iteration. Note that
1412 * because the extent record key is changing while we are searching,
1413 * the record can not be updated directly, instead it has to be
1414 * deleted and inserted again.
1416 while (shift_extent
.blockCount
) {
1417 if (hfs_resize_debug
) {
1418 printf ("hfs_split_extent: Will shift (%u,%u) into overflow record with startBlock=%u\n", shift_extent
.startBlock
, shift_extent
.blockCount
, read_recStartBlock
);
1421 /* Search if there is any existing overflow extent record
1422 * that matches the current file and the logical start block
1425 * For this, the logical start block number in the key is
1426 * the value calculated based on the logical start block
1427 * number of the current extent record and the total number
1428 * of blocks existing in the current extent record.
1431 xattr_key
->startBlock
= read_recStartBlock
;
1433 extents_key
->startBlock
= read_recStartBlock
;
1435 error
= BTSearchRecord(extent_info
->fcb
, &iterator
, &btdata
, &reclen
, &iterator
);
1437 if (error
!= btNotFound
) {
1438 printf ("hfs_split_extent: fileID=%u startBlock=%u BTSearchRecord error=%d\n", extent_info
->fileID
, read_recStartBlock
, error
);
1441 /* No matching record was found, so create a new extent record.
1442 * Note: Since no record was found, we can't rely on the
1443 * btree key in the iterator any longer. This will be initialized
1444 * later before we insert the record.
1446 create_record
= true;
1449 /* The extra extent entry from the previous record is being inserted
1450 * as the first entry in the current extent record. This will change
1451 * the file allocation block number (FABN) of the current extent
1452 * record, which is the startBlock value from the extent record key.
1453 * Since one extra entry is being inserted in the record, the new
1454 * FABN for the record will less than old FABN by the number of blocks
1455 * in the new extent entry being inserted at the start. We have to
1456 * do this before we update read_recStartBlock to point at the
1457 * startBlock of the following record.
1459 write_recStartBlock
= read_recStartBlock
- shift_extent
.blockCount
;
1460 if (hfs_resize_debug
) {
1461 if (create_record
) {
1462 printf ("hfs_split_extent: No records found for startBlock=%u, will create new with startBlock=%u\n", read_recStartBlock
, write_recStartBlock
);
1466 /* Now update the read_recStartBlock to account for total number
1467 * of blocks in this extent record. It will now point to the
1468 * starting allocation block number for the next extent record.
1470 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
1471 if (extents
[i
].blockCount
== 0) {
1474 read_recStartBlock
+= extents
[i
].blockCount
;
1477 if (create_record
== true) {
1478 /* Initialize new record content with only one extent entry */
1479 bzero(extents
, sizeof(HFSPlusExtentRecord
));
1480 /* The new record will contain only one extent entry */
1481 extents
[0] = shift_extent
;
1482 /* There are no more overflow extents to be shifted */
1483 shift_extent
.startBlock
= shift_extent
.blockCount
= 0;
1486 /* BTSearchRecord above returned btNotFound,
1487 * but since the attribute btree is never empty
1488 * if we are trying to insert new overflow
1489 * record for the xattrs, the extents_key will
1490 * contain correct data. So we don't need to
1491 * re-initialize it again like below.
1494 /* Initialize the new xattr record */
1495 xattr_rec
->recordType
= kHFSPlusAttrExtents
;
1496 xattr_rec
->overflowExtents
.reserved
= 0;
1497 reclen
= sizeof(HFSPlusAttrExtents
);
1499 /* BTSearchRecord above returned btNotFound,
1500 * which means that extents_key content might
1501 * not correspond to the record that we are
1502 * trying to create, especially when the extents
1503 * overflow btree is empty. So we reinitialize
1504 * the extents_key again always.
1506 extents_key
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
1507 extents_key
->forkType
= extent_info
->forkType
;
1508 extents_key
->fileID
= extent_info
->fileID
;
1510 /* Initialize the new extent record */
1511 reclen
= sizeof(HFSPlusExtentRecord
);
1514 /* The overflow extent entry from previous record will be
1515 * the first entry in this extent record. If the last
1516 * extent entry in this record is valid, it will be shifted
1517 * into the following extent record as its first entry. So
1518 * save the last entry before shifting entries in current
1521 last_extent
= extents
[kHFSPlusExtentDensity
-1];
1523 /* Shift all entries by one index towards the end */
1524 for (i
= kHFSPlusExtentDensity
-2; i
>= 0; i
--) {
1525 extents
[i
+1] = extents
[i
];
1528 /* Overflow extent entry saved from previous record
1529 * is now the first entry in the current record.
1531 extents
[0] = shift_extent
;
1533 if (hfs_resize_debug
) {
1534 printf ("hfs_split_extent: Shift overflow=(%u,%u) to record with updated startBlock=%u\n", shift_extent
.startBlock
, shift_extent
.blockCount
, write_recStartBlock
);
1537 /* The last entry from current record will be the
1538 * overflow entry which will be the first entry for
1539 * the following extent record.
1541 shift_extent
= last_extent
;
1543 /* Since the key->startBlock is being changed for this record,
1544 * it should be deleted and inserted with the new key.
1546 error
= BTDeleteRecord(extent_info
->fcb
, &iterator
);
1548 printf ("hfs_split_extent: fileID=%u startBlock=%u BTDeleteRecord error=%d\n", extent_info
->fileID
, read_recStartBlock
, error
);
1551 if (hfs_resize_debug
) {
1552 printf ("hfs_split_extent: Deleted extent record with startBlock=%u\n", (is_xattr
? xattr_key
->startBlock
: extents_key
->startBlock
));
1556 /* Insert the newly created or modified extent record */
1557 bzero(&iterator
.hint
, sizeof(iterator
.hint
));
1559 xattr_key
->startBlock
= write_recStartBlock
;
1561 extents_key
->startBlock
= write_recStartBlock
;
1563 error
= BTInsertRecord(extent_info
->fcb
, &iterator
, &btdata
, reclen
);
1565 printf ("hfs_split_extent: fileID=%u, startBlock=%u BTInsertRecord error=%d\n", extent_info
->fileID
, write_recStartBlock
, error
);
1568 if (hfs_resize_debug
) {
1569 printf ("hfs_split_extent: Inserted extent record with startBlock=%u\n", write_recStartBlock
);
1575 * Extents overflow btree or attributes btree headers might have
1576 * been modified during the split/shift operation, so flush the
1577 * changes to the disk while we are inside journal transaction.
1578 * We should only be able to generate I/O that modifies the B-Tree
1579 * header nodes while we're in the middle of a journal transaction.
1580 * Otherwise it might result in panic during unmount.
1582 BTFlushPath(extent_info
->fcb
);
1584 hfs_free(extents_rec
, sizeof(*extents_rec
));
1585 hfs_free(xattr_rec
, sizeof(*xattr_rec
));
1591 * Relocate an extent if it lies beyond the expected end of volume.
1593 * This function is called for every extent of the file being relocated.
1594 * It allocates space for relocation, copies the data, deallocates
1595 * the old extent, and update corresponding on-disk extent. If the function
1596 * does not find contiguous space to relocate an extent, it splits the
1597 * extent in smaller size to be able to relocate it out of the area of
1598 * disk being reclaimed. As an optimization, if an extent lies partially
1599 * in the area of the disk being reclaimed, it is split so that we only
1600 * have to relocate the area that was overlapping with the area of disk
1603 * Note that every extent is relocated in its own transaction so that
1604 * they do not overwhelm the journal. This function handles the extent
1605 * record that exists in the catalog record, extent record from overflow
1606 * extents btree, and extents for large EAs.
1609 * extent_info - This is the structure that contains state about
1610 * the current file, extent, and extent record that
1611 * is being relocated. This structure is shared
1612 * among code that traverses through all the extents
1613 * of the file, code that relocates extents, and
1614 * code that splits the extent.
1617 hfs_reclaim_extent(struct hfsmount
*hfsmp
, const u_long allocLimit
, struct hfs_reclaim_extent_info
*extent_info
, vfs_context_t context
)
1622 u_int32_t oldStartBlock
;
1623 u_int32_t oldBlockCount
;
1624 u_int32_t newStartBlock
= 0;
1625 u_int32_t newBlockCount
;
1626 u_int32_t roundedBlockCount
;
1628 uint32_t remainder_blocks
;
1629 u_int32_t alloc_flags
;
1630 int blocks_allocated
= false;
1632 index
= extent_info
->extent_index
;
1633 cp
= VTOC(extent_info
->vp
);
1635 oldStartBlock
= extent_info
->extents
[index
].startBlock
;
1636 oldBlockCount
= extent_info
->extents
[index
].blockCount
;
1638 if (0 && hfs_resize_debug
) {
1639 printf ("hfs_reclaim_extent: Examine record:%u recStartBlock=%u, %u:(%u,%u)\n", extent_info
->overflow_count
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
);
1642 /* If the current extent lies completely within allocLimit,
1643 * it does not require any relocation.
1645 if ((oldStartBlock
+ oldBlockCount
) <= allocLimit
) {
1646 extent_info
->cur_blockCount
+= oldBlockCount
;
1650 /* Every extent should be relocated in its own transaction
1651 * to make sure that we don't overflow the journal buffer.
1653 error
= hfs_start_transaction(hfsmp
);
1657 extent_info
->lockflags
= hfs_systemfile_lock(hfsmp
, extent_info
->lockflags
, HFS_EXCLUSIVE_LOCK
);
1659 /* Check if the extent lies partially in the area to reclaim,
1660 * i.e. it starts before allocLimit and ends beyond allocLimit.
1661 * We have already skipped extents that lie completely within
1662 * allocLimit in the check above, so we only check for the
1663 * startBlock. If it lies partially, split it so that we
1664 * only relocate part of the extent.
1666 if (oldStartBlock
< allocLimit
) {
1667 newBlockCount
= allocLimit
- oldStartBlock
;
1669 if (hfs_resize_debug
) {
1670 int idx
= extent_info
->extent_index
;
1671 printf ("hfs_reclaim_extent: Split straddling extent %u:(%u,%u) for %u blocks\n", idx
, extent_info
->extents
[idx
].startBlock
, extent_info
->extents
[idx
].blockCount
, newBlockCount
);
1674 /* If the extent belongs to a btree, check and trim
1675 * it to be multiple of the node size.
1677 if (extent_info
->is_sysfile
) {
1678 node_size
= get_btree_nodesize(extent_info
->vp
);
1679 /* If the btree node size is less than the block size,
1680 * splitting this extent will not split a node across
1681 * different extents. So we only check and trim if
1682 * node size is more than the allocation block size.
1684 if (node_size
> hfsmp
->blockSize
) {
1685 remainder_blocks
= newBlockCount
% (node_size
/ hfsmp
->blockSize
);
1686 if (remainder_blocks
) {
1687 newBlockCount
-= remainder_blocks
;
1688 if (hfs_resize_debug
) {
1689 printf ("hfs_reclaim_extent: Round-down newBlockCount to be multiple of nodeSize, node_allocblks=%u, old=%u, new=%u\n", node_size
/hfsmp
->blockSize
, newBlockCount
+ remainder_blocks
, newBlockCount
);
1693 /* The newBlockCount is zero because of rounding-down so that
1694 * btree nodes are not split across extents. Therefore this
1695 * straddling extent across resize-boundary does not require
1696 * splitting. Skip over to relocating of complete extent.
1698 if (newBlockCount
== 0) {
1699 if (hfs_resize_debug
) {
1700 printf ("hfs_reclaim_extent: After round-down newBlockCount=0, skip split, relocate full extent\n");
1702 goto relocate_full_extent
;
1706 /* Split the extents into two parts --- the first extent lies
1707 * completely within allocLimit and therefore does not require
1708 * relocation. The second extent will require relocation which
1709 * will be handled when the caller calls this function again
1710 * for the next extent.
1712 error
= hfs_split_extent(extent_info
, newBlockCount
);
1714 /* Split success, no relocation required */
1717 /* Split failed, so try to relocate entire extent */
1718 if (hfs_resize_debug
) {
1719 int idx
= extent_info
->extent_index
;
1720 printf ("hfs_reclaim_extent: Split straddling extent %u:(%u,%u) for %u blocks failed, relocate full extent\n", idx
, extent_info
->extents
[idx
].startBlock
, extent_info
->extents
[idx
].blockCount
, newBlockCount
);
1724 relocate_full_extent
:
1725 /* At this point, the current extent requires relocation.
1726 * We will try to allocate space equal to the size of the extent
1727 * being relocated first to try to relocate it without splitting.
1728 * If the allocation fails, we will try to allocate contiguous
1729 * blocks out of metadata zone. If that allocation also fails,
1730 * then we will take a whatever contiguous block run is returned
1731 * by the allocation, split the extent into two parts, and then
1732 * relocate the first splitted extent.
1734 alloc_flags
= HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_SKIPFREEBLKS
;
1735 if (extent_info
->is_sysfile
) {
1736 alloc_flags
|= HFS_ALLOC_METAZONE
;
1739 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
, alloc_flags
,
1740 &newStartBlock
, &newBlockCount
);
1741 if ((extent_info
->is_sysfile
== false) &&
1742 ((error
== dskFulErr
) || (error
== ENOSPC
))) {
1743 /* For non-system files, try reallocating space in metadata zone */
1744 alloc_flags
|= HFS_ALLOC_METAZONE
;
1745 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
,
1746 alloc_flags
, &newStartBlock
, &newBlockCount
);
1748 if ((error
== dskFulErr
) || (error
== ENOSPC
)) {
1750 * We did not find desired contiguous space for this
1751 * extent, when we asked for it, including the metazone allocations.
1752 * At this point we are not worrying about getting contiguity anymore.
1754 * HOWEVER, if we now allow blocks to be used which were recently
1755 * de-allocated, we may find a contiguous range (though this seems
1756 * unlikely). As a result, assume that we will have to split the
1757 * current extent into two pieces, but if we are able to satisfy
1758 * the request with a single extent, detect that as well.
1760 alloc_flags
&= ~HFS_ALLOC_FORCECONTIG
;
1761 alloc_flags
|= HFS_ALLOC_FLUSHTXN
;
1763 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
,
1764 alloc_flags
, &newStartBlock
, &newBlockCount
);
1766 printf ("hfs_reclaim_extent: fileID=%u start=%u, %u:(%u,%u) BlockAllocate error=%d\n", extent_info
->fileID
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
, error
);
1771 * Allowing recently deleted extents may now allow us to find
1772 * a single contiguous extent in the amount & size desired. If so,
1773 * do NOT split this extent into two pieces. This is technically a
1774 * check for "< oldBlockCount", but we use != to highlight the point
1775 * that the special case is when they're equal. The allocator should
1776 * never vend back more blocks than were requested.
1778 if (newBlockCount
!= oldBlockCount
) {
1779 blocks_allocated
= true;
1781 /* The number of blocks allocated is less than the requested
1782 * number of blocks. For btree extents, check and trim the
1783 * extent to be multiple of the node size.
1785 if (extent_info
->is_sysfile
) {
1786 node_size
= get_btree_nodesize(extent_info
->vp
);
1787 if (node_size
> hfsmp
->blockSize
) {
1788 remainder_blocks
= newBlockCount
% (node_size
/ hfsmp
->blockSize
);
1789 if (remainder_blocks
) {
1790 roundedBlockCount
= newBlockCount
- remainder_blocks
;
1791 /* Free tail-end blocks of the newly allocated extent */
1792 BlockDeallocate(hfsmp
, newStartBlock
+ roundedBlockCount
,
1793 newBlockCount
- roundedBlockCount
,
1794 HFS_ALLOC_SKIPFREEBLKS
);
1795 newBlockCount
= roundedBlockCount
;
1796 if (hfs_resize_debug
) {
1797 printf ("hfs_reclaim_extent: Fixing extent block count, node_blks=%u, old=%u, new=%u\n", node_size
/hfsmp
->blockSize
, newBlockCount
+ remainder_blocks
, newBlockCount
);
1799 if (newBlockCount
== 0) {
1800 printf ("hfs_reclaim_extent: Not enough contiguous blocks available to relocate fileID=%d\n", extent_info
->fileID
);
1808 /* The number of blocks allocated is less than the number of
1809 * blocks requested, so split this extent --- the first extent
1810 * will be relocated as part of this function call and the caller
1811 * will handle relocating the second extent by calling this
1812 * function again for the second extent.
1814 error
= hfs_split_extent(extent_info
, newBlockCount
);
1816 printf ("hfs_reclaim_extent: fileID=%u start=%u, %u:(%u,%u) split error=%d\n", extent_info
->fileID
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
, error
);
1819 oldBlockCount
= newBlockCount
;
1820 } /* end oldBlockCount != newBlockCount */
1821 } /* end allocation request for any available free space */
1824 printf ("hfs_reclaim_extent: fileID=%u start=%u, %u:(%u,%u) contig BlockAllocate error=%d\n", extent_info
->fileID
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
, error
);
1827 blocks_allocated
= true;
1829 /* Copy data from old location to new location */
1830 error
= hfs_copy_extent(hfsmp
, extent_info
->vp
, oldStartBlock
,
1831 newStartBlock
, newBlockCount
, context
);
1833 printf ("hfs_reclaim_extent: fileID=%u start=%u, %u:(%u,%u)=>(%u,%u) hfs_copy_extent error=%d\n", extent_info
->fileID
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
, newStartBlock
, newBlockCount
, error
);
1837 /* Update the extent record with the new start block information */
1838 extent_info
->extents
[index
].startBlock
= newStartBlock
;
1840 /* Sync the content back to the disk */
1841 if (extent_info
->catalog_fp
) {
1842 /* Update the extents in catalog record */
1843 if (extent_info
->is_dirlink
) {
1844 error
= cat_update_dirlink(hfsmp
, extent_info
->forkType
,
1845 extent_info
->dirlink_desc
, extent_info
->dirlink_attr
,
1846 &(extent_info
->dirlink_fork
->ff_data
));
1848 cp
->c_flag
|= C_MODIFIED
;
1849 /* If this is a system file, sync volume headers on disk */
1850 if (extent_info
->is_sysfile
) {
1851 error
= hfs_flushvolumeheader(hfsmp
, HFS_FVH_WAIT
| HFS_FVH_WRITE_ALT
);
1855 /* Replace record for extents overflow or extents-based xattrs */
1856 error
= BTReplaceRecord(extent_info
->fcb
, extent_info
->iterator
,
1857 &(extent_info
->btdata
), extent_info
->recordlen
);
1860 printf ("hfs_reclaim_extent: fileID=%u, update record error=%u\n", extent_info
->fileID
, error
);
1864 /* Deallocate the old extent */
1865 error
= BlockDeallocate(hfsmp
, oldStartBlock
, oldBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
1867 printf ("hfs_reclaim_extent: fileID=%u start=%u, %u:(%u,%u) BlockDeallocate error=%d\n", extent_info
->fileID
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
, error
);
1870 extent_info
->blocks_relocated
+= newBlockCount
;
1872 if (hfs_resize_debug
) {
1873 printf ("hfs_reclaim_extent: Relocated record:%u %u:(%u,%u) to (%u,%u)\n", extent_info
->overflow_count
, index
, oldStartBlock
, oldBlockCount
, newStartBlock
, newBlockCount
);
1878 if (blocks_allocated
== true) {
1879 BlockDeallocate(hfsmp
, newStartBlock
, newBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
1882 /* On success, increment the total allocation blocks processed */
1883 extent_info
->cur_blockCount
+= newBlockCount
;
1886 hfs_systemfile_unlock(hfsmp
, extent_info
->lockflags
);
1888 /* For a non-system file, if an extent entry from catalog record
1889 * was modified, sync the in-memory changes to the catalog record
1890 * on disk before ending the transaction.
1892 if ((extent_info
->catalog_fp
) &&
1893 (extent_info
->is_sysfile
== false)) {
1894 hfs_update(extent_info
->vp
, 0);
1897 hfs_end_transaction(hfsmp
);
1902 /* Report intermediate progress during volume resize */
1904 hfs_truncatefs_progress(struct hfsmount
*hfsmp
)
1906 u_int32_t cur_progress
= 0;
1908 hfs_resize_progress(hfsmp
, &cur_progress
);
1909 if (cur_progress
> (hfsmp
->hfs_resize_progress
+ 9)) {
1910 printf("hfs_truncatefs: %d%% done...\n", cur_progress
);
1911 hfsmp
->hfs_resize_progress
= cur_progress
;
1917 * Reclaim space at the end of a volume for given file and forktype.
1919 * This routine attempts to move any extent which contains allocation blocks
1920 * at or after "allocLimit." A separate transaction is used for every extent
1921 * that needs to be moved. If there is not contiguous space available for
1922 * moving an extent, it can be split into smaller extents. The contents of
1923 * any moved extents are read and written via the volume's device vnode --
1924 * NOT via "vp." During the move, moved blocks which are part of a transaction
1925 * have their physical block numbers invalidated so they will eventually be
1926 * written to their new locations.
1928 * This function is also called for directory hard links. Directory hard links
1929 * are regular files with no data fork and resource fork that contains alias
1930 * information for backward compatibility with pre-Leopard systems. However
1931 * non-Mac OS X implementation can add/modify data fork or resource fork
1932 * information to directory hard links, so we check, and if required, relocate
1933 * both data fork and resource fork.
1936 * hfsmp The volume being resized.
1937 * vp The vnode for the system file.
1938 * fileID ID of the catalog record that needs to be relocated
1939 * forktype The type of fork that needs relocated,
1940 * kHFSResourceForkType for resource fork,
1941 * kHFSDataForkType for data fork
1942 * allocLimit Allocation limit for the new volume size,
1943 * do not use this block or beyond. All extents
1944 * that use this block or any blocks beyond this limit
1945 * will be relocated.
1948 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
1949 * blocks that were relocated.
1952 hfs_reclaim_file(struct hfsmount
*hfsmp
, struct vnode
*vp
, u_int32_t fileID
,
1953 u_int8_t forktype
, u_long allocLimit
, vfs_context_t context
)
1956 struct hfs_reclaim_extent_info
*extent_info
;
1960 struct filefork
*fp
;
1961 int took_truncate_lock
= false;
1962 int release_desc
= false;
1963 HFSPlusExtentKey
*key
;
1965 /* If there is no vnode for this file, then there's nothing to do. */
1972 if (hfs_resize_debug
) {
1973 const char *filename
= (const char *) cp
->c_desc
.cd_nameptr
;
1974 int namelen
= cp
->c_desc
.cd_namelen
;
1976 if (filename
== NULL
) {
1980 printf("hfs_reclaim_file: reclaiming '%.*s'\n", namelen
, filename
);
1983 extent_info
= hfs_mallocz(sizeof(struct hfs_reclaim_extent_info
));
1985 extent_info
->vp
= vp
;
1986 extent_info
->fileID
= fileID
;
1987 extent_info
->forkType
= forktype
;
1988 extent_info
->is_sysfile
= vnode_issystem(vp
);
1989 if (vnode_isdir(vp
) && (cp
->c_flag
& C_HARDLINK
)) {
1990 extent_info
->is_dirlink
= true;
1992 /* We always need allocation bitmap and extent btree lock */
1993 lockflags
= SFL_BITMAP
| SFL_EXTENTS
;
1994 if ((fileID
== kHFSCatalogFileID
) || (extent_info
->is_dirlink
== true)) {
1995 lockflags
|= SFL_CATALOG
;
1996 } else if (fileID
== kHFSAttributesFileID
) {
1997 lockflags
|= SFL_ATTRIBUTE
;
1998 } else if (fileID
== kHFSStartupFileID
) {
1999 lockflags
|= SFL_STARTUP
;
2001 extent_info
->lockflags
= lockflags
;
2002 extent_info
->fcb
= VTOF(hfsmp
->hfs_extents_vp
);
2004 /* Flush data associated with current file on disk.
2006 * If the current vnode is directory hard link, no flushing of
2007 * journal or vnode is required. The current kernel does not
2008 * modify data/resource fork of directory hard links, so nothing
2009 * will be in the cache. If a directory hard link is newly created,
2010 * the resource fork data is written directly using devvp and
2011 * the code that actually relocates data (hfs_copy_extent()) also
2012 * uses devvp for its I/O --- so they will see a consistent copy.
2014 if (extent_info
->is_sysfile
) {
2015 /* If the current vnode is system vnode, flush journal
2016 * to make sure that all data is written to the disk.
2018 error
= hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
2020 printf ("hfs_reclaim_file: journal_flush returned %d\n", error
);
2023 } else if (extent_info
->is_dirlink
== false) {
2024 /* Flush all blocks associated with this regular file vnode.
2025 * Normally there should not be buffer cache blocks for regular
2026 * files, but for objects like symlinks, we can have buffer cache
2027 * blocks associated with the vnode. Therefore we call
2028 * buf_flushdirtyblks() also.
2030 buf_flushdirtyblks(vp
, 0, BUF_SKIP_LOCKED
, "hfs_reclaim_file");
2033 hfs_lock_truncate(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
);
2034 took_truncate_lock
= true;
2035 (void) cluster_push(vp
, 0);
2036 error
= hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
, HFS_LOCK_ALLOW_NOEXISTS
);
2041 /* If the file no longer exists, nothing left to do */
2042 if (cp
->c_flag
& C_NOEXISTS
) {
2047 /* Wait for any in-progress writes to this vnode to complete, so that we'll
2048 * be copying consistent bits. (Otherwise, it's possible that an async
2049 * write will complete to the old extent after we read from it. That
2050 * could lead to corruption.)
2052 error
= vnode_waitforwrites(vp
, 0, 0, 0, "hfs_reclaim_file");
2058 if (hfs_resize_debug
) {
2059 printf("hfs_reclaim_file: === Start reclaiming %sfork for %sid=%u ===\n", (forktype
? "rsrc" : "data"), (extent_info
->is_dirlink
? "dirlink" : "file"), fileID
);
2062 if (extent_info
->is_dirlink
) {
2063 extent_info
->dirlink_desc
= hfs_malloc(sizeof(struct cat_desc
));
2064 extent_info
->dirlink_attr
= hfs_malloc(sizeof(struct cat_attr
));
2065 extent_info
->dirlink_fork
= hfs_mallocz(sizeof(struct filefork
));
2067 /* Lookup catalog record for directory hard link and
2068 * create a fake filefork for the value looked up from
2071 fp
= extent_info
->dirlink_fork
;
2072 extent_info
->dirlink_fork
->ff_cp
= cp
;
2073 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
2074 error
= cat_lookup_dirlink(hfsmp
, fileID
, forktype
,
2075 extent_info
->dirlink_desc
, extent_info
->dirlink_attr
,
2076 &(extent_info
->dirlink_fork
->ff_data
));
2077 hfs_systemfile_unlock(hfsmp
, lockflags
);
2079 printf ("hfs_reclaim_file: cat_lookup_dirlink for fileID=%u returned error=%u\n", fileID
, error
);
2082 release_desc
= true;
2087 extent_info
->catalog_fp
= fp
;
2088 extent_info
->recStartBlock
= 0;
2089 extent_info
->extents
= extent_info
->catalog_fp
->ff_extents
;
2090 /* Relocate extents from the catalog record */
2091 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
2092 if (fp
->ff_extents
[i
].blockCount
== 0) {
2095 extent_info
->extent_index
= i
;
2096 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
2098 printf ("hfs_reclaim_file: fileID=%u #%d %u:(%u,%u) hfs_reclaim_extent error=%d\n", fileID
, extent_info
->overflow_count
, i
, fp
->ff_extents
[i
].startBlock
, fp
->ff_extents
[i
].blockCount
, error
);
2103 /* If the number of allocation blocks processed for reclaiming
2104 * are less than total number of blocks for the file, continuing
2105 * working on overflow extents record.
2107 if (fp
->ff_blocks
<= extent_info
->cur_blockCount
) {
2108 if (0 && hfs_resize_debug
) {
2109 printf ("hfs_reclaim_file: Nothing more to relocate, offset=%d, ff_blocks=%u, cur_blockCount=%u\n", i
, fp
->ff_blocks
, extent_info
->cur_blockCount
);
2114 if (hfs_resize_debug
) {
2115 printf ("hfs_reclaim_file: Will check overflow records, offset=%d, ff_blocks=%u, cur_blockCount=%u\n", i
, fp
->ff_blocks
, extent_info
->cur_blockCount
);
2118 extent_info
->iterator
= hfs_mallocz(sizeof(struct BTreeIterator
));
2119 key
= (HFSPlusExtentKey
*) &(extent_info
->iterator
->key
);
2120 key
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
2121 key
->forkType
= forktype
;
2122 key
->fileID
= fileID
;
2123 key
->startBlock
= extent_info
->cur_blockCount
;
2125 extent_info
->btdata
.bufferAddress
= extent_info
->record
.overflow
;
2126 extent_info
->btdata
.itemSize
= sizeof(HFSPlusExtentRecord
);
2127 extent_info
->btdata
.itemCount
= 1;
2129 extent_info
->catalog_fp
= NULL
;
2131 /* Search the first overflow extent with expected startBlock as 'cur_blockCount' */
2132 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
2133 error
= BTSearchRecord(extent_info
->fcb
, extent_info
->iterator
,
2134 &(extent_info
->btdata
), &(extent_info
->recordlen
),
2135 extent_info
->iterator
);
2136 hfs_systemfile_unlock(hfsmp
, lockflags
);
2137 while (error
== 0) {
2138 extent_info
->overflow_count
++;
2139 extent_info
->recStartBlock
= key
->startBlock
;
2140 extent_info
->extents
= extent_info
->record
.overflow
;
2141 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
2142 if (extent_info
->record
.overflow
[i
].blockCount
== 0) {
2145 extent_info
->extent_index
= i
;
2146 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
2148 printf ("hfs_reclaim_file: fileID=%u #%d %u:(%u,%u) hfs_reclaim_extent error=%d\n", fileID
, extent_info
->overflow_count
, i
, extent_info
->record
.overflow
[i
].startBlock
, extent_info
->record
.overflow
[i
].blockCount
, error
);
2153 /* Look for more overflow records */
2154 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
2155 error
= BTIterateRecord(extent_info
->fcb
, kBTreeNextRecord
,
2156 extent_info
->iterator
, &(extent_info
->btdata
),
2157 &(extent_info
->recordlen
));
2158 hfs_systemfile_unlock(hfsmp
, lockflags
);
2162 /* Stop when we encounter a different file or fork. */
2163 if ((key
->fileID
!= fileID
) || (key
->forkType
!= forktype
)) {
2167 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
2172 /* If any blocks were relocated, account them and report progress */
2173 if (extent_info
->blocks_relocated
) {
2174 hfsmp
->hfs_resize_blocksmoved
+= extent_info
->blocks_relocated
;
2175 hfs_truncatefs_progress(hfsmp
);
2176 if (fileID
< kHFSFirstUserCatalogNodeID
) {
2177 printf ("hfs_reclaim_file: Relocated %u blocks from fileID=%u on \"%s\"\n",
2178 extent_info
->blocks_relocated
, fileID
, hfsmp
->vcbVN
);
2181 if (extent_info
->iterator
) {
2182 hfs_free(extent_info
->iterator
, sizeof(*extent_info
->iterator
));
2184 if (release_desc
== true) {
2185 cat_releasedesc(extent_info
->dirlink_desc
);
2187 if (extent_info
->dirlink_desc
) {
2188 hfs_free(extent_info
->dirlink_desc
, sizeof(*extent_info
->dirlink_desc
));
2190 if (extent_info
->dirlink_attr
) {
2191 hfs_free(extent_info
->dirlink_attr
, sizeof(*extent_info
->dirlink_attr
));
2193 if (extent_info
->dirlink_fork
) {
2194 hfs_free(extent_info
->dirlink_fork
, sizeof(*extent_info
->dirlink_fork
));
2196 if ((extent_info
->blocks_relocated
!= 0) && (extent_info
->is_sysfile
== false)) {
2199 if (took_truncate_lock
) {
2200 hfs_unlock_truncate(cp
, HFS_LOCK_DEFAULT
);
2203 hfs_free(extent_info
, sizeof(*extent_info
));
2205 if (hfs_resize_debug
) {
2206 printf("hfs_reclaim_file: === Finished relocating %sfork for fileid=%u (error=%d) ===\n", (forktype
? "rsrc" : "data"), fileID
, error
);
2214 * This journal_relocate callback updates the journal info block to point
2215 * at the new journal location. This write must NOT be done using the
2216 * transaction. We must write the block immediately. We must also force
2217 * it to get to the media so that the new journal location will be seen by
2218 * the replay code before we can safely let journaled blocks be written
2219 * to their normal locations.
2221 * The tests for journal_uses_fua below are mildly hacky. Since the journal
2222 * and the file system are both on the same device, I'm leveraging what
2223 * the journal has decided about FUA.
2225 struct hfs_journal_relocate_args
{
2226 struct hfsmount
*hfsmp
;
2227 vfs_context_t context
;
2228 u_int32_t newStartBlock
;
2229 u_int32_t newBlockCount
;
2233 hfs_journal_relocate_callback(void *_args
)
2236 struct hfs_journal_relocate_args
*args
= _args
;
2237 struct hfsmount
*hfsmp
= args
->hfsmp
;
2239 JournalInfoBlock
*jibp
;
2241 error
= buf_meta_bread(hfsmp
->hfs_devvp
,
2242 (uint64_t)hfsmp
->vcbJinfoBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
2243 hfsmp
->blockSize
, vfs_context_ucred(args
->context
), &bp
);
2245 printf("hfs_journal_relocate_callback: failed to read JIB (%d)\n", error
);
2251 jibp
= (JournalInfoBlock
*) buf_dataptr(bp
);
2252 jibp
->offset
= SWAP_BE64((u_int64_t
)args
->newStartBlock
* hfsmp
->blockSize
);
2253 jibp
->size
= SWAP_BE64((u_int64_t
)args
->newBlockCount
* hfsmp
->blockSize
);
2254 if (journal_uses_fua(hfsmp
->jnl
))
2256 error
= buf_bwrite(bp
);
2258 printf("hfs_journal_relocate_callback: failed to write JIB (%d)\n", error
);
2261 if (!journal_uses_fua(hfsmp
->jnl
)) {
2262 error
= hfs_flush(hfsmp
, HFS_FLUSH_CACHE
);
2264 printf("hfs_journal_relocate_callback: hfs_flush failed (%d)\n", error
);
2265 error
= 0; /* Don't fail the operation. */
2273 /* Type of resize operation in progress */
2274 #define HFS_RESIZE_TRUNCATE 1
2275 #define HFS_RESIZE_EXTEND 2
2278 * Core function to relocate the journal file. This function takes the
2279 * journal size of the newly relocated journal --- the caller can
2280 * provide a new journal size if they want to change the size of
2281 * the journal. The function takes care of updating the journal info
2282 * block and all other data structures correctly.
2284 * Note: This function starts a transaction and grabs the btree locks.
2287 hfs_relocate_journal_file(struct hfsmount
*hfsmp
, u_int32_t jnl_size
, int resize_type
, vfs_context_t context
)
2292 u_int32_t oldStartBlock
;
2293 u_int32_t newStartBlock
;
2294 u_int32_t oldBlockCount
;
2295 u_int32_t newBlockCount
;
2296 u_int32_t jnlBlockCount
;
2297 u_int32_t alloc_skipfreeblks
;
2298 struct cat_desc journal_desc
;
2299 struct cat_attr journal_attr
;
2300 struct cat_fork journal_fork
;
2301 struct hfs_journal_relocate_args callback_args
;
2303 /* Calculate the number of allocation blocks required for the journal */
2304 jnlBlockCount
= howmany(jnl_size
, hfsmp
->blockSize
);
2307 * During truncatefs(), the volume free block count is updated
2308 * before relocating data and reflects the total number of free
2309 * blocks that will exist on volume after the resize is successful.
2310 * This means that the allocation blocks required for relocation
2311 * have already been reserved and accounted for in the free block
2312 * count. Therefore, block allocation and deallocation routines
2313 * can skip the free block check by passing HFS_ALLOC_SKIPFREEBLKS
2316 * This special handling is not required when the file system
2317 * is being extended as we want all the allocated and deallocated
2318 * blocks to be accounted for correctly.
2320 if (resize_type
== HFS_RESIZE_TRUNCATE
) {
2321 alloc_skipfreeblks
= HFS_ALLOC_SKIPFREEBLKS
;
2323 alloc_skipfreeblks
= 0;
2326 error
= hfs_start_transaction(hfsmp
);
2328 printf("hfs_relocate_journal_file: hfs_start_transaction returned %d\n", error
);
2331 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
2333 error
= BlockAllocate(hfsmp
, 1, jnlBlockCount
, jnlBlockCount
,
2334 HFS_ALLOC_METAZONE
| HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_FLUSHTXN
| alloc_skipfreeblks
,
2335 &newStartBlock
, &newBlockCount
);
2337 printf("hfs_relocate_journal_file: BlockAllocate returned %d\n", error
);
2340 if (newBlockCount
!= jnlBlockCount
) {
2341 printf("hfs_relocate_journal_file: newBlockCount != jnlBlockCount (%u, %u)\n", newBlockCount
, jnlBlockCount
);
2345 error
= cat_idlookup(hfsmp
, hfsmp
->hfs_jnlfileid
, 1, 0, &journal_desc
, &journal_attr
, &journal_fork
);
2347 printf("hfs_relocate_journal_file: cat_idlookup returned %d\n", error
);
2351 oldStartBlock
= journal_fork
.cf_extents
[0].startBlock
;
2352 oldBlockCount
= journal_fork
.cf_extents
[0].blockCount
;
2353 error
= BlockDeallocate(hfsmp
, oldStartBlock
, oldBlockCount
, alloc_skipfreeblks
);
2355 printf("hfs_relocate_journal_file: BlockDeallocate returned %d\n", error
);
2359 /* Update the catalog record for .journal */
2360 journal_fork
.cf_size
= hfs_blk_to_bytes(newBlockCount
, hfsmp
->blockSize
);
2361 journal_fork
.cf_extents
[0].startBlock
= newStartBlock
;
2362 journal_fork
.cf_extents
[0].blockCount
= newBlockCount
;
2363 journal_fork
.cf_blocks
= newBlockCount
;
2364 error
= cat_update(hfsmp
, &journal_desc
, &journal_attr
, &journal_fork
, NULL
);
2365 cat_releasedesc(&journal_desc
); /* all done with cat descriptor */
2367 printf("hfs_relocate_journal_file: cat_update returned %d\n", error
);
2372 * If the journal is part of the file system, then tell the journal
2373 * code about the new location. If the journal is on an external
2374 * device, then just keep using it as-is.
2376 if (hfsmp
->jvp
== hfsmp
->hfs_devvp
) {
2377 callback_args
.hfsmp
= hfsmp
;
2378 callback_args
.context
= context
;
2379 callback_args
.newStartBlock
= newStartBlock
;
2380 callback_args
.newBlockCount
= newBlockCount
;
2382 error
= journal_relocate(hfsmp
->jnl
, (off_t
)newStartBlock
*hfsmp
->blockSize
,
2383 (off_t
)newBlockCount
*hfsmp
->blockSize
, 0,
2384 hfs_journal_relocate_callback
, &callback_args
);
2386 /* NOTE: journal_relocate will mark the journal invalid. */
2387 printf("hfs_relocate_journal_file: journal_relocate returned %d\n", error
);
2390 if (hfs_resize_debug
) {
2391 printf ("hfs_relocate_journal_file: Successfully relocated journal from (%u,%u) to (%u,%u)\n", oldStartBlock
, oldBlockCount
, newStartBlock
, newBlockCount
);
2393 hfsmp
->jnl_start
= newStartBlock
;
2394 hfsmp
->jnl_size
= (off_t
)newBlockCount
* hfsmp
->blockSize
;
2397 hfs_systemfile_unlock(hfsmp
, lockflags
);
2398 error
= hfs_end_transaction(hfsmp
);
2400 printf("hfs_relocate_journal_file: hfs_end_transaction returned %d\n", error
);
2406 journal_err
= BlockDeallocate(hfsmp
, newStartBlock
, newBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
2408 printf("hfs_relocate_journal_file: BlockDeallocate returned %d\n", error
);
2409 hfs_mark_inconsistent(hfsmp
, HFS_ROLLBACK_FAILED
);
2412 hfs_systemfile_unlock(hfsmp
, lockflags
);
2413 (void) hfs_end_transaction(hfsmp
);
2414 if (hfs_resize_debug
) {
2415 printf ("hfs_relocate_journal_file: Error relocating journal file (error=%d)\n", error
);
2422 * Relocate the journal file when the file system is being truncated.
2423 * We do not down-size the journal when the file system size is
2424 * reduced, so we always provide the current journal size to the
2428 hfs_reclaim_journal_file(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
2431 u_int32_t startBlock
;
2432 u_int32_t blockCount
= hfsmp
->jnl_size
/ hfsmp
->blockSize
;
2435 * Figure out the location of the .journal file. When the journal
2436 * is on an external device, we need to look up the .journal file.
2438 if (hfsmp
->jvp
== hfsmp
->hfs_devvp
) {
2439 startBlock
= hfsmp
->jnl_start
;
2440 blockCount
= hfsmp
->jnl_size
/ hfsmp
->blockSize
;
2443 u_int32_t old_jnlfileid
;
2444 struct cat_attr attr
;
2445 struct cat_fork fork
;
2448 * The cat_lookup inside GetFileInfo will fail because hfs_jnlfileid
2449 * is set, and it is trying to hide the .journal file. So temporarily
2450 * unset the field while calling GetFileInfo.
2452 old_jnlfileid
= hfsmp
->hfs_jnlfileid
;
2453 hfsmp
->hfs_jnlfileid
= 0;
2454 fileid
= GetFileInfo(hfsmp
, kHFSRootFolderID
, ".journal", &attr
, &fork
);
2455 hfsmp
->hfs_jnlfileid
= old_jnlfileid
;
2456 if (fileid
!= old_jnlfileid
) {
2457 printf("hfs_reclaim_journal_file: cannot find .journal file!\n");
2461 startBlock
= fork
.cf_extents
[0].startBlock
;
2462 blockCount
= fork
.cf_extents
[0].blockCount
;
2465 if (startBlock
+ blockCount
<= allocLimit
) {
2466 /* The journal file does not require relocation */
2470 error
= hfs_relocate_journal_file(hfsmp
, hfs_blk_to_bytes(blockCount
, hfsmp
->blockSize
),
2471 HFS_RESIZE_TRUNCATE
, context
);
2473 hfsmp
->hfs_resize_blocksmoved
+= blockCount
;
2474 hfs_truncatefs_progress(hfsmp
);
2475 printf ("hfs_reclaim_journal_file: Relocated %u blocks from journal on \"%s\"\n",
2476 blockCount
, hfsmp
->vcbVN
);
2484 * Move the journal info block to a new location. We have to make sure the
2485 * new copy of the journal info block gets to the media first, then change
2486 * the field in the volume header and the catalog record.
2489 hfs_reclaim_journal_info_block(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
2496 u_int32_t blockCount
;
2497 struct cat_desc jib_desc
;
2498 struct cat_attr jib_attr
;
2499 struct cat_fork jib_fork
;
2500 buf_t old_bp
, new_bp
;
2502 if (hfsmp
->vcbJinfoBlock
<= allocLimit
) {
2503 /* The journal info block does not require relocation */
2507 error
= hfs_start_transaction(hfsmp
);
2509 printf("hfs_reclaim_journal_info_block: hfs_start_transaction returned %d\n", error
);
2512 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
2514 error
= BlockAllocate(hfsmp
, 1, 1, 1,
2515 HFS_ALLOC_METAZONE
| HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_SKIPFREEBLKS
| HFS_ALLOC_FLUSHTXN
,
2516 &newBlock
, &blockCount
);
2518 printf("hfs_reclaim_journal_info_block: BlockAllocate returned %d\n", error
);
2521 if (blockCount
!= 1) {
2522 printf("hfs_reclaim_journal_info_block: blockCount != 1 (%u)\n", blockCount
);
2526 /* Copy the old journal info block content to the new location */
2527 error
= buf_meta_bread(hfsmp
->hfs_devvp
,
2528 (uint64_t)hfsmp
->vcbJinfoBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
2529 hfsmp
->blockSize
, vfs_context_ucred(context
), &old_bp
);
2531 printf("hfs_reclaim_journal_info_block: failed to read JIB (%d)\n", error
);
2537 new_bp
= buf_getblk(hfsmp
->hfs_devvp
,
2538 (uint64_t)newBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
2539 hfsmp
->blockSize
, 0, 0, BLK_META
);
2540 bcopy((char*)buf_dataptr(old_bp
), (char*)buf_dataptr(new_bp
), hfsmp
->blockSize
);
2542 if (journal_uses_fua(hfsmp
->jnl
))
2543 buf_markfua(new_bp
);
2544 error
= buf_bwrite(new_bp
);
2546 printf("hfs_reclaim_journal_info_block: failed to write new JIB (%d)\n", error
);
2549 if (!journal_uses_fua(hfsmp
->jnl
)) {
2550 error
= hfs_flush(hfsmp
, HFS_FLUSH_CACHE
);
2552 printf("hfs_reclaim_journal_info_block: hfs_flush failed (%d)\n", error
);
2553 /* Don't fail the operation. */
2557 /* Deallocate the old block once the new one has the new valid content */
2558 error
= BlockDeallocate(hfsmp
, hfsmp
->vcbJinfoBlock
, 1, HFS_ALLOC_SKIPFREEBLKS
);
2560 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error
);
2565 /* Update the catalog record for .journal_info_block */
2566 error
= cat_idlookup(hfsmp
, hfsmp
->hfs_jnlinfoblkid
, 1, 0, &jib_desc
, &jib_attr
, &jib_fork
);
2568 printf("hfs_reclaim_journal_info_block: cat_idlookup returned %d\n", error
);
2571 oldBlock
= jib_fork
.cf_extents
[0].startBlock
;
2572 jib_fork
.cf_size
= hfsmp
->blockSize
;
2573 jib_fork
.cf_extents
[0].startBlock
= newBlock
;
2574 jib_fork
.cf_extents
[0].blockCount
= 1;
2575 jib_fork
.cf_blocks
= 1;
2576 error
= cat_update(hfsmp
, &jib_desc
, &jib_attr
, &jib_fork
, NULL
);
2577 cat_releasedesc(&jib_desc
); /* all done with cat descriptor */
2579 printf("hfs_reclaim_journal_info_block: cat_update returned %d\n", error
);
2583 /* Update the pointer to the journal info block in the volume header. */
2584 hfsmp
->vcbJinfoBlock
= newBlock
;
2585 error
= hfs_flushvolumeheader(hfsmp
, HFS_FVH_WAIT
| HFS_FVH_WRITE_ALT
);
2587 printf("hfs_reclaim_journal_info_block: hfs_flushvolumeheader returned %d\n", error
);
2590 hfs_systemfile_unlock(hfsmp
, lockflags
);
2591 error
= hfs_end_transaction(hfsmp
);
2593 printf("hfs_reclaim_journal_info_block: hfs_end_transaction returned %d\n", error
);
2595 error
= hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL
);
2597 printf("hfs_reclaim_journal_info_block: journal_flush returned %d\n", error
);
2600 /* Account for the block relocated and print progress */
2601 hfsmp
->hfs_resize_blocksmoved
+= 1;
2602 hfs_truncatefs_progress(hfsmp
);
2604 printf ("hfs_reclaim_journal_info: Relocated 1 block from journal info on \"%s\"\n",
2606 if (hfs_resize_debug
) {
2607 printf ("hfs_reclaim_journal_info_block: Successfully relocated journal info block from (%u,%u) to (%u,%u)\n", oldBlock
, blockCount
, newBlock
, blockCount
);
2613 journal_err
= BlockDeallocate(hfsmp
, newBlock
, blockCount
, HFS_ALLOC_SKIPFREEBLKS
);
2615 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error
);
2616 hfs_mark_inconsistent(hfsmp
, HFS_ROLLBACK_FAILED
);
2620 hfs_systemfile_unlock(hfsmp
, lockflags
);
2621 (void) hfs_end_transaction(hfsmp
);
2622 if (hfs_resize_debug
) {
2623 printf ("hfs_reclaim_journal_info_block: Error relocating journal info block (error=%d)\n", error
);
2630 calculate_journal_size(struct hfsmount
*hfsmp
, u_int32_t sector_size
, u_int64_t sector_count
)
2632 u_int64_t journal_size
;
2633 u_int32_t journal_scale
;
2635 #define DEFAULT_JOURNAL_SIZE (8*1024*1024)
2636 #define MAX_JOURNAL_SIZE (512*1024*1024)
2638 /* Calculate the journal size for this volume. We want
2639 * at least 8 MB of journal for each 100 GB of disk space.
2640 * We cap the size at 512 MB, unless the allocation block
2641 * size is larger, in which case, we use one allocation
2644 journal_scale
= (sector_size
* sector_count
) / ((u_int64_t
)100 * 1024 * 1024 * 1024);
2645 journal_size
= DEFAULT_JOURNAL_SIZE
* (journal_scale
+ 1);
2646 if (journal_size
> MAX_JOURNAL_SIZE
) {
2647 journal_size
= MAX_JOURNAL_SIZE
;
2649 if (journal_size
< hfsmp
->blockSize
) {
2650 journal_size
= hfsmp
->blockSize
;
2652 return journal_size
;
2657 * Calculate the expected journal size based on current partition size.
2658 * If the size of the current journal is less than the calculated size,
2659 * force journal relocation with the new journal size.
2662 hfs_extend_journal(struct hfsmount
*hfsmp
, u_int32_t sector_size
, u_int64_t sector_count
, vfs_context_t context
)
2665 u_int64_t calc_journal_size
;
2667 if (hfsmp
->jvp
!= hfsmp
->hfs_devvp
) {
2668 if (hfs_resize_debug
) {
2669 printf("hfs_extend_journal: not resizing the journal because it is on an external device.\n");
2674 calc_journal_size
= calculate_journal_size(hfsmp
, sector_size
, sector_count
);
2675 if (calc_journal_size
<= hfsmp
->jnl_size
) {
2676 /* The journal size requires no modification */
2680 if (hfs_resize_debug
) {
2681 printf ("hfs_extend_journal: journal old=%u, new=%qd\n", hfsmp
->jnl_size
, calc_journal_size
);
2684 /* Extend the journal to the new calculated size */
2685 error
= hfs_relocate_journal_file(hfsmp
, calc_journal_size
, HFS_RESIZE_EXTEND
, context
);
2687 printf ("hfs_extend_journal: Extended journal size to %u bytes on \"%s\"\n",
2688 hfsmp
->jnl_size
, hfsmp
->vcbVN
);
2696 * This function traverses through all extended attribute records for a given
2697 * fileID, and calls function that reclaims data blocks that exist in the
2698 * area of the disk being reclaimed which in turn is responsible for allocating
2699 * new space, copying extent data, deallocating new space, and if required,
2700 * splitting the extent.
2702 * Note: The caller has already acquired the cnode lock on the file. Therefore
2703 * we are assured that no other thread would be creating/deleting/modifying
2704 * extended attributes for this file.
2707 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
2708 * blocks that were relocated.
2711 * 0 on success, non-zero on failure.
2714 hfs_reclaim_xattr(struct hfsmount
*hfsmp
, struct vnode
*vp
, u_int32_t fileID
, u_int32_t allocLimit
, vfs_context_t context
)
2717 struct hfs_reclaim_extent_info
*extent_info
;
2719 HFSPlusAttrKey
*key
;
2722 if (hfs_resize_debug
) {
2723 printf("hfs_reclaim_xattr: === Start reclaiming xattr for id=%u ===\n", fileID
);
2726 extent_info
= hfs_mallocz(sizeof(struct hfs_reclaim_extent_info
));
2727 extent_info
->vp
= vp
;
2728 extent_info
->fileID
= fileID
;
2729 extent_info
->is_xattr
= true;
2730 extent_info
->is_sysfile
= vnode_issystem(vp
);
2731 extent_info
->fcb
= VTOF(hfsmp
->hfs_attribute_vp
);
2732 lockflags
= &(extent_info
->lockflags
);
2733 *lockflags
= SFL_ATTRIBUTE
| SFL_BITMAP
;
2735 /* Initialize iterator from the extent_info structure */
2736 extent_info
->iterator
= hfs_mallocz(sizeof(struct BTreeIterator
));
2738 /* Build attribute key */
2739 key
= (HFSPlusAttrKey
*)&(extent_info
->iterator
->key
);
2740 error
= hfs_buildattrkey(fileID
, NULL
, key
);
2745 /* Initialize btdata from extent_info structure. Note that the
2746 * buffer pointer actually points to the xattr record from the
2747 * extent_info structure itself.
2749 extent_info
->btdata
.bufferAddress
= &(extent_info
->record
.xattr
);
2750 extent_info
->btdata
.itemSize
= sizeof(HFSPlusAttrRecord
);
2751 extent_info
->btdata
.itemCount
= 1;
2754 * Sync all extent-based attribute data to the disk.
2756 * All extent-based attribute data I/O is performed via cluster
2757 * I/O using a virtual file that spans across entire file system
2760 hfs_lock_truncate(VTOC(hfsmp
->hfs_attrdata_vp
), HFS_EXCLUSIVE_LOCK
, HFS_LOCK_DEFAULT
);
2761 (void)cluster_push(hfsmp
->hfs_attrdata_vp
, 0);
2762 error
= vnode_waitforwrites(hfsmp
->hfs_attrdata_vp
, 0, 0, 0, "hfs_reclaim_xattr");
2763 hfs_unlock_truncate(VTOC(hfsmp
->hfs_attrdata_vp
), HFS_LOCK_DEFAULT
);
2768 /* Search for extended attribute for current file. This
2769 * will place the iterator before the first matching record.
2771 *lockflags
= hfs_systemfile_lock(hfsmp
, *lockflags
, HFS_EXCLUSIVE_LOCK
);
2772 error
= BTSearchRecord(extent_info
->fcb
, extent_info
->iterator
,
2773 &(extent_info
->btdata
), &(extent_info
->recordlen
),
2774 extent_info
->iterator
);
2775 hfs_systemfile_unlock(hfsmp
, *lockflags
);
2777 if (error
!= btNotFound
) {
2780 /* btNotFound is expected here, so just mask it */
2785 /* Iterate to the next record */
2786 *lockflags
= hfs_systemfile_lock(hfsmp
, *lockflags
, HFS_EXCLUSIVE_LOCK
);
2787 error
= BTIterateRecord(extent_info
->fcb
, kBTreeNextRecord
,
2788 extent_info
->iterator
, &(extent_info
->btdata
),
2789 &(extent_info
->recordlen
));
2790 hfs_systemfile_unlock(hfsmp
, *lockflags
);
2792 /* Stop the iteration if we encounter end of btree or xattr with different fileID */
2793 if (error
|| key
->fileID
!= fileID
) {
2794 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
2800 /* We only care about extent-based EAs */
2801 if ((extent_info
->record
.xattr
.recordType
!= kHFSPlusAttrForkData
) &&
2802 (extent_info
->record
.xattr
.recordType
!= kHFSPlusAttrExtents
)) {
2806 if (extent_info
->record
.xattr
.recordType
== kHFSPlusAttrForkData
) {
2807 extent_info
->overflow_count
= 0;
2808 extent_info
->extents
= extent_info
->record
.xattr
.forkData
.theFork
.extents
;
2809 } else if (extent_info
->record
.xattr
.recordType
== kHFSPlusAttrExtents
) {
2810 extent_info
->overflow_count
++;
2811 extent_info
->extents
= extent_info
->record
.xattr
.overflowExtents
.extents
;
2814 extent_info
->recStartBlock
= key
->startBlock
;
2815 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
2816 if (extent_info
->extents
[i
].blockCount
== 0) {
2819 extent_info
->extent_index
= i
;
2820 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
2822 printf ("hfs_reclaim_xattr: fileID=%u hfs_reclaim_extent error=%d\n", fileID
, error
);
2829 /* If any blocks were relocated, account them and report progress */
2830 if (extent_info
->blocks_relocated
) {
2831 hfsmp
->hfs_resize_blocksmoved
+= extent_info
->blocks_relocated
;
2832 hfs_truncatefs_progress(hfsmp
);
2834 if (extent_info
->iterator
) {
2835 hfs_free(extent_info
->iterator
, sizeof(*extent_info
->iterator
));
2838 hfs_free(extent_info
, sizeof(*extent_info
));
2840 if (hfs_resize_debug
) {
2841 printf("hfs_reclaim_xattr: === Finished relocating xattr for fileid=%u (error=%d) ===\n", fileID
, error
);
2847 * Reclaim any extent-based extended attributes allocation blocks from
2848 * the area of the disk that is being truncated.
2850 * The function traverses the attribute btree to find out the fileIDs
2851 * of the extended attributes that need to be relocated. For every
2852 * file whose large EA requires relocation, it looks up the cnode and
2853 * calls hfs_reclaim_xattr() to do all the work for allocating
2854 * new space, copying data, deallocating old space, and if required,
2855 * splitting the extents.
2858 * allocLimit - starting block of the area being reclaimed
2861 * returns 0 on success, non-zero on failure.
2864 hfs_reclaim_xattrspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
2868 struct BTreeIterator
*iterator
= NULL
;
2869 struct FSBufferDescriptor btdata
;
2870 HFSPlusAttrKey
*key
;
2871 HFSPlusAttrRecord rec
;
2873 cnid_t prev_fileid
= 0;
2876 int btree_operation
;
2877 u_int32_t files_moved
= 0;
2878 u_int32_t prev_blocksmoved
;
2881 fcb
= VTOF(hfsmp
->hfs_attribute_vp
);
2882 /* Store the value to print total blocks moved by this function in end */
2883 prev_blocksmoved
= hfsmp
->hfs_resize_blocksmoved
;
2885 iterator
= hfs_mallocz(sizeof(*iterator
));
2886 key
= (HFSPlusAttrKey
*)&iterator
->key
;
2887 btdata
.bufferAddress
= &rec
;
2888 btdata
.itemSize
= sizeof(rec
);
2889 btdata
.itemCount
= 1;
2891 need_relocate
= false;
2892 btree_operation
= kBTreeFirstRecord
;
2893 /* Traverse the attribute btree to find extent-based EAs to reclaim */
2895 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
, HFS_SHARED_LOCK
);
2896 error
= BTIterateRecord(fcb
, btree_operation
, iterator
, &btdata
, NULL
);
2897 hfs_systemfile_unlock(hfsmp
, lockflags
);
2899 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
2904 btree_operation
= kBTreeNextRecord
;
2906 /* If the extents of current fileID were already relocated, skip it */
2907 if (prev_fileid
== key
->fileID
) {
2911 /* Check if any of the extents in the current record need to be relocated */
2912 need_relocate
= false;
2913 switch(rec
.recordType
) {
2914 case kHFSPlusAttrForkData
:
2915 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
2916 if (rec
.forkData
.theFork
.extents
[i
].blockCount
== 0) {
2919 if ((rec
.forkData
.theFork
.extents
[i
].startBlock
+
2920 rec
.forkData
.theFork
.extents
[i
].blockCount
) > allocLimit
) {
2921 need_relocate
= true;
2927 case kHFSPlusAttrExtents
:
2928 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
2929 if (rec
.overflowExtents
.extents
[i
].blockCount
== 0) {
2932 if ((rec
.overflowExtents
.extents
[i
].startBlock
+
2933 rec
.overflowExtents
.extents
[i
].blockCount
) > allocLimit
) {
2934 need_relocate
= true;
2941 /* Continue iterating to next attribute record */
2942 if (need_relocate
== false) {
2946 /* Look up the vnode for corresponding file. The cnode
2947 * will be locked which will ensure that no one modifies
2948 * the xattrs when we are relocating them.
2950 * We want to allow open-unlinked files to be moved,
2951 * so provide allow_deleted == 1 for hfs_vget().
2953 if (hfs_vget(hfsmp
, key
->fileID
, &vp
, 0, 1) != 0) {
2957 error
= hfs_reclaim_xattr(hfsmp
, vp
, key
->fileID
, allocLimit
, context
);
2958 hfs_unlock(VTOC(vp
));
2961 printf ("hfs_reclaim_xattrspace: Error relocating xattrs for fileid=%u (error=%d)\n", key
->fileID
, error
);
2964 prev_fileid
= key
->fileID
;
2969 printf("hfs_reclaim_xattrspace: Relocated %u xattr blocks from %u files on \"%s\"\n",
2970 (hfsmp
->hfs_resize_blocksmoved
- prev_blocksmoved
),
2971 files_moved
, hfsmp
->vcbVN
);
2974 hfs_free(iterator
, sizeof(*iterator
));
2979 * Reclaim blocks from regular files.
2981 * This function iterates over all the record in catalog btree looking
2982 * for files with extents that overlap into the space we're trying to
2983 * free up. If a file extent requires relocation, it looks up the vnode
2984 * and calls function to relocate the data.
2987 * Zero on success, non-zero on failure.
2990 hfs_reclaim_filespace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
2994 struct BTreeIterator
*iterator
= NULL
;
2995 struct FSBufferDescriptor btdata
;
2996 int btree_operation
;
2998 struct HFSPlusCatalogFile filerec
;
3001 struct filefork
*datafork
;
3002 u_int32_t files_moved
= 0;
3003 u_int32_t prev_blocksmoved
;
3006 int keys_generated
= 0;
3009 fcb
= VTOF(hfsmp
->hfs_catalog_vp
);
3010 /* Store the value to print total blocks moved by this function at the end */
3011 prev_blocksmoved
= hfsmp
->hfs_resize_blocksmoved
;
3015 * For content-protected filesystems, we may need to relocate files that
3016 * are encrypted. If they use the new-style offset-based IVs, then
3017 * we can move them regardless of the lock state. We create a temporary
3018 * key here that we use to read/write the data, then we discard it at the
3019 * end of the function.
3021 if (cp_fs_protected (hfsmp
->hfs_mp
)) {
3022 error
= cpx_gentempkeys(&hfsmp
->hfs_resize_cpx
, hfsmp
);
3028 printf("hfs_reclaimspace: Error generating temporary keys for resize (%d)\n", error
);
3029 goto reclaim_filespace_done
;
3035 iterator
= hfs_mallocz(sizeof(*iterator
));
3037 btdata
.bufferAddress
= &filerec
;
3038 btdata
.itemSize
= sizeof(filerec
);
3039 btdata
.itemCount
= 1;
3041 btree_operation
= kBTreeFirstRecord
;
3043 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
3044 error
= BTIterateRecord(fcb
, btree_operation
, iterator
, &btdata
, NULL
);
3045 hfs_systemfile_unlock(hfsmp
, lockflags
);
3047 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
3052 btree_operation
= kBTreeNextRecord
;
3054 if (filerec
.recordType
!= kHFSPlusFileRecord
) {
3058 /* Check if any of the extents require relocation */
3060 error
= hfs_file_extent_overlaps(hfsmp
, allocLimit
, &filerec
, &overlaps
);
3067 /* We want to allow open-unlinked files to be moved, so allow_deleted == 1 */
3068 if (hfs_vget(hfsmp
, filerec
.fileID
, &vp
, 0, 1) != 0) {
3069 if (hfs_resize_debug
) {
3070 printf("hfs_reclaim_filespace: hfs_vget(%u) failed.\n", filerec
.fileID
);
3075 /* If data fork exists or item is a directory hard link, relocate blocks */
3076 datafork
= VTOF(vp
);
3077 if ((datafork
&& datafork
->ff_blocks
> 0) || vnode_isdir(vp
)) {
3078 error
= hfs_reclaim_file(hfsmp
, vp
, filerec
.fileID
,
3079 kHFSDataForkType
, allocLimit
, context
);
3081 printf ("hfs_reclaimspace: Error reclaiming datafork blocks of fileid=%u (error=%d)\n", filerec
.fileID
, error
);
3082 hfs_unlock(VTOC(vp
));
3088 /* If resource fork exists or item is a directory hard link, relocate blocks */
3089 if (((VTOC(vp
)->c_blocks
- (datafork
? datafork
->ff_blocks
: 0)) > 0) || vnode_isdir(vp
)) {
3090 if (vnode_isdir(vp
)) {
3091 /* Resource fork vnode lookup is invalid for directory hard link.
3092 * So we fake data fork vnode as resource fork vnode.
3096 error
= hfs_vgetrsrc(hfsmp
, vp
, &rvp
);
3098 printf ("hfs_reclaimspace: Error looking up rvp for fileid=%u (error=%d)\n", filerec
.fileID
, error
);
3099 hfs_unlock(VTOC(vp
));
3103 VTOC(rvp
)->c_flag
|= C_NEED_RVNODE_PUT
;
3106 error
= hfs_reclaim_file(hfsmp
, rvp
, filerec
.fileID
,
3107 kHFSResourceForkType
, allocLimit
, context
);
3109 printf ("hfs_reclaimspace: Error reclaiming rsrcfork blocks of fileid=%u (error=%d)\n", filerec
.fileID
, error
);
3110 hfs_unlock(VTOC(vp
));
3116 /* The file forks were relocated successfully, now drop the
3117 * cnode lock and vnode reference, and continue iterating to
3118 * next catalog record.
3120 hfs_unlock(VTOC(vp
));
3126 printf("hfs_reclaim_filespace: Relocated %u blocks from %u files on \"%s\"\n",
3127 (hfsmp
->hfs_resize_blocksmoved
- prev_blocksmoved
),
3128 files_moved
, hfsmp
->vcbVN
);
3132 reclaim_filespace_done
:
3134 if (keys_generated
) {
3135 cpx_free(hfsmp
->hfs_resize_cpx
);
3136 hfsmp
->hfs_resize_cpx
= NULL
;
3140 hfs_free(iterator
, sizeof(*iterator
));
3146 * Reclaim space at the end of a file system.
3149 * allocLimit - start block of the space being reclaimed
3150 * reclaimblks - number of allocation blocks to reclaim
3153 hfs_reclaimspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, u_int32_t reclaimblks
, vfs_context_t context
)
3158 * Preflight the bitmap to find out total number of blocks that need
3161 * Note: Since allocLimit is set to the location of new alternate volume
3162 * header, the check below does not account for blocks allocated for old
3163 * alternate volume header.
3165 error
= hfs_count_allocated(hfsmp
, allocLimit
, reclaimblks
, &(hfsmp
->hfs_resize_totalblocks
));
3167 printf ("hfs_reclaimspace: Unable to determine total blocks to reclaim error=%d\n", error
);
3170 if (hfs_resize_debug
) {
3171 printf ("hfs_reclaimspace: Total number of blocks to reclaim = %u\n", hfsmp
->hfs_resize_totalblocks
);
3174 /* Just to be safe, sync the content of the journal to the disk before we proceed */
3175 hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
3177 /* First, relocate journal file blocks if they're in the way.
3178 * Doing this first will make sure that journal relocate code
3179 * gets access to contiguous blocks on disk first. The journal
3180 * file has to be contiguous on the disk, otherwise resize will
3183 error
= hfs_reclaim_journal_file(hfsmp
, allocLimit
, context
);
3185 printf("hfs_reclaimspace: hfs_reclaim_journal_file failed (%d)\n", error
);
3189 /* Relocate journal info block blocks if they're in the way. */
3190 error
= hfs_reclaim_journal_info_block(hfsmp
, allocLimit
, context
);
3192 printf("hfs_reclaimspace: hfs_reclaim_journal_info_block failed (%d)\n", error
);
3196 /* Relocate extents of the Extents B-tree if they're in the way.
3197 * Relocating extents btree before other btrees is important as
3198 * this will provide access to largest contiguous block range on
3199 * the disk for relocating extents btree. Note that extents btree
3200 * can only have maximum of 8 extents.
3202 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_extents_vp
, kHFSExtentsFileID
,
3203 kHFSDataForkType
, allocLimit
, context
);
3205 printf("hfs_reclaimspace: reclaim extents b-tree returned %d\n", error
);
3209 /* Relocate extents of the Allocation file if they're in the way. */
3210 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_allocation_vp
, kHFSAllocationFileID
,
3211 kHFSDataForkType
, allocLimit
, context
);
3213 printf("hfs_reclaimspace: reclaim allocation file returned %d\n", error
);
3217 /* Relocate extents of the Catalog B-tree if they're in the way. */
3218 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_catalog_vp
, kHFSCatalogFileID
,
3219 kHFSDataForkType
, allocLimit
, context
);
3221 printf("hfs_reclaimspace: reclaim catalog b-tree returned %d\n", error
);
3225 /* Relocate extents of the Attributes B-tree if they're in the way. */
3226 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_attribute_vp
, kHFSAttributesFileID
,
3227 kHFSDataForkType
, allocLimit
, context
);
3229 printf("hfs_reclaimspace: reclaim attribute b-tree returned %d\n", error
);
3233 /* Relocate extents of the Startup File if there is one and they're in the way. */
3234 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_startup_vp
, kHFSStartupFileID
,
3235 kHFSDataForkType
, allocLimit
, context
);
3237 printf("hfs_reclaimspace: reclaim startup file returned %d\n", error
);
3242 * We need to make sure the alternate volume header gets flushed if we moved
3243 * any extents in the volume header. But we need to do that before
3244 * shrinking the size of the volume, or else the journal code will panic
3245 * with an invalid (too large) block number.
3247 * Note that blks_moved will be set if ANY extent was moved, even
3248 * if it was just an overflow extent. In this case, the journal_flush isn't
3249 * strictly required, but shouldn't hurt.
3251 if (hfsmp
->hfs_resize_blocksmoved
) {
3252 hfs_flush(hfsmp
, HFS_FLUSH_JOURNAL_META
);
3255 /* Reclaim extents from catalog file records */
3256 error
= hfs_reclaim_filespace(hfsmp
, allocLimit
, context
);
3258 printf ("hfs_reclaimspace: hfs_reclaim_filespace returned error=%d\n", error
);
3262 /* Reclaim extents from extent-based extended attributes, if any */
3263 error
= hfs_reclaim_xattrspace(hfsmp
, allocLimit
, context
);
3265 printf ("hfs_reclaimspace: hfs_reclaim_xattrspace returned error=%d\n", error
);
3270 * Make sure reserved ranges in the region we're to allocate don't
3273 struct rl_entry
*range
;
3275 int lockf
= hfs_systemfile_lock(hfsmp
, SFL_BITMAP
, HFS_SHARED_LOCK
);
3276 TAILQ_FOREACH(range
, &hfsmp
->hfs_reserved_ranges
[HFS_LOCKED_BLOCKS
], rl_link
) {
3277 if (rl_overlap(range
, hfsmp
->allocLimit
, RL_INFINITY
) != RL_NOOVERLAP
) {
3279 hfs_systemfile_unlock(hfsmp
, lockf
);
3280 msleep(hfs_reclaimspace
, NULL
, PINOD
, "waiting on reserved blocks",
3281 &(struct timespec
){ 0, 100 * 1000000 });
3285 hfs_systemfile_unlock(hfsmp
, lockf
);
3292 * Check if there are any extents (including overflow extents) that overlap
3293 * into the disk space that is being reclaimed.
3296 * true - One of the extents need to be relocated
3297 * false - No overflow extents need to be relocated, or there was an error
3300 hfs_file_extent_overlaps(struct hfsmount
*hfsmp
, u_int32_t allocLimit
,
3301 struct HFSPlusCatalogFile
*filerec
, bool *overlaps
)
3303 struct BTreeIterator
* iterator
= NULL
;
3304 struct FSBufferDescriptor btdata
;
3305 HFSPlusExtentRecord extrec
;
3306 HFSPlusExtentKey
*extkeyptr
;
3314 /* Check if data fork overlaps the target space */
3315 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
3316 if (filerec
->dataFork
.extents
[i
].blockCount
== 0) {
3319 endblock
= filerec
->dataFork
.extents
[i
].startBlock
+
3320 filerec
->dataFork
.extents
[i
].blockCount
;
3321 if (endblock
> allocLimit
) {
3327 /* Check if resource fork overlaps the target space */
3328 for (j
= 0; j
< kHFSPlusExtentDensity
; ++j
) {
3329 if (filerec
->resourceFork
.extents
[j
].blockCount
== 0) {
3332 endblock
= filerec
->resourceFork
.extents
[j
].startBlock
+
3333 filerec
->resourceFork
.extents
[j
].blockCount
;
3334 if (endblock
> allocLimit
) {
3340 /* Return back if there are no overflow extents for this file */
3341 if ((i
< kHFSPlusExtentDensity
) && (j
< kHFSPlusExtentDensity
)) {
3346 iterator
= hfs_malloc(sizeof(*iterator
));
3348 bzero(iterator
, sizeof(*iterator
));
3349 extkeyptr
= (HFSPlusExtentKey
*)&iterator
->key
;
3350 extkeyptr
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
3351 extkeyptr
->forkType
= 0;
3352 extkeyptr
->fileID
= filerec
->fileID
;
3353 extkeyptr
->startBlock
= 0;
3355 btdata
.bufferAddress
= &extrec
;
3356 btdata
.itemSize
= sizeof(extrec
);
3357 btdata
.itemCount
= 1;
3359 fcb
= VTOF(hfsmp
->hfs_extents_vp
);
3361 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_EXTENTS
, HFS_SHARED_LOCK
);
3363 /* This will position the iterator just before the first overflow
3364 * extent record for given fileID. It will always return btNotFound,
3365 * so we special case the error code.
3367 error
= BTSearchRecord(fcb
, iterator
, &btdata
, NULL
, iterator
);
3368 if (error
&& (error
!= btNotFound
)) {
3369 ret
= MacToVFSError(error
);
3373 /* BTIterateRecord() might return error if the btree is empty, and
3374 * therefore we return that the extent does not overflow to the caller
3376 error
= BTIterateRecord(fcb
, kBTreeNextRecord
, iterator
, &btdata
, NULL
);
3377 while (error
== 0) {
3378 /* Stop when we encounter a different file. */
3379 if (extkeyptr
->fileID
!= filerec
->fileID
) {
3382 /* Check if any of the forks exist in the target space. */
3383 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
3384 if (extrec
[i
].blockCount
== 0) {
3387 endblock
= extrec
[i
].startBlock
+ extrec
[i
].blockCount
;
3388 if (endblock
> allocLimit
) {
3393 /* Look for more records. */
3394 error
= BTIterateRecord(fcb
, kBTreeNextRecord
, iterator
, &btdata
, NULL
);
3397 if (error
&& error
!= btNotFound
) {
3398 ret
= MacToVFSError(error
);
3406 hfs_systemfile_unlock(hfsmp
, lockflags
);
3409 hfs_free(iterator
, sizeof(*iterator
));
3416 * Calculate the progress of a file system resize operation.
3419 hfs_resize_progress(struct hfsmount
*hfsmp
, u_int32_t
*progress
)
3421 if ((hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) == 0) {
3425 if (hfsmp
->hfs_resize_totalblocks
> 0) {
3426 *progress
= (u_int32_t
)((hfsmp
->hfs_resize_blocksmoved
* 100ULL) / hfsmp
->hfs_resize_totalblocks
);