]> git.saurik.com Git - apple/hfs.git/blob - core/hfs_resize.c
hfs-556.100.11.tar.gz
[apple/hfs.git] / core / hfs_resize.c
1 /*
2 * Copyright (c) 2013-2015 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 #include <sys/systm.h>
29 #include <sys/kauth.h>
30 #include <sys/ubc.h>
31
32 #include "hfs_journal.h"
33 #include <miscfs/specfs/specdev.h>
34
35 #include "hfs.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"
41
42 /* Enable/disable debugging code for live volume resizing */
43 int hfs_resize_debug = 0;
44
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);
49
50 /*
51 * Extend a file system.
52 */
53 int
54 hfs_extendfs(struct hfsmount *hfsmp, u_int64_t newsize, vfs_context_t context)
55 {
56 struct proc *p = vfs_context_proc(context);
57 kauth_cred_t cred = vfs_context_ucred(context);
58 struct vnode *vp = NULL;
59 struct vnode *devvp;
60 struct buf *bp;
61 struct filefork *fp = NULL;
62 ExtendedVCB *vcb;
63 struct cat_fork forkdata;
64 u_int64_t oldsize;
65 uint32_t newblkcnt;
66 u_int64_t prev_phys_block_count;
67 u_int32_t addblks;
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;
73 daddr_t bitmapblks;
74 int lockflags = 0;
75 int error;
76 int64_t oldBitmapSize;
77
78 Boolean usedExtendFileC = false;
79 int transaction_begun = 0;
80
81 devvp = hfsmp->hfs_devvp;
82 vcb = HFSTOVCB(hfsmp);
83
84 /*
85 * - HFS Plus file systems only.
86 * - Journaling must be enabled.
87 * - No embedded volumes.
88 */
89 if ((vcb->vcbSigWord == kHFSSigWord) ||
90 (hfsmp->jnl == NULL) ||
91 (vcb->hfsPlusIOPosOffset != 0)) {
92 return (EPERM);
93 }
94 /*
95 * If extending file system by non-root, then verify
96 * ownership and check permissions.
97 */
98 if (suser(cred, NULL)) {
99 error = hfs_vget(hfsmp, kHFSRootFolderID, &vp, 0, 0);
100
101 if (error)
102 return (error);
103 error = hfs_owner_rights(hfsmp, VTOC(vp)->c_uid, cred, p, 0);
104 if (error == 0) {
105 error = hfs_write_access(vp, cred, p, false);
106 }
107 hfs_unlock(VTOC(vp));
108 vnode_put(vp);
109 if (error)
110 return (error);
111
112 error = vnode_authorize(devvp, NULL, KAUTH_VNODE_READ_DATA | KAUTH_VNODE_WRITE_DATA, context);
113 if (error)
114 return (error);
115 }
116 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKSIZE, (caddr_t)&sector_size, 0, context)) {
117 return (ENXIO);
118 }
119 if (sector_size != hfsmp->hfs_logical_block_size) {
120 return (ENXIO);
121 }
122 if (VNOP_IOCTL(devvp, DKIOCGETBLOCKCOUNT, (caddr_t)&sector_count, 0, context)) {
123 return (ENXIO);
124 }
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);
128 return (ENOSPC);
129 }
130 error = VNOP_IOCTL(devvp, DKIOCGETPHYSICALBLOCKSIZE, (caddr_t)&phys_sector_size, 0, context);
131 if (error) {
132 if ((error != ENOTSUP) && (error != ENOTTY)) {
133 return (ENXIO);
134 }
135 /* If ioctl is not supported, force physical and logical sector size to be same */
136 phys_sector_size = sector_size;
137 }
138 oldsize = (u_int64_t)hfsmp->totalBlocks * (u_int64_t)hfsmp->blockSize;
139
140 /*
141 * Validate new size.
142 */
143 if ((newsize <= oldsize) || (newsize % sector_size) || (newsize % phys_sector_size)) {
144 printf("hfs_extendfs: invalid size (newsize=%qu, oldsize=%qu)\n", newsize, oldsize);
145 return (EINVAL);
146 }
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);
150 return (EOVERFLOW);
151 }
152
153 newblkcnt = (uint32_t)cnt;
154
155 addblks = newblkcnt - vcb->totalBlocks;
156
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);
160 }
161 printf("hfs_extendfs: will extend \"%s\" by %d blocks\n", vcb->vcbVN, addblks);
162
163 hfs_lock_mount (hfsmp);
164 if (hfsmp->hfs_flags & HFS_RESIZE_IN_PROGRESS) {
165 hfs_unlock_mount(hfsmp);
166 error = EALREADY;
167 goto out;
168 }
169 hfsmp->hfs_flags |= HFS_RESIZE_IN_PROGRESS;
170 hfs_unlock_mount (hfsmp);
171
172 /* Start with a clean journal. */
173 hfs_flush(hfsmp, HFS_FLUSH_JOURNAL_META);
174
175 /*
176 * Enclose changes inside a transaction.
177 */
178 if (hfs_start_transaction(hfsmp) != 0) {
179 error = EINVAL;
180 goto out;
181 }
182 transaction_begun = 1;
183
184
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;
188
189 hfsmp->hfs_logical_block_count = sector_count;
190 hfsmp->hfs_logical_bytes = (uint64_t) sector_count * (uint64_t) sector_size;
191
192 /*
193 * It is possible that the new file system is smaller than the partition size.
194 * Therefore, update offsets for AVH accordingly.
195 */
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);
199 }
200 hfsmp->hfs_partition_avh_sector = (hfsmp->hfsPlusIOPosOffset / sector_size) +
201 HFS_ALT_SECTOR(sector_size, hfsmp->hfs_logical_block_count);
202
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);
208 }
209
210 /*
211 * Note: we take the attributes lock in case we have an attribute data vnode
212 * which needs to change size.
213 */
214 lockflags = hfs_systemfile_lock(hfsmp, SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
215 vp = vcb->allocationsRefNum;
216 fp = VTOF(vp);
217 bcopy(&fp->ff_data, &forkdata, sizeof(forkdata));
218
219 /*
220 * Calculate additional space required (if any) by allocation bitmap.
221 */
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;
226 else
227 bitmapblks = 0;
228
229 /*
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".
236 *
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.
243 */
244 overage_blocks = fp->ff_blocks * vcb->blockSize * 8;
245 overage_blocks = MIN (overage_blocks, newblkcnt);
246 overage_blocks -= vcb->totalBlocks;
247
248 BlockMarkFreeUnused(vcb, vcb->totalBlocks, overage_blocks);
249
250 if (bitmapblks > 0) {
251 daddr64_t blkno;
252 daddr_t blkcnt;
253 off_t bytesAdded;
254
255 /*
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.
259 */
260 blkno = (daddr64_t)fp->ff_blocks;
261
262 /*
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
266 * zone.
267 */
268 error = ExtendFileC(vcb, fp, bitmapblks * vcb->blockSize, 0,
269 kEFAllMask | kEFNoClumpMask | kEFReserveMask
270 | kEFMetadataMask | kEFContigMask, &bytesAdded);
271
272 if (error == 0) {
273 usedExtendFileC = true;
274 } else {
275 /*
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.
280 */
281 bytesAdded = 0;
282 error = AddFileExtent(vcb, fp, vcb->totalBlocks, bitmapblks);
283 if (error) {
284 printf("hfs_extendfs: error %d adding extents\n", error);
285 goto out;
286 }
287 fp->ff_blocks += bitmapblks;
288 VTOC(vp)->c_blocks = fp->ff_blocks;
289 VTOC(vp)->c_flag |= C_MODIFIED;
290 }
291
292 /*
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.
296 */
297 fp->ff_size += (u_int64_t)bitmapblks * (u_int64_t)vcb->blockSize;
298
299 /*
300 * Zero out the new bitmap blocks.
301 */
302 {
303
304 bp = NULL;
305 blkcnt = bitmapblks;
306 while (blkcnt > 0) {
307 error = (int)buf_meta_bread(vp, blkno, vcb->blockSize, NOCRED, &bp);
308 if (error) {
309 if (bp) {
310 buf_brelse(bp);
311 }
312 break;
313 }
314 bzero((char *)buf_dataptr(bp), vcb->blockSize);
315 buf_markaged(bp);
316 error = (int)buf_bwrite(bp);
317 if (error)
318 break;
319 --blkcnt;
320 ++blkno;
321 }
322 }
323 if (error) {
324 printf("hfs_extendfs: error %d clearing blocks\n", error);
325 goto out;
326 }
327 /*
328 * Mark the new bitmap space as allocated.
329 *
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).
335 */
336 if (!usedExtendFileC) {
337 error = BlockMarkAllocated(vcb, vcb->totalBlocks, bitmapblks);
338 if (error) {
339 printf("hfs_extendfs: error %d setting bitmap\n", error);
340 goto out;
341 }
342 vcb->freeBlocks -= bitmapblks;
343 }
344 }
345
346 /*
347 * Mark the new alternate VH as allocated.
348 */
349 if (vcb->blockSize == 512)
350 error = BlockMarkAllocated(vcb, vcb->totalBlocks + addblks - 2, 2);
351 else
352 error = BlockMarkAllocated(vcb, vcb->totalBlocks + addblks - 1, 1);
353 if (error) {
354 printf("hfs_extendfs: error %d setting bitmap (VH)\n", error);
355 goto out;
356 }
357
358 /*
359 * Mark the old alternate VH as free.
360 */
361 if (vcb->blockSize == 512)
362 (void) BlockMarkFree(vcb, vcb->totalBlocks - 2, 2);
363 else
364 (void) BlockMarkFree(vcb, vcb->totalBlocks - 1, 1);
365
366 /*
367 * Adjust file system variables for new space.
368 */
369 vcb->totalBlocks += addblks;
370 vcb->freeBlocks += addblks;
371 MarkVCBDirty(vcb);
372 error = hfs_flushvolumeheader(hfsmp, HFS_FVH_WAIT | HFS_FVH_WRITE_ALT);
373 if (error) {
374 printf("hfs_extendfs: couldn't flush volume headers (%d)", error);
375 /*
376 * Restore to old state.
377 */
378 if (usedExtendFileC) {
379 (void) TruncateFileC(vcb, fp, oldBitmapSize, 0, FORK_IS_RSRC(fp),
380 FTOC(fp)->c_fileid, false);
381 } else {
382 fp->ff_blocks -= bitmapblks;
383 fp->ff_size -= (u_int64_t)bitmapblks * (u_int64_t)vcb->blockSize;
384 /*
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.
388 */
389 vcb->freeBlocks += bitmapblks;
390 }
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
397 */
398 MarkVCBDirty(vcb);
399 if (vcb->blockSize == 512) {
400 if (BlockMarkAllocated(vcb, vcb->totalBlocks - 2, 2)) {
401 hfs_mark_inconsistent(hfsmp, HFS_ROLLBACK_FAILED);
402 }
403 } else {
404 if (BlockMarkAllocated(vcb, vcb->totalBlocks - 1, 1)) {
405 hfs_mark_inconsistent(hfsmp, HFS_ROLLBACK_FAILED);
406 }
407 }
408 goto out;
409 }
410 /*
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.
413 */
414 bp = NULL;
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);
420
421 bzero((char *)buf_dataptr(bp) + HFS_ALT_OFFSET(hfsmp->hfs_physical_block_size), kMDBSize);
422
423 journal_modify_block_end(hfsmp->jnl, bp, NULL, NULL);
424 } else if (bp) {
425 buf_brelse(bp);
426 }
427 }
428
429 /*
430 * Update the metadata zone size based on current volume size
431 */
432 hfs_metadatazone_init(hfsmp, false);
433
434 /*
435 * Adjust the size of hfsmp->hfs_attrdata_vp
436 */
437 if (hfsmp->hfs_attrdata_vp) {
438 struct cnode *attr_cp;
439 struct filefork *attr_fp;
440
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);
444
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);
451 }
452 }
453
454 /*
455 * We only update hfsmp->allocLimit if totalBlocks actually increased.
456 */
457 if (error == 0) {
458 UpdateAllocLimit(hfsmp, hfsmp->totalBlocks);
459 }
460
461 /* Release all locks and sync up journal content before
462 * checking and extending, if required, the journal
463 */
464 if (lockflags) {
465 hfs_systemfile_unlock(hfsmp, lockflags);
466 lockflags = 0;
467 }
468 if (transaction_begun) {
469 hfs_end_transaction(hfsmp);
470 hfs_flush(hfsmp, HFS_FLUSH_JOURNAL_META);
471 transaction_begun = 0;
472 }
473
474 /* Increase the journal size, if required. */
475 error = hfs_extend_journal(hfsmp, sector_size, sector_count, context);
476 if (error) {
477 printf ("hfs_extendfs: Could not extend journal size\n");
478 goto out_noalloc;
479 }
480
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));
484
485 out:
486 if (error && fp) {
487 /* Restore allocation fork. */
488 bcopy(&forkdata, &fp->ff_data, sizeof(forkdata));
489 VTOC(vp)->c_blocks = fp->ff_blocks;
490
491 }
492
493 out_noalloc:
494 hfs_lock_mount (hfsmp);
495 hfsmp->hfs_flags &= ~HFS_RESIZE_IN_PROGRESS;
496 hfs_unlock_mount (hfsmp);
497 if (lockflags) {
498 hfs_systemfile_unlock(hfsmp, lockflags);
499 }
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)
505 error = flush_error;
506 }
507 if (error) {
508 printf ("hfs_extentfs: failed error=%d on vol=%s\n", MacToVFSError(error), hfsmp->vcbVN);
509 }
510
511 return MacToVFSError(error);
512 }
513
514 #define HFS_MIN_SIZE (32LL * 1024LL * 1024LL)
515
516 /*
517 * Truncate a file system (while still mounted).
518 */
519 int
520 hfs_truncatefs(struct hfsmount *hfsmp, u_int64_t newsize, vfs_context_t context)
521 {
522 u_int64_t oldsize;
523 u_int32_t newblkcnt;
524 u_int32_t reclaimblks = 0;
525 int lockflags = 0;
526 int transaction_begun = 0;
527 Boolean updateFreeBlocks = false;
528 Boolean disable_sparse = false;
529 int error = 0;
530
531 hfs_lock_mount (hfsmp);
532 if (hfsmp->hfs_flags & HFS_RESIZE_IN_PROGRESS) {
533 hfs_unlock_mount (hfsmp);
534 return (EALREADY);
535 }
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);
541
542 /*
543 * - Journaled HFS Plus volumes only.
544 * - No embedded volumes.
545 */
546 if ((hfsmp->jnl == NULL) ||
547 (hfsmp->hfsPlusIOPosOffset != 0)) {
548 error = EPERM;
549 goto out;
550 }
551 oldsize = (u_int64_t)hfsmp->totalBlocks * (u_int64_t)hfsmp->blockSize;
552 newblkcnt = newsize / hfsmp->blockSize;
553 reclaimblks = hfsmp->totalBlocks - newblkcnt;
554
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);
558 }
559
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);
566 error = EINVAL;
567 goto out;
568 }
569
570 /*
571 * Make sure that the file system has enough free blocks reclaim.
572 *
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
587 * them.
588 *
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
593 *
594 * Total number of blocks that need to be reclaimed:
595 * ------------------------------------------------
596 * Blocks to Reclaim = Allocated_To-Reclaim + Free_To-Reclaim
597 *
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
601 * later in the code.
602 *
603 * The condition below gets converted to:
604 *
605 * Allocated To-Reclaim + Free To-Reclaim >= Free Stationary + Free To-Reclaim
606 *
607 * which is equivalent to:
608 *
609 * Allocated To-Reclaim >= Free Stationary
610 */
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));
613 error = ENOSPC;
614 goto out;
615 }
616
617 /* Start with a clean journal. */
618 hfs_flush(hfsmp, HFS_FLUSH_JOURNAL_META);
619
620 if (hfs_start_transaction(hfsmp) != 0) {
621 error = EINVAL;
622 goto out;
623 }
624 transaction_begun = 1;
625
626 /* Take the bitmap lock to update the alloc limit field */
627 lockflags = hfs_systemfile_lock(hfsmp, SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
628
629 /*
630 * Prevent new allocations from using the part we're trying to truncate.
631 *
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
636 * truncate away.
637 */
638 if (hfsmp->blockSize == 512) {
639 error = UpdateAllocLimit (hfsmp, newblkcnt - 2);
640 }
641 else {
642 error = UpdateAllocLimit (hfsmp, newblkcnt - 1);
643 }
644
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.
651 *
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
656 * solution for now.
657 */
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;
663 }
664
665 /*
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.
675 */
676 hfsmp->reclaimBlocks = reclaimblks;
677 hfsmp->freeBlocks -= reclaimblks;
678 updateFreeBlocks = true;
679 hfs_unlock_mount(hfsmp);
680
681 if (lockflags) {
682 hfs_systemfile_unlock(hfsmp, lockflags);
683 lockflags = 0;
684 }
685
686 /*
687 * Update the metadata zone size to match the new volume size,
688 * and if it too less, metadata zone might be disabled.
689 */
690 hfs_metadatazone_init(hfsmp, false);
691
692 /*
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.
696 *
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.
701 */
702 if (hfs_isallocated(hfsmp, hfsmp->allocLimit, reclaimblks)) {
703 /*
704 * hfs_reclaimspace will use separate transactions when
705 * relocating files (so we don't overwhelm the journal).
706 */
707 hfs_end_transaction(hfsmp);
708 transaction_begun = 0;
709
710 /* Attempt to reclaim some space. */
711 error = hfs_reclaimspace(hfsmp, hfsmp->allocLimit, reclaimblks, context);
712 if (error != 0) {
713 printf("hfs_truncatefs: couldn't reclaim space on %s (error=%d)\n", hfsmp->vcbVN, error);
714 error = ENOSPC;
715 goto out;
716 }
717
718 if (hfs_start_transaction(hfsmp) != 0) {
719 error = EINVAL;
720 goto out;
721 }
722 transaction_begun = 1;
723
724 /* Check if we're clear now. */
725 error = hfs_isallocated(hfsmp, hfsmp->allocLimit, reclaimblks);
726 if (error != 0) {
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 */
729 goto out;
730 }
731 }
732
733 /*
734 * Note: we take the attributes lock in case we have an attribute data vnode
735 * which needs to change size.
736 */
737 lockflags = hfs_systemfile_lock(hfsmp, SFL_ATTRIBUTE | SFL_EXTENTS | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
738
739 /*
740 * Allocate last 1KB for alternate volume header.
741 */
742 error = BlockMarkAllocated(hfsmp, hfsmp->allocLimit, (hfsmp->blockSize == 512) ? 2 : 1);
743 if (error) {
744 printf("hfs_truncatefs: Error %d allocating new alternate volume header\n", error);
745 goto out;
746 }
747
748 /*
749 * Mark the old alternate volume header as free.
750 * We don't bother shrinking allocation bitmap file.
751 */
752 if (hfsmp->blockSize == 512)
753 (void) BlockMarkFree(hfsmp, hfsmp->totalBlocks - 2, 2);
754 else
755 (void) BlockMarkFree(hfsmp, hfsmp->totalBlocks - 1, 1);
756
757 /* Don't invalidate the old AltVH yet. It is still valid until the partition size is updated ! */
758
759 /* Log successful shrinking. */
760 printf("hfs_truncatefs: shrank \"%s\" to %d blocks (was %d blocks)\n",
761 hfsmp->vcbVN, newblkcnt, hfsmp->totalBlocks);
762
763 /*
764 * Adjust file system variables and flush them to disk.
765 *
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).
770 */
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;
775
776 /*
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.
785 */
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);
789 }
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);
795 }
796
797 MarkVCBDirty(hfsmp);
798 error = hfs_flushvolumeheader(hfsmp, HFS_FVH_WAIT | HFS_FVH_WRITE_ALT);
799 if (error) {
800 panic("hfs_truncatefs: unexpected error flushing volume header (%d)\n", error);
801 }
802
803 /*
804 * Adjust the size of hfsmp->hfs_attrdata_vp
805 */
806 if (hfsmp->hfs_attrdata_vp) {
807 struct cnode *cp;
808 struct filefork *fp;
809
810 if (vnode_get(hfsmp->hfs_attrdata_vp) == 0) {
811 cp = VTOC(hfsmp->hfs_attrdata_vp);
812 fp = VTOF(hfsmp->hfs_attrdata_vp);
813
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);
820 }
821 }
822
823 out:
824 /*
825 * Update the allocLimit to acknowledge the last one or two blocks now.
826 * Add it to the tree as well if necessary.
827 */
828 UpdateAllocLimit (hfsmp, hfsmp->totalBlocks);
829
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
835 * it is rebuilt.
836 */
837 hfsmp->hfs_flags |= HFS_HAS_SPARSE_DEVICE;
838 ResetVCBFreeExtCache(hfsmp);
839 }
840
841 if (error && (updateFreeBlocks == true)) {
842 hfsmp->freeBlocks += reclaimblks;
843 }
844 hfsmp->reclaimBlocks = 0;
845
846 if (hfsmp->nextAllocation >= hfsmp->allocLimit) {
847 hfsmp->nextAllocation = hfsmp->hfs_metazone_end + 1;
848 }
849 hfsmp->hfs_flags &= ~HFS_RESIZE_IN_PROGRESS;
850 hfs_unlock_mount (hfsmp);
851
852 /* On error, reset the metadata zone for original volume size */
853 if (error && (updateFreeBlocks == true)) {
854 hfs_metadatazone_init(hfsmp, false);
855 }
856
857 if (lockflags) {
858 hfs_systemfile_unlock(hfsmp, lockflags);
859 }
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)
865 error = flush_error;
866 }
867
868 if (error) {
869 printf ("hfs_truncatefs: failed error=%d on vol=%s\n", MacToVFSError(error), hfsmp->vcbVN);
870 }
871
872 return MacToVFSError(error);
873 }
874
875
876 /*
877 * Invalidate the physical block numbers associated with buffer cache blocks
878 * in the given extent of the given vnode.
879 */
880 struct hfs_inval_blk_no {
881 daddr64_t sectorStart;
882 daddr64_t sectorCount;
883 };
884 static int
885 hfs_invalidate_block_numbers_callback(buf_t bp, void *args_in)
886 {
887 daddr64_t blkno;
888 struct hfs_inval_blk_no *args;
889
890 blkno = buf_blkno(bp);
891 args = args_in;
892
893 if (blkno >= args->sectorStart && blkno < args->sectorStart+args->sectorCount)
894 buf_setblkno(bp, buf_lblkno(bp));
895
896 return BUF_RETURNED;
897 }
898 static void
899 hfs_invalidate_sectors(struct vnode *vp, daddr64_t sectorStart, daddr64_t sectorCount)
900 {
901 struct hfs_inval_blk_no args;
902 args.sectorStart = sectorStart;
903 args.sectorCount = sectorCount;
904
905 buf_iterate(vp, hfs_invalidate_block_numbers_callback, BUF_SCAN_DIRTY|BUF_SCAN_CLEAN, &args);
906 }
907
908
909 /*
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).
914 *
915 * At this point, for regular files, we hold the truncate lock exclusive
916 * and the cnode lock exclusive.
917 */
918 static int
919 hfs_copy_extent(
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)
926 {
927 int err = 0;
928 size_t bufferSize;
929 void *buffer = NULL;
930 struct vfsioattr ioattr;
931 buf_t bp = NULL;
932 off_t resid;
933 size_t ioSize;
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;
937 #if CONFIG_PROTECT
938 int cpenabled = 0;
939 #endif
940
941 /*
942 * Sanity check that we have locked the vnode of the file we're copying.
943 *
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.
947 */
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);
951
952 #if CONFIG_PROTECT
953 /*
954 * Prepare the CP blob and get it ready for use, if necessary.
955 *
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.
960 */
961 if (!vnode_issystem (vp) && vnode_isreg(vp) && cp_fs_protected (hfsmp->hfs_mp)) {
962 cpenabled = 1;
963 }
964 #endif
965
966 /*
967 * Determine the I/O size to use
968 *
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?
972 */
973 vfs_ioattr(hfsmp->hfs_mp, &ioattr);
974 bufferSize = MIN(ioattr.io_maxreadcnt, ioattr.io_maxwritecnt);
975 buffer = hfs_malloc(bufferSize);
976
977 /* Get a buffer for doing the I/O */
978 bp = buf_alloc(hfsmp->hfs_devvp);
979 buf_setdataptr(bp, (uintptr_t)buffer);
980
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;
984 while (resid > 0) {
985 ioSize = MIN(bufferSize, (size_t) resid);
986 ioSizeSectors = ioSize / hfsmp->hfs_logical_block_size;
987
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);
994
995 /*
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.
1000 */
1001
1002 /* Attach the new CP blob to the buffer if needed */
1003 #if CONFIG_PROTECT
1004 if (cpenabled) {
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);
1008
1009 /* Initialize the content protection file offset to start at 0 */
1010 bufattr_setcpoff(buf_attr(bp), 0);
1011 }
1012 #endif
1013
1014 /* Do the read */
1015 err = VNOP_STRATEGY(bp);
1016 if (!err)
1017 err = buf_biowait(bp);
1018 if (err) {
1019 #if CONFIG_PROTECT
1020 /* Turn the flag off in error cases. */
1021 if (cpenabled) {
1022 cp->c_cpentry->cp_flags &= ~CP_RELOCATION_INFLIGHT;
1023 }
1024 #endif
1025 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (read)\n", err);
1026 break;
1027 }
1028
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))
1036 buf_markfua(bp);
1037
1038 #if CONFIG_PROTECT
1039 /* Attach the CP to the buffer if needed */
1040 if (cpenabled) {
1041 bufattr_setcpx(buf_attr(bp), hfsmp->hfs_resize_cpx);
1042 /*
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.
1046 */
1047 bufattr_setcpoff(buf_attr(bp), 0);
1048 }
1049 #endif
1050
1051 /* Do the write */
1052 vnode_startwrite(hfsmp->hfs_devvp);
1053 err = VNOP_STRATEGY(bp);
1054 if (!err) {
1055 err = buf_biowait(bp);
1056 }
1057 #if CONFIG_PROTECT
1058 /* Turn the flag off regardless once the strategy call finishes. */
1059 if (cpenabled) {
1060 cp->c_cpentry->cp_flags &= ~CP_RELOCATION_INFLIGHT;
1061 }
1062 #endif
1063 if (err) {
1064 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (write)\n", err);
1065 break;
1066 }
1067
1068 resid -= ioSize;
1069 srcSector += ioSizeSectors;
1070 destSector += ioSizeSectors;
1071 }
1072 if (bp)
1073 buf_free(bp);
1074 hfs_free(buffer, bufferSize);
1075
1076 /* Make sure all writes have been flushed to disk. */
1077 if (vnode_issystem(vp) && !journal_uses_fua(hfsmp->jnl)) {
1078
1079 err = hfs_flush(hfsmp, HFS_FLUSH_CACHE);
1080 if (err) {
1081 printf("hfs_copy_extent: hfs_flush failed (%d)\n", err);
1082 err = 0; /* Don't fail the copy. */
1083 }
1084 }
1085
1086 if (!err)
1087 hfs_invalidate_sectors(vp, (daddr64_t)oldStart*sectorsPerBlock, (daddr64_t)blockCount*sectorsPerBlock);
1088
1089 return err;
1090 }
1091
1092
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.
1097 */
1098 struct hfs_reclaim_extent_info {
1099 struct vnode *vp;
1100 u_int32_t fileID;
1101 u_int8_t forkType;
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 */
1111 union record {
1112 HFSPlusExtentRecord overflow;/* Extent record from overflow extents btree */
1113 HFSPlusAttrRecord xattr; /* Attribute record for large EAs */
1114 } record;
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
1120 */
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
1127 */
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 */
1132 };
1133
1134 /*
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
1140 * extent btree.
1141 *
1142 * Example:
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.
1151 *
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.
1164 *
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.
1168 *
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.
1175 *
1176 * Before:
1177 * record X record X+1
1178 * ---------------------===--------- ---------------------------------
1179 * | A | . | . | . | B | C | D | E | | F | . | . | . | G | 0 | 0 | 0 |
1180 * ---------------------===--------- ---------------------------------
1181 *
1182 * After:
1183 * ---------------------=======----- ---------------------------------
1184 * | A | . | . | . | B | C1| C2| D | | E | F | . | . | . | G | 0 | 0 |
1185 * ---------------------=======----- ---------------------------------
1186 *
1187 * C1.startBlock = C.startBlock
1188 * C1.blockCount = N
1189 *
1190 * C2.startBlock = C.startBlock + N
1191 * C2.blockCount = C.blockCount - N
1192 *
1193 * FABN = old FABN - E.blockCount
1194 *
1195 * Inputs:
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.
1204 * Output:
1205 * Zero on success, non-zero on failure.
1206 */
1207 static int
1208 hfs_split_extent(struct hfs_reclaim_extent_info *extent_info, uint32_t newBlockCount)
1209 {
1210 int error = 0;
1211 int index = extent_info->extent_index;
1212 int i;
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;
1222 uint16_t reclen;
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;
1226 Boolean is_xattr;
1227 struct cnode *cp;
1228
1229 is_xattr = extent_info->is_xattr;
1230 extents = extent_info->extents;
1231 cp = VTOC(extent_info->vp);
1232
1233 if (newBlockCount == 0) {
1234 if (hfs_resize_debug) {
1235 printf ("hfs_split_extent: No splitting required for newBlockCount=0\n");
1236 }
1237 return error;
1238 }
1239
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);
1242 }
1243
1244 /* Extents overflow btree can not have more than 8 extents.
1245 * No split allowed if the 8th extent is already used.
1246 */
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");
1249 error = ENOSPC;
1250 goto out;
1251 }
1252
1253 /* Determine the starting allocation block number for the following
1254 * overflow extent record, if any, before the current record
1255 * gets modified.
1256 */
1257 read_recStartBlock = extent_info->recStartBlock;
1258 for (i = 0; i < kHFSPlusExtentDensity; i++) {
1259 if (extents[i].blockCount == 0) {
1260 break;
1261 }
1262 read_recStartBlock += extents[i].blockCount;
1263 }
1264
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;
1270
1271 /* Last extent in the record will be split, so nothing to shift */
1272 } else {
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.
1276 */
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);
1280 }
1281
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.
1287 */
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);
1292 }
1293 }
1294 extents[i+1] = extents[i];
1295 }
1296 }
1297
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.
1303 */
1304 } else {
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.
1310 */
1311 extents[index+1].startBlock = extents[index].startBlock + newBlockCount;
1312 extents[index+1].blockCount = extents[index].blockCount - newBlockCount;
1313 }
1314 /* Update the extent being split, only the block count will change */
1315 extents[index].blockCount = newBlockCount;
1316
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);
1321 } else {
1322 printf ("overflow:(%u,%u)\n", shift_extent.startBlock, shift_extent.blockCount);
1323 }
1324 }
1325
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.
1334 */
1335 cp->c_flag |= C_MODIFIED;
1336 } else {
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
1340 */
1341 error = BTReplaceRecord(extent_info->fcb, extent_info->iterator,
1342 &(extent_info->btdata), extent_info->recordlen);
1343 if (error) {
1344 printf ("hfs_split_extent: fileID=%u BTReplaceRecord returned error=%d\n", extent_info->fileID, error);
1345 goto out;
1346 }
1347 }
1348
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");
1353 }
1354 error = 0;
1355 goto out;
1356 }
1357
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.
1365 */
1366
1367 /* Initialize iterator to search the next record */
1368 bzero(&iterator, sizeof(iterator));
1369 if (is_xattr) {
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 */
1374
1375 xattr_rec = hfs_malloc(sizeof(*xattr_rec));
1376
1377 btdata.bufferAddress = xattr_rec;
1378 btdata.itemSize = sizeof(HFSPlusAttrRecord);
1379 btdata.itemCount = 1;
1380 extents = xattr_rec->overflowExtents.extents;
1381 } else {
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 */
1388
1389 extents_rec = hfs_malloc(sizeof(*extents_rec));
1390
1391 btdata.bufferAddress = extents_rec;
1392 btdata.itemSize = sizeof(HFSPlusExtentRecord);
1393 btdata.itemCount = 1;
1394 extents = extents_rec[0];
1395 }
1396
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
1404 * file.
1405 *
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.
1415 */
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);
1419 }
1420
1421 /* Search if there is any existing overflow extent record
1422 * that matches the current file and the logical start block
1423 * number.
1424 *
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.
1429 */
1430 if (is_xattr) {
1431 xattr_key->startBlock = read_recStartBlock;
1432 } else {
1433 extents_key->startBlock = read_recStartBlock;
1434 }
1435 error = BTSearchRecord(extent_info->fcb, &iterator, &btdata, &reclen, &iterator);
1436 if (error) {
1437 if (error != btNotFound) {
1438 printf ("hfs_split_extent: fileID=%u startBlock=%u BTSearchRecord error=%d\n", extent_info->fileID, read_recStartBlock, error);
1439 goto out;
1440 }
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.
1445 */
1446 create_record = true;
1447 }
1448
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.
1458 */
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);
1463 }
1464 }
1465
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.
1469 */
1470 for (i = 0; i < kHFSPlusExtentDensity; i++) {
1471 if (extents[i].blockCount == 0) {
1472 break;
1473 }
1474 read_recStartBlock += extents[i].blockCount;
1475 }
1476
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;
1484
1485 if (is_xattr) {
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.
1492 */
1493
1494 /* Initialize the new xattr record */
1495 xattr_rec->recordType = kHFSPlusAttrExtents;
1496 xattr_rec->overflowExtents.reserved = 0;
1497 reclen = sizeof(HFSPlusAttrExtents);
1498 } else {
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.
1505 */
1506 extents_key->keyLength = kHFSPlusExtentKeyMaximumLength;
1507 extents_key->forkType = extent_info->forkType;
1508 extents_key->fileID = extent_info->fileID;
1509
1510 /* Initialize the new extent record */
1511 reclen = sizeof(HFSPlusExtentRecord);
1512 }
1513 } else {
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
1519 * record.
1520 */
1521 last_extent = extents[kHFSPlusExtentDensity-1];
1522
1523 /* Shift all entries by one index towards the end */
1524 for (i = kHFSPlusExtentDensity-2; i >= 0; i--) {
1525 extents[i+1] = extents[i];
1526 }
1527
1528 /* Overflow extent entry saved from previous record
1529 * is now the first entry in the current record.
1530 */
1531 extents[0] = shift_extent;
1532
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);
1535 }
1536
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.
1540 */
1541 shift_extent = last_extent;
1542
1543 /* Since the key->startBlock is being changed for this record,
1544 * it should be deleted and inserted with the new key.
1545 */
1546 error = BTDeleteRecord(extent_info->fcb, &iterator);
1547 if (error) {
1548 printf ("hfs_split_extent: fileID=%u startBlock=%u BTDeleteRecord error=%d\n", extent_info->fileID, read_recStartBlock, error);
1549 goto out;
1550 }
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));
1553 }
1554 }
1555
1556 /* Insert the newly created or modified extent record */
1557 bzero(&iterator.hint, sizeof(iterator.hint));
1558 if (is_xattr) {
1559 xattr_key->startBlock = write_recStartBlock;
1560 } else {
1561 extents_key->startBlock = write_recStartBlock;
1562 }
1563 error = BTInsertRecord(extent_info->fcb, &iterator, &btdata, reclen);
1564 if (error) {
1565 printf ("hfs_split_extent: fileID=%u, startBlock=%u BTInsertRecord error=%d\n", extent_info->fileID, write_recStartBlock, error);
1566 goto out;
1567 }
1568 if (hfs_resize_debug) {
1569 printf ("hfs_split_extent: Inserted extent record with startBlock=%u\n", write_recStartBlock);
1570 }
1571 }
1572
1573 out:
1574 /*
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.
1581 */
1582 BTFlushPath(extent_info->fcb);
1583
1584 hfs_free(extents_rec, sizeof(*extents_rec));
1585 hfs_free(xattr_rec, sizeof(*xattr_rec));
1586 return error;
1587 }
1588
1589
1590 /*
1591 * Relocate an extent if it lies beyond the expected end of volume.
1592 *
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
1601 * being reclaimed.
1602 *
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.
1607 *
1608 * Inputs:
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.
1615 */
1616 static int
1617 hfs_reclaim_extent(struct hfsmount *hfsmp, const u_long allocLimit, struct hfs_reclaim_extent_info *extent_info, vfs_context_t context)
1618 {
1619 int error = 0;
1620 int index;
1621 struct cnode *cp;
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;
1627 uint16_t node_size;
1628 uint32_t remainder_blocks;
1629 u_int32_t alloc_flags;
1630 int blocks_allocated = false;
1631
1632 index = extent_info->extent_index;
1633 cp = VTOC(extent_info->vp);
1634
1635 oldStartBlock = extent_info->extents[index].startBlock;
1636 oldBlockCount = extent_info->extents[index].blockCount;
1637
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);
1640 }
1641
1642 /* If the current extent lies completely within allocLimit,
1643 * it does not require any relocation.
1644 */
1645 if ((oldStartBlock + oldBlockCount) <= allocLimit) {
1646 extent_info->cur_blockCount += oldBlockCount;
1647 return error;
1648 }
1649
1650 /* Every extent should be relocated in its own transaction
1651 * to make sure that we don't overflow the journal buffer.
1652 */
1653 error = hfs_start_transaction(hfsmp);
1654 if (error) {
1655 return error;
1656 }
1657 extent_info->lockflags = hfs_systemfile_lock(hfsmp, extent_info->lockflags, HFS_EXCLUSIVE_LOCK);
1658
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.
1665 */
1666 if (oldStartBlock < allocLimit) {
1667 newBlockCount = allocLimit - oldStartBlock;
1668
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);
1672 }
1673
1674 /* If the extent belongs to a btree, check and trim
1675 * it to be multiple of the node size.
1676 */
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.
1683 */
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);
1690 }
1691 }
1692 }
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.
1697 */
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");
1701 }
1702 goto relocate_full_extent;
1703 }
1704 }
1705
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.
1711 */
1712 error = hfs_split_extent(extent_info, newBlockCount);
1713 if (error == 0) {
1714 /* Split success, no relocation required */
1715 goto out;
1716 }
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);
1721 }
1722 }
1723
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.
1733 */
1734 alloc_flags = HFS_ALLOC_FORCECONTIG | HFS_ALLOC_SKIPFREEBLKS;
1735 if (extent_info->is_sysfile) {
1736 alloc_flags |= HFS_ALLOC_METAZONE;
1737 }
1738
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);
1747 }
1748 if ((error == dskFulErr) || (error == ENOSPC)) {
1749 /*
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.
1753 *
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.
1759 */
1760 alloc_flags &= ~HFS_ALLOC_FORCECONTIG;
1761 alloc_flags |= HFS_ALLOC_FLUSHTXN;
1762
1763 error = BlockAllocate(hfsmp, 1, oldBlockCount, oldBlockCount,
1764 alloc_flags, &newStartBlock, &newBlockCount);
1765 if (error) {
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);
1767 goto out;
1768 }
1769
1770 /*
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.
1777 */
1778 if (newBlockCount != oldBlockCount) {
1779 blocks_allocated = true;
1780
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.
1784 */
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);
1798 }
1799 if (newBlockCount == 0) {
1800 printf ("hfs_reclaim_extent: Not enough contiguous blocks available to relocate fileID=%d\n", extent_info->fileID);
1801 error = ENOSPC;
1802 goto out;
1803 }
1804 }
1805 }
1806 }
1807
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.
1813 */
1814 error = hfs_split_extent(extent_info, newBlockCount);
1815 if (error) {
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);
1817 goto out;
1818 }
1819 oldBlockCount = newBlockCount;
1820 } /* end oldBlockCount != newBlockCount */
1821 } /* end allocation request for any available free space */
1822
1823 if (error) {
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);
1825 goto out;
1826 }
1827 blocks_allocated = true;
1828
1829 /* Copy data from old location to new location */
1830 error = hfs_copy_extent(hfsmp, extent_info->vp, oldStartBlock,
1831 newStartBlock, newBlockCount, context);
1832 if (error) {
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);
1834 goto out;
1835 }
1836
1837 /* Update the extent record with the new start block information */
1838 extent_info->extents[index].startBlock = newStartBlock;
1839
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));
1847 } else {
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);
1852 }
1853 }
1854 } else {
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);
1858 }
1859 if (error) {
1860 printf ("hfs_reclaim_extent: fileID=%u, update record error=%u\n", extent_info->fileID, error);
1861 goto out;
1862 }
1863
1864 /* Deallocate the old extent */
1865 error = BlockDeallocate(hfsmp, oldStartBlock, oldBlockCount, HFS_ALLOC_SKIPFREEBLKS);
1866 if (error) {
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);
1868 goto out;
1869 }
1870 extent_info->blocks_relocated += newBlockCount;
1871
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);
1874 }
1875
1876 out:
1877 if (error != 0) {
1878 if (blocks_allocated == true) {
1879 BlockDeallocate(hfsmp, newStartBlock, newBlockCount, HFS_ALLOC_SKIPFREEBLKS);
1880 }
1881 } else {
1882 /* On success, increment the total allocation blocks processed */
1883 extent_info->cur_blockCount += newBlockCount;
1884 }
1885
1886 hfs_systemfile_unlock(hfsmp, extent_info->lockflags);
1887
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.
1891 */
1892 if ((extent_info->catalog_fp) &&
1893 (extent_info->is_sysfile == false)) {
1894 hfs_update(extent_info->vp, 0);
1895 }
1896
1897 hfs_end_transaction(hfsmp);
1898
1899 return error;
1900 }
1901
1902 /* Report intermediate progress during volume resize */
1903 static void
1904 hfs_truncatefs_progress(struct hfsmount *hfsmp)
1905 {
1906 u_int32_t cur_progress = 0;
1907
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;
1912 }
1913 return;
1914 }
1915
1916 /*
1917 * Reclaim space at the end of a volume for given file and forktype.
1918 *
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.
1927 *
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.
1934 *
1935 * Inputs:
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.
1946 *
1947 * Side Effects:
1948 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
1949 * blocks that were relocated.
1950 */
1951 static int
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)
1954 {
1955 int error = 0;
1956 struct hfs_reclaim_extent_info *extent_info;
1957 int i;
1958 int lockflags = 0;
1959 struct cnode *cp;
1960 struct filefork *fp;
1961 int took_truncate_lock = false;
1962 int release_desc = false;
1963 HFSPlusExtentKey *key;
1964
1965 /* If there is no vnode for this file, then there's nothing to do. */
1966 if (vp == NULL) {
1967 return 0;
1968 }
1969
1970 cp = VTOC(vp);
1971
1972 if (hfs_resize_debug) {
1973 const char *filename = (const char *) cp->c_desc.cd_nameptr;
1974 int namelen = cp->c_desc.cd_namelen;
1975
1976 if (filename == NULL) {
1977 filename = "";
1978 namelen = 0;
1979 }
1980 printf("hfs_reclaim_file: reclaiming '%.*s'\n", namelen, filename);
1981 }
1982
1983 extent_info = hfs_mallocz(sizeof(struct hfs_reclaim_extent_info));
1984
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;
1991 }
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;
2000 }
2001 extent_info->lockflags = lockflags;
2002 extent_info->fcb = VTOF(hfsmp->hfs_extents_vp);
2003
2004 /* Flush data associated with current file on disk.
2005 *
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.
2013 */
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.
2017 */
2018 error = hfs_flush(hfsmp, HFS_FLUSH_JOURNAL_META);
2019 if (error) {
2020 printf ("hfs_reclaim_file: journal_flush returned %d\n", error);
2021 goto out;
2022 }
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.
2029 */
2030 buf_flushdirtyblks(vp, 0, BUF_SKIP_LOCKED, "hfs_reclaim_file");
2031
2032 hfs_unlock(cp);
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);
2037 if (error) {
2038 goto out;
2039 }
2040
2041 /* If the file no longer exists, nothing left to do */
2042 if (cp->c_flag & C_NOEXISTS) {
2043 error = 0;
2044 goto out;
2045 }
2046
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.)
2051 */
2052 error = vnode_waitforwrites(vp, 0, 0, 0, "hfs_reclaim_file");
2053 if (error) {
2054 goto out;
2055 }
2056 }
2057
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);
2060 }
2061
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));
2066
2067 /* Lookup catalog record for directory hard link and
2068 * create a fake filefork for the value looked up from
2069 * the disk.
2070 */
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);
2078 if (error) {
2079 printf ("hfs_reclaim_file: cat_lookup_dirlink for fileID=%u returned error=%u\n", fileID, error);
2080 goto out;
2081 }
2082 release_desc = true;
2083 } else {
2084 fp = VTOF(vp);
2085 }
2086
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) {
2093 break;
2094 }
2095 extent_info->extent_index = i;
2096 error = hfs_reclaim_extent(hfsmp, allocLimit, extent_info, context);
2097 if (error) {
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);
2099 goto out;
2100 }
2101 }
2102
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.
2106 */
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);
2110 }
2111 goto out;
2112 }
2113
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);
2116 }
2117
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;
2124
2125 extent_info->btdata.bufferAddress = extent_info->record.overflow;
2126 extent_info->btdata.itemSize = sizeof(HFSPlusExtentRecord);
2127 extent_info->btdata.itemCount = 1;
2128
2129 extent_info->catalog_fp = NULL;
2130
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) {
2143 goto out;
2144 }
2145 extent_info->extent_index = i;
2146 error = hfs_reclaim_extent(hfsmp, allocLimit, extent_info, context);
2147 if (error) {
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);
2149 goto out;
2150 }
2151 }
2152
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);
2159 if (error) {
2160 break;
2161 }
2162 /* Stop when we encounter a different file or fork. */
2163 if ((key->fileID != fileID) || (key->forkType != forktype)) {
2164 break;
2165 }
2166 }
2167 if (error == fsBTRecordNotFoundErr || error == fsBTEndOfIterationErr) {
2168 error = 0;
2169 }
2170
2171 out:
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);
2179 }
2180 }
2181 if (extent_info->iterator) {
2182 hfs_free(extent_info->iterator, sizeof(*extent_info->iterator));
2183 }
2184 if (release_desc == true) {
2185 cat_releasedesc(extent_info->dirlink_desc);
2186 }
2187 if (extent_info->dirlink_desc) {
2188 hfs_free(extent_info->dirlink_desc, sizeof(*extent_info->dirlink_desc));
2189 }
2190 if (extent_info->dirlink_attr) {
2191 hfs_free(extent_info->dirlink_attr, sizeof(*extent_info->dirlink_attr));
2192 }
2193 if (extent_info->dirlink_fork) {
2194 hfs_free(extent_info->dirlink_fork, sizeof(*extent_info->dirlink_fork));
2195 }
2196 if ((extent_info->blocks_relocated != 0) && (extent_info->is_sysfile == false)) {
2197 hfs_update(vp, 0);
2198 }
2199 if (took_truncate_lock) {
2200 hfs_unlock_truncate(cp, HFS_LOCK_DEFAULT);
2201 }
2202 if (extent_info) {
2203 hfs_free(extent_info, sizeof(*extent_info));
2204 }
2205 if (hfs_resize_debug) {
2206 printf("hfs_reclaim_file: === Finished relocating %sfork for fileid=%u (error=%d) ===\n", (forktype ? "rsrc" : "data"), fileID, error);
2207 }
2208
2209 return error;
2210 }
2211
2212
2213 /*
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.
2220 *
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.
2224 */
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;
2230 };
2231
2232 static errno_t
2233 hfs_journal_relocate_callback(void *_args)
2234 {
2235 int error;
2236 struct hfs_journal_relocate_args *args = _args;
2237 struct hfsmount *hfsmp = args->hfsmp;
2238 buf_t bp;
2239 JournalInfoBlock *jibp;
2240
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);
2244 if (error) {
2245 printf("hfs_journal_relocate_callback: failed to read JIB (%d)\n", error);
2246 if (bp) {
2247 buf_brelse(bp);
2248 }
2249 return error;
2250 }
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))
2255 buf_markfua(bp);
2256 error = buf_bwrite(bp);
2257 if (error) {
2258 printf("hfs_journal_relocate_callback: failed to write JIB (%d)\n", error);
2259 return error;
2260 }
2261 if (!journal_uses_fua(hfsmp->jnl)) {
2262 error = hfs_flush(hfsmp, HFS_FLUSH_CACHE);
2263 if (error) {
2264 printf("hfs_journal_relocate_callback: hfs_flush failed (%d)\n", error);
2265 error = 0; /* Don't fail the operation. */
2266 }
2267 }
2268
2269 return error;
2270 }
2271
2272
2273 /* Type of resize operation in progress */
2274 #define HFS_RESIZE_TRUNCATE 1
2275 #define HFS_RESIZE_EXTEND 2
2276
2277 /*
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.
2283 *
2284 * Note: This function starts a transaction and grabs the btree locks.
2285 */
2286 static int
2287 hfs_relocate_journal_file(struct hfsmount *hfsmp, u_int32_t jnl_size, int resize_type, vfs_context_t context)
2288 {
2289 int error;
2290 int journal_err;
2291 int lockflags;
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;
2302
2303 /* Calculate the number of allocation blocks required for the journal */
2304 jnlBlockCount = howmany(jnl_size, hfsmp->blockSize);
2305
2306 /*
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
2314 * flag.
2315 *
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.
2319 */
2320 if (resize_type == HFS_RESIZE_TRUNCATE) {
2321 alloc_skipfreeblks = HFS_ALLOC_SKIPFREEBLKS;
2322 } else {
2323 alloc_skipfreeblks = 0;
2324 }
2325
2326 error = hfs_start_transaction(hfsmp);
2327 if (error) {
2328 printf("hfs_relocate_journal_file: hfs_start_transaction returned %d\n", error);
2329 return error;
2330 }
2331 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
2332
2333 error = BlockAllocate(hfsmp, 1, jnlBlockCount, jnlBlockCount,
2334 HFS_ALLOC_METAZONE | HFS_ALLOC_FORCECONTIG | HFS_ALLOC_FLUSHTXN | alloc_skipfreeblks,
2335 &newStartBlock, &newBlockCount);
2336 if (error) {
2337 printf("hfs_relocate_journal_file: BlockAllocate returned %d\n", error);
2338 goto fail;
2339 }
2340 if (newBlockCount != jnlBlockCount) {
2341 printf("hfs_relocate_journal_file: newBlockCount != jnlBlockCount (%u, %u)\n", newBlockCount, jnlBlockCount);
2342 goto free_fail;
2343 }
2344
2345 error = cat_idlookup(hfsmp, hfsmp->hfs_jnlfileid, 1, 0, &journal_desc, &journal_attr, &journal_fork);
2346 if (error) {
2347 printf("hfs_relocate_journal_file: cat_idlookup returned %d\n", error);
2348 goto free_fail;
2349 }
2350
2351 oldStartBlock = journal_fork.cf_extents[0].startBlock;
2352 oldBlockCount = journal_fork.cf_extents[0].blockCount;
2353 error = BlockDeallocate(hfsmp, oldStartBlock, oldBlockCount, alloc_skipfreeblks);
2354 if (error) {
2355 printf("hfs_relocate_journal_file: BlockDeallocate returned %d\n", error);
2356 goto free_fail;
2357 }
2358
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 */
2366 if (error) {
2367 printf("hfs_relocate_journal_file: cat_update returned %d\n", error);
2368 goto free_fail;
2369 }
2370
2371 /*
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.
2375 */
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;
2381
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);
2385 if (error) {
2386 /* NOTE: journal_relocate will mark the journal invalid. */
2387 printf("hfs_relocate_journal_file: journal_relocate returned %d\n", error);
2388 goto fail;
2389 }
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);
2392 }
2393 hfsmp->jnl_start = newStartBlock;
2394 hfsmp->jnl_size = (off_t)newBlockCount * hfsmp->blockSize;
2395 }
2396
2397 hfs_systemfile_unlock(hfsmp, lockflags);
2398 error = hfs_end_transaction(hfsmp);
2399 if (error) {
2400 printf("hfs_relocate_journal_file: hfs_end_transaction returned %d\n", error);
2401 }
2402
2403 return error;
2404
2405 free_fail:
2406 journal_err = BlockDeallocate(hfsmp, newStartBlock, newBlockCount, HFS_ALLOC_SKIPFREEBLKS);
2407 if (journal_err) {
2408 printf("hfs_relocate_journal_file: BlockDeallocate returned %d\n", error);
2409 hfs_mark_inconsistent(hfsmp, HFS_ROLLBACK_FAILED);
2410 }
2411 fail:
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);
2416 }
2417 return error;
2418 }
2419
2420
2421 /*
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
2425 * relocate code.
2426 */
2427 static int
2428 hfs_reclaim_journal_file(struct hfsmount *hfsmp, u_int32_t allocLimit, vfs_context_t context)
2429 {
2430 int error = 0;
2431 u_int32_t startBlock;
2432 u_int32_t blockCount = hfsmp->jnl_size / hfsmp->blockSize;
2433
2434 /*
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.
2437 */
2438 if (hfsmp->jvp == hfsmp->hfs_devvp) {
2439 startBlock = hfsmp->jnl_start;
2440 blockCount = hfsmp->jnl_size / hfsmp->blockSize;
2441 } else {
2442 u_int32_t fileid;
2443 u_int32_t old_jnlfileid;
2444 struct cat_attr attr;
2445 struct cat_fork fork;
2446
2447 /*
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.
2451 */
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");
2458 return EIO;
2459 }
2460
2461 startBlock = fork.cf_extents[0].startBlock;
2462 blockCount = fork.cf_extents[0].blockCount;
2463 }
2464
2465 if (startBlock + blockCount <= allocLimit) {
2466 /* The journal file does not require relocation */
2467 return 0;
2468 }
2469
2470 error = hfs_relocate_journal_file(hfsmp, hfs_blk_to_bytes(blockCount, hfsmp->blockSize),
2471 HFS_RESIZE_TRUNCATE, context);
2472 if (error == 0) {
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);
2477 }
2478
2479 return error;
2480 }
2481
2482
2483 /*
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.
2487 */
2488 static int
2489 hfs_reclaim_journal_info_block(struct hfsmount *hfsmp, u_int32_t allocLimit, vfs_context_t context)
2490 {
2491 int error;
2492 int journal_err;
2493 int lockflags;
2494 u_int32_t oldBlock;
2495 u_int32_t newBlock;
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;
2501
2502 if (hfsmp->vcbJinfoBlock <= allocLimit) {
2503 /* The journal info block does not require relocation */
2504 return 0;
2505 }
2506
2507 error = hfs_start_transaction(hfsmp);
2508 if (error) {
2509 printf("hfs_reclaim_journal_info_block: hfs_start_transaction returned %d\n", error);
2510 return error;
2511 }
2512 lockflags = hfs_systemfile_lock(hfsmp, SFL_CATALOG | SFL_BITMAP, HFS_EXCLUSIVE_LOCK);
2513
2514 error = BlockAllocate(hfsmp, 1, 1, 1,
2515 HFS_ALLOC_METAZONE | HFS_ALLOC_FORCECONTIG | HFS_ALLOC_SKIPFREEBLKS | HFS_ALLOC_FLUSHTXN,
2516 &newBlock, &blockCount);
2517 if (error) {
2518 printf("hfs_reclaim_journal_info_block: BlockAllocate returned %d\n", error);
2519 goto fail;
2520 }
2521 if (blockCount != 1) {
2522 printf("hfs_reclaim_journal_info_block: blockCount != 1 (%u)\n", blockCount);
2523 goto free_fail;
2524 }
2525
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);
2530 if (error) {
2531 printf("hfs_reclaim_journal_info_block: failed to read JIB (%d)\n", error);
2532 if (old_bp) {
2533 buf_brelse(old_bp);
2534 }
2535 goto free_fail;
2536 }
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);
2541 buf_brelse(old_bp);
2542 if (journal_uses_fua(hfsmp->jnl))
2543 buf_markfua(new_bp);
2544 error = buf_bwrite(new_bp);
2545 if (error) {
2546 printf("hfs_reclaim_journal_info_block: failed to write new JIB (%d)\n", error);
2547 goto free_fail;
2548 }
2549 if (!journal_uses_fua(hfsmp->jnl)) {
2550 error = hfs_flush(hfsmp, HFS_FLUSH_CACHE);
2551 if (error) {
2552 printf("hfs_reclaim_journal_info_block: hfs_flush failed (%d)\n", error);
2553 /* Don't fail the operation. */
2554 }
2555 }
2556
2557 /* Deallocate the old block once the new one has the new valid content */
2558 error = BlockDeallocate(hfsmp, hfsmp->vcbJinfoBlock, 1, HFS_ALLOC_SKIPFREEBLKS);
2559 if (error) {
2560 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error);
2561 goto free_fail;
2562 }
2563
2564
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);
2567 if (error) {
2568 printf("hfs_reclaim_journal_info_block: cat_idlookup returned %d\n", error);
2569 goto fail;
2570 }
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 */
2578 if (error) {
2579 printf("hfs_reclaim_journal_info_block: cat_update returned %d\n", error);
2580 goto fail;
2581 }
2582
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);
2586 if (error) {
2587 printf("hfs_reclaim_journal_info_block: hfs_flushvolumeheader returned %d\n", error);
2588 goto fail;
2589 }
2590 hfs_systemfile_unlock(hfsmp, lockflags);
2591 error = hfs_end_transaction(hfsmp);
2592 if (error) {
2593 printf("hfs_reclaim_journal_info_block: hfs_end_transaction returned %d\n", error);
2594 }
2595 error = hfs_flush(hfsmp, HFS_FLUSH_JOURNAL);
2596 if (error) {
2597 printf("hfs_reclaim_journal_info_block: journal_flush returned %d\n", error);
2598 }
2599
2600 /* Account for the block relocated and print progress */
2601 hfsmp->hfs_resize_blocksmoved += 1;
2602 hfs_truncatefs_progress(hfsmp);
2603 if (!error) {
2604 printf ("hfs_reclaim_journal_info: Relocated 1 block from journal info on \"%s\"\n",
2605 hfsmp->vcbVN);
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);
2608 }
2609 }
2610 return error;
2611
2612 free_fail:
2613 journal_err = BlockDeallocate(hfsmp, newBlock, blockCount, HFS_ALLOC_SKIPFREEBLKS);
2614 if (journal_err) {
2615 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error);
2616 hfs_mark_inconsistent(hfsmp, HFS_ROLLBACK_FAILED);
2617 }
2618
2619 fail:
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);
2624 }
2625 return error;
2626 }
2627
2628
2629 static u_int64_t
2630 calculate_journal_size(struct hfsmount *hfsmp, u_int32_t sector_size, u_int64_t sector_count)
2631 {
2632 u_int64_t journal_size;
2633 u_int32_t journal_scale;
2634
2635 #define DEFAULT_JOURNAL_SIZE (8*1024*1024)
2636 #define MAX_JOURNAL_SIZE (512*1024*1024)
2637
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
2642 * block.
2643 */
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;
2648 }
2649 if (journal_size < hfsmp->blockSize) {
2650 journal_size = hfsmp->blockSize;
2651 }
2652 return journal_size;
2653 }
2654
2655
2656 /*
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.
2660 */
2661 static int
2662 hfs_extend_journal(struct hfsmount *hfsmp, u_int32_t sector_size, u_int64_t sector_count, vfs_context_t context)
2663 {
2664 int error = 0;
2665 u_int64_t calc_journal_size;
2666
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");
2670 }
2671 return 0;
2672 }
2673
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 */
2677 goto out;
2678 }
2679
2680 if (hfs_resize_debug) {
2681 printf ("hfs_extend_journal: journal old=%u, new=%qd\n", hfsmp->jnl_size, calc_journal_size);
2682 }
2683
2684 /* Extend the journal to the new calculated size */
2685 error = hfs_relocate_journal_file(hfsmp, calc_journal_size, HFS_RESIZE_EXTEND, context);
2686 if (error == 0) {
2687 printf ("hfs_extend_journal: Extended journal size to %u bytes on \"%s\"\n",
2688 hfsmp->jnl_size, hfsmp->vcbVN);
2689 }
2690 out:
2691 return error;
2692 }
2693
2694
2695 /*
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.
2701 *
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.
2705 *
2706 * Side Effects:
2707 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
2708 * blocks that were relocated.
2709 *
2710 * Returns:
2711 * 0 on success, non-zero on failure.
2712 */
2713 static int
2714 hfs_reclaim_xattr(struct hfsmount *hfsmp, struct vnode *vp, u_int32_t fileID, u_int32_t allocLimit, vfs_context_t context)
2715 {
2716 int error = 0;
2717 struct hfs_reclaim_extent_info *extent_info;
2718 int i;
2719 HFSPlusAttrKey *key;
2720 int *lockflags;
2721
2722 if (hfs_resize_debug) {
2723 printf("hfs_reclaim_xattr: === Start reclaiming xattr for id=%u ===\n", fileID);
2724 }
2725
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;
2734
2735 /* Initialize iterator from the extent_info structure */
2736 extent_info->iterator = hfs_mallocz(sizeof(struct BTreeIterator));
2737
2738 /* Build attribute key */
2739 key = (HFSPlusAttrKey *)&(extent_info->iterator->key);
2740 error = hfs_buildattrkey(fileID, NULL, key);
2741 if (error) {
2742 goto out;
2743 }
2744
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.
2748 */
2749 extent_info->btdata.bufferAddress = &(extent_info->record.xattr);
2750 extent_info->btdata.itemSize = sizeof(HFSPlusAttrRecord);
2751 extent_info->btdata.itemCount = 1;
2752
2753 /*
2754 * Sync all extent-based attribute data to the disk.
2755 *
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
2758 * space.
2759 */
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);
2764 if (error) {
2765 goto out;
2766 }
2767
2768 /* Search for extended attribute for current file. This
2769 * will place the iterator before the first matching record.
2770 */
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);
2776 if (error) {
2777 if (error != btNotFound) {
2778 goto out;
2779 }
2780 /* btNotFound is expected here, so just mask it */
2781 error = 0;
2782 }
2783
2784 while (1) {
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);
2791
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) {
2795 error = 0;
2796 }
2797 break;
2798 }
2799
2800 /* We only care about extent-based EAs */
2801 if ((extent_info->record.xattr.recordType != kHFSPlusAttrForkData) &&
2802 (extent_info->record.xattr.recordType != kHFSPlusAttrExtents)) {
2803 continue;
2804 }
2805
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;
2812 }
2813
2814 extent_info->recStartBlock = key->startBlock;
2815 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2816 if (extent_info->extents[i].blockCount == 0) {
2817 break;
2818 }
2819 extent_info->extent_index = i;
2820 error = hfs_reclaim_extent(hfsmp, allocLimit, extent_info, context);
2821 if (error) {
2822 printf ("hfs_reclaim_xattr: fileID=%u hfs_reclaim_extent error=%d\n", fileID, error);
2823 goto out;
2824 }
2825 }
2826 }
2827
2828 out:
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);
2833 }
2834 if (extent_info->iterator) {
2835 hfs_free(extent_info->iterator, sizeof(*extent_info->iterator));
2836 }
2837 if (extent_info) {
2838 hfs_free(extent_info, sizeof(*extent_info));
2839 }
2840 if (hfs_resize_debug) {
2841 printf("hfs_reclaim_xattr: === Finished relocating xattr for fileid=%u (error=%d) ===\n", fileID, error);
2842 }
2843 return error;
2844 }
2845
2846 /*
2847 * Reclaim any extent-based extended attributes allocation blocks from
2848 * the area of the disk that is being truncated.
2849 *
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.
2856 *
2857 * Inputs:
2858 * allocLimit - starting block of the area being reclaimed
2859 *
2860 * Returns:
2861 * returns 0 on success, non-zero on failure.
2862 */
2863 static int
2864 hfs_reclaim_xattrspace(struct hfsmount *hfsmp, u_int32_t allocLimit, vfs_context_t context)
2865 {
2866 int error = 0;
2867 FCB *fcb;
2868 struct BTreeIterator *iterator = NULL;
2869 struct FSBufferDescriptor btdata;
2870 HFSPlusAttrKey *key;
2871 HFSPlusAttrRecord rec;
2872 int lockflags = 0;
2873 cnid_t prev_fileid = 0;
2874 struct vnode *vp;
2875 int need_relocate;
2876 int btree_operation;
2877 u_int32_t files_moved = 0;
2878 u_int32_t prev_blocksmoved;
2879 int i;
2880
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;
2884
2885 iterator = hfs_mallocz(sizeof(*iterator));
2886 key = (HFSPlusAttrKey *)&iterator->key;
2887 btdata.bufferAddress = &rec;
2888 btdata.itemSize = sizeof(rec);
2889 btdata.itemCount = 1;
2890
2891 need_relocate = false;
2892 btree_operation = kBTreeFirstRecord;
2893 /* Traverse the attribute btree to find extent-based EAs to reclaim */
2894 while (1) {
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);
2898 if (error) {
2899 if (error == fsBTRecordNotFoundErr || error == fsBTEndOfIterationErr) {
2900 error = 0;
2901 }
2902 break;
2903 }
2904 btree_operation = kBTreeNextRecord;
2905
2906 /* If the extents of current fileID were already relocated, skip it */
2907 if (prev_fileid == key->fileID) {
2908 continue;
2909 }
2910
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) {
2917 break;
2918 }
2919 if ((rec.forkData.theFork.extents[i].startBlock +
2920 rec.forkData.theFork.extents[i].blockCount) > allocLimit) {
2921 need_relocate = true;
2922 break;
2923 }
2924 }
2925 break;
2926
2927 case kHFSPlusAttrExtents:
2928 for (i = 0; i < kHFSPlusExtentDensity; i++) {
2929 if (rec.overflowExtents.extents[i].blockCount == 0) {
2930 break;
2931 }
2932 if ((rec.overflowExtents.extents[i].startBlock +
2933 rec.overflowExtents.extents[i].blockCount) > allocLimit) {
2934 need_relocate = true;
2935 break;
2936 }
2937 }
2938 break;
2939 };
2940
2941 /* Continue iterating to next attribute record */
2942 if (need_relocate == false) {
2943 continue;
2944 }
2945
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.
2949 *
2950 * We want to allow open-unlinked files to be moved,
2951 * so provide allow_deleted == 1 for hfs_vget().
2952 */
2953 if (hfs_vget(hfsmp, key->fileID, &vp, 0, 1) != 0) {
2954 continue;
2955 }
2956
2957 error = hfs_reclaim_xattr(hfsmp, vp, key->fileID, allocLimit, context);
2958 hfs_unlock(VTOC(vp));
2959 vnode_put(vp);
2960 if (error) {
2961 printf ("hfs_reclaim_xattrspace: Error relocating xattrs for fileid=%u (error=%d)\n", key->fileID, error);
2962 break;
2963 }
2964 prev_fileid = key->fileID;
2965 files_moved++;
2966 }
2967
2968 if (files_moved) {
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);
2972 }
2973
2974 hfs_free(iterator, sizeof(*iterator));
2975 return error;
2976 }
2977
2978 /*
2979 * Reclaim blocks from regular files.
2980 *
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.
2985 *
2986 * Returns:
2987 * Zero on success, non-zero on failure.
2988 */
2989 static int
2990 hfs_reclaim_filespace(struct hfsmount *hfsmp, u_int32_t allocLimit, vfs_context_t context)
2991 {
2992 int error;
2993 FCB *fcb;
2994 struct BTreeIterator *iterator = NULL;
2995 struct FSBufferDescriptor btdata;
2996 int btree_operation;
2997 int lockflags;
2998 struct HFSPlusCatalogFile filerec;
2999 struct vnode *vp;
3000 struct vnode *rvp;
3001 struct filefork *datafork;
3002 u_int32_t files_moved = 0;
3003 u_int32_t prev_blocksmoved;
3004
3005 #if CONFIG_PROTECT
3006 int keys_generated = 0;
3007 #endif
3008
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;
3012
3013 #if CONFIG_PROTECT
3014 /*
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.
3020 */
3021 if (cp_fs_protected (hfsmp->hfs_mp)) {
3022 error = cpx_gentempkeys(&hfsmp->hfs_resize_cpx, hfsmp);
3023 if (error == 0) {
3024 keys_generated = 1;
3025 }
3026
3027 if (error) {
3028 printf("hfs_reclaimspace: Error generating temporary keys for resize (%d)\n", error);
3029 goto reclaim_filespace_done;
3030 }
3031 }
3032
3033 #endif
3034
3035 iterator = hfs_mallocz(sizeof(*iterator));
3036
3037 btdata.bufferAddress = &filerec;
3038 btdata.itemSize = sizeof(filerec);
3039 btdata.itemCount = 1;
3040
3041 btree_operation = kBTreeFirstRecord;
3042 while (1) {
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);
3046 if (error) {
3047 if (error == fsBTRecordNotFoundErr || error == fsBTEndOfIterationErr) {
3048 error = 0;
3049 }
3050 break;
3051 }
3052 btree_operation = kBTreeNextRecord;
3053
3054 if (filerec.recordType != kHFSPlusFileRecord) {
3055 continue;
3056 }
3057
3058 /* Check if any of the extents require relocation */
3059 bool overlaps;
3060 error = hfs_file_extent_overlaps(hfsmp, allocLimit, &filerec, &overlaps);
3061 if (error)
3062 break;
3063
3064 if (!overlaps)
3065 continue;
3066
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);
3071 }
3072 continue;
3073 }
3074
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);
3080 if (error) {
3081 printf ("hfs_reclaimspace: Error reclaiming datafork blocks of fileid=%u (error=%d)\n", filerec.fileID, error);
3082 hfs_unlock(VTOC(vp));
3083 vnode_put(vp);
3084 break;
3085 }
3086 }
3087
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.
3093 */
3094 rvp = vp;
3095 } else {
3096 error = hfs_vgetrsrc(hfsmp, vp, &rvp);
3097 if (error) {
3098 printf ("hfs_reclaimspace: Error looking up rvp for fileid=%u (error=%d)\n", filerec.fileID, error);
3099 hfs_unlock(VTOC(vp));
3100 vnode_put(vp);
3101 break;
3102 }
3103 VTOC(rvp)->c_flag |= C_NEED_RVNODE_PUT;
3104 }
3105
3106 error = hfs_reclaim_file(hfsmp, rvp, filerec.fileID,
3107 kHFSResourceForkType, allocLimit, context);
3108 if (error) {
3109 printf ("hfs_reclaimspace: Error reclaiming rsrcfork blocks of fileid=%u (error=%d)\n", filerec.fileID, error);
3110 hfs_unlock(VTOC(vp));
3111 vnode_put(vp);
3112 break;
3113 }
3114 }
3115
3116 /* The file forks were relocated successfully, now drop the
3117 * cnode lock and vnode reference, and continue iterating to
3118 * next catalog record.
3119 */
3120 hfs_unlock(VTOC(vp));
3121 vnode_put(vp);
3122 files_moved++;
3123 }
3124
3125 if (files_moved) {
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);
3129 }
3130
3131 #if CONFIG_PROTECT
3132 reclaim_filespace_done:
3133
3134 if (keys_generated) {
3135 cpx_free(hfsmp->hfs_resize_cpx);
3136 hfsmp->hfs_resize_cpx = NULL;
3137 }
3138 #endif
3139
3140 hfs_free(iterator, sizeof(*iterator));
3141
3142 return error;
3143 }
3144
3145 /*
3146 * Reclaim space at the end of a file system.
3147 *
3148 * Inputs -
3149 * allocLimit - start block of the space being reclaimed
3150 * reclaimblks - number of allocation blocks to reclaim
3151 */
3152 static int
3153 hfs_reclaimspace(struct hfsmount *hfsmp, u_int32_t allocLimit, u_int32_t reclaimblks, vfs_context_t context)
3154 {
3155 int error = 0;
3156
3157 /*
3158 * Preflight the bitmap to find out total number of blocks that need
3159 * relocation.
3160 *
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.
3164 */
3165 error = hfs_count_allocated(hfsmp, allocLimit, reclaimblks, &(hfsmp->hfs_resize_totalblocks));
3166 if (error) {
3167 printf ("hfs_reclaimspace: Unable to determine total blocks to reclaim error=%d\n", error);
3168 return error;
3169 }
3170 if (hfs_resize_debug) {
3171 printf ("hfs_reclaimspace: Total number of blocks to reclaim = %u\n", hfsmp->hfs_resize_totalblocks);
3172 }
3173
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);
3176
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
3181 * fail.
3182 */
3183 error = hfs_reclaim_journal_file(hfsmp, allocLimit, context);
3184 if (error) {
3185 printf("hfs_reclaimspace: hfs_reclaim_journal_file failed (%d)\n", error);
3186 return error;
3187 }
3188
3189 /* Relocate journal info block blocks if they're in the way. */
3190 error = hfs_reclaim_journal_info_block(hfsmp, allocLimit, context);
3191 if (error) {
3192 printf("hfs_reclaimspace: hfs_reclaim_journal_info_block failed (%d)\n", error);
3193 return error;
3194 }
3195
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.
3201 */
3202 error = hfs_reclaim_file(hfsmp, hfsmp->hfs_extents_vp, kHFSExtentsFileID,
3203 kHFSDataForkType, allocLimit, context);
3204 if (error) {
3205 printf("hfs_reclaimspace: reclaim extents b-tree returned %d\n", error);
3206 return error;
3207 }
3208
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);
3212 if (error) {
3213 printf("hfs_reclaimspace: reclaim allocation file returned %d\n", error);
3214 return error;
3215 }
3216
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);
3220 if (error) {
3221 printf("hfs_reclaimspace: reclaim catalog b-tree returned %d\n", error);
3222 return error;
3223 }
3224
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);
3228 if (error) {
3229 printf("hfs_reclaimspace: reclaim attribute b-tree returned %d\n", error);
3230 return error;
3231 }
3232
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);
3236 if (error) {
3237 printf("hfs_reclaimspace: reclaim startup file returned %d\n", error);
3238 return error;
3239 }
3240
3241 /*
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.
3246 *
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.
3250 */
3251 if (hfsmp->hfs_resize_blocksmoved) {
3252 hfs_flush(hfsmp, HFS_FLUSH_JOURNAL_META);
3253 }
3254
3255 /* Reclaim extents from catalog file records */
3256 error = hfs_reclaim_filespace(hfsmp, allocLimit, context);
3257 if (error) {
3258 printf ("hfs_reclaimspace: hfs_reclaim_filespace returned error=%d\n", error);
3259 return error;
3260 }
3261
3262 /* Reclaim extents from extent-based extended attributes, if any */
3263 error = hfs_reclaim_xattrspace(hfsmp, allocLimit, context);
3264 if (error) {
3265 printf ("hfs_reclaimspace: hfs_reclaim_xattrspace returned error=%d\n", error);
3266 return error;
3267 }
3268
3269 /*
3270 * Make sure reserved ranges in the region we're to allocate don't
3271 * overlap.
3272 */
3273 struct rl_entry *range;
3274 again:;
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) {
3278 // Wait 100ms
3279 hfs_systemfile_unlock(hfsmp, lockf);
3280 msleep(hfs_reclaimspace, NULL, PINOD, "waiting on reserved blocks",
3281 &(struct timespec){ 0, 100 * 1000000 });
3282 goto again;
3283 }
3284 }
3285 hfs_systemfile_unlock(hfsmp, lockf);
3286
3287 return error;
3288 }
3289
3290
3291 /*
3292 * Check if there are any extents (including overflow extents) that overlap
3293 * into the disk space that is being reclaimed.
3294 *
3295 * Output -
3296 * true - One of the extents need to be relocated
3297 * false - No overflow extents need to be relocated, or there was an error
3298 */
3299 static errno_t
3300 hfs_file_extent_overlaps(struct hfsmount *hfsmp, u_int32_t allocLimit,
3301 struct HFSPlusCatalogFile *filerec, bool *overlaps)
3302 {
3303 struct BTreeIterator * iterator = NULL;
3304 struct FSBufferDescriptor btdata;
3305 HFSPlusExtentRecord extrec;
3306 HFSPlusExtentKey *extkeyptr;
3307 FCB *fcb;
3308 int i, j;
3309 int error;
3310 int lockflags = 0;
3311 u_int32_t endblock;
3312 errno_t ret = 0;
3313
3314 /* Check if data fork overlaps the target space */
3315 for (i = 0; i < kHFSPlusExtentDensity; ++i) {
3316 if (filerec->dataFork.extents[i].blockCount == 0) {
3317 break;
3318 }
3319 endblock = filerec->dataFork.extents[i].startBlock +
3320 filerec->dataFork.extents[i].blockCount;
3321 if (endblock > allocLimit) {
3322 *overlaps = true;
3323 goto out;
3324 }
3325 }
3326
3327 /* Check if resource fork overlaps the target space */
3328 for (j = 0; j < kHFSPlusExtentDensity; ++j) {
3329 if (filerec->resourceFork.extents[j].blockCount == 0) {
3330 break;
3331 }
3332 endblock = filerec->resourceFork.extents[j].startBlock +
3333 filerec->resourceFork.extents[j].blockCount;
3334 if (endblock > allocLimit) {
3335 *overlaps = true;
3336 goto out;
3337 }
3338 }
3339
3340 /* Return back if there are no overflow extents for this file */
3341 if ((i < kHFSPlusExtentDensity) && (j < kHFSPlusExtentDensity)) {
3342 *overlaps = false;
3343 goto out;
3344 }
3345
3346 iterator = hfs_malloc(sizeof(*iterator));
3347
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;
3354
3355 btdata.bufferAddress = &extrec;
3356 btdata.itemSize = sizeof(extrec);
3357 btdata.itemCount = 1;
3358
3359 fcb = VTOF(hfsmp->hfs_extents_vp);
3360
3361 lockflags = hfs_systemfile_lock(hfsmp, SFL_EXTENTS, HFS_SHARED_LOCK);
3362
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.
3366 */
3367 error = BTSearchRecord(fcb, iterator, &btdata, NULL, iterator);
3368 if (error && (error != btNotFound)) {
3369 ret = MacToVFSError(error);
3370 goto out;
3371 }
3372
3373 /* BTIterateRecord() might return error if the btree is empty, and
3374 * therefore we return that the extent does not overflow to the caller
3375 */
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) {
3380 break;
3381 }
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) {
3385 break;
3386 }
3387 endblock = extrec[i].startBlock + extrec[i].blockCount;
3388 if (endblock > allocLimit) {
3389 *overlaps = true;
3390 goto out;
3391 }
3392 }
3393 /* Look for more records. */
3394 error = BTIterateRecord(fcb, kBTreeNextRecord, iterator, &btdata, NULL);
3395 }
3396
3397 if (error && error != btNotFound) {
3398 ret = MacToVFSError(error);
3399 goto out;
3400 }
3401
3402 *overlaps = false;
3403
3404 out:
3405 if (lockflags) {
3406 hfs_systemfile_unlock(hfsmp, lockflags);
3407 }
3408
3409 hfs_free(iterator, sizeof(*iterator));
3410
3411 return ret;
3412 }
3413
3414
3415 /*
3416 * Calculate the progress of a file system resize operation.
3417 */
3418 int
3419 hfs_resize_progress(struct hfsmount *hfsmp, u_int32_t *progress)
3420 {
3421 if ((hfsmp->hfs_flags & HFS_RESIZE_IN_PROGRESS) == 0) {
3422 return (ENXIO);
3423 }
3424
3425 if (hfsmp->hfs_resize_totalblocks > 0) {
3426 *progress = (u_int32_t)((hfsmp->hfs_resize_blocksmoved * 100ULL) / hfsmp->hfs_resize_totalblocks);
3427 } else {
3428 *progress = 0;
3429 }
3430
3431 return (0);
3432 }