2 * Copyright (c) 1999-2010 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1991, 1993, 1994
30 * The Regents of the University of California. All rights reserved.
31 * (c) UNIX System Laboratories, Inc.
32 * All or some portions of this file are derived from material licensed
33 * to the University of California by American Telephone and Telegraph
34 * Co. or Unix System Laboratories, Inc. and are reproduced herein with
35 * the permission of UNIX System Laboratories, Inc.
37 * Redistribution and use in source and binary forms, with or without
38 * modification, are permitted provided that the following conditions
40 * 1. Redistributions of source code must retain the above copyright
41 * notice, this list of conditions and the following disclaimer.
42 * 2. Redistributions in binary form must reproduce the above copyright
43 * notice, this list of conditions and the following disclaimer in the
44 * documentation and/or other materials provided with the distribution.
45 * 3. All advertising materials mentioning features or use of this software
46 * must display the following acknowledgement:
47 * This product includes software developed by the University of
48 * California, Berkeley and its contributors.
49 * 4. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * derived from @(#)ufs_vfsops.c 8.8 (Berkeley) 5/20/95
68 * (c) Copyright 1997-2002 Apple Computer, Inc. All rights reserved.
70 * hfs_vfsops.c -- VFS layer for loadable HFS file system.
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/kauth.h>
78 #include <sys/ubc_internal.h>
79 #include <sys/vnode_internal.h>
80 #include <sys/mount_internal.h>
81 #include <sys/sysctl.h>
82 #include <sys/malloc.h>
84 #include <sys/quota.h>
86 #include <sys/paths.h>
87 #include <sys/utfconv.h>
88 #include <sys/kdebug.h>
89 #include <sys/fslog.h>
92 #include <kern/locks.h>
94 #include <vfs/vfs_journal.h>
96 #include <miscfs/specfs/specdev.h>
97 #include <hfs/hfs_mount.h>
99 #include <libkern/crypto/md5.h>
100 #include <uuid/uuid.h>
103 #include "hfs_catalog.h"
104 #include "hfs_cnode.h"
106 #include "hfs_endian.h"
107 #include "hfs_hotfiles.h"
108 #include "hfs_quota.h"
110 #include "hfscommon/headers/FileMgrInternal.h"
111 #include "hfscommon/headers/BTreesInternal.h"
114 #include <sys/cprotect.h>
117 #if CONFIG_HFS_ALLOC_RBTREE
118 #include "hfscommon/headers/HybridAllocator.h"
121 #define HFS_MOUNT_DEBUG 1
128 /* Enable/disable debugging code for live volume resizing */
129 int hfs_resize_debug
= 0;
131 lck_grp_attr_t
* hfs_group_attr
;
132 lck_attr_t
* hfs_lock_attr
;
133 lck_grp_t
* hfs_mutex_group
;
134 lck_grp_t
* hfs_rwlock_group
;
135 lck_grp_t
* hfs_spinlock_group
;
137 extern struct vnodeopv_desc hfs_vnodeop_opv_desc
;
138 extern struct vnodeopv_desc hfs_std_vnodeop_opv_desc
;
140 /* not static so we can re-use in hfs_readwrite.c for build_path calls */
141 int hfs_vfs_vget(struct mount
*mp
, ino64_t ino
, struct vnode
**vpp
, vfs_context_t context
);
143 static int hfs_changefs(struct mount
*mp
, struct hfs_mount_args
*args
);
144 static int hfs_fhtovp(struct mount
*mp
, int fhlen
, unsigned char *fhp
, struct vnode
**vpp
, vfs_context_t context
);
145 static int hfs_flushfiles(struct mount
*, int, struct proc
*);
146 static int hfs_flushMDB(struct hfsmount
*hfsmp
, int waitfor
, int altflush
);
147 static int hfs_getmountpoint(struct vnode
*vp
, struct hfsmount
**hfsmpp
);
148 static int hfs_init(struct vfsconf
*vfsp
);
149 static int hfs_vfs_root(struct mount
*mp
, struct vnode
**vpp
, vfs_context_t context
);
150 static int hfs_quotactl(struct mount
*, int, uid_t
, caddr_t
, vfs_context_t context
);
151 static int hfs_start(struct mount
*mp
, int flags
, vfs_context_t context
);
152 static int hfs_vptofh(struct vnode
*vp
, int *fhlenp
, unsigned char *fhp
, vfs_context_t context
);
153 static int hfs_file_extent_overlaps(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, struct HFSPlusCatalogFile
*filerec
);
154 static int hfs_journal_replay(vnode_t devvp
, vfs_context_t context
);
155 static int hfs_reclaimspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, u_int32_t reclaimblks
, vfs_context_t context
);
157 void hfs_initialize_allocator (struct hfsmount
*hfsmp
);
158 int hfs_teardown_allocator (struct hfsmount
*hfsmp
);
160 int hfs_mount(struct mount
*mp
, vnode_t devvp
, user_addr_t data
, vfs_context_t context
);
161 int hfs_mountfs(struct vnode
*devvp
, struct mount
*mp
, struct hfs_mount_args
*args
, int journal_replay_only
, vfs_context_t context
);
162 int hfs_reload(struct mount
*mp
);
163 int hfs_statfs(struct mount
*mp
, register struct vfsstatfs
*sbp
, vfs_context_t context
);
164 int hfs_sync(struct mount
*mp
, int waitfor
, vfs_context_t context
);
165 int hfs_sysctl(int *name
, u_int namelen
, user_addr_t oldp
, size_t *oldlenp
,
166 user_addr_t newp
, size_t newlen
, vfs_context_t context
);
167 int hfs_unmount(struct mount
*mp
, int mntflags
, vfs_context_t context
);
170 * Called by vfs_mountroot when mounting HFS Plus as root.
174 hfs_mountroot(mount_t mp
, vnode_t rvp
, vfs_context_t context
)
176 struct hfsmount
*hfsmp
;
178 struct vfsstatfs
*vfsp
;
181 if ((error
= hfs_mountfs(rvp
, mp
, NULL
, 0, context
))) {
182 if (HFS_MOUNT_DEBUG
) {
183 printf("hfs_mountroot: hfs_mountfs returned %d, rvp (%p) name (%s) \n",
184 error
, rvp
, (rvp
->v_name
? rvp
->v_name
: "unknown device"));
190 hfsmp
= VFSTOHFS(mp
);
192 hfsmp
->hfs_uid
= UNKNOWNUID
;
193 hfsmp
->hfs_gid
= UNKNOWNGID
;
194 hfsmp
->hfs_dir_mask
= (S_IRWXU
| S_IRGRP
|S_IXGRP
| S_IROTH
|S_IXOTH
); /* 0755 */
195 hfsmp
->hfs_file_mask
= (S_IRWXU
| S_IRGRP
|S_IXGRP
| S_IROTH
|S_IXOTH
); /* 0755 */
197 /* Establish the free block reserve. */
198 vcb
= HFSTOVCB(hfsmp
);
199 vcb
->reserveBlocks
= ((u_int64_t
)vcb
->totalBlocks
* HFS_MINFREE
) / 100;
200 vcb
->reserveBlocks
= MIN(vcb
->reserveBlocks
, HFS_MAXRESERVE
/ vcb
->blockSize
);
202 vfsp
= vfs_statfs(mp
);
203 (void)hfs_statfs(mp
, vfsp
, NULL
);
216 hfs_mount(struct mount
*mp
, vnode_t devvp
, user_addr_t data
, vfs_context_t context
)
218 struct proc
*p
= vfs_context_proc(context
);
219 struct hfsmount
*hfsmp
= NULL
;
220 struct hfs_mount_args args
;
224 if ((retval
= copyin(data
, (caddr_t
)&args
, sizeof(args
)))) {
225 if (HFS_MOUNT_DEBUG
) {
226 printf("hfs_mount: copyin returned %d for fs\n", retval
);
230 cmdflags
= (u_int32_t
)vfs_flags(mp
) & MNT_CMDFLAGS
;
231 if (cmdflags
& MNT_UPDATE
) {
232 hfsmp
= VFSTOHFS(mp
);
234 /* Reload incore data after an fsck. */
235 if (cmdflags
& MNT_RELOAD
) {
236 if (vfs_isrdonly(mp
)) {
237 int error
= hfs_reload(mp
);
238 if (error
&& HFS_MOUNT_DEBUG
) {
239 printf("hfs_mount: hfs_reload returned %d on %s \n", error
, hfsmp
->vcbVN
);
244 if (HFS_MOUNT_DEBUG
) {
245 printf("hfs_mount: MNT_RELOAD not supported on rdwr filesystem %s\n", hfsmp
->vcbVN
);
251 /* Change to a read-only file system. */
252 if (((hfsmp
->hfs_flags
& HFS_READ_ONLY
) == 0) &&
256 /* Set flag to indicate that a downgrade to read-only
257 * is in progress and therefore block any further
258 * modifications to the file system.
260 hfs_lock_global (hfsmp
, HFS_EXCLUSIVE_LOCK
);
261 hfsmp
->hfs_flags
|= HFS_RDONLY_DOWNGRADE
;
262 hfsmp
->hfs_downgrading_proc
= current_thread();
263 hfs_unlock_global (hfsmp
);
265 /* use VFS_SYNC to push out System (btree) files */
266 retval
= VFS_SYNC(mp
, MNT_WAIT
, context
);
267 if (retval
&& ((cmdflags
& MNT_FORCE
) == 0)) {
268 hfsmp
->hfs_flags
&= ~HFS_RDONLY_DOWNGRADE
;
269 hfsmp
->hfs_downgrading_proc
= NULL
;
270 if (HFS_MOUNT_DEBUG
) {
271 printf("hfs_mount: VFS_SYNC returned %d during b-tree sync of %s \n", retval
, hfsmp
->vcbVN
);
277 if (cmdflags
& MNT_FORCE
)
280 if ((retval
= hfs_flushfiles(mp
, flags
, p
))) {
281 hfsmp
->hfs_flags
&= ~HFS_RDONLY_DOWNGRADE
;
282 hfsmp
->hfs_downgrading_proc
= NULL
;
283 if (HFS_MOUNT_DEBUG
) {
284 printf("hfs_mount: hfs_flushfiles returned %d on %s \n", retval
, hfsmp
->vcbVN
);
289 /* mark the volume cleanly unmounted */
290 hfsmp
->vcbAtrb
|= kHFSVolumeUnmountedMask
;
291 retval
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 0);
292 hfsmp
->hfs_flags
|= HFS_READ_ONLY
;
294 /* also get the volume bitmap blocks */
296 if (vnode_mount(hfsmp
->hfs_devvp
) == mp
) {
297 retval
= hfs_fsync(hfsmp
->hfs_devvp
, MNT_WAIT
, 0, p
);
299 vnode_get(hfsmp
->hfs_devvp
);
300 retval
= VNOP_FSYNC(hfsmp
->hfs_devvp
, MNT_WAIT
, context
);
301 vnode_put(hfsmp
->hfs_devvp
);
305 if (HFS_MOUNT_DEBUG
) {
306 printf("hfs_mount: FSYNC on devvp returned %d for fs %s\n", retval
, hfsmp
->vcbVN
);
308 hfsmp
->hfs_flags
&= ~HFS_RDONLY_DOWNGRADE
;
309 hfsmp
->hfs_downgrading_proc
= NULL
;
310 hfsmp
->hfs_flags
&= ~HFS_READ_ONLY
;
314 hfs_lock_global (hfsmp
, HFS_EXCLUSIVE_LOCK
);
316 journal_close(hfsmp
->jnl
);
319 // Note: we explicitly don't want to shutdown
320 // access to the jvp because we may need
321 // it later if we go back to being read-write.
323 hfs_unlock_global (hfsmp
);
326 #if CONFIG_HFS_ALLOC_RBTREE
327 (void) hfs_teardown_allocator(hfsmp
);
329 hfsmp
->hfs_downgrading_proc
= NULL
;
332 /* Change to a writable file system. */
333 if (vfs_iswriteupgrade(mp
)) {
334 #if CONFIG_HFS_ALLOC_RBTREE
335 thread_t allocator_thread
;
339 * On inconsistent disks, do not allow read-write mount
340 * unless it is the boot volume being mounted.
342 if (!(vfs_flags(mp
) & MNT_ROOTFS
) &&
343 (hfsmp
->vcbAtrb
& kHFSVolumeInconsistentMask
)) {
344 if (HFS_MOUNT_DEBUG
) {
345 printf("hfs_mount: attempting to mount inconsistent non-root volume %s\n", (hfsmp
->vcbVN
));
351 // If the journal was shut-down previously because we were
352 // asked to be read-only, let's start it back up again now
354 if ( (HFSTOVCB(hfsmp
)->vcbAtrb
& kHFSVolumeJournaledMask
)
355 && hfsmp
->jnl
== NULL
356 && hfsmp
->jvp
!= NULL
) {
359 if (hfsmp
->hfs_flags
& HFS_NEED_JNL_RESET
) {
360 jflags
= JOURNAL_RESET
;
365 hfs_lock_global (hfsmp
, HFS_EXCLUSIVE_LOCK
);
367 hfsmp
->jnl
= journal_open(hfsmp
->jvp
,
368 (hfsmp
->jnl_start
* HFSTOVCB(hfsmp
)->blockSize
) + (off_t
)HFSTOVCB(hfsmp
)->hfsPlusIOPosOffset
,
371 hfsmp
->hfs_logical_block_size
,
374 hfs_sync_metadata
, hfsmp
->hfs_mp
);
377 * Set up the trim callback function so that we can add
378 * recently freed extents to the free extent cache once
379 * the transaction that freed them is written to the
383 journal_trim_set_callback(hfsmp
->jnl
, hfs_trim_callback
, hfsmp
);
385 hfs_unlock_global (hfsmp
);
387 if (hfsmp
->jnl
== NULL
) {
388 if (HFS_MOUNT_DEBUG
) {
389 printf("hfs_mount: journal_open == NULL; couldn't be opened on %s \n", (hfsmp
->vcbVN
));
394 hfsmp
->hfs_flags
&= ~HFS_NEED_JNL_RESET
;
399 /* See if we need to erase unused Catalog nodes due to <rdar://problem/6947811>. */
400 retval
= hfs_erase_unused_nodes(hfsmp
);
401 if (retval
!= E_NONE
) {
402 if (HFS_MOUNT_DEBUG
) {
403 printf("hfs_mount: hfs_erase_unused_nodes returned %d for fs %s\n", retval
, hfsmp
->vcbVN
);
408 /* If this mount point was downgraded from read-write
409 * to read-only, clear that information as we are now
410 * moving back to read-write.
412 hfsmp
->hfs_flags
&= ~HFS_RDONLY_DOWNGRADE
;
413 hfsmp
->hfs_downgrading_proc
= NULL
;
415 /* mark the volume dirty (clear clean unmount bit) */
416 hfsmp
->vcbAtrb
&= ~kHFSVolumeUnmountedMask
;
418 retval
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 0);
419 if (retval
!= E_NONE
) {
420 if (HFS_MOUNT_DEBUG
) {
421 printf("hfs_mount: hfs_flushvolumeheader returned %d for fs %s\n", retval
, hfsmp
->vcbVN
);
426 /* Only clear HFS_READ_ONLY after a successful write */
427 hfsmp
->hfs_flags
&= ~HFS_READ_ONLY
;
430 if (!(hfsmp
->hfs_flags
& (HFS_READ_ONLY
| HFS_STANDARD
))) {
431 /* Setup private/hidden directories for hardlinks. */
432 hfs_privatedir_init(hfsmp
, FILE_HARDLINKS
);
433 hfs_privatedir_init(hfsmp
, DIR_HARDLINKS
);
435 hfs_remove_orphans(hfsmp
);
438 * Allow hot file clustering if conditions allow.
440 if ((hfsmp
->hfs_flags
& HFS_METADATA_ZONE
) &&
441 ((hfsmp
->hfs_flags
& HFS_SSD
) == 0)) {
442 (void) hfs_recording_init(hfsmp
);
444 /* Force ACLs on HFS+ file systems. */
445 if (vfs_extendedsecurity(HFSTOVFS(hfsmp
)) == 0) {
446 vfs_setextendedsecurity(HFSTOVFS(hfsmp
));
450 #if CONFIG_HFS_ALLOC_RBTREE
452 * Like the normal mount case, we need to handle creation of the allocation red-black tree
453 * if we're upgrading from read-only to read-write.
455 * We spawn a thread to create the pair of red-black trees for this volume.
456 * However, in so doing, we must be careful to ensure that if this thread is still
457 * running after mount has finished, it doesn't interfere with an unmount. Specifically,
458 * we'll need to set a bit that indicates we're in progress building the trees here.
459 * Unmount will check for this bit, and then if it's set, mark a corresponding bit that
460 * notifies the tree generation code that an unmount is waiting. Also, mark the extent
461 * tree flags that the allocator is enabled for use before we spawn the thread that will start
462 * scanning the RB tree.
464 * Only do this if we're operating on a read-write mount (we wouldn't care for read-only),
465 * which has not previously encountered a bad error on the red-black tree code. Also, don't
466 * try to re-build a tree that already exists.
469 if (hfsmp
->extent_tree_flags
== 0) {
470 hfsmp
->extent_tree_flags
|= (HFS_ALLOC_TREEBUILD_INFLIGHT
| HFS_ALLOC_RB_ENABLED
);
471 /* Initialize EOF counter so that the thread can assume it started at initial values */
472 hfsmp
->offset_block_end
= 0;
476 kernel_thread_start ((thread_continue_t
) hfs_initialize_allocator
, hfsmp
, &allocator_thread
);
477 thread_deallocate(allocator_thread
);
483 /* Update file system parameters. */
484 retval
= hfs_changefs(mp
, &args
);
485 if (retval
&& HFS_MOUNT_DEBUG
) {
486 printf("hfs_mount: hfs_changefs returned %d for %s\n", retval
, hfsmp
->vcbVN
);
489 } else /* not an update request */ {
491 /* Set the mount flag to indicate that we support volfs */
492 vfs_setflags(mp
, (u_int64_t
)((unsigned int)MNT_DOVOLFS
));
494 retval
= hfs_mountfs(devvp
, mp
, &args
, 0, context
);
495 if (retval
&& HFS_MOUNT_DEBUG
) {
496 printf("hfs_mount: hfs_mountfs returned %d\n", retval
);
500 * If above mount call was successful, and this mount is content protection
501 * enabled, then verify the on-disk EA on the root to ensure that the filesystem
502 * is of a suitable vintage to allow the mount to proceed.
504 if ((retval
== 0) && (cp_fs_protected (mp
))) {
506 struct cp_root_xattr xattr
;
507 bzero (&xattr
, sizeof(struct cp_root_xattr
));
508 hfsmp
= vfs_fsprivate(mp
);
510 /* go get the EA to get the version information */
511 err
= cp_getrootxattr (hfsmp
, &xattr
);
512 /* If there was no EA there, then write one out. */
513 if (err
== ENOATTR
) {
514 bzero(&xattr
, sizeof(struct cp_root_xattr
));
515 xattr
.major_version
= CP_CURRENT_MAJOR_VERS
;
516 xattr
.minor_version
= CP_CURRENT_MINOR_VERS
;
519 err
= cp_setrootxattr (hfsmp
, &xattr
);
522 * For any other error, including having an out of date CP version in the
523 * EA, or for an error out of cp_setrootxattr, deny the mount
524 * and do not proceed further.
526 if (err
|| xattr
.major_version
!= CP_CURRENT_MAJOR_VERS
) {
527 /* Deny the mount and tear down. */
529 (void) hfs_unmount (mp
, MNT_FORCE
, context
);
536 (void)hfs_statfs(mp
, vfs_statfs(mp
), context
);
542 struct hfs_changefs_cargs
{
543 struct hfsmount
*hfsmp
;
550 hfs_changefs_callback(struct vnode
*vp
, void *cargs
)
554 struct cat_desc cndesc
;
555 struct cat_attr cnattr
;
556 struct hfs_changefs_cargs
*args
;
560 args
= (struct hfs_changefs_cargs
*)cargs
;
563 vcb
= HFSTOVCB(args
->hfsmp
);
565 lockflags
= hfs_systemfile_lock(args
->hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
566 error
= cat_lookup(args
->hfsmp
, &cp
->c_desc
, 0, &cndesc
, &cnattr
, NULL
, NULL
);
567 hfs_systemfile_unlock(args
->hfsmp
, lockflags
);
570 * If we couldn't find this guy skip to the next one
575 return (VNODE_RETURNED
);
578 * Get the real uid/gid and perm mask from disk.
580 if (args
->permswitch
|| args
->permfix
) {
581 cp
->c_uid
= cnattr
.ca_uid
;
582 cp
->c_gid
= cnattr
.ca_gid
;
583 cp
->c_mode
= cnattr
.ca_mode
;
586 * If we're switching name converters then...
587 * Remove the existing entry from the namei cache.
588 * Update name to one based on new encoder.
592 replace_desc(cp
, &cndesc
);
594 if (cndesc
.cd_cnid
== kHFSRootFolderID
) {
595 strlcpy((char *)vcb
->vcbVN
, (const char *)cp
->c_desc
.cd_nameptr
, NAME_MAX
+1);
596 cp
->c_desc
.cd_encoding
= args
->hfsmp
->hfs_encoding
;
599 cat_releasedesc(&cndesc
);
601 return (VNODE_RETURNED
);
604 /* Change fs mount parameters */
606 hfs_changefs(struct mount
*mp
, struct hfs_mount_args
*args
)
609 int namefix
, permfix
, permswitch
;
610 struct hfsmount
*hfsmp
;
612 hfs_to_unicode_func_t get_unicode_func
;
613 unicode_to_hfs_func_t get_hfsname_func
;
614 u_int32_t old_encoding
= 0;
615 struct hfs_changefs_cargs cargs
;
616 u_int32_t mount_flags
;
618 hfsmp
= VFSTOHFS(mp
);
619 vcb
= HFSTOVCB(hfsmp
);
620 mount_flags
= (unsigned int)vfs_flags(mp
);
622 hfsmp
->hfs_flags
|= HFS_IN_CHANGEFS
;
624 permswitch
= (((hfsmp
->hfs_flags
& HFS_UNKNOWN_PERMS
) &&
625 ((mount_flags
& MNT_UNKNOWNPERMISSIONS
) == 0)) ||
626 (((hfsmp
->hfs_flags
& HFS_UNKNOWN_PERMS
) == 0) &&
627 (mount_flags
& MNT_UNKNOWNPERMISSIONS
)));
629 /* The root filesystem must operate with actual permissions: */
630 if (permswitch
&& (mount_flags
& MNT_ROOTFS
) && (mount_flags
& MNT_UNKNOWNPERMISSIONS
)) {
631 vfs_clearflags(mp
, (u_int64_t
)((unsigned int)MNT_UNKNOWNPERMISSIONS
)); /* Just say "No". */
635 if (mount_flags
& MNT_UNKNOWNPERMISSIONS
)
636 hfsmp
->hfs_flags
|= HFS_UNKNOWN_PERMS
;
638 hfsmp
->hfs_flags
&= ~HFS_UNKNOWN_PERMS
;
640 namefix
= permfix
= 0;
643 * Tracking of hot files requires up-to-date access times. So if
644 * access time updates are disabled, we must also disable hot files.
646 if (mount_flags
& MNT_NOATIME
) {
647 (void) hfs_recording_suspend(hfsmp
);
650 /* Change the timezone (Note: this affects all hfs volumes and hfs+ volume create dates) */
651 if (args
->hfs_timezone
.tz_minuteswest
!= VNOVAL
) {
652 gTimeZone
= args
->hfs_timezone
;
655 /* Change the default uid, gid and/or mask */
656 if ((args
->hfs_uid
!= (uid_t
)VNOVAL
) && (hfsmp
->hfs_uid
!= args
->hfs_uid
)) {
657 hfsmp
->hfs_uid
= args
->hfs_uid
;
658 if (vcb
->vcbSigWord
== kHFSPlusSigWord
)
661 if ((args
->hfs_gid
!= (gid_t
)VNOVAL
) && (hfsmp
->hfs_gid
!= args
->hfs_gid
)) {
662 hfsmp
->hfs_gid
= args
->hfs_gid
;
663 if (vcb
->vcbSigWord
== kHFSPlusSigWord
)
666 if (args
->hfs_mask
!= (mode_t
)VNOVAL
) {
667 if (hfsmp
->hfs_dir_mask
!= (args
->hfs_mask
& ALLPERMS
)) {
668 hfsmp
->hfs_dir_mask
= args
->hfs_mask
& ALLPERMS
;
669 hfsmp
->hfs_file_mask
= args
->hfs_mask
& ALLPERMS
;
670 if ((args
->flags
!= VNOVAL
) && (args
->flags
& HFSFSMNT_NOXONFILES
))
671 hfsmp
->hfs_file_mask
= (args
->hfs_mask
& DEFFILEMODE
);
672 if (vcb
->vcbSigWord
== kHFSPlusSigWord
)
677 /* Change the hfs encoding value (hfs only) */
678 if ((vcb
->vcbSigWord
== kHFSSigWord
) &&
679 (args
->hfs_encoding
!= (u_int32_t
)VNOVAL
) &&
680 (hfsmp
->hfs_encoding
!= args
->hfs_encoding
)) {
682 retval
= hfs_getconverter(args
->hfs_encoding
, &get_unicode_func
, &get_hfsname_func
);
687 * Connect the new hfs_get_unicode converter but leave
688 * the old hfs_get_hfsname converter in place so that
689 * we can lookup existing vnodes to get their correctly
692 * When we're all finished, we can then connect the new
693 * hfs_get_hfsname converter and release our interest
694 * in the old converters.
696 hfsmp
->hfs_get_unicode
= get_unicode_func
;
697 old_encoding
= hfsmp
->hfs_encoding
;
698 hfsmp
->hfs_encoding
= args
->hfs_encoding
;
702 if (!(namefix
|| permfix
|| permswitch
))
705 /* XXX 3762912 hack to support HFS filesystem 'owner' */
708 hfsmp
->hfs_uid
== UNKNOWNUID
? KAUTH_UID_NONE
: hfsmp
->hfs_uid
,
709 hfsmp
->hfs_gid
== UNKNOWNGID
? KAUTH_GID_NONE
: hfsmp
->hfs_gid
);
712 * For each active vnode fix things that changed
714 * Note that we can visit a vnode more than once
715 * and we can race with fsync.
717 * hfs_changefs_callback will be called for each vnode
718 * hung off of this mount point
720 * The vnode will be properly referenced and unreferenced
721 * around the callback
724 cargs
.namefix
= namefix
;
725 cargs
.permfix
= permfix
;
726 cargs
.permswitch
= permswitch
;
728 vnode_iterate(mp
, 0, hfs_changefs_callback
, (void *)&cargs
);
731 * If we're switching name converters we can now
732 * connect the new hfs_get_hfsname converter and
733 * release our interest in the old converters.
736 hfsmp
->hfs_get_hfsname
= get_hfsname_func
;
737 vcb
->volumeNameEncodingHint
= args
->hfs_encoding
;
738 (void) hfs_relconverter(old_encoding
);
741 hfsmp
->hfs_flags
&= ~HFS_IN_CHANGEFS
;
746 struct hfs_reload_cargs
{
747 struct hfsmount
*hfsmp
;
752 hfs_reload_callback(struct vnode
*vp
, void *cargs
)
755 struct hfs_reload_cargs
*args
;
758 args
= (struct hfs_reload_cargs
*)cargs
;
760 * flush all the buffers associated with this node
762 (void) buf_invalidateblks(vp
, 0, 0, 0);
766 * Remove any directory hints
769 hfs_reldirhints(cp
, 0);
772 * Re-read cnode data for all active vnodes (non-metadata files).
774 if (!vnode_issystem(vp
) && !VNODE_IS_RSRC(vp
) && (cp
->c_fileid
>= kHFSFirstUserCatalogNodeID
)) {
775 struct cat_fork
*datafork
;
776 struct cat_desc desc
;
778 datafork
= cp
->c_datafork
? &cp
->c_datafork
->ff_data
: NULL
;
780 /* lookup by fileID since name could have changed */
781 lockflags
= hfs_systemfile_lock(args
->hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
782 args
->error
= cat_idlookup(args
->hfsmp
, cp
->c_fileid
, 0, &desc
, &cp
->c_attr
, datafork
);
783 hfs_systemfile_unlock(args
->hfsmp
, lockflags
);
785 return (VNODE_RETURNED_DONE
);
788 /* update cnode's catalog descriptor */
789 (void) replace_desc(cp
, &desc
);
791 return (VNODE_RETURNED
);
795 * Reload all incore data for a filesystem (used after running fsck on
796 * the root filesystem and finding things to fix). The filesystem must
797 * be mounted read-only.
799 * Things to do to update the mount:
800 * invalidate all cached meta-data.
801 * invalidate all inactive vnodes.
802 * invalidate all cached file data.
803 * re-read volume header from disk.
804 * re-load meta-file info (extents, file size).
805 * re-load B-tree header data.
806 * re-read cnode data for all active vnodes.
809 hfs_reload(struct mount
*mountp
)
811 register struct vnode
*devvp
;
814 struct hfsmount
*hfsmp
;
815 struct HFSPlusVolumeHeader
*vhp
;
817 struct filefork
*forkp
;
818 struct cat_desc cndesc
;
819 struct hfs_reload_cargs args
;
820 daddr64_t priIDSector
;
822 hfsmp
= VFSTOHFS(mountp
);
823 vcb
= HFSTOVCB(hfsmp
);
825 if (vcb
->vcbSigWord
== kHFSSigWord
)
826 return (EINVAL
); /* rooting from HFS is not supported! */
829 * Invalidate all cached meta-data.
831 devvp
= hfsmp
->hfs_devvp
;
832 if (buf_invalidateblks(devvp
, 0, 0, 0))
833 panic("hfs_reload: dirty1");
838 * hfs_reload_callback will be called for each vnode
839 * hung off of this mount point that can't be recycled...
840 * vnode_iterate will recycle those that it can (the VNODE_RELOAD option)
841 * the vnode will be in an 'unbusy' state (VNODE_WAIT) and
842 * properly referenced and unreferenced around the callback
844 vnode_iterate(mountp
, VNODE_RELOAD
| VNODE_WAIT
, hfs_reload_callback
, (void *)&args
);
850 * Re-read VolumeHeader from disk.
852 priIDSector
= (daddr64_t
)((vcb
->hfsPlusIOPosOffset
/ hfsmp
->hfs_logical_block_size
) +
853 HFS_PRI_SECTOR(hfsmp
->hfs_logical_block_size
));
855 error
= (int)buf_meta_bread(hfsmp
->hfs_devvp
,
856 HFS_PHYSBLK_ROUNDDOWN(priIDSector
, hfsmp
->hfs_log_per_phys
),
857 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
);
864 vhp
= (HFSPlusVolumeHeader
*) (buf_dataptr(bp
) + HFS_PRI_OFFSET(hfsmp
->hfs_physical_block_size
));
866 /* Do a quick sanity check */
867 if ((SWAP_BE16(vhp
->signature
) != kHFSPlusSigWord
&&
868 SWAP_BE16(vhp
->signature
) != kHFSXSigWord
) ||
869 (SWAP_BE16(vhp
->version
) != kHFSPlusVersion
&&
870 SWAP_BE16(vhp
->version
) != kHFSXVersion
) ||
871 SWAP_BE32(vhp
->blockSize
) != vcb
->blockSize
) {
876 vcb
->vcbLsMod
= to_bsd_time(SWAP_BE32(vhp
->modifyDate
));
877 vcb
->vcbAtrb
= SWAP_BE32 (vhp
->attributes
);
878 vcb
->vcbJinfoBlock
= SWAP_BE32(vhp
->journalInfoBlock
);
879 vcb
->vcbClpSiz
= SWAP_BE32 (vhp
->rsrcClumpSize
);
880 vcb
->vcbNxtCNID
= SWAP_BE32 (vhp
->nextCatalogID
);
881 vcb
->vcbVolBkUp
= to_bsd_time(SWAP_BE32(vhp
->backupDate
));
882 vcb
->vcbWrCnt
= SWAP_BE32 (vhp
->writeCount
);
883 vcb
->vcbFilCnt
= SWAP_BE32 (vhp
->fileCount
);
884 vcb
->vcbDirCnt
= SWAP_BE32 (vhp
->folderCount
);
885 HFS_UPDATE_NEXT_ALLOCATION(vcb
, SWAP_BE32 (vhp
->nextAllocation
));
886 vcb
->totalBlocks
= SWAP_BE32 (vhp
->totalBlocks
);
887 vcb
->freeBlocks
= SWAP_BE32 (vhp
->freeBlocks
);
888 vcb
->encodingsBitmap
= SWAP_BE64 (vhp
->encodingsBitmap
);
889 bcopy(vhp
->finderInfo
, vcb
->vcbFndrInfo
, sizeof(vhp
->finderInfo
));
890 vcb
->localCreateDate
= SWAP_BE32 (vhp
->createDate
); /* hfs+ create date is in local time */
893 * Re-load meta-file vnode data (extent info, file size, etc).
895 forkp
= VTOF((struct vnode
*)vcb
->extentsRefNum
);
896 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
897 forkp
->ff_extents
[i
].startBlock
=
898 SWAP_BE32 (vhp
->extentsFile
.extents
[i
].startBlock
);
899 forkp
->ff_extents
[i
].blockCount
=
900 SWAP_BE32 (vhp
->extentsFile
.extents
[i
].blockCount
);
902 forkp
->ff_size
= SWAP_BE64 (vhp
->extentsFile
.logicalSize
);
903 forkp
->ff_blocks
= SWAP_BE32 (vhp
->extentsFile
.totalBlocks
);
904 forkp
->ff_clumpsize
= SWAP_BE32 (vhp
->extentsFile
.clumpSize
);
907 forkp
= VTOF((struct vnode
*)vcb
->catalogRefNum
);
908 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
909 forkp
->ff_extents
[i
].startBlock
=
910 SWAP_BE32 (vhp
->catalogFile
.extents
[i
].startBlock
);
911 forkp
->ff_extents
[i
].blockCount
=
912 SWAP_BE32 (vhp
->catalogFile
.extents
[i
].blockCount
);
914 forkp
->ff_size
= SWAP_BE64 (vhp
->catalogFile
.logicalSize
);
915 forkp
->ff_blocks
= SWAP_BE32 (vhp
->catalogFile
.totalBlocks
);
916 forkp
->ff_clumpsize
= SWAP_BE32 (vhp
->catalogFile
.clumpSize
);
918 if (hfsmp
->hfs_attribute_vp
) {
919 forkp
= VTOF(hfsmp
->hfs_attribute_vp
);
920 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
921 forkp
->ff_extents
[i
].startBlock
=
922 SWAP_BE32 (vhp
->attributesFile
.extents
[i
].startBlock
);
923 forkp
->ff_extents
[i
].blockCount
=
924 SWAP_BE32 (vhp
->attributesFile
.extents
[i
].blockCount
);
926 forkp
->ff_size
= SWAP_BE64 (vhp
->attributesFile
.logicalSize
);
927 forkp
->ff_blocks
= SWAP_BE32 (vhp
->attributesFile
.totalBlocks
);
928 forkp
->ff_clumpsize
= SWAP_BE32 (vhp
->attributesFile
.clumpSize
);
931 forkp
= VTOF((struct vnode
*)vcb
->allocationsRefNum
);
932 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
933 forkp
->ff_extents
[i
].startBlock
=
934 SWAP_BE32 (vhp
->allocationFile
.extents
[i
].startBlock
);
935 forkp
->ff_extents
[i
].blockCount
=
936 SWAP_BE32 (vhp
->allocationFile
.extents
[i
].blockCount
);
938 forkp
->ff_size
= SWAP_BE64 (vhp
->allocationFile
.logicalSize
);
939 forkp
->ff_blocks
= SWAP_BE32 (vhp
->allocationFile
.totalBlocks
);
940 forkp
->ff_clumpsize
= SWAP_BE32 (vhp
->allocationFile
.clumpSize
);
946 * Re-load B-tree header data
948 forkp
= VTOF((struct vnode
*)vcb
->extentsRefNum
);
949 if ( (error
= MacToVFSError( BTReloadData((FCB
*)forkp
) )) )
952 forkp
= VTOF((struct vnode
*)vcb
->catalogRefNum
);
953 if ( (error
= MacToVFSError( BTReloadData((FCB
*)forkp
) )) )
956 if (hfsmp
->hfs_attribute_vp
) {
957 forkp
= VTOF(hfsmp
->hfs_attribute_vp
);
958 if ( (error
= MacToVFSError( BTReloadData((FCB
*)forkp
) )) )
962 /* Reload the volume name */
963 if ((error
= cat_idlookup(hfsmp
, kHFSRootFolderID
, 0, &cndesc
, NULL
, NULL
)))
965 vcb
->volumeNameEncodingHint
= cndesc
.cd_encoding
;
966 bcopy(cndesc
.cd_nameptr
, vcb
->vcbVN
, min(255, cndesc
.cd_namelen
));
967 cat_releasedesc(&cndesc
);
969 /* Re-establish private/hidden directories. */
970 hfs_privatedir_init(hfsmp
, FILE_HARDLINKS
);
971 hfs_privatedir_init(hfsmp
, DIR_HARDLINKS
);
973 /* In case any volume information changed to trigger a notification */
974 hfs_generate_volume_notifications(hfsmp
);
982 hfs_syncer(void *arg0
, void *unused
)
984 #pragma unused(unused)
986 struct hfsmount
*hfsmp
= arg0
;
989 uint32_t delay
= HFS_META_DELAY
;
993 clock_get_calendar_microtime(&secs
, &usecs
);
994 now
= ((uint64_t)secs
* 1000000ULL) + (uint64_t)usecs
;
997 // If the amount of pending writes is more than our limit, wait
998 // for 2/3 of it to drain and then flush the journal.
1000 if (hfsmp
->hfs_mp
->mnt_pending_write_size
> hfsmp
->hfs_max_pending_io
) {
1002 uint64_t pending_io
, start
, rate
= 0;
1006 hfs_start_transaction(hfsmp
); // so we hold off any new i/o's
1008 pending_io
= hfsmp
->hfs_mp
->mnt_pending_write_size
;
1010 clock_get_calendar_microtime(&secs
, &usecs
);
1011 start
= ((uint64_t)secs
* 1000000ULL) + (uint64_t)usecs
;
1013 while(hfsmp
->hfs_mp
->mnt_pending_write_size
> (pending_io
/3) && counter
++ < 500) {
1014 tsleep((caddr_t
)hfsmp
, PRIBIO
, "hfs-wait-for-io-to-drain", 10);
1017 if (counter
>= 500) {
1018 printf("hfs: timed out waiting for io to drain (%lld)\n", (int64_t)hfsmp
->hfs_mp
->mnt_pending_write_size
);
1022 journal_flush(hfsmp
->jnl
, FALSE
);
1024 hfs_sync(hfsmp
->hfs_mp
, MNT_WAIT
, vfs_context_kernel());
1027 clock_get_calendar_microtime(&secs
, &usecs
);
1028 now
= ((uint64_t)secs
* 1000000ULL) + (uint64_t)usecs
;
1029 hfsmp
->hfs_last_sync_time
= now
;
1031 rate
= ((pending_io
* 1000000ULL) / (now
- start
)); // yields bytes per second
1034 hfs_end_transaction(hfsmp
);
1037 // If a reasonable amount of time elapsed then check the
1038 // i/o rate. If it's taking less than 1 second or more
1039 // than 2 seconds, adjust hfs_max_pending_io so that we
1040 // will allow about 1.5 seconds of i/o to queue up.
1042 if (((now
- start
) >= 300000) && (rate
!= 0)) {
1043 uint64_t scale
= (pending_io
* 100) / rate
;
1045 if (scale
< 100 || scale
> 200) {
1046 // set it so that it should take about 1.5 seconds to drain
1047 hfsmp
->hfs_max_pending_io
= (rate
* 150ULL) / 100ULL;
1051 } else if ( ((now
- hfsmp
->hfs_last_sync_time
) >= 5000000ULL)
1052 || (((now
- hfsmp
->hfs_last_sync_time
) >= 100000LL)
1053 && ((now
- hfsmp
->hfs_last_sync_request_time
) >= 100000LL)
1054 && (hfsmp
->hfs_active_threads
== 0)
1055 && (hfsmp
->hfs_global_lock_nesting
== 0))) {
1058 // Flush the journal if more than 5 seconds elapsed since
1059 // the last sync OR we have not sync'ed recently and the
1060 // last sync request time was more than 100 milliseconds
1061 // ago and no one is in the middle of a transaction right
1062 // now. Else we defer the sync and reschedule it.
1065 hfs_lock_global (hfsmp
, HFS_SHARED_LOCK
);
1067 journal_flush(hfsmp
->jnl
, FALSE
);
1069 hfs_unlock_global (hfsmp
);
1071 hfs_sync(hfsmp
->hfs_mp
, MNT_WAIT
, vfs_context_kernel());
1074 clock_get_calendar_microtime(&secs
, &usecs
);
1075 now
= ((uint64_t)secs
* 1000000ULL) + (uint64_t)usecs
;
1076 hfsmp
->hfs_last_sync_time
= now
;
1078 } else if (hfsmp
->hfs_active_threads
== 0) {
1081 clock_interval_to_deadline(delay
, HFS_MILLISEC_SCALE
, &deadline
);
1082 thread_call_enter_delayed(hfsmp
->hfs_syncer
, deadline
);
1084 // note: we intentionally return early here and do not
1085 // decrement the sync_scheduled and sync_incomplete
1086 // variables because we rescheduled the timer.
1092 // NOTE: we decrement these *after* we're done the journal_flush() since
1093 // it can take a significant amount of time and so we don't want more
1094 // callbacks scheduled until we're done this one.
1096 OSDecrementAtomic((volatile SInt32
*)&hfsmp
->hfs_sync_scheduled
);
1097 OSDecrementAtomic((volatile SInt32
*)&hfsmp
->hfs_sync_incomplete
);
1098 wakeup((caddr_t
)&hfsmp
->hfs_sync_incomplete
);
1102 extern int IOBSDIsMediaEjectable( const char *cdev_name
);
1105 * Initialization code for Red-Black Tree Allocator
1107 * This function will build the two red-black trees necessary for allocating space
1108 * from the metadata zone as well as normal allocations. Currently, we use
1109 * an advisory read to get most of the data into the buffer cache.
1110 * This function is intended to be run in a separate thread so as not to slow down mount.
1115 hfs_initialize_allocator (struct hfsmount
*hfsmp
) {
1117 #if CONFIG_HFS_ALLOC_RBTREE
1121 * Take the allocation file lock. Journal transactions will block until
1124 int flags
= hfs_systemfile_lock(hfsmp
, SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
1127 * GenerateTree assumes that the bitmap lock is held when you call the function.
1128 * It will drop and re-acquire the lock periodically as needed to let other allocations
1129 * through. It returns with the bitmap lock held. Since we only maintain one tree,
1130 * we don't need to specify a start block (always starts at 0).
1132 err
= GenerateTree(hfsmp
, hfsmp
->totalBlocks
, &flags
, 1);
1136 /* Mark offset tree as built */
1137 hfsmp
->extent_tree_flags
|= HFS_ALLOC_RB_ACTIVE
;
1141 * GenerateTree may drop the bitmap lock during operation in order to give other
1142 * threads a chance to allocate blocks, but it will always return with the lock held, so
1143 * we don't need to re-grab the lock in order to update the TREEBUILD_INFLIGHT bit.
1145 hfsmp
->extent_tree_flags
&= ~HFS_ALLOC_TREEBUILD_INFLIGHT
;
1147 /* Wakeup any waiters on the allocation bitmap lock */
1148 wakeup((caddr_t
)&hfsmp
->extent_tree_flags
);
1151 hfs_systemfile_unlock(hfsmp
, flags
);
1153 #pragma unused (hfsmp)
1159 * Teardown code for the Red-Black Tree allocator.
1160 * This function consolidates the code which serializes with respect
1161 * to a thread that may be potentially still building the tree when we need to begin
1162 * tearing it down. Since the red-black tree may not be live when we enter this function
1164 * 1 -> Tree was live.
1165 * 0 -> Tree was not active at time of call.
1169 hfs_teardown_allocator (struct hfsmount
*hfsmp
) {
1172 #if CONFIG_HFS_ALLOC_RBTREE
1177 * Check to see if the tree-generation is still on-going.
1178 * If it is, then block until it's done.
1181 flags
= hfs_systemfile_lock(hfsmp
, SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
1184 while (hfsmp
->extent_tree_flags
& HFS_ALLOC_TREEBUILD_INFLIGHT
) {
1185 hfsmp
->extent_tree_flags
|= HFS_ALLOC_TEARDOWN_INFLIGHT
;
1187 lck_rw_sleep(&(VTOC(hfsmp
->hfs_allocation_vp
))->c_rwlock
, LCK_SLEEP_EXCLUSIVE
,
1188 &hfsmp
->extent_tree_flags
, THREAD_UNINT
);
1191 if (hfs_isrbtree_active (hfsmp
)) {
1194 /* Tear down the RB Trees while we have the bitmap locked */
1195 DestroyTrees(hfsmp
);
1199 hfs_systemfile_unlock(hfsmp
, flags
);
1201 #pragma unused (hfsmp)
1208 static int hfs_root_unmounted_cleanly
= 0;
1210 SYSCTL_DECL(_vfs_generic
);
1211 SYSCTL_INT(_vfs_generic
, OID_AUTO
, root_unmounted_cleanly
, CTLFLAG_RD
, &hfs_root_unmounted_cleanly
, 0, "Root filesystem was unmounted cleanly");
1214 * Common code for mount and mountroot
1217 hfs_mountfs(struct vnode
*devvp
, struct mount
*mp
, struct hfs_mount_args
*args
,
1218 int journal_replay_only
, vfs_context_t context
)
1220 struct proc
*p
= vfs_context_proc(context
);
1221 int retval
= E_NONE
;
1222 struct hfsmount
*hfsmp
= NULL
;
1225 HFSMasterDirectoryBlock
*mdbp
= NULL
;
1233 daddr64_t log_blkcnt
;
1234 u_int32_t log_blksize
;
1235 u_int32_t phys_blksize
;
1236 u_int32_t minblksize
;
1237 u_int32_t iswritable
;
1238 daddr64_t mdb_offset
;
1242 #if CONFIG_HFS_ALLOC_RBTREE
1243 thread_t allocator_thread
;
1247 /* only hfs_mountroot passes us NULL as the 'args' argument */
1251 ronly
= vfs_isrdonly(mp
);
1252 dev
= vnode_specrdev(devvp
);
1253 cred
= p
? vfs_context_ucred(context
) : NOCRED
;
1259 minblksize
= kHFSBlockSize
;
1261 /* Advisory locking should be handled at the VFS layer */
1262 vfs_setlocklocal(mp
);
1264 /* Get the logical block size (treated as physical block size everywhere) */
1265 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKSIZE
, (caddr_t
)&log_blksize
, 0, context
)) {
1266 if (HFS_MOUNT_DEBUG
) {
1267 printf("hfs_mountfs: DKIOCGETBLOCKSIZE failed\n");
1272 if (log_blksize
== 0 || log_blksize
> 1024*1024*1024) {
1273 printf("hfs: logical block size 0x%x looks bad. Not mounting.\n", log_blksize
);
1278 /* Get the physical block size. */
1279 retval
= VNOP_IOCTL(devvp
, DKIOCGETPHYSICALBLOCKSIZE
, (caddr_t
)&phys_blksize
, 0, context
);
1281 if ((retval
!= ENOTSUP
) && (retval
!= ENOTTY
)) {
1282 if (HFS_MOUNT_DEBUG
) {
1283 printf("hfs_mountfs: DKIOCGETPHYSICALBLOCKSIZE failed\n");
1288 /* If device does not support this ioctl, assume that physical
1289 * block size is same as logical block size
1291 phys_blksize
= log_blksize
;
1293 if (phys_blksize
== 0 || phys_blksize
> 1024*1024*1024) {
1294 printf("hfs: physical block size 0x%x looks bad. Not mounting.\n", phys_blksize
);
1299 /* Switch to 512 byte sectors (temporarily) */
1300 if (log_blksize
> 512) {
1301 u_int32_t size512
= 512;
1303 if (VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
, (caddr_t
)&size512
, FWRITE
, context
)) {
1304 if (HFS_MOUNT_DEBUG
) {
1305 printf("hfs_mountfs: DKIOCSETBLOCKSIZE failed \n");
1311 /* Get the number of 512 byte physical blocks. */
1312 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)&log_blkcnt
, 0, context
)) {
1313 /* resetting block size may fail if getting block count did */
1314 (void)VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
, (caddr_t
)&log_blksize
, FWRITE
, context
);
1315 if (HFS_MOUNT_DEBUG
) {
1316 printf("hfs_mountfs: DKIOCGETBLOCKCOUNT failed\n");
1321 /* Compute an accurate disk size (i.e. within 512 bytes) */
1322 disksize
= (u_int64_t
)log_blkcnt
* (u_int64_t
)512;
1325 * On Tiger it is not necessary to switch the device
1326 * block size to be 4k if there are more than 31-bits
1327 * worth of blocks but to insure compatibility with
1328 * pre-Tiger systems we have to do it.
1330 * If the device size is not a multiple of 4K (8 * 512), then
1331 * switching the logical block size isn't going to help because
1332 * we will be unable to write the alternate volume header.
1333 * In this case, just leave the logical block size unchanged.
1335 if (log_blkcnt
> 0x000000007fffffff && (log_blkcnt
& 7) == 0) {
1336 minblksize
= log_blksize
= 4096;
1337 if (phys_blksize
< log_blksize
)
1338 phys_blksize
= log_blksize
;
1342 * The cluster layer is not currently prepared to deal with a logical
1343 * block size larger than the system's page size. (It can handle
1344 * blocks per page, but not multiple pages per block.) So limit the
1345 * logical block size to the page size.
1347 if (log_blksize
> PAGE_SIZE
)
1348 log_blksize
= PAGE_SIZE
;
1350 /* Now switch to our preferred physical block size. */
1351 if (log_blksize
> 512) {
1352 if (VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
, (caddr_t
)&log_blksize
, FWRITE
, context
)) {
1353 if (HFS_MOUNT_DEBUG
) {
1354 printf("hfs_mountfs: DKIOCSETBLOCKSIZE (2) failed\n");
1359 /* Get the count of physical blocks. */
1360 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)&log_blkcnt
, 0, context
)) {
1361 if (HFS_MOUNT_DEBUG
) {
1362 printf("hfs_mountfs: DKIOCGETBLOCKCOUNT (2) failed\n");
1370 * minblksize is the minimum physical block size
1371 * log_blksize has our preferred physical block size
1372 * log_blkcnt has the total number of physical blocks
1375 mdb_offset
= (daddr64_t
)HFS_PRI_SECTOR(log_blksize
);
1376 if ((retval
= (int)buf_meta_bread(devvp
,
1377 HFS_PHYSBLK_ROUNDDOWN(mdb_offset
, (phys_blksize
/log_blksize
)),
1378 phys_blksize
, cred
, &bp
))) {
1379 if (HFS_MOUNT_DEBUG
) {
1380 printf("hfs_mountfs: buf_meta_bread failed with %d\n", retval
);
1384 MALLOC(mdbp
, HFSMasterDirectoryBlock
*, kMDBSize
, M_TEMP
, M_WAITOK
);
1387 if (HFS_MOUNT_DEBUG
) {
1388 printf("hfs_mountfs: MALLOC failed\n");
1392 bcopy((char *)buf_dataptr(bp
) + HFS_PRI_OFFSET(phys_blksize
), mdbp
, kMDBSize
);
1396 MALLOC(hfsmp
, struct hfsmount
*, sizeof(struct hfsmount
), M_HFSMNT
, M_WAITOK
);
1397 if (hfsmp
== NULL
) {
1398 if (HFS_MOUNT_DEBUG
) {
1399 printf("hfs_mountfs: MALLOC (2) failed\n");
1404 bzero(hfsmp
, sizeof(struct hfsmount
));
1406 hfs_chashinit_finish(hfsmp
);
1409 * See if the disk is a solid state device. We need this to decide what to do about
1412 if (VNOP_IOCTL(devvp
, DKIOCISSOLIDSTATE
, (caddr_t
)&isssd
, 0, context
) == 0) {
1414 hfsmp
->hfs_flags
|= HFS_SSD
;
1420 * Init the volume information structure
1423 lck_mtx_init(&hfsmp
->hfs_mutex
, hfs_mutex_group
, hfs_lock_attr
);
1424 lck_mtx_init(&hfsmp
->hfc_mutex
, hfs_mutex_group
, hfs_lock_attr
);
1425 lck_rw_init(&hfsmp
->hfs_global_lock
, hfs_rwlock_group
, hfs_lock_attr
);
1426 lck_rw_init(&hfsmp
->hfs_insync
, hfs_rwlock_group
, hfs_lock_attr
);
1427 lck_spin_init(&hfsmp
->vcbFreeExtLock
, hfs_spinlock_group
, hfs_lock_attr
);
1429 vfs_setfsprivate(mp
, hfsmp
);
1430 hfsmp
->hfs_mp
= mp
; /* Make VFSTOHFS work */
1431 hfsmp
->hfs_raw_dev
= vnode_specrdev(devvp
);
1432 hfsmp
->hfs_devvp
= devvp
;
1433 vnode_ref(devvp
); /* Hold a ref on the device, dropped when hfsmp is freed. */
1434 hfsmp
->hfs_logical_block_size
= log_blksize
;
1435 hfsmp
->hfs_logical_block_count
= log_blkcnt
;
1436 hfsmp
->hfs_physical_block_size
= phys_blksize
;
1437 hfsmp
->hfs_log_per_phys
= (phys_blksize
/ log_blksize
);
1438 hfsmp
->hfs_flags
|= HFS_WRITEABLE_MEDIA
;
1440 hfsmp
->hfs_flags
|= HFS_READ_ONLY
;
1441 if (((unsigned int)vfs_flags(mp
)) & MNT_UNKNOWNPERMISSIONS
)
1442 hfsmp
->hfs_flags
|= HFS_UNKNOWN_PERMS
;
1445 for (i
= 0; i
< MAXQUOTAS
; i
++)
1446 dqfileinit(&hfsmp
->hfs_qfiles
[i
]);
1450 hfsmp
->hfs_uid
= (args
->hfs_uid
== (uid_t
)VNOVAL
) ? UNKNOWNUID
: args
->hfs_uid
;
1451 if (hfsmp
->hfs_uid
== 0xfffffffd) hfsmp
->hfs_uid
= UNKNOWNUID
;
1452 hfsmp
->hfs_gid
= (args
->hfs_gid
== (gid_t
)VNOVAL
) ? UNKNOWNGID
: args
->hfs_gid
;
1453 if (hfsmp
->hfs_gid
== 0xfffffffd) hfsmp
->hfs_gid
= UNKNOWNGID
;
1454 vfs_setowner(mp
, hfsmp
->hfs_uid
, hfsmp
->hfs_gid
); /* tell the VFS */
1455 if (args
->hfs_mask
!= (mode_t
)VNOVAL
) {
1456 hfsmp
->hfs_dir_mask
= args
->hfs_mask
& ALLPERMS
;
1457 if (args
->flags
& HFSFSMNT_NOXONFILES
) {
1458 hfsmp
->hfs_file_mask
= (args
->hfs_mask
& DEFFILEMODE
);
1460 hfsmp
->hfs_file_mask
= args
->hfs_mask
& ALLPERMS
;
1463 hfsmp
->hfs_dir_mask
= UNKNOWNPERMISSIONS
& ALLPERMS
; /* 0777: rwx---rwx */
1464 hfsmp
->hfs_file_mask
= UNKNOWNPERMISSIONS
& DEFFILEMODE
; /* 0666: no --x by default? */
1466 if ((args
->flags
!= (int)VNOVAL
) && (args
->flags
& HFSFSMNT_WRAPPER
))
1469 /* Even w/o explicit mount arguments, MNT_UNKNOWNPERMISSIONS requires setting up uid, gid, and mask: */
1470 if (((unsigned int)vfs_flags(mp
)) & MNT_UNKNOWNPERMISSIONS
) {
1471 hfsmp
->hfs_uid
= UNKNOWNUID
;
1472 hfsmp
->hfs_gid
= UNKNOWNGID
;
1473 vfs_setowner(mp
, hfsmp
->hfs_uid
, hfsmp
->hfs_gid
); /* tell the VFS */
1474 hfsmp
->hfs_dir_mask
= UNKNOWNPERMISSIONS
& ALLPERMS
; /* 0777: rwx---rwx */
1475 hfsmp
->hfs_file_mask
= UNKNOWNPERMISSIONS
& DEFFILEMODE
; /* 0666: no --x by default? */
1479 /* Find out if disk media is writable. */
1480 if (VNOP_IOCTL(devvp
, DKIOCISWRITABLE
, (caddr_t
)&iswritable
, 0, context
) == 0) {
1482 hfsmp
->hfs_flags
|= HFS_WRITEABLE_MEDIA
;
1484 hfsmp
->hfs_flags
&= ~HFS_WRITEABLE_MEDIA
;
1487 // record the current time at which we're mounting this volume
1490 hfsmp
->hfs_mount_time
= tv
.tv_sec
;
1492 /* Mount a standard HFS disk */
1493 if ((SWAP_BE16(mdbp
->drSigWord
) == kHFSSigWord
) &&
1494 (mntwrapper
|| (SWAP_BE16(mdbp
->drEmbedSigWord
) != kHFSPlusSigWord
))) {
1496 /* On 10.6 and beyond, non read-only mounts for HFS standard vols get rejected */
1497 if (vfs_isrdwr(mp
)) {
1502 printf("hfs_mountfs: Mounting HFS Standard volumes was deprecated in Mac OS 10.7 \n");
1504 /* Treat it as if it's read-only and not writeable */
1505 hfsmp
->hfs_flags
|= HFS_READ_ONLY
;
1506 hfsmp
->hfs_flags
&= ~HFS_WRITEABLE_MEDIA
;
1508 /* If only journal replay is requested, exit immediately */
1509 if (journal_replay_only
) {
1514 if ((vfs_flags(mp
) & MNT_ROOTFS
)) {
1515 retval
= EINVAL
; /* Cannot root from HFS standard disks */
1518 /* HFS disks can only use 512 byte physical blocks */
1519 if (log_blksize
> kHFSBlockSize
) {
1520 log_blksize
= kHFSBlockSize
;
1521 if (VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
, (caddr_t
)&log_blksize
, FWRITE
, context
)) {
1525 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)&log_blkcnt
, 0, context
)) {
1529 hfsmp
->hfs_logical_block_size
= log_blksize
;
1530 hfsmp
->hfs_logical_block_count
= log_blkcnt
;
1531 hfsmp
->hfs_physical_block_size
= log_blksize
;
1532 hfsmp
->hfs_log_per_phys
= 1;
1535 hfsmp
->hfs_encoding
= args
->hfs_encoding
;
1536 HFSTOVCB(hfsmp
)->volumeNameEncodingHint
= args
->hfs_encoding
;
1538 /* establish the timezone */
1539 gTimeZone
= args
->hfs_timezone
;
1542 retval
= hfs_getconverter(hfsmp
->hfs_encoding
, &hfsmp
->hfs_get_unicode
,
1543 &hfsmp
->hfs_get_hfsname
);
1547 retval
= hfs_MountHFSVolume(hfsmp
, mdbp
, p
);
1549 (void) hfs_relconverter(hfsmp
->hfs_encoding
);
1551 } else /* Mount an HFS Plus disk */ {
1552 HFSPlusVolumeHeader
*vhp
;
1553 off_t embeddedOffset
;
1554 int jnl_disable
= 0;
1556 /* Get the embedded Volume Header */
1557 if (SWAP_BE16(mdbp
->drEmbedSigWord
) == kHFSPlusSigWord
) {
1558 embeddedOffset
= SWAP_BE16(mdbp
->drAlBlSt
) * kHFSBlockSize
;
1559 embeddedOffset
+= (u_int64_t
)SWAP_BE16(mdbp
->drEmbedExtent
.startBlock
) *
1560 (u_int64_t
)SWAP_BE32(mdbp
->drAlBlkSiz
);
1563 * If the embedded volume doesn't start on a block
1564 * boundary, then switch the device to a 512-byte
1565 * block size so everything will line up on a block
1568 if ((embeddedOffset
% log_blksize
) != 0) {
1569 printf("hfs_mountfs: embedded volume offset not"
1570 " a multiple of physical block size (%d);"
1571 " switching to 512\n", log_blksize
);
1573 if (VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
,
1574 (caddr_t
)&log_blksize
, FWRITE
, context
)) {
1576 if (HFS_MOUNT_DEBUG
) {
1577 printf("hfs_mountfs: DKIOCSETBLOCKSIZE (3) failed\n");
1582 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
,
1583 (caddr_t
)&log_blkcnt
, 0, context
)) {
1584 if (HFS_MOUNT_DEBUG
) {
1585 printf("hfs_mountfs: DKIOCGETBLOCKCOUNT (3) failed\n");
1590 /* Note: relative block count adjustment */
1591 hfsmp
->hfs_logical_block_count
*=
1592 hfsmp
->hfs_logical_block_size
/ log_blksize
;
1594 /* Update logical /physical block size */
1595 hfsmp
->hfs_logical_block_size
= log_blksize
;
1596 hfsmp
->hfs_physical_block_size
= log_blksize
;
1597 phys_blksize
= log_blksize
;
1598 hfsmp
->hfs_log_per_phys
= 1;
1601 disksize
= (u_int64_t
)SWAP_BE16(mdbp
->drEmbedExtent
.blockCount
) *
1602 (u_int64_t
)SWAP_BE32(mdbp
->drAlBlkSiz
);
1604 hfsmp
->hfs_logical_block_count
= disksize
/ log_blksize
;
1606 mdb_offset
= (daddr64_t
)((embeddedOffset
/ log_blksize
) + HFS_PRI_SECTOR(log_blksize
));
1607 retval
= (int)buf_meta_bread(devvp
, HFS_PHYSBLK_ROUNDDOWN(mdb_offset
, hfsmp
->hfs_log_per_phys
),
1608 phys_blksize
, cred
, &bp
);
1610 if (HFS_MOUNT_DEBUG
) {
1611 printf("hfs_mountfs: buf_meta_bread (2) failed with %d\n", retval
);
1615 bcopy((char *)buf_dataptr(bp
) + HFS_PRI_OFFSET(phys_blksize
), mdbp
, 512);
1618 vhp
= (HFSPlusVolumeHeader
*) mdbp
;
1620 } else /* pure HFS+ */ {
1622 vhp
= (HFSPlusVolumeHeader
*) mdbp
;
1626 hfs_root_unmounted_cleanly
= (SWAP_BE32(vhp
->attributes
) & kHFSVolumeUnmountedMask
) != 0;
1630 * On inconsistent disks, do not allow read-write mount
1631 * unless it is the boot volume being mounted. We also
1632 * always want to replay the journal if the journal_replay_only
1633 * flag is set because that will (most likely) get the
1634 * disk into a consistent state before fsck_hfs starts
1637 if ( !(vfs_flags(mp
) & MNT_ROOTFS
)
1638 && (SWAP_BE32(vhp
->attributes
) & kHFSVolumeInconsistentMask
)
1639 && !journal_replay_only
1640 && !(hfsmp
->hfs_flags
& HFS_READ_ONLY
)) {
1642 if (HFS_MOUNT_DEBUG
) {
1643 printf("hfs_mountfs: failed to mount non-root inconsistent disk\n");
1654 if (args
!= NULL
&& (args
->flags
& HFSFSMNT_EXTENDED_ARGS
) &&
1655 args
->journal_disable
) {
1660 // We only initialize the journal here if the last person
1661 // to mount this volume was journaling aware. Otherwise
1662 // we delay journal initialization until later at the end
1663 // of hfs_MountHFSPlusVolume() because the last person who
1664 // mounted it could have messed things up behind our back
1665 // (so we need to go find the .journal file, make sure it's
1666 // the right size, re-sync up if it was moved, etc).
1668 if ( (SWAP_BE32(vhp
->lastMountedVersion
) == kHFSJMountVersion
)
1669 && (SWAP_BE32(vhp
->attributes
) & kHFSVolumeJournaledMask
)
1672 // if we're able to init the journal, mark the mount
1673 // point as journaled.
1675 if ((retval
= hfs_early_journal_init(hfsmp
, vhp
, args
, embeddedOffset
, mdb_offset
, mdbp
, cred
)) == 0) {
1676 vfs_setflags(mp
, (u_int64_t
)((unsigned int)MNT_JOURNALED
));
1678 if (retval
== EROFS
) {
1679 // EROFS is a special error code that means the volume has an external
1680 // journal which we couldn't find. in that case we do not want to
1681 // rewrite the volume header - we'll just refuse to mount the volume.
1682 if (HFS_MOUNT_DEBUG
) {
1683 printf("hfs_mountfs: hfs_early_journal_init indicated external jnl \n");
1689 // if the journal failed to open, then set the lastMountedVersion
1690 // to be "FSK!" which fsck_hfs will see and force the fsck instead
1691 // of just bailing out because the volume is journaled.
1693 if (HFS_MOUNT_DEBUG
) {
1694 printf("hfs_mountfs: hfs_early_journal_init failed, setting to FSK \n");
1697 HFSPlusVolumeHeader
*jvhp
;
1699 hfsmp
->hfs_flags
|= HFS_NEED_JNL_RESET
;
1701 if (mdb_offset
== 0) {
1702 mdb_offset
= (daddr64_t
)((embeddedOffset
/ log_blksize
) + HFS_PRI_SECTOR(log_blksize
));
1706 retval
= (int)buf_meta_bread(devvp
,
1707 HFS_PHYSBLK_ROUNDDOWN(mdb_offset
, hfsmp
->hfs_log_per_phys
),
1708 phys_blksize
, cred
, &bp
);
1710 jvhp
= (HFSPlusVolumeHeader
*)(buf_dataptr(bp
) + HFS_PRI_OFFSET(phys_blksize
));
1712 if (SWAP_BE16(jvhp
->signature
) == kHFSPlusSigWord
|| SWAP_BE16(jvhp
->signature
) == kHFSXSigWord
) {
1713 printf ("hfs(1): Journal replay fail. Writing lastMountVersion as FSK!\n");
1714 jvhp
->lastMountedVersion
= SWAP_BE32(kFSKMountVersion
);
1722 // clear this so the error exit path won't try to use it
1727 // if this isn't the root device just bail out.
1728 // If it is the root device we just continue on
1729 // in the hopes that fsck_hfs will be able to
1730 // fix any damage that exists on the volume.
1731 if ( !(vfs_flags(mp
) & MNT_ROOTFS
)) {
1732 if (HFS_MOUNT_DEBUG
) {
1733 printf("hfs_mountfs: hfs_early_journal_init failed, erroring out \n");
1742 /* Either the journal is replayed successfully, or there
1743 * was nothing to replay, or no journal exists. In any case,
1746 if (journal_replay_only
) {
1751 (void) hfs_getconverter(0, &hfsmp
->hfs_get_unicode
, &hfsmp
->hfs_get_hfsname
);
1753 retval
= hfs_MountHFSPlusVolume(hfsmp
, vhp
, embeddedOffset
, disksize
, p
, args
, cred
);
1755 * If the backend didn't like our physical blocksize
1756 * then retry with physical blocksize of 512.
1758 if ((retval
== ENXIO
) && (log_blksize
> 512) && (log_blksize
!= minblksize
)) {
1759 printf("hfs_mountfs: could not use physical block size "
1760 "(%d) switching to 512\n", log_blksize
);
1762 if (VNOP_IOCTL(devvp
, DKIOCSETBLOCKSIZE
, (caddr_t
)&log_blksize
, FWRITE
, context
)) {
1763 if (HFS_MOUNT_DEBUG
) {
1764 printf("hfs_mountfs: DKIOCSETBLOCKSIZE (4) failed \n");
1769 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)&log_blkcnt
, 0, context
)) {
1770 if (HFS_MOUNT_DEBUG
) {
1771 printf("hfs_mountfs: DKIOCGETBLOCKCOUNT (4) failed \n");
1776 devvp
->v_specsize
= log_blksize
;
1777 /* Note: relative block count adjustment (in case this is an embedded volume). */
1778 hfsmp
->hfs_logical_block_count
*= hfsmp
->hfs_logical_block_size
/ log_blksize
;
1779 hfsmp
->hfs_logical_block_size
= log_blksize
;
1780 hfsmp
->hfs_log_per_phys
= hfsmp
->hfs_physical_block_size
/ log_blksize
;
1782 if (hfsmp
->jnl
&& hfsmp
->jvp
== devvp
) {
1783 // close and re-open this with the new block size
1784 journal_close(hfsmp
->jnl
);
1786 if (hfs_early_journal_init(hfsmp
, vhp
, args
, embeddedOffset
, mdb_offset
, mdbp
, cred
) == 0) {
1787 vfs_setflags(mp
, (u_int64_t
)((unsigned int)MNT_JOURNALED
));
1789 // if the journal failed to open, then set the lastMountedVersion
1790 // to be "FSK!" which fsck_hfs will see and force the fsck instead
1791 // of just bailing out because the volume is journaled.
1793 if (HFS_MOUNT_DEBUG
) {
1794 printf("hfs_mountfs: hfs_early_journal_init (2) resetting.. \n");
1796 HFSPlusVolumeHeader
*jvhp
;
1798 hfsmp
->hfs_flags
|= HFS_NEED_JNL_RESET
;
1800 if (mdb_offset
== 0) {
1801 mdb_offset
= (daddr64_t
)((embeddedOffset
/ log_blksize
) + HFS_PRI_SECTOR(log_blksize
));
1805 retval
= (int)buf_meta_bread(devvp
, HFS_PHYSBLK_ROUNDDOWN(mdb_offset
, hfsmp
->hfs_log_per_phys
),
1806 phys_blksize
, cred
, &bp
);
1808 jvhp
= (HFSPlusVolumeHeader
*)(buf_dataptr(bp
) + HFS_PRI_OFFSET(phys_blksize
));
1810 if (SWAP_BE16(jvhp
->signature
) == kHFSPlusSigWord
|| SWAP_BE16(jvhp
->signature
) == kHFSXSigWord
) {
1811 printf ("hfs(2): Journal replay fail. Writing lastMountVersion as FSK!\n");
1812 jvhp
->lastMountedVersion
= SWAP_BE32(kFSKMountVersion
);
1820 // clear this so the error exit path won't try to use it
1825 // if this isn't the root device just bail out.
1826 // If it is the root device we just continue on
1827 // in the hopes that fsck_hfs will be able to
1828 // fix any damage that exists on the volume.
1829 if ( !(vfs_flags(mp
) & MNT_ROOTFS
)) {
1830 if (HFS_MOUNT_DEBUG
) {
1831 printf("hfs_mountfs: hfs_early_journal_init (2) failed \n");
1839 /* Try again with a smaller block size... */
1840 retval
= hfs_MountHFSPlusVolume(hfsmp
, vhp
, embeddedOffset
, disksize
, p
, args
, cred
);
1841 if (retval
&& HFS_MOUNT_DEBUG
) {
1842 printf("hfs_MountHFSPlusVolume (late) returned %d\n",retval
);
1846 (void) hfs_relconverter(0);
1849 // save off a snapshot of the mtime from the previous mount
1851 hfsmp
->hfs_last_mounted_mtime
= hfsmp
->hfs_mtime
;
1854 if (HFS_MOUNT_DEBUG
) {
1855 printf("hfs_mountfs: encountered failure %d \n", retval
);
1860 mp
->mnt_vfsstat
.f_fsid
.val
[0] = (long)dev
;
1861 mp
->mnt_vfsstat
.f_fsid
.val
[1] = vfs_typenum(mp
);
1862 vfs_setmaxsymlen(mp
, 0);
1864 mp
->mnt_vtable
->vfc_vfsflags
|= VFC_VFSNATIVEXATTR
;
1866 mp
->mnt_kern_flag
|= MNTK_NAMED_STREAMS
;
1868 if (!(hfsmp
->hfs_flags
& HFS_STANDARD
)) {
1869 /* Tell VFS that we support directory hard links. */
1870 mp
->mnt_vtable
->vfc_vfsflags
|= VFC_VFSDIRLINKS
;
1872 /* HFS standard doesn't support extended readdir! */
1873 mount_set_noreaddirext (mp
);
1878 * Set the free space warning levels for a non-root volume:
1880 * Set the "danger" limit to 1% of the volume size or 100MB, whichever
1881 * is less. Set the "warning" limit to 2% of the volume size or 150MB,
1882 * whichever is less. And last, set the "desired" freespace level to
1883 * to 3% of the volume size or 200MB, whichever is less.
1885 hfsmp
->hfs_freespace_notify_dangerlimit
=
1886 MIN(HFS_VERYLOWDISKTRIGGERLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1887 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_VERYLOWDISKTRIGGERFRACTION
);
1888 hfsmp
->hfs_freespace_notify_warninglimit
=
1889 MIN(HFS_LOWDISKTRIGGERLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1890 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_LOWDISKTRIGGERFRACTION
);
1891 hfsmp
->hfs_freespace_notify_desiredlevel
=
1892 MIN(HFS_LOWDISKSHUTOFFLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1893 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_LOWDISKSHUTOFFFRACTION
);
1896 * Set the free space warning levels for the root volume:
1898 * Set the "danger" limit to 5% of the volume size or 512MB, whichever
1899 * is less. Set the "warning" limit to 10% of the volume size or 1GB,
1900 * whichever is less. And last, set the "desired" freespace level to
1901 * to 11% of the volume size or 1.25GB, whichever is less.
1903 hfsmp
->hfs_freespace_notify_dangerlimit
=
1904 MIN(HFS_ROOTVERYLOWDISKTRIGGERLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1905 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_ROOTVERYLOWDISKTRIGGERFRACTION
);
1906 hfsmp
->hfs_freespace_notify_warninglimit
=
1907 MIN(HFS_ROOTLOWDISKTRIGGERLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1908 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_ROOTLOWDISKTRIGGERFRACTION
);
1909 hfsmp
->hfs_freespace_notify_desiredlevel
=
1910 MIN(HFS_ROOTLOWDISKSHUTOFFLEVEL
/ HFSTOVCB(hfsmp
)->blockSize
,
1911 (HFSTOVCB(hfsmp
)->totalBlocks
/ 100) * HFS_ROOTLOWDISKSHUTOFFFRACTION
);
1914 /* Check if the file system exists on virtual device, like disk image */
1915 if (VNOP_IOCTL(devvp
, DKIOCISVIRTUAL
, (caddr_t
)&isvirtual
, 0, context
) == 0) {
1917 hfsmp
->hfs_flags
|= HFS_VIRTUAL_DEVICE
;
1921 /* do not allow ejectability checks on the root device */
1923 if ((hfsmp
->hfs_flags
& HFS_VIRTUAL_DEVICE
) == 0 &&
1924 IOBSDIsMediaEjectable(mp
->mnt_vfsstat
.f_mntfromname
)) {
1925 hfsmp
->hfs_max_pending_io
= 4096*1024; // a reasonable value to start with.
1926 hfsmp
->hfs_syncer
= thread_call_allocate(hfs_syncer
, hfsmp
);
1927 if (hfsmp
->hfs_syncer
== NULL
) {
1928 printf("hfs: failed to allocate syncer thread callback for %s (%s)\n",
1929 mp
->mnt_vfsstat
.f_mntfromname
, mp
->mnt_vfsstat
.f_mntonname
);
1934 #if CONFIG_HFS_ALLOC_RBTREE
1936 * We spawn a thread to create the pair of red-black trees for this volume.
1937 * However, in so doing, we must be careful to ensure that if this thread is still
1938 * running after mount has finished, it doesn't interfere with an unmount. Specifically,
1939 * we'll need to set a bit that indicates we're in progress building the trees here.
1940 * Unmount will check for this bit, and then if it's set, mark a corresponding bit that
1941 * notifies the tree generation code that an unmount is waiting. Also mark the bit that
1942 * indicates the tree is live and operating.
1944 * Only do this if we're operating on a read-write mount (we wouldn't care for read-only).
1947 if ((hfsmp
->hfs_flags
& HFS_READ_ONLY
) == 0) {
1948 hfsmp
->extent_tree_flags
|= (HFS_ALLOC_TREEBUILD_INFLIGHT
| HFS_ALLOC_RB_ENABLED
);
1950 /* Initialize EOF counter so that the thread can assume it started at initial values */
1951 hfsmp
->offset_block_end
= 0;
1954 kernel_thread_start ((thread_continue_t
) hfs_initialize_allocator
, hfsmp
, &allocator_thread
);
1955 thread_deallocate(allocator_thread
);
1961 * Start looking for free space to drop below this level and generate a
1962 * warning immediately if needed:
1964 hfsmp
->hfs_notification_conditions
= 0;
1965 hfs_generate_volume_notifications(hfsmp
);
1968 (void) hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 0);
1979 if (hfsmp
&& hfsmp
->jvp
&& hfsmp
->jvp
!= hfsmp
->hfs_devvp
) {
1980 vnode_clearmountedon(hfsmp
->jvp
);
1981 (void)VNOP_CLOSE(hfsmp
->jvp
, ronly
? FREAD
: FREAD
|FWRITE
, vfs_context_kernel());
1985 if (hfsmp
->hfs_devvp
) {
1986 vnode_rele(hfsmp
->hfs_devvp
);
1988 hfs_delete_chash(hfsmp
);
1990 FREE(hfsmp
, M_HFSMNT
);
1991 vfs_setfsprivate(mp
, NULL
);
1998 * Make a filesystem operational.
1999 * Nothing to do at the moment.
2003 hfs_start(__unused
struct mount
*mp
, __unused
int flags
, __unused vfs_context_t context
)
2010 * unmount system call
2013 hfs_unmount(struct mount
*mp
, int mntflags
, vfs_context_t context
)
2015 struct proc
*p
= vfs_context_proc(context
);
2016 struct hfsmount
*hfsmp
= VFSTOHFS(mp
);
2017 int retval
= E_NONE
;
2025 if (mntflags
& MNT_FORCE
) {
2026 flags
|= FORCECLOSE
;
2030 if ((retval
= hfs_flushfiles(mp
, flags
, p
)) && !force
)
2033 if (hfsmp
->hfs_flags
& HFS_METADATA_ZONE
)
2034 (void) hfs_recording_suspend(hfsmp
);
2037 * Cancel any pending timers for this volume. Then wait for any timers
2038 * which have fired, but whose callbacks have not yet completed.
2040 if (hfsmp
->hfs_syncer
)
2042 struct timespec ts
= {0, 100000000}; /* 0.1 seconds */
2045 * Cancel any timers that have been scheduled, but have not
2046 * fired yet. NOTE: The kernel considers a timer complete as
2047 * soon as it starts your callback, so the kernel does not
2048 * keep track of the number of callbacks in progress.
2050 if (thread_call_cancel(hfsmp
->hfs_syncer
))
2051 OSDecrementAtomic((volatile SInt32
*)&hfsmp
->hfs_sync_incomplete
);
2052 thread_call_free(hfsmp
->hfs_syncer
);
2053 hfsmp
->hfs_syncer
= NULL
;
2056 * This waits for all of the callbacks that were entered before
2057 * we did thread_call_cancel above, but have not completed yet.
2059 while(hfsmp
->hfs_sync_incomplete
> 0)
2061 msleep((caddr_t
)&hfsmp
->hfs_sync_incomplete
, NULL
, PWAIT
, "hfs_unmount", &ts
);
2064 if (hfsmp
->hfs_sync_incomplete
< 0)
2065 panic("hfs_unmount: pm_sync_incomplete underflow!\n");
2068 #if CONFIG_HFS_ALLOC_RBTREE
2069 rb_used
= hfs_teardown_allocator(hfsmp
);
2073 * Flush out the b-trees, volume bitmap and Volume Header
2075 if ((hfsmp
->hfs_flags
& HFS_READ_ONLY
) == 0) {
2076 retval
= hfs_start_transaction(hfsmp
);
2079 } else if (!force
) {
2083 if (hfsmp
->hfs_startup_vp
) {
2084 (void) hfs_lock(VTOC(hfsmp
->hfs_startup_vp
), HFS_EXCLUSIVE_LOCK
);
2085 retval
= hfs_fsync(hfsmp
->hfs_startup_vp
, MNT_WAIT
, 0, p
);
2086 hfs_unlock(VTOC(hfsmp
->hfs_startup_vp
));
2087 if (retval
&& !force
)
2091 if (hfsmp
->hfs_attribute_vp
) {
2092 (void) hfs_lock(VTOC(hfsmp
->hfs_attribute_vp
), HFS_EXCLUSIVE_LOCK
);
2093 retval
= hfs_fsync(hfsmp
->hfs_attribute_vp
, MNT_WAIT
, 0, p
);
2094 hfs_unlock(VTOC(hfsmp
->hfs_attribute_vp
));
2095 if (retval
&& !force
)
2099 (void) hfs_lock(VTOC(hfsmp
->hfs_catalog_vp
), HFS_EXCLUSIVE_LOCK
);
2100 retval
= hfs_fsync(hfsmp
->hfs_catalog_vp
, MNT_WAIT
, 0, p
);
2101 hfs_unlock(VTOC(hfsmp
->hfs_catalog_vp
));
2102 if (retval
&& !force
)
2105 (void) hfs_lock(VTOC(hfsmp
->hfs_extents_vp
), HFS_EXCLUSIVE_LOCK
);
2106 retval
= hfs_fsync(hfsmp
->hfs_extents_vp
, MNT_WAIT
, 0, p
);
2107 hfs_unlock(VTOC(hfsmp
->hfs_extents_vp
));
2108 if (retval
&& !force
)
2111 if (hfsmp
->hfs_allocation_vp
) {
2112 (void) hfs_lock(VTOC(hfsmp
->hfs_allocation_vp
), HFS_EXCLUSIVE_LOCK
);
2113 retval
= hfs_fsync(hfsmp
->hfs_allocation_vp
, MNT_WAIT
, 0, p
);
2114 hfs_unlock(VTOC(hfsmp
->hfs_allocation_vp
));
2115 if (retval
&& !force
)
2119 if (hfsmp
->hfc_filevp
&& vnode_issystem(hfsmp
->hfc_filevp
)) {
2120 retval
= hfs_fsync(hfsmp
->hfc_filevp
, MNT_WAIT
, 0, p
);
2121 if (retval
&& !force
)
2125 /* If runtime corruption was detected, indicate that the volume
2126 * was not unmounted cleanly.
2128 if (hfsmp
->vcbAtrb
& kHFSVolumeInconsistentMask
) {
2129 HFSTOVCB(hfsmp
)->vcbAtrb
&= ~kHFSVolumeUnmountedMask
;
2131 HFSTOVCB(hfsmp
)->vcbAtrb
|= kHFSVolumeUnmountedMask
;
2136 /* If the rb-tree was live, just set min_start to 0 */
2137 hfsmp
->nextAllocation
= 0;
2140 if (hfsmp
->hfs_flags
& HFS_HAS_SPARSE_DEVICE
) {
2142 u_int32_t min_start
= hfsmp
->totalBlocks
;
2144 // set the nextAllocation pointer to the smallest free block number
2145 // we've seen so on the next mount we won't rescan unnecessarily
2146 lck_spin_lock(&hfsmp
->vcbFreeExtLock
);
2147 for(i
=0; i
< (int)hfsmp
->vcbFreeExtCnt
; i
++) {
2148 if (hfsmp
->vcbFreeExt
[i
].startBlock
< min_start
) {
2149 min_start
= hfsmp
->vcbFreeExt
[i
].startBlock
;
2152 lck_spin_unlock(&hfsmp
->vcbFreeExtLock
);
2153 if (min_start
< hfsmp
->nextAllocation
) {
2154 hfsmp
->nextAllocation
= min_start
;
2160 retval
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 0);
2162 HFSTOVCB(hfsmp
)->vcbAtrb
&= ~kHFSVolumeUnmountedMask
;
2164 goto err_exit
; /* could not flush everything */
2168 hfs_end_transaction(hfsmp
);
2174 hfs_journal_flush(hfsmp
, FALSE
);
2178 * Invalidate our caches and release metadata vnodes
2180 (void) hfsUnmount(hfsmp
, p
);
2182 if (HFSTOVCB(hfsmp
)->vcbSigWord
== kHFSSigWord
)
2183 (void) hfs_relconverter(hfsmp
->hfs_encoding
);
2187 journal_close(hfsmp
->jnl
);
2191 VNOP_FSYNC(hfsmp
->hfs_devvp
, MNT_WAIT
, context
);
2193 if (hfsmp
->jvp
&& hfsmp
->jvp
!= hfsmp
->hfs_devvp
) {
2194 vnode_clearmountedon(hfsmp
->jvp
);
2195 retval
= VNOP_CLOSE(hfsmp
->jvp
,
2196 hfsmp
->hfs_flags
& HFS_READ_ONLY
? FREAD
: FREAD
|FWRITE
,
2197 vfs_context_kernel());
2198 vnode_put(hfsmp
->jvp
);
2204 * Last chance to dump unreferenced system files.
2206 (void) vflush(mp
, NULLVP
, FORCECLOSE
);
2209 /* Drop our reference on the backing fs (if any). */
2210 if ((hfsmp
->hfs_flags
& HFS_HAS_SPARSE_DEVICE
) && hfsmp
->hfs_backingfs_rootvp
) {
2211 struct vnode
* tmpvp
;
2213 hfsmp
->hfs_flags
&= ~HFS_HAS_SPARSE_DEVICE
;
2214 tmpvp
= hfsmp
->hfs_backingfs_rootvp
;
2215 hfsmp
->hfs_backingfs_rootvp
= NULLVP
;
2218 #endif /* HFS_SPARSE_DEV */
2219 lck_mtx_destroy(&hfsmp
->hfc_mutex
, hfs_mutex_group
);
2220 lck_spin_destroy(&hfsmp
->vcbFreeExtLock
, hfs_spinlock_group
);
2221 vnode_rele(hfsmp
->hfs_devvp
);
2223 hfs_delete_chash(hfsmp
);
2224 FREE(hfsmp
, M_HFSMNT
);
2230 hfs_end_transaction(hfsmp
);
2237 * Return the root of a filesystem.
2240 hfs_vfs_root(struct mount
*mp
, struct vnode
**vpp
, __unused vfs_context_t context
)
2242 return hfs_vget(VFSTOHFS(mp
), (cnid_t
)kHFSRootFolderID
, vpp
, 1, 0);
2247 * Do operations associated with quotas
2251 hfs_quotactl(__unused
struct mount
*mp
, __unused
int cmds
, __unused uid_t uid
, __unused caddr_t datap
, __unused vfs_context_t context
)
2257 hfs_quotactl(struct mount
*mp
, int cmds
, uid_t uid
, caddr_t datap
, vfs_context_t context
)
2259 struct proc
*p
= vfs_context_proc(context
);
2260 int cmd
, type
, error
;
2263 uid
= kauth_cred_getuid(vfs_context_ucred(context
));
2264 cmd
= cmds
>> SUBCMDSHIFT
;
2271 if (uid
== kauth_cred_getuid(vfs_context_ucred(context
)))
2275 if ( (error
= vfs_context_suser(context
)) )
2279 type
= cmds
& SUBCMDMASK
;
2280 if ((u_int
)type
>= MAXQUOTAS
)
2282 if (vfs_busy(mp
, LK_NOWAIT
))
2288 error
= hfs_quotaon(p
, mp
, type
, datap
);
2292 error
= hfs_quotaoff(p
, mp
, type
);
2296 error
= hfs_setquota(mp
, uid
, type
, datap
);
2300 error
= hfs_setuse(mp
, uid
, type
, datap
);
2304 error
= hfs_getquota(mp
, uid
, type
, datap
);
2308 error
= hfs_qsync(mp
);
2312 error
= hfs_quotastat(mp
, type
, datap
);
2325 /* Subtype is composite of bits */
2326 #define HFS_SUBTYPE_JOURNALED 0x01
2327 #define HFS_SUBTYPE_CASESENSITIVE 0x02
2328 /* bits 2 - 6 reserved */
2329 #define HFS_SUBTYPE_STANDARDHFS 0x80
2332 * Get file system statistics.
2335 hfs_statfs(struct mount
*mp
, register struct vfsstatfs
*sbp
, __unused vfs_context_t context
)
2337 ExtendedVCB
*vcb
= VFSTOVCB(mp
);
2338 struct hfsmount
*hfsmp
= VFSTOHFS(mp
);
2339 u_int32_t freeCNIDs
;
2340 u_int16_t subtype
= 0;
2342 freeCNIDs
= (u_int32_t
)0xFFFFFFFF - (u_int32_t
)vcb
->vcbNxtCNID
;
2344 sbp
->f_bsize
= (u_int32_t
)vcb
->blockSize
;
2345 sbp
->f_iosize
= (size_t)cluster_max_io_size(mp
, 0);
2346 sbp
->f_blocks
= (u_int64_t
)((u_int32_t
)vcb
->totalBlocks
);
2347 sbp
->f_bfree
= (u_int64_t
)((u_int32_t
)hfs_freeblks(hfsmp
, 0));
2348 sbp
->f_bavail
= (u_int64_t
)((u_int32_t
)hfs_freeblks(hfsmp
, 1));
2349 sbp
->f_files
= (u_int64_t
)((u_int32_t
)(vcb
->totalBlocks
- 2)); /* max files is constrained by total blocks */
2350 sbp
->f_ffree
= (u_int64_t
)((u_int32_t
)(MIN(freeCNIDs
, sbp
->f_bavail
)));
2353 * Subtypes (flavors) for HFS
2354 * 0: Mac OS Extended
2355 * 1: Mac OS Extended (Journaled)
2356 * 2: Mac OS Extended (Case Sensitive)
2357 * 3: Mac OS Extended (Case Sensitive, Journaled)
2359 * 128: Mac OS Standard
2362 if (hfsmp
->hfs_flags
& HFS_STANDARD
) {
2363 subtype
= HFS_SUBTYPE_STANDARDHFS
;
2364 } else /* HFS Plus */ {
2366 subtype
|= HFS_SUBTYPE_JOURNALED
;
2367 if (hfsmp
->hfs_flags
& HFS_CASE_SENSITIVE
)
2368 subtype
|= HFS_SUBTYPE_CASESENSITIVE
;
2370 sbp
->f_fssubtype
= subtype
;
2377 // XXXdbg -- this is a callback to be used by the journal to
2378 // get meta data blocks flushed out to disk.
2380 // XXXdbg -- be smarter and don't flush *every* block on each
2381 // call. try to only flush some so we don't wind up
2382 // being too synchronous.
2386 hfs_sync_metadata(void *arg
)
2388 struct mount
*mp
= (struct mount
*)arg
;
2389 struct hfsmount
*hfsmp
;
2393 daddr64_t priIDSector
;
2394 hfsmp
= VFSTOHFS(mp
);
2395 vcb
= HFSTOVCB(hfsmp
);
2397 // now make sure the super block is flushed
2398 priIDSector
= (daddr64_t
)((vcb
->hfsPlusIOPosOffset
/ hfsmp
->hfs_logical_block_size
) +
2399 HFS_PRI_SECTOR(hfsmp
->hfs_logical_block_size
));
2401 retval
= (int)buf_meta_bread(hfsmp
->hfs_devvp
,
2402 HFS_PHYSBLK_ROUNDDOWN(priIDSector
, hfsmp
->hfs_log_per_phys
),
2403 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
);
2404 if ((retval
!= 0 ) && (retval
!= ENXIO
)) {
2405 printf("hfs_sync_metadata: can't read volume header at %d! (retval 0x%x)\n",
2406 (int)priIDSector
, retval
);
2409 if (retval
== 0 && ((buf_flags(bp
) & (B_DELWRI
| B_LOCKED
)) == B_DELWRI
)) {
2415 // the alternate super block...
2416 // XXXdbg - we probably don't need to do this each and every time.
2417 // hfs_btreeio.c:FlushAlternate() should flag when it was
2419 if (hfsmp
->hfs_alt_id_sector
) {
2420 retval
= (int)buf_meta_bread(hfsmp
->hfs_devvp
,
2421 HFS_PHYSBLK_ROUNDDOWN(hfsmp
->hfs_alt_id_sector
, hfsmp
->hfs_log_per_phys
),
2422 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
);
2423 if (retval
== 0 && ((buf_flags(bp
) & (B_DELWRI
| B_LOCKED
)) == B_DELWRI
)) {
2432 struct hfs_sync_cargs
{
2441 hfs_sync_callback(struct vnode
*vp
, void *cargs
)
2444 struct hfs_sync_cargs
*args
;
2447 args
= (struct hfs_sync_cargs
*)cargs
;
2449 if (hfs_lock(VTOC(vp
), HFS_EXCLUSIVE_LOCK
) != 0) {
2450 return (VNODE_RETURNED
);
2454 if ((cp
->c_flag
& C_MODIFIED
) ||
2455 (cp
->c_touch_acctime
| cp
->c_touch_chgtime
| cp
->c_touch_modtime
) ||
2456 vnode_hasdirtyblks(vp
)) {
2457 error
= hfs_fsync(vp
, args
->waitfor
, 0, args
->p
);
2460 args
->error
= error
;
2463 return (VNODE_RETURNED
);
2469 * Go through the disk queues to initiate sandbagged IO;
2470 * go through the inodes to write those that have been modified;
2471 * initiate the writing of the super block if it has been modified.
2473 * Note: we are always called with the filesystem marked `MPBUSY'.
2476 hfs_sync(struct mount
*mp
, int waitfor
, vfs_context_t context
)
2478 struct proc
*p
= vfs_context_proc(context
);
2480 struct hfsmount
*hfsmp
;
2482 struct vnode
*meta_vp
[4];
2484 int error
, allerror
= 0;
2485 struct hfs_sync_cargs args
;
2487 hfsmp
= VFSTOHFS(mp
);
2490 * hfs_changefs might be manipulating vnodes so back off
2492 if (hfsmp
->hfs_flags
& HFS_IN_CHANGEFS
)
2495 if (hfsmp
->hfs_flags
& HFS_READ_ONLY
)
2498 /* skip over frozen volumes */
2499 if (!lck_rw_try_lock_shared(&hfsmp
->hfs_insync
))
2502 args
.cred
= kauth_cred_get();
2503 args
.waitfor
= waitfor
;
2507 * hfs_sync_callback will be called for each vnode
2508 * hung off of this mount point... the vnode will be
2509 * properly referenced and unreferenced around the callback
2511 vnode_iterate(mp
, 0, hfs_sync_callback
, (void *)&args
);
2514 allerror
= args
.error
;
2516 vcb
= HFSTOVCB(hfsmp
);
2518 meta_vp
[0] = vcb
->extentsRefNum
;
2519 meta_vp
[1] = vcb
->catalogRefNum
;
2520 meta_vp
[2] = vcb
->allocationsRefNum
; /* This is NULL for standard HFS */
2521 meta_vp
[3] = hfsmp
->hfs_attribute_vp
; /* Optional file */
2523 /* Now sync our three metadata files */
2524 for (i
= 0; i
< 4; ++i
) {
2528 if ((btvp
==0) || (vnode_mount(btvp
) != mp
))
2531 /* XXX use hfs_systemfile_lock instead ? */
2532 (void) hfs_lock(VTOC(btvp
), HFS_EXCLUSIVE_LOCK
);
2535 if (((cp
->c_flag
& C_MODIFIED
) == 0) &&
2536 (cp
->c_touch_acctime
== 0) &&
2537 (cp
->c_touch_chgtime
== 0) &&
2538 (cp
->c_touch_modtime
== 0) &&
2539 vnode_hasdirtyblks(btvp
) == 0) {
2540 hfs_unlock(VTOC(btvp
));
2543 error
= vnode_get(btvp
);
2545 hfs_unlock(VTOC(btvp
));
2548 if ((error
= hfs_fsync(btvp
, waitfor
, 0, p
)))
2556 * Force stale file system control information to be flushed.
2558 if (vcb
->vcbSigWord
== kHFSSigWord
) {
2559 if ((error
= VNOP_FSYNC(hfsmp
->hfs_devvp
, waitfor
, context
))) {
2567 hfs_hotfilesync(hfsmp
, vfs_context_kernel());
2570 * Write back modified superblock.
2572 if (IsVCBDirty(vcb
)) {
2573 error
= hfs_flushvolumeheader(hfsmp
, waitfor
, 0);
2579 hfs_journal_flush(hfsmp
, FALSE
);
2587 clock_get_calendar_microtime(&secs
, &usecs
);
2588 now
= ((uint64_t)secs
* 1000000ULL) + (uint64_t)usecs
;
2589 hfsmp
->hfs_last_sync_time
= now
;
2592 lck_rw_unlock_shared(&hfsmp
->hfs_insync
);
2598 * File handle to vnode
2600 * Have to be really careful about stale file handles:
2601 * - check that the cnode id is valid
2602 * - call hfs_vget() to get the locked cnode
2603 * - check for an unallocated cnode (i_mode == 0)
2604 * - check that the given client host has export rights and return
2605 * those rights via. exflagsp and credanonp
2608 hfs_fhtovp(struct mount
*mp
, int fhlen
, unsigned char *fhp
, struct vnode
**vpp
, __unused vfs_context_t context
)
2610 struct hfsfid
*hfsfhp
;
2615 hfsfhp
= (struct hfsfid
*)fhp
;
2617 if (fhlen
< (int)sizeof(struct hfsfid
))
2620 result
= hfs_vget(VFSTOHFS(mp
), ntohl(hfsfhp
->hfsfid_cnid
), &nvp
, 0, 0);
2622 if (result
== ENOENT
)
2628 * We used to use the create time as the gen id of the file handle,
2629 * but it is not static enough because it can change at any point
2630 * via system calls. We still don't have another volume ID or other
2631 * unique identifier to use for a generation ID across reboots that
2632 * persists until the file is removed. Using only the CNID exposes
2633 * us to the potential wrap-around case, but as of 2/2008, it would take
2634 * over 2 months to wrap around if the machine did nothing but allocate
2635 * CNIDs. Using some kind of wrap counter would only be effective if
2636 * each file had the wrap counter associated with it. For now,
2637 * we use only the CNID to identify the file as it's good enough.
2642 hfs_unlock(VTOC(nvp
));
2648 * Vnode pointer to File handle
2652 hfs_vptofh(struct vnode
*vp
, int *fhlenp
, unsigned char *fhp
, __unused vfs_context_t context
)
2655 struct hfsfid
*hfsfhp
;
2657 if (ISHFS(VTOVCB(vp
)))
2658 return (ENOTSUP
); /* hfs standard is not exportable */
2660 if (*fhlenp
< (int)sizeof(struct hfsfid
))
2664 hfsfhp
= (struct hfsfid
*)fhp
;
2665 /* only the CNID is used to identify the file now */
2666 hfsfhp
->hfsfid_cnid
= htonl(cp
->c_fileid
);
2667 hfsfhp
->hfsfid_gen
= htonl(cp
->c_fileid
);
2668 *fhlenp
= sizeof(struct hfsfid
);
2675 * Initial HFS filesystems, done only once.
2678 hfs_init(__unused
struct vfsconf
*vfsp
)
2680 static int done
= 0;
2686 hfs_converterinit();
2691 hfs_lock_attr
= lck_attr_alloc_init();
2692 hfs_group_attr
= lck_grp_attr_alloc_init();
2693 hfs_mutex_group
= lck_grp_alloc_init("hfs-mutex", hfs_group_attr
);
2694 hfs_rwlock_group
= lck_grp_alloc_init("hfs-rwlock", hfs_group_attr
);
2695 hfs_spinlock_group
= lck_grp_alloc_init("hfs-spinlock", hfs_group_attr
);
2705 hfs_getmountpoint(struct vnode
*vp
, struct hfsmount
**hfsmpp
)
2707 struct hfsmount
* hfsmp
;
2708 char fstypename
[MFSNAMELEN
];
2713 if (!vnode_isvroot(vp
))
2716 vnode_vfsname(vp
, fstypename
);
2717 if (strncmp(fstypename
, "hfs", sizeof(fstypename
)) != 0)
2722 if (HFSTOVCB(hfsmp
)->vcbSigWord
== kHFSSigWord
)
2731 #include <sys/filedesc.h>
2734 * HFS filesystem related variables.
2737 hfs_sysctl(int *name
, __unused u_int namelen
, user_addr_t oldp
, size_t *oldlenp
,
2738 user_addr_t newp
, size_t newlen
, vfs_context_t context
)
2740 struct proc
*p
= vfs_context_proc(context
);
2742 struct hfsmount
*hfsmp
;
2744 /* all sysctl names at this level are terminal */
2746 if (name
[0] == HFS_ENCODINGBIAS
) {
2749 bias
= hfs_getencodingbias();
2750 error
= sysctl_int(oldp
, oldlenp
, newp
, newlen
, &bias
);
2751 if (error
== 0 && newp
)
2752 hfs_setencodingbias(bias
);
2755 } else if (name
[0] == HFS_EXTEND_FS
) {
2757 vnode_t vp
= vfs_context_cwd(context
);
2759 if (newp
== USER_ADDR_NULL
|| vp
== NULLVP
)
2761 if ((error
= hfs_getmountpoint(vp
, &hfsmp
)))
2763 error
= sysctl_quad(oldp
, oldlenp
, newp
, newlen
, (quad_t
*)&newsize
);
2767 error
= hfs_extendfs(hfsmp
, newsize
, context
);
2770 } else if (name
[0] == HFS_ENCODINGHINT
) {
2774 u_int16_t
*unicode_name
= NULL
;
2775 char *filename
= NULL
;
2777 if ((newlen
<= 0) || (newlen
> MAXPATHLEN
))
2780 bufsize
= MAX(newlen
* 3, MAXPATHLEN
);
2781 MALLOC(filename
, char *, newlen
, M_TEMP
, M_WAITOK
);
2782 if (filename
== NULL
) {
2784 goto encodinghint_exit
;
2786 MALLOC(unicode_name
, u_int16_t
*, bufsize
, M_TEMP
, M_WAITOK
);
2787 if (filename
== NULL
) {
2789 goto encodinghint_exit
;
2792 error
= copyin(newp
, (caddr_t
)filename
, newlen
);
2794 error
= utf8_decodestr((u_int8_t
*)filename
, newlen
- 1, unicode_name
,
2795 &bytes
, bufsize
, 0, UTF_DECOMPOSED
);
2797 hint
= hfs_pickencoding(unicode_name
, bytes
/ 2);
2798 error
= sysctl_int(oldp
, oldlenp
, USER_ADDR_NULL
, 0, (int32_t *)&hint
);
2804 FREE(unicode_name
, M_TEMP
);
2806 FREE(filename
, M_TEMP
);
2809 } else if (name
[0] == HFS_ENABLE_JOURNALING
) {
2810 // make the file system journaled...
2811 vnode_t vp
= vfs_context_cwd(context
);
2814 struct cat_attr jnl_attr
, jinfo_attr
;
2815 struct cat_fork jnl_fork
, jinfo_fork
;
2819 /* Only root can enable journaling */
2827 if (hfsmp
->hfs_flags
& HFS_READ_ONLY
) {
2830 if (HFSTOVCB(hfsmp
)->vcbSigWord
== kHFSSigWord
) {
2831 printf("hfs: can't make a plain hfs volume journaled.\n");
2836 printf("hfs: volume @ mp %p is already journaled!\n", vnode_mount(vp
));
2840 vcb
= HFSTOVCB(hfsmp
);
2841 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
| SFL_EXTENTS
, HFS_EXCLUSIVE_LOCK
);
2842 if (BTHasContiguousNodes(VTOF(vcb
->catalogRefNum
)) == 0 ||
2843 BTHasContiguousNodes(VTOF(vcb
->extentsRefNum
)) == 0) {
2845 printf("hfs: volume has a btree w/non-contiguous nodes. can not enable journaling.\n");
2846 hfs_systemfile_unlock(hfsmp
, lockflags
);
2849 hfs_systemfile_unlock(hfsmp
, lockflags
);
2851 // make sure these both exist!
2852 if ( GetFileInfo(vcb
, kHFSRootFolderID
, ".journal_info_block", &jinfo_attr
, &jinfo_fork
) == 0
2853 || GetFileInfo(vcb
, kHFSRootFolderID
, ".journal", &jnl_attr
, &jnl_fork
) == 0) {
2858 hfs_sync(hfsmp
->hfs_mp
, MNT_WAIT
, context
);
2860 printf("hfs: Initializing the journal (joffset 0x%llx sz 0x%llx)...\n",
2861 (off_t
)name
[2], (off_t
)name
[3]);
2864 // XXXdbg - note that currently (Sept, 08) hfs_util does not support
2865 // enabling the journal on a separate device so it is safe
2866 // to just copy hfs_devvp here. If hfs_util gets the ability
2867 // to dynamically enable the journal on a separate device then
2868 // we will have to do the same thing as hfs_early_journal_init()
2869 // to locate and open the journal device.
2871 jvp
= hfsmp
->hfs_devvp
;
2872 jnl
= journal_create(jvp
,
2873 (off_t
)name
[2] * (off_t
)HFSTOVCB(hfsmp
)->blockSize
2874 + HFSTOVCB(hfsmp
)->hfsPlusIOPosOffset
,
2875 (off_t
)((unsigned)name
[3]),
2877 hfsmp
->hfs_logical_block_size
,
2880 hfs_sync_metadata
, hfsmp
->hfs_mp
);
2883 * Set up the trim callback function so that we can add
2884 * recently freed extents to the free extent cache once
2885 * the transaction that freed them is written to the
2889 journal_trim_set_callback(jnl
, hfs_trim_callback
, hfsmp
);
2892 printf("hfs: FAILED to create the journal!\n");
2893 if (jvp
&& jvp
!= hfsmp
->hfs_devvp
) {
2894 vnode_clearmountedon(jvp
);
2895 VNOP_CLOSE(jvp
, hfsmp
->hfs_flags
& HFS_READ_ONLY
? FREAD
: FREAD
|FWRITE
, vfs_context_kernel());
2902 hfs_lock_global (hfsmp
, HFS_EXCLUSIVE_LOCK
);
2905 * Flush all dirty metadata buffers.
2907 buf_flushdirtyblks(hfsmp
->hfs_devvp
, TRUE
, 0, "hfs_sysctl");
2908 buf_flushdirtyblks(hfsmp
->hfs_extents_vp
, TRUE
, 0, "hfs_sysctl");
2909 buf_flushdirtyblks(hfsmp
->hfs_catalog_vp
, TRUE
, 0, "hfs_sysctl");
2910 buf_flushdirtyblks(hfsmp
->hfs_allocation_vp
, TRUE
, 0, "hfs_sysctl");
2911 if (hfsmp
->hfs_attribute_vp
)
2912 buf_flushdirtyblks(hfsmp
->hfs_attribute_vp
, TRUE
, 0, "hfs_sysctl");
2914 HFSTOVCB(hfsmp
)->vcbJinfoBlock
= name
[1];
2915 HFSTOVCB(hfsmp
)->vcbAtrb
|= kHFSVolumeJournaledMask
;
2919 // save this off for the hack-y check in hfs_remove()
2920 hfsmp
->jnl_start
= (u_int32_t
)name
[2];
2921 hfsmp
->jnl_size
= (off_t
)((unsigned)name
[3]);
2922 hfsmp
->hfs_jnlinfoblkid
= jinfo_attr
.ca_fileid
;
2923 hfsmp
->hfs_jnlfileid
= jnl_attr
.ca_fileid
;
2925 vfs_setflags(hfsmp
->hfs_mp
, (u_int64_t
)((unsigned int)MNT_JOURNALED
));
2927 hfs_unlock_global (hfsmp
);
2928 hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 1);
2933 fsid
.val
[0] = (int32_t)hfsmp
->hfs_raw_dev
;
2934 fsid
.val
[1] = (int32_t)vfs_typenum(HFSTOVFS(hfsmp
));
2935 vfs_event_signal(&fsid
, VQ_UPDATE
, (intptr_t)NULL
);
2938 } else if (name
[0] == HFS_DISABLE_JOURNALING
) {
2939 // clear the journaling bit
2940 vnode_t vp
= vfs_context_cwd(context
);
2942 /* Only root can disable journaling */
2952 * Disabling journaling is disallowed on volumes with directory hard links
2953 * because we have not tested the relevant code path.
2955 if (hfsmp
->hfs_private_attr
[DIR_HARDLINKS
].ca_entries
!= 0){
2956 printf("hfs: cannot disable journaling on volumes with directory hardlinks\n");
2960 printf("hfs: disabling journaling for mount @ %p\n", vnode_mount(vp
));
2962 hfs_lock_global (hfsmp
, HFS_EXCLUSIVE_LOCK
);
2964 // Lights out for you buddy!
2965 journal_close(hfsmp
->jnl
);
2968 if (hfsmp
->jvp
&& hfsmp
->jvp
!= hfsmp
->hfs_devvp
) {
2969 vnode_clearmountedon(hfsmp
->jvp
);
2970 VNOP_CLOSE(hfsmp
->jvp
, hfsmp
->hfs_flags
& HFS_READ_ONLY
? FREAD
: FREAD
|FWRITE
, vfs_context_kernel());
2971 vnode_put(hfsmp
->jvp
);
2974 vfs_clearflags(hfsmp
->hfs_mp
, (u_int64_t
)((unsigned int)MNT_JOURNALED
));
2975 hfsmp
->jnl_start
= 0;
2976 hfsmp
->hfs_jnlinfoblkid
= 0;
2977 hfsmp
->hfs_jnlfileid
= 0;
2979 HFSTOVCB(hfsmp
)->vcbAtrb
&= ~kHFSVolumeJournaledMask
;
2981 hfs_unlock_global (hfsmp
);
2983 hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 1);
2988 fsid
.val
[0] = (int32_t)hfsmp
->hfs_raw_dev
;
2989 fsid
.val
[1] = (int32_t)vfs_typenum(HFSTOVFS(hfsmp
));
2990 vfs_event_signal(&fsid
, VQ_UPDATE
, (intptr_t)NULL
);
2993 } else if (name
[0] == HFS_GET_JOURNAL_INFO
) {
2994 vnode_t vp
= vfs_context_cwd(context
);
2995 off_t jnl_start
, jnl_size
;
3000 /* 64-bit processes won't work with this sysctl -- can't fit a pointer into an int! */
3001 if (proc_is64bit(current_proc()))
3005 if (hfsmp
->jnl
== NULL
) {
3009 jnl_start
= (off_t
)(hfsmp
->jnl_start
* HFSTOVCB(hfsmp
)->blockSize
) + (off_t
)HFSTOVCB(hfsmp
)->hfsPlusIOPosOffset
;
3010 jnl_size
= (off_t
)hfsmp
->jnl_size
;
3013 if ((error
= copyout((caddr_t
)&jnl_start
, CAST_USER_ADDR_T(name
[1]), sizeof(off_t
))) != 0) {
3016 if ((error
= copyout((caddr_t
)&jnl_size
, CAST_USER_ADDR_T(name
[2]), sizeof(off_t
))) != 0) {
3021 } else if (name
[0] == HFS_SET_PKG_EXTENSIONS
) {
3023 return set_package_extensions_table((user_addr_t
)((unsigned)name
[1]), name
[2], name
[3]);
3025 } else if (name
[0] == VFS_CTL_QUERY
) {
3026 struct sysctl_req
*req
;
3027 union union_vfsidctl vc
;
3031 req
= CAST_DOWN(struct sysctl_req
*, oldp
); /* we're new style vfs sysctl. */
3033 error
= SYSCTL_IN(req
, &vc
, proc_is64bit(p
)? sizeof(vc
.vc64
):sizeof(vc
.vc32
));
3034 if (error
) return (error
);
3036 mp
= vfs_getvfs(&vc
.vc32
.vc_fsid
); /* works for 32 and 64 */
3037 if (mp
== NULL
) return (ENOENT
);
3039 hfsmp
= VFSTOHFS(mp
);
3040 bzero(&vq
, sizeof(vq
));
3041 vq
.vq_flags
= hfsmp
->hfs_notification_conditions
;
3042 return SYSCTL_OUT(req
, &vq
, sizeof(vq
));;
3043 } else if (name
[0] == HFS_REPLAY_JOURNAL
) {
3044 vnode_t devvp
= NULL
;
3049 device_fd
= name
[1];
3050 error
= file_vnode(device_fd
, &devvp
);
3054 error
= vnode_getwithref(devvp
);
3056 file_drop(device_fd
);
3059 error
= hfs_journal_replay(devvp
, context
);
3060 file_drop(device_fd
);
3063 } else if (name
[0] == HFS_ENABLE_RESIZE_DEBUG
) {
3064 hfs_resize_debug
= 1;
3065 printf ("hfs_sysctl: Enabled volume resize debugging.\n");
3073 * hfs_vfs_vget is not static since it is used in hfs_readwrite.c to support
3074 * the build_path ioctl. We use it to leverage the code below that updates
3075 * the origin list cache if necessary
3079 hfs_vfs_vget(struct mount
*mp
, ino64_t ino
, struct vnode
**vpp
, __unused vfs_context_t context
)
3083 struct hfsmount
*hfsmp
;
3085 hfsmp
= VFSTOHFS(mp
);
3087 error
= hfs_vget(hfsmp
, (cnid_t
)ino
, vpp
, 1, 0);
3092 * ADLs may need to have their origin state updated
3093 * since build_path needs a valid parent. The same is true
3094 * for hardlinked files as well. There isn't a race window here
3095 * in re-acquiring the cnode lock since we aren't pulling any data
3096 * out of the cnode; instead, we're going to the catalog.
3098 if ((VTOC(*vpp
)->c_flag
& C_HARDLINK
) &&
3099 (hfs_lock(VTOC(*vpp
), HFS_EXCLUSIVE_LOCK
) == 0)) {
3100 cnode_t
*cp
= VTOC(*vpp
);
3101 struct cat_desc cdesc
;
3103 if (!hfs_haslinkorigin(cp
)) {
3104 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
3105 error
= cat_findname(hfsmp
, (cnid_t
)ino
, &cdesc
);
3106 hfs_systemfile_unlock(hfsmp
, lockflags
);
3108 if ((cdesc
.cd_parentcnid
!= hfsmp
->hfs_private_desc
[DIR_HARDLINKS
].cd_cnid
) &&
3109 (cdesc
.cd_parentcnid
!= hfsmp
->hfs_private_desc
[FILE_HARDLINKS
].cd_cnid
)) {
3110 hfs_savelinkorigin(cp
, cdesc
.cd_parentcnid
);
3112 cat_releasedesc(&cdesc
);
3122 * Look up an HFS object by ID.
3124 * The object is returned with an iocount reference and the cnode locked.
3126 * If the object is a file then it will represent the data fork.
3129 hfs_vget(struct hfsmount
*hfsmp
, cnid_t cnid
, struct vnode
**vpp
, int skiplock
, int allow_deleted
)
3131 struct vnode
*vp
= NULLVP
;
3132 struct cat_desc cndesc
;
3133 struct cat_attr cnattr
;
3134 struct cat_fork cnfork
;
3135 u_int32_t linkref
= 0;
3138 /* Check for cnids that should't be exported. */
3139 if ((cnid
< kHFSFirstUserCatalogNodeID
) &&
3140 (cnid
!= kHFSRootFolderID
&& cnid
!= kHFSRootParentID
)) {
3143 /* Don't export our private directories. */
3144 if (cnid
== hfsmp
->hfs_private_desc
[FILE_HARDLINKS
].cd_cnid
||
3145 cnid
== hfsmp
->hfs_private_desc
[DIR_HARDLINKS
].cd_cnid
) {
3149 * Check the hash first
3151 vp
= hfs_chash_getvnode(hfsmp
, cnid
, 0, skiplock
, allow_deleted
);
3157 bzero(&cndesc
, sizeof(cndesc
));
3158 bzero(&cnattr
, sizeof(cnattr
));
3159 bzero(&cnfork
, sizeof(cnfork
));
3162 * Not in hash, lookup in catalog
3164 if (cnid
== kHFSRootParentID
) {
3165 static char hfs_rootname
[] = "/";
3167 cndesc
.cd_nameptr
= (const u_int8_t
*)&hfs_rootname
[0];
3168 cndesc
.cd_namelen
= 1;
3169 cndesc
.cd_parentcnid
= kHFSRootParentID
;
3170 cndesc
.cd_cnid
= kHFSRootFolderID
;
3171 cndesc
.cd_flags
= CD_ISDIR
;
3173 cnattr
.ca_fileid
= kHFSRootFolderID
;
3174 cnattr
.ca_linkcount
= 1;
3175 cnattr
.ca_entries
= 1;
3176 cnattr
.ca_dircount
= 1;
3177 cnattr
.ca_mode
= (S_IFDIR
| S_IRWXU
| S_IRWXG
| S_IRWXO
);
3181 const char *nameptr
;
3183 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
3184 error
= cat_idlookup(hfsmp
, cnid
, 0, &cndesc
, &cnattr
, &cnfork
);
3185 hfs_systemfile_unlock(hfsmp
, lockflags
);
3193 * Check for a raw hardlink inode and save its linkref.
3195 pid
= cndesc
.cd_parentcnid
;
3196 nameptr
= (const char *)cndesc
.cd_nameptr
;
3198 if ((pid
== hfsmp
->hfs_private_desc
[FILE_HARDLINKS
].cd_cnid
) &&
3199 (bcmp(nameptr
, HFS_INODE_PREFIX
, HFS_INODE_PREFIX_LEN
) == 0)) {
3200 linkref
= strtoul(&nameptr
[HFS_INODE_PREFIX_LEN
], NULL
, 10);
3202 } else if ((pid
== hfsmp
->hfs_private_desc
[DIR_HARDLINKS
].cd_cnid
) &&
3203 (bcmp(nameptr
, HFS_DIRINODE_PREFIX
, HFS_DIRINODE_PREFIX_LEN
) == 0)) {
3204 linkref
= strtoul(&nameptr
[HFS_DIRINODE_PREFIX_LEN
], NULL
, 10);
3206 } else if ((pid
== hfsmp
->hfs_private_desc
[FILE_HARDLINKS
].cd_cnid
) &&
3207 (bcmp(nameptr
, HFS_DELETE_PREFIX
, HFS_DELETE_PREFIX_LEN
) == 0)) {
3209 cat_releasedesc(&cndesc
);
3210 return (ENOENT
); /* open unlinked file */
3215 * Finish initializing cnode descriptor for hardlinks.
3217 * We need a valid name and parent for reverse lookups.
3222 struct cat_desc linkdesc
;
3225 cnattr
.ca_linkref
= linkref
;
3228 * Pick up the first link in the chain and get a descriptor for it.
3229 * This allows blind volfs paths to work for hardlinks.
3231 if ((hfs_lookup_siblinglinks(hfsmp
, linkref
, &prevlinkid
, &nextlinkid
) == 0) &&
3232 (nextlinkid
!= 0)) {
3233 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
3234 error
= cat_findname(hfsmp
, nextlinkid
, &linkdesc
);
3235 hfs_systemfile_unlock(hfsmp
, lockflags
);
3237 cat_releasedesc(&cndesc
);
3238 bcopy(&linkdesc
, &cndesc
, sizeof(linkdesc
));
3244 int newvnode_flags
= 0;
3246 error
= hfs_getnewvnode(hfsmp
, NULL
, NULL
, &cndesc
, 0, &cnattr
,
3247 &cnfork
, &vp
, &newvnode_flags
);
3249 VTOC(vp
)->c_flag
|= C_HARDLINK
;
3250 vnode_setmultipath(vp
);
3253 struct componentname cn
;
3254 int newvnode_flags
= 0;
3256 /* Supply hfs_getnewvnode with a component name. */
3257 MALLOC_ZONE(cn
.cn_pnbuf
, caddr_t
, MAXPATHLEN
, M_NAMEI
, M_WAITOK
);
3258 cn
.cn_nameiop
= LOOKUP
;
3259 cn
.cn_flags
= ISLASTCN
| HASBUF
;
3260 cn
.cn_context
= NULL
;
3261 cn
.cn_pnlen
= MAXPATHLEN
;
3262 cn
.cn_nameptr
= cn
.cn_pnbuf
;
3263 cn
.cn_namelen
= cndesc
.cd_namelen
;
3266 bcopy(cndesc
.cd_nameptr
, cn
.cn_nameptr
, cndesc
.cd_namelen
+ 1);
3268 error
= hfs_getnewvnode(hfsmp
, NULLVP
, &cn
, &cndesc
, 0, &cnattr
,
3269 &cnfork
, &vp
, &newvnode_flags
);
3271 if (error
== 0 && (VTOC(vp
)->c_flag
& C_HARDLINK
)) {
3272 hfs_savelinkorigin(VTOC(vp
), cndesc
.cd_parentcnid
);
3274 FREE_ZONE(cn
.cn_pnbuf
, cn
.cn_pnlen
, M_NAMEI
);
3276 cat_releasedesc(&cndesc
);
3279 if (vp
&& skiplock
) {
3280 hfs_unlock(VTOC(vp
));
3287 * Flush out all the files in a filesystem.
3291 hfs_flushfiles(struct mount
*mp
, int flags
, struct proc
*p
)
3293 hfs_flushfiles(struct mount
*mp
, int flags
, __unused
struct proc
*p
)
3296 struct hfsmount
*hfsmp
;
3297 struct vnode
*skipvp
= NULLVP
;
3304 hfsmp
= VFSTOHFS(mp
);
3308 * The open quota files have an indirect reference on
3309 * the root directory vnode. We must account for this
3310 * extra reference when doing the intial vflush.
3313 if (((unsigned int)vfs_flags(mp
)) & MNT_QUOTA
) {
3315 /* Find out how many quota files we have open. */
3316 for (i
= 0; i
< MAXQUOTAS
; i
++) {
3317 if (hfsmp
->hfs_qfiles
[i
].qf_vp
!= NULLVP
)
3321 /* Obtain the root vnode so we can skip over it. */
3322 skipvp
= hfs_chash_getvnode(hfsmp
, kHFSRootFolderID
, 0, 0, 0);
3326 error
= vflush(mp
, skipvp
, SKIPSYSTEM
| SKIPSWAP
| flags
);
3330 error
= vflush(mp
, skipvp
, SKIPSYSTEM
| flags
);
3333 if (((unsigned int)vfs_flags(mp
)) & MNT_QUOTA
) {
3336 * See if there are additional references on the
3337 * root vp besides the ones obtained from the open
3338 * quota files and the hfs_chash_getvnode call above.
3341 (vnode_isinuse(skipvp
, quotafilecnt
))) {
3342 error
= EBUSY
; /* root directory is still open */
3344 hfs_unlock(VTOC(skipvp
));
3347 if (error
&& (flags
& FORCECLOSE
) == 0)
3350 for (i
= 0; i
< MAXQUOTAS
; i
++) {
3351 if (hfsmp
->hfs_qfiles
[i
].qf_vp
== NULLVP
)
3353 hfs_quotaoff(p
, mp
, i
);
3355 error
= vflush(mp
, NULLVP
, SKIPSYSTEM
| flags
);
3363 * Update volume encoding bitmap (HFS Plus only)
3367 hfs_setencodingbits(struct hfsmount
*hfsmp
, u_int32_t encoding
)
3369 #define kIndexMacUkrainian 48 /* MacUkrainian encoding is 152 */
3370 #define kIndexMacFarsi 49 /* MacFarsi encoding is 140 */
3375 case kTextEncodingMacUkrainian
:
3376 index
= kIndexMacUkrainian
;
3378 case kTextEncodingMacFarsi
:
3379 index
= kIndexMacFarsi
;
3386 if (index
< 64 && (hfsmp
->encodingsBitmap
& (u_int64_t
)(1ULL << index
)) == 0) {
3387 HFS_MOUNT_LOCK(hfsmp
, TRUE
)
3388 hfsmp
->encodingsBitmap
|= (u_int64_t
)(1ULL << index
);
3389 MarkVCBDirty(hfsmp
);
3390 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
3395 * Update volume stats
3397 * On journal volumes this will cause a volume header flush
3400 hfs_volupdate(struct hfsmount
*hfsmp
, enum volop op
, int inroot
)
3406 lck_mtx_lock(&hfsmp
->hfs_mutex
);
3408 MarkVCBDirty(hfsmp
);
3409 hfsmp
->hfs_mtime
= tv
.tv_sec
;
3415 if (hfsmp
->hfs_dircount
!= 0xFFFFFFFF)
3416 ++hfsmp
->hfs_dircount
;
3417 if (inroot
&& hfsmp
->vcbNmRtDirs
!= 0xFFFF)
3418 ++hfsmp
->vcbNmRtDirs
;
3421 if (hfsmp
->hfs_dircount
!= 0)
3422 --hfsmp
->hfs_dircount
;
3423 if (inroot
&& hfsmp
->vcbNmRtDirs
!= 0xFFFF)
3424 --hfsmp
->vcbNmRtDirs
;
3427 if (hfsmp
->hfs_filecount
!= 0xFFFFFFFF)
3428 ++hfsmp
->hfs_filecount
;
3429 if (inroot
&& hfsmp
->vcbNmFls
!= 0xFFFF)
3433 if (hfsmp
->hfs_filecount
!= 0)
3434 --hfsmp
->hfs_filecount
;
3435 if (inroot
&& hfsmp
->vcbNmFls
!= 0xFFFF)
3440 lck_mtx_unlock(&hfsmp
->hfs_mutex
);
3443 hfs_flushvolumeheader(hfsmp
, 0, 0);
3451 hfs_flushMDB(struct hfsmount
*hfsmp
, int waitfor
, int altflush
)
3453 ExtendedVCB
*vcb
= HFSTOVCB(hfsmp
);
3454 struct filefork
*fp
;
3455 HFSMasterDirectoryBlock
*mdb
;
3456 struct buf
*bp
= NULL
;
3461 sectorsize
= hfsmp
->hfs_logical_block_size
;
3462 retval
= (int)buf_bread(hfsmp
->hfs_devvp
, (daddr64_t
)HFS_PRI_SECTOR(sectorsize
), sectorsize
, NOCRED
, &bp
);
3469 lck_mtx_lock(&hfsmp
->hfs_mutex
);
3471 mdb
= (HFSMasterDirectoryBlock
*)(buf_dataptr(bp
) + HFS_PRI_OFFSET(sectorsize
));
3473 mdb
->drCrDate
= SWAP_BE32 (UTCToLocal(to_hfs_time(vcb
->hfs_itime
)));
3474 mdb
->drLsMod
= SWAP_BE32 (UTCToLocal(to_hfs_time(vcb
->vcbLsMod
)));
3475 mdb
->drAtrb
= SWAP_BE16 (vcb
->vcbAtrb
);
3476 mdb
->drNmFls
= SWAP_BE16 (vcb
->vcbNmFls
);
3477 mdb
->drAllocPtr
= SWAP_BE16 (vcb
->nextAllocation
);
3478 mdb
->drClpSiz
= SWAP_BE32 (vcb
->vcbClpSiz
);
3479 mdb
->drNxtCNID
= SWAP_BE32 (vcb
->vcbNxtCNID
);
3480 mdb
->drFreeBks
= SWAP_BE16 (vcb
->freeBlocks
);
3482 namelen
= strlen((char *)vcb
->vcbVN
);
3483 retval
= utf8_to_hfs(vcb
, namelen
, vcb
->vcbVN
, mdb
->drVN
);
3484 /* Retry with MacRoman in case that's how it was exported. */
3486 retval
= utf8_to_mac_roman(namelen
, vcb
->vcbVN
, mdb
->drVN
);
3488 mdb
->drVolBkUp
= SWAP_BE32 (UTCToLocal(to_hfs_time(vcb
->vcbVolBkUp
)));
3489 mdb
->drWrCnt
= SWAP_BE32 (vcb
->vcbWrCnt
);
3490 mdb
->drNmRtDirs
= SWAP_BE16 (vcb
->vcbNmRtDirs
);
3491 mdb
->drFilCnt
= SWAP_BE32 (vcb
->vcbFilCnt
);
3492 mdb
->drDirCnt
= SWAP_BE32 (vcb
->vcbDirCnt
);
3494 bcopy(vcb
->vcbFndrInfo
, mdb
->drFndrInfo
, sizeof(mdb
->drFndrInfo
));
3496 fp
= VTOF(vcb
->extentsRefNum
);
3497 mdb
->drXTExtRec
[0].startBlock
= SWAP_BE16 (fp
->ff_extents
[0].startBlock
);
3498 mdb
->drXTExtRec
[0].blockCount
= SWAP_BE16 (fp
->ff_extents
[0].blockCount
);
3499 mdb
->drXTExtRec
[1].startBlock
= SWAP_BE16 (fp
->ff_extents
[1].startBlock
);
3500 mdb
->drXTExtRec
[1].blockCount
= SWAP_BE16 (fp
->ff_extents
[1].blockCount
);
3501 mdb
->drXTExtRec
[2].startBlock
= SWAP_BE16 (fp
->ff_extents
[2].startBlock
);
3502 mdb
->drXTExtRec
[2].blockCount
= SWAP_BE16 (fp
->ff_extents
[2].blockCount
);
3503 mdb
->drXTFlSize
= SWAP_BE32 (fp
->ff_blocks
* vcb
->blockSize
);
3504 mdb
->drXTClpSiz
= SWAP_BE32 (fp
->ff_clumpsize
);
3505 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3507 fp
= VTOF(vcb
->catalogRefNum
);
3508 mdb
->drCTExtRec
[0].startBlock
= SWAP_BE16 (fp
->ff_extents
[0].startBlock
);
3509 mdb
->drCTExtRec
[0].blockCount
= SWAP_BE16 (fp
->ff_extents
[0].blockCount
);
3510 mdb
->drCTExtRec
[1].startBlock
= SWAP_BE16 (fp
->ff_extents
[1].startBlock
);
3511 mdb
->drCTExtRec
[1].blockCount
= SWAP_BE16 (fp
->ff_extents
[1].blockCount
);
3512 mdb
->drCTExtRec
[2].startBlock
= SWAP_BE16 (fp
->ff_extents
[2].startBlock
);
3513 mdb
->drCTExtRec
[2].blockCount
= SWAP_BE16 (fp
->ff_extents
[2].blockCount
);
3514 mdb
->drCTFlSize
= SWAP_BE32 (fp
->ff_blocks
* vcb
->blockSize
);
3515 mdb
->drCTClpSiz
= SWAP_BE32 (fp
->ff_clumpsize
);
3516 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3518 MarkVCBClean( vcb
);
3520 lck_mtx_unlock(&hfsmp
->hfs_mutex
);
3522 /* If requested, flush out the alternate MDB */
3524 struct buf
*alt_bp
= NULL
;
3526 if (buf_meta_bread(hfsmp
->hfs_devvp
, hfsmp
->hfs_alt_id_sector
, sectorsize
, NOCRED
, &alt_bp
) == 0) {
3527 bcopy(mdb
, (char *)buf_dataptr(alt_bp
) + HFS_ALT_OFFSET(sectorsize
), kMDBSize
);
3529 (void) VNOP_BWRITE(alt_bp
);
3534 if (waitfor
!= MNT_WAIT
)
3537 retval
= VNOP_BWRITE(bp
);
3543 * Flush any dirty in-memory mount data to the on-disk
3546 * Note: the on-disk volume signature is intentionally
3547 * not flushed since the on-disk "H+" and "HX" signatures
3548 * are always stored in-memory as "H+".
3551 hfs_flushvolumeheader(struct hfsmount
*hfsmp
, int waitfor
, int altflush
)
3553 ExtendedVCB
*vcb
= HFSTOVCB(hfsmp
);
3554 struct filefork
*fp
;
3555 HFSPlusVolumeHeader
*volumeHeader
, *altVH
;
3557 struct buf
*bp
, *alt_bp
;
3559 daddr64_t priIDSector
;
3561 u_int16_t signature
;
3562 u_int16_t hfsversion
;
3564 if (hfsmp
->hfs_flags
& HFS_READ_ONLY
) {
3567 if (hfsmp
->hfs_flags
& HFS_STANDARD
) {
3568 return hfs_flushMDB(hfsmp
, waitfor
, altflush
);
3570 critical
= altflush
;
3571 priIDSector
= (daddr64_t
)((vcb
->hfsPlusIOPosOffset
/ hfsmp
->hfs_logical_block_size
) +
3572 HFS_PRI_SECTOR(hfsmp
->hfs_logical_block_size
));
3574 if (hfs_start_transaction(hfsmp
) != 0) {
3581 retval
= (int)buf_meta_bread(hfsmp
->hfs_devvp
,
3582 HFS_PHYSBLK_ROUNDDOWN(priIDSector
, hfsmp
->hfs_log_per_phys
),
3583 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
);
3585 printf("hfs: err %d reading VH blk (%s)\n", retval
, vcb
->vcbVN
);
3589 volumeHeader
= (HFSPlusVolumeHeader
*)((char *)buf_dataptr(bp
) +
3590 HFS_PRI_OFFSET(hfsmp
->hfs_physical_block_size
));
3593 * Sanity check what we just read. If it's bad, try the alternate
3596 signature
= SWAP_BE16 (volumeHeader
->signature
);
3597 hfsversion
= SWAP_BE16 (volumeHeader
->version
);
3598 if ((signature
!= kHFSPlusSigWord
&& signature
!= kHFSXSigWord
) ||
3599 (hfsversion
< kHFSPlusVersion
) || (hfsversion
> 100) ||
3600 (SWAP_BE32 (volumeHeader
->blockSize
) != vcb
->blockSize
)) {
3601 printf("hfs: corrupt VH on %s, sig 0x%04x, ver %d, blksize %d%s\n",
3602 vcb
->vcbVN
, signature
, hfsversion
,
3603 SWAP_BE32 (volumeHeader
->blockSize
),
3604 hfsmp
->hfs_alt_id_sector
? "; trying alternate" : "");
3605 hfs_mark_volume_inconsistent(hfsmp
);
3607 if (hfsmp
->hfs_alt_id_sector
) {
3608 retval
= buf_meta_bread(hfsmp
->hfs_devvp
,
3609 HFS_PHYSBLK_ROUNDDOWN(hfsmp
->hfs_alt_id_sector
, hfsmp
->hfs_log_per_phys
),
3610 hfsmp
->hfs_physical_block_size
, NOCRED
, &alt_bp
);
3612 printf("hfs: err %d reading alternate VH (%s)\n", retval
, vcb
->vcbVN
);
3616 altVH
= (HFSPlusVolumeHeader
*)((char *)buf_dataptr(alt_bp
) +
3617 HFS_ALT_OFFSET(hfsmp
->hfs_physical_block_size
));
3618 signature
= SWAP_BE16(altVH
->signature
);
3619 hfsversion
= SWAP_BE16(altVH
->version
);
3621 if ((signature
!= kHFSPlusSigWord
&& signature
!= kHFSXSigWord
) ||
3622 (hfsversion
< kHFSPlusVersion
) || (kHFSPlusVersion
> 100) ||
3623 (SWAP_BE32(altVH
->blockSize
) != vcb
->blockSize
)) {
3624 printf("hfs: corrupt alternate VH on %s, sig 0x%04x, ver %d, blksize %d\n",
3625 vcb
->vcbVN
, signature
, hfsversion
,
3626 SWAP_BE32(altVH
->blockSize
));
3631 /* The alternate is plausible, so use it. */
3632 bcopy(altVH
, volumeHeader
, kMDBSize
);
3636 /* No alternate VH, nothing more we can do. */
3643 journal_modify_block_start(hfsmp
->jnl
, bp
);
3647 * For embedded HFS+ volumes, update create date if it changed
3648 * (ie from a setattrlist call)
3650 if ((vcb
->hfsPlusIOPosOffset
!= 0) &&
3651 (SWAP_BE32 (volumeHeader
->createDate
) != vcb
->localCreateDate
)) {
3653 HFSMasterDirectoryBlock
*mdb
;
3655 retval
= (int)buf_meta_bread(hfsmp
->hfs_devvp
,
3656 HFS_PHYSBLK_ROUNDDOWN(HFS_PRI_SECTOR(hfsmp
->hfs_logical_block_size
), hfsmp
->hfs_log_per_phys
),
3657 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp2
);
3663 mdb
= (HFSMasterDirectoryBlock
*)(buf_dataptr(bp2
) +
3664 HFS_PRI_OFFSET(hfsmp
->hfs_physical_block_size
));
3666 if ( SWAP_BE32 (mdb
->drCrDate
) != vcb
->localCreateDate
)
3669 journal_modify_block_start(hfsmp
->jnl
, bp2
);
3672 mdb
->drCrDate
= SWAP_BE32 (vcb
->localCreateDate
); /* pick up the new create date */
3675 journal_modify_block_end(hfsmp
->jnl
, bp2
, NULL
, NULL
);
3677 (void) VNOP_BWRITE(bp2
); /* write out the changes */
3682 buf_brelse(bp2
); /* just release it */
3687 lck_mtx_lock(&hfsmp
->hfs_mutex
);
3689 /* Note: only update the lower 16 bits worth of attributes */
3690 volumeHeader
->attributes
= SWAP_BE32 (vcb
->vcbAtrb
);
3691 volumeHeader
->journalInfoBlock
= SWAP_BE32 (vcb
->vcbJinfoBlock
);
3693 volumeHeader
->lastMountedVersion
= SWAP_BE32 (kHFSJMountVersion
);
3695 volumeHeader
->lastMountedVersion
= SWAP_BE32 (kHFSPlusMountVersion
);
3697 volumeHeader
->createDate
= SWAP_BE32 (vcb
->localCreateDate
); /* volume create date is in local time */
3698 volumeHeader
->modifyDate
= SWAP_BE32 (to_hfs_time(vcb
->vcbLsMod
));
3699 volumeHeader
->backupDate
= SWAP_BE32 (to_hfs_time(vcb
->vcbVolBkUp
));
3700 volumeHeader
->fileCount
= SWAP_BE32 (vcb
->vcbFilCnt
);
3701 volumeHeader
->folderCount
= SWAP_BE32 (vcb
->vcbDirCnt
);
3702 volumeHeader
->totalBlocks
= SWAP_BE32 (vcb
->totalBlocks
);
3703 volumeHeader
->freeBlocks
= SWAP_BE32 (vcb
->freeBlocks
);
3704 volumeHeader
->nextAllocation
= SWAP_BE32 (vcb
->nextAllocation
);
3705 volumeHeader
->rsrcClumpSize
= SWAP_BE32 (vcb
->vcbClpSiz
);
3706 volumeHeader
->dataClumpSize
= SWAP_BE32 (vcb
->vcbClpSiz
);
3707 volumeHeader
->nextCatalogID
= SWAP_BE32 (vcb
->vcbNxtCNID
);
3708 volumeHeader
->writeCount
= SWAP_BE32 (vcb
->vcbWrCnt
);
3709 volumeHeader
->encodingsBitmap
= SWAP_BE64 (vcb
->encodingsBitmap
);
3711 if (bcmp(vcb
->vcbFndrInfo
, volumeHeader
->finderInfo
, sizeof(volumeHeader
->finderInfo
)) != 0) {
3712 bcopy(vcb
->vcbFndrInfo
, volumeHeader
->finderInfo
, sizeof(volumeHeader
->finderInfo
));
3717 * System files are only dirty when altflush is set.
3719 if (altflush
== 0) {
3723 /* Sync Extents over-flow file meta data */
3724 fp
= VTOF(vcb
->extentsRefNum
);
3725 if (FTOC(fp
)->c_flag
& C_MODIFIED
) {
3726 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
3727 volumeHeader
->extentsFile
.extents
[i
].startBlock
=
3728 SWAP_BE32 (fp
->ff_extents
[i
].startBlock
);
3729 volumeHeader
->extentsFile
.extents
[i
].blockCount
=
3730 SWAP_BE32 (fp
->ff_extents
[i
].blockCount
);
3732 volumeHeader
->extentsFile
.logicalSize
= SWAP_BE64 (fp
->ff_size
);
3733 volumeHeader
->extentsFile
.totalBlocks
= SWAP_BE32 (fp
->ff_blocks
);
3734 volumeHeader
->extentsFile
.clumpSize
= SWAP_BE32 (fp
->ff_clumpsize
);
3735 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3738 /* Sync Catalog file meta data */
3739 fp
= VTOF(vcb
->catalogRefNum
);
3740 if (FTOC(fp
)->c_flag
& C_MODIFIED
) {
3741 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
3742 volumeHeader
->catalogFile
.extents
[i
].startBlock
=
3743 SWAP_BE32 (fp
->ff_extents
[i
].startBlock
);
3744 volumeHeader
->catalogFile
.extents
[i
].blockCount
=
3745 SWAP_BE32 (fp
->ff_extents
[i
].blockCount
);
3747 volumeHeader
->catalogFile
.logicalSize
= SWAP_BE64 (fp
->ff_size
);
3748 volumeHeader
->catalogFile
.totalBlocks
= SWAP_BE32 (fp
->ff_blocks
);
3749 volumeHeader
->catalogFile
.clumpSize
= SWAP_BE32 (fp
->ff_clumpsize
);
3750 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3753 /* Sync Allocation file meta data */
3754 fp
= VTOF(vcb
->allocationsRefNum
);
3755 if (FTOC(fp
)->c_flag
& C_MODIFIED
) {
3756 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
3757 volumeHeader
->allocationFile
.extents
[i
].startBlock
=
3758 SWAP_BE32 (fp
->ff_extents
[i
].startBlock
);
3759 volumeHeader
->allocationFile
.extents
[i
].blockCount
=
3760 SWAP_BE32 (fp
->ff_extents
[i
].blockCount
);
3762 volumeHeader
->allocationFile
.logicalSize
= SWAP_BE64 (fp
->ff_size
);
3763 volumeHeader
->allocationFile
.totalBlocks
= SWAP_BE32 (fp
->ff_blocks
);
3764 volumeHeader
->allocationFile
.clumpSize
= SWAP_BE32 (fp
->ff_clumpsize
);
3765 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3768 /* Sync Attribute file meta data */
3769 if (hfsmp
->hfs_attribute_vp
) {
3770 fp
= VTOF(hfsmp
->hfs_attribute_vp
);
3771 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
3772 volumeHeader
->attributesFile
.extents
[i
].startBlock
=
3773 SWAP_BE32 (fp
->ff_extents
[i
].startBlock
);
3774 volumeHeader
->attributesFile
.extents
[i
].blockCount
=
3775 SWAP_BE32 (fp
->ff_extents
[i
].blockCount
);
3777 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3778 volumeHeader
->attributesFile
.logicalSize
= SWAP_BE64 (fp
->ff_size
);
3779 volumeHeader
->attributesFile
.totalBlocks
= SWAP_BE32 (fp
->ff_blocks
);
3780 volumeHeader
->attributesFile
.clumpSize
= SWAP_BE32 (fp
->ff_clumpsize
);
3783 /* Sync Startup file meta data */
3784 if (hfsmp
->hfs_startup_vp
) {
3785 fp
= VTOF(hfsmp
->hfs_startup_vp
);
3786 if (FTOC(fp
)->c_flag
& C_MODIFIED
) {
3787 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
3788 volumeHeader
->startupFile
.extents
[i
].startBlock
=
3789 SWAP_BE32 (fp
->ff_extents
[i
].startBlock
);
3790 volumeHeader
->startupFile
.extents
[i
].blockCount
=
3791 SWAP_BE32 (fp
->ff_extents
[i
].blockCount
);
3793 volumeHeader
->startupFile
.logicalSize
= SWAP_BE64 (fp
->ff_size
);
3794 volumeHeader
->startupFile
.totalBlocks
= SWAP_BE32 (fp
->ff_blocks
);
3795 volumeHeader
->startupFile
.clumpSize
= SWAP_BE32 (fp
->ff_clumpsize
);
3796 FTOC(fp
)->c_flag
&= ~C_MODIFIED
;
3801 MarkVCBClean(hfsmp
);
3802 lck_mtx_unlock(&hfsmp
->hfs_mutex
);
3804 /* If requested, flush out the alternate volume header */
3805 if (altflush
&& hfsmp
->hfs_alt_id_sector
) {
3806 if (buf_meta_bread(hfsmp
->hfs_devvp
,
3807 HFS_PHYSBLK_ROUNDDOWN(hfsmp
->hfs_alt_id_sector
, hfsmp
->hfs_log_per_phys
),
3808 hfsmp
->hfs_physical_block_size
, NOCRED
, &alt_bp
) == 0) {
3810 journal_modify_block_start(hfsmp
->jnl
, alt_bp
);
3813 bcopy(volumeHeader
, (char *)buf_dataptr(alt_bp
) +
3814 HFS_ALT_OFFSET(hfsmp
->hfs_physical_block_size
),
3818 journal_modify_block_end(hfsmp
->jnl
, alt_bp
, NULL
, NULL
);
3820 (void) VNOP_BWRITE(alt_bp
);
3827 journal_modify_block_end(hfsmp
->jnl
, bp
, NULL
, NULL
);
3829 if (waitfor
!= MNT_WAIT
)
3832 retval
= VNOP_BWRITE(bp
);
3833 /* When critical data changes, flush the device cache */
3834 if (critical
&& (retval
== 0)) {
3835 (void) VNOP_IOCTL(hfsmp
->hfs_devvp
, DKIOCSYNCHRONIZECACHE
,
3836 NULL
, FWRITE
, NULL
);
3840 hfs_end_transaction(hfsmp
);
3849 hfs_end_transaction(hfsmp
);
3855 * Extend a file system.
3858 hfs_extendfs(struct hfsmount
*hfsmp
, u_int64_t newsize
, vfs_context_t context
)
3860 struct proc
*p
= vfs_context_proc(context
);
3861 kauth_cred_t cred
= vfs_context_ucred(context
);
3863 struct vnode
*devvp
;
3865 struct filefork
*fp
= NULL
;
3867 struct cat_fork forkdata
;
3869 u_int64_t newblkcnt
;
3870 u_int64_t prev_phys_block_count
;
3872 u_int64_t sectorcnt
;
3873 u_int32_t sectorsize
;
3874 u_int32_t phys_sectorsize
;
3875 daddr64_t prev_alt_sector
;
3879 int64_t oldBitmapSize
;
3880 Boolean usedExtendFileC
= false;
3881 int transaction_begun
= 0;
3883 devvp
= hfsmp
->hfs_devvp
;
3884 vcb
= HFSTOVCB(hfsmp
);
3887 * - HFS Plus file systems only.
3888 * - Journaling must be enabled.
3889 * - No embedded volumes.
3891 if ((vcb
->vcbSigWord
== kHFSSigWord
) ||
3892 (hfsmp
->jnl
== NULL
) ||
3893 (vcb
->hfsPlusIOPosOffset
!= 0)) {
3897 * If extending file system by non-root, then verify
3898 * ownership and check permissions.
3900 if (suser(cred
, NULL
)) {
3901 error
= hfs_vget(hfsmp
, kHFSRootFolderID
, &vp
, 0, 0);
3905 error
= hfs_owner_rights(hfsmp
, VTOC(vp
)->c_uid
, cred
, p
, 0);
3907 error
= hfs_write_access(vp
, cred
, p
, false);
3909 hfs_unlock(VTOC(vp
));
3914 error
= vnode_authorize(devvp
, NULL
, KAUTH_VNODE_READ_DATA
| KAUTH_VNODE_WRITE_DATA
, context
);
3918 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKSIZE
, (caddr_t
)§orsize
, 0, context
)) {
3921 if (sectorsize
!= hfsmp
->hfs_logical_block_size
) {
3924 if (VNOP_IOCTL(devvp
, DKIOCGETBLOCKCOUNT
, (caddr_t
)§orcnt
, 0, context
)) {
3927 if ((sectorsize
* sectorcnt
) < newsize
) {
3928 printf("hfs_extendfs: not enough space on device\n");
3931 error
= VNOP_IOCTL(devvp
, DKIOCGETPHYSICALBLOCKSIZE
, (caddr_t
)&phys_sectorsize
, 0, context
);
3933 if ((error
!= ENOTSUP
) && (error
!= ENOTTY
)) {
3936 /* If ioctl is not supported, force physical and logical sector size to be same */
3937 phys_sectorsize
= sectorsize
;
3939 oldsize
= (u_int64_t
)hfsmp
->totalBlocks
* (u_int64_t
)hfsmp
->blockSize
;
3942 * Validate new size.
3944 if ((newsize
<= oldsize
) || (newsize
% sectorsize
) || (newsize
% phys_sectorsize
)) {
3945 printf("hfs_extendfs: invalid size\n");
3948 newblkcnt
= newsize
/ vcb
->blockSize
;
3949 if (newblkcnt
> (u_int64_t
)0xFFFFFFFF)
3952 addblks
= newblkcnt
- vcb
->totalBlocks
;
3954 if (hfs_resize_debug
) {
3955 printf ("hfs_extendfs: old: size=%qu, blkcnt=%u\n", oldsize
, hfsmp
->totalBlocks
);
3956 printf ("hfs_extendfs: new: size=%qu, blkcnt=%u, addblks=%u\n", newsize
, (u_int32_t
)newblkcnt
, addblks
);
3958 printf("hfs_extendfs: will extend \"%s\" by %d blocks\n", vcb
->vcbVN
, addblks
);
3960 HFS_MOUNT_LOCK(hfsmp
, TRUE
);
3961 if (hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) {
3962 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
3966 hfsmp
->hfs_flags
|= HFS_RESIZE_IN_PROGRESS
;
3967 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
3970 * Enclose changes inside a transaction.
3972 if (hfs_start_transaction(hfsmp
) != 0) {
3976 transaction_begun
= 1;
3979 * Note: we take the attributes lock in case we have an attribute data vnode
3980 * which needs to change size.
3982 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
| SFL_EXTENTS
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
3983 vp
= vcb
->allocationsRefNum
;
3985 bcopy(&fp
->ff_data
, &forkdata
, sizeof(forkdata
));
3988 * Calculate additional space required (if any) by allocation bitmap.
3990 oldBitmapSize
= fp
->ff_size
;
3991 bitmapblks
= roundup((newblkcnt
+7) / 8, vcb
->vcbVBMIOSize
) / vcb
->blockSize
;
3992 if (bitmapblks
> (daddr_t
)fp
->ff_blocks
)
3993 bitmapblks
-= fp
->ff_blocks
;
3998 * The allocation bitmap can contain unused bits that are beyond end of
3999 * current volume's allocation blocks. Usually they are supposed to be
4000 * zero'ed out but there can be cases where they might be marked as used.
4001 * After extending the file system, those bits can represent valid
4002 * allocation blocks, so we mark all the bits from the end of current
4003 * volume to end of allocation bitmap as "free".
4005 BlockMarkFreeUnused(vcb
, vcb
->totalBlocks
,
4006 (fp
->ff_blocks
* vcb
->blockSize
* 8) - vcb
->totalBlocks
);
4008 if (bitmapblks
> 0) {
4014 * Get the bitmap's current size (in allocation blocks) so we know
4015 * where to start zero filling once the new space is added. We've
4016 * got to do this before the bitmap is grown.
4018 blkno
= (daddr64_t
)fp
->ff_blocks
;
4021 * Try to grow the allocation file in the normal way, using allocation
4022 * blocks already existing in the file system. This way, we might be
4023 * able to grow the bitmap contiguously, or at least in the metadata
4026 error
= ExtendFileC(vcb
, fp
, bitmapblks
* vcb
->blockSize
, 0,
4027 kEFAllMask
| kEFNoClumpMask
| kEFReserveMask
4028 | kEFMetadataMask
| kEFContigMask
, &bytesAdded
);
4031 usedExtendFileC
= true;
4034 * If the above allocation failed, fall back to allocating the new
4035 * extent of the bitmap from the space we're going to add. Since those
4036 * blocks don't yet belong to the file system, we have to update the
4037 * extent list directly, and manually adjust the file size.
4040 error
= AddFileExtent(vcb
, fp
, vcb
->totalBlocks
, bitmapblks
);
4042 printf("hfs_extendfs: error %d adding extents\n", error
);
4045 fp
->ff_blocks
+= bitmapblks
;
4046 VTOC(vp
)->c_blocks
= fp
->ff_blocks
;
4047 VTOC(vp
)->c_flag
|= C_MODIFIED
;
4051 * Update the allocation file's size to include the newly allocated
4052 * blocks. Note that ExtendFileC doesn't do this, which is why this
4053 * statement is outside the above "if" statement.
4055 fp
->ff_size
+= (u_int64_t
)bitmapblks
* (u_int64_t
)vcb
->blockSize
;
4058 * Zero out the new bitmap blocks.
4063 blkcnt
= bitmapblks
;
4064 while (blkcnt
> 0) {
4065 error
= (int)buf_meta_bread(vp
, blkno
, vcb
->blockSize
, NOCRED
, &bp
);
4072 bzero((char *)buf_dataptr(bp
), vcb
->blockSize
);
4074 error
= (int)buf_bwrite(bp
);
4082 printf("hfs_extendfs: error %d clearing blocks\n", error
);
4086 * Mark the new bitmap space as allocated.
4088 * Note that ExtendFileC will have marked any blocks it allocated, so
4089 * this is only needed if we used AddFileExtent. Also note that this
4090 * has to come *after* the zero filling of new blocks in the case where
4091 * we used AddFileExtent (since the part of the bitmap we're touching
4092 * is in those newly allocated blocks).
4094 if (!usedExtendFileC
) {
4095 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
, bitmapblks
);
4097 printf("hfs_extendfs: error %d setting bitmap\n", error
);
4100 vcb
->freeBlocks
-= bitmapblks
;
4104 * Mark the new alternate VH as allocated.
4106 if (vcb
->blockSize
== 512)
4107 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
+ addblks
- 2, 2);
4109 error
= BlockMarkAllocated(vcb
, vcb
->totalBlocks
+ addblks
- 1, 1);
4111 printf("hfs_extendfs: error %d setting bitmap (VH)\n", error
);
4115 * Mark the old alternate VH as free.
4117 if (vcb
->blockSize
== 512)
4118 (void) BlockMarkFree(vcb
, vcb
->totalBlocks
- 2, 2);
4120 (void) BlockMarkFree(vcb
, vcb
->totalBlocks
- 1, 1);
4122 * Adjust file system variables for new space.
4124 prev_phys_block_count
= hfsmp
->hfs_logical_block_count
;
4125 prev_alt_sector
= hfsmp
->hfs_alt_id_sector
;
4127 vcb
->totalBlocks
+= addblks
;
4128 vcb
->freeBlocks
+= addblks
;
4129 hfsmp
->hfs_logical_block_count
= newsize
/ sectorsize
;
4130 hfsmp
->hfs_alt_id_sector
= (hfsmp
->hfsPlusIOPosOffset
/ sectorsize
) +
4131 HFS_ALT_SECTOR(sectorsize
, hfsmp
->hfs_logical_block_count
);
4133 error
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, HFS_ALTFLUSH
);
4135 printf("hfs_extendfs: couldn't flush volume headers (%d)", error
);
4137 * Restore to old state.
4139 if (usedExtendFileC
) {
4140 (void) TruncateFileC(vcb
, fp
, oldBitmapSize
, 0, FORK_IS_RSRC(fp
),
4141 FTOC(fp
)->c_fileid
, false);
4143 fp
->ff_blocks
-= bitmapblks
;
4144 fp
->ff_size
-= (u_int64_t
)bitmapblks
* (u_int64_t
)vcb
->blockSize
;
4146 * No need to mark the excess blocks free since those bitmap blocks
4147 * are no longer part of the bitmap. But we do need to undo the
4148 * effect of the "vcb->freeBlocks -= bitmapblks" above.
4150 vcb
->freeBlocks
+= bitmapblks
;
4152 vcb
->totalBlocks
-= addblks
;
4153 vcb
->freeBlocks
-= addblks
;
4154 hfsmp
->hfs_logical_block_count
= prev_phys_block_count
;
4155 hfsmp
->hfs_alt_id_sector
= prev_alt_sector
;
4157 if (vcb
->blockSize
== 512) {
4158 if (BlockMarkAllocated(vcb
, vcb
->totalBlocks
- 2, 2)) {
4159 hfs_mark_volume_inconsistent(hfsmp
);
4162 if (BlockMarkAllocated(vcb
, vcb
->totalBlocks
- 1, 1)) {
4163 hfs_mark_volume_inconsistent(hfsmp
);
4169 * Invalidate the old alternate volume header.
4172 if (prev_alt_sector
) {
4173 if (buf_meta_bread(hfsmp
->hfs_devvp
,
4174 HFS_PHYSBLK_ROUNDDOWN(prev_alt_sector
, hfsmp
->hfs_log_per_phys
),
4175 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
) == 0) {
4176 journal_modify_block_start(hfsmp
->jnl
, bp
);
4178 bzero((char *)buf_dataptr(bp
) + HFS_ALT_OFFSET(hfsmp
->hfs_physical_block_size
), kMDBSize
);
4180 journal_modify_block_end(hfsmp
->jnl
, bp
, NULL
, NULL
);
4187 * Update the metadata zone size based on current volume size
4189 hfs_metadatazone_init(hfsmp
, false);
4192 * Adjust the size of hfsmp->hfs_attrdata_vp
4194 if (hfsmp
->hfs_attrdata_vp
) {
4195 struct cnode
*attr_cp
;
4196 struct filefork
*attr_fp
;
4198 if (vnode_get(hfsmp
->hfs_attrdata_vp
) == 0) {
4199 attr_cp
= VTOC(hfsmp
->hfs_attrdata_vp
);
4200 attr_fp
= VTOF(hfsmp
->hfs_attrdata_vp
);
4202 attr_cp
->c_blocks
= newblkcnt
;
4203 attr_fp
->ff_blocks
= newblkcnt
;
4204 attr_fp
->ff_extents
[0].blockCount
= newblkcnt
;
4205 attr_fp
->ff_size
= (off_t
) newblkcnt
* hfsmp
->blockSize
;
4206 ubc_setsize(hfsmp
->hfs_attrdata_vp
, attr_fp
->ff_size
);
4207 vnode_put(hfsmp
->hfs_attrdata_vp
);
4212 * Update the R/B Tree if necessary. Since we don't have to drop the systemfile
4213 * locks in the middle of these operations like we do in the truncate case
4214 * where we have to relocate files, we can only update the red-black tree
4215 * if there were actual changes made to the bitmap. Also, we can't really scan the
4216 * new portion of the bitmap before it has been allocated. The BlockMarkAllocated
4217 * routines are smart enough to avoid the r/b tree if the portion they are manipulating is
4218 * not currently controlled by the tree.
4220 * We only update hfsmp->allocLimit if totalBlocks actually increased.
4224 UpdateAllocLimit(hfsmp
, hfsmp
->totalBlocks
);
4227 /* Log successful extending */
4228 printf("hfs_extendfs: extended \"%s\" to %d blocks (was %d blocks)\n",
4229 hfsmp
->vcbVN
, hfsmp
->totalBlocks
, (u_int32_t
)(oldsize
/hfsmp
->blockSize
));
4233 /* Restore allocation fork. */
4234 bcopy(&forkdata
, &fp
->ff_data
, sizeof(forkdata
));
4235 VTOC(vp
)->c_blocks
= fp
->ff_blocks
;
4239 HFS_MOUNT_LOCK(hfsmp
, TRUE
);
4240 hfsmp
->hfs_flags
&= ~HFS_RESIZE_IN_PROGRESS
;
4241 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
4243 hfs_systemfile_unlock(hfsmp
, lockflags
);
4245 if (transaction_begun
) {
4246 hfs_end_transaction(hfsmp
);
4249 return MacToVFSError(error
);
4252 #define HFS_MIN_SIZE (32LL * 1024LL * 1024LL)
4255 * Truncate a file system (while still mounted).
4258 hfs_truncatefs(struct hfsmount
*hfsmp
, u_int64_t newsize
, vfs_context_t context
)
4260 struct buf
*bp
= NULL
;
4262 u_int32_t newblkcnt
;
4263 u_int32_t reclaimblks
= 0;
4265 int transaction_begun
= 0;
4266 Boolean updateFreeBlocks
= false;
4267 Boolean disable_sparse
= false;
4270 lck_mtx_lock(&hfsmp
->hfs_mutex
);
4271 if (hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) {
4272 lck_mtx_unlock(&hfsmp
->hfs_mutex
);
4275 hfsmp
->hfs_flags
|= HFS_RESIZE_IN_PROGRESS
;
4276 hfsmp
->hfs_resize_blocksmoved
= 0;
4277 hfsmp
->hfs_resize_totalblocks
= 0;
4278 hfsmp
->hfs_resize_progress
= 0;
4279 lck_mtx_unlock(&hfsmp
->hfs_mutex
);
4282 * - Journaled HFS Plus volumes only.
4283 * - No embedded volumes.
4285 if ((hfsmp
->jnl
== NULL
) ||
4286 (hfsmp
->hfsPlusIOPosOffset
!= 0)) {
4290 oldsize
= (u_int64_t
)hfsmp
->totalBlocks
* (u_int64_t
)hfsmp
->blockSize
;
4291 newblkcnt
= newsize
/ hfsmp
->blockSize
;
4292 reclaimblks
= hfsmp
->totalBlocks
- newblkcnt
;
4294 if (hfs_resize_debug
) {
4295 printf ("hfs_truncatefs: old: size=%qu, blkcnt=%u, freeblks=%u\n", oldsize
, hfsmp
->totalBlocks
, hfs_freeblks(hfsmp
, 1));
4296 printf ("hfs_truncatefs: new: size=%qu, blkcnt=%u, reclaimblks=%u\n", newsize
, newblkcnt
, reclaimblks
);
4299 /* Make sure new size is valid. */
4300 if ((newsize
< HFS_MIN_SIZE
) ||
4301 (newsize
>= oldsize
) ||
4302 (newsize
% hfsmp
->hfs_logical_block_size
) ||
4303 (newsize
% hfsmp
->hfs_physical_block_size
)) {
4304 printf ("hfs_truncatefs: invalid size (newsize=%qu, oldsize=%qu)\n", newsize
, oldsize
);
4310 * Make sure that the file system has enough free blocks reclaim.
4312 * Before resize, the disk is divided into four zones -
4313 * A. Allocated_Stationary - These are allocated blocks that exist
4314 * before the new end of disk. These blocks will not be
4315 * relocated or modified during resize.
4316 * B. Free_Stationary - These are free blocks that exist before the
4317 * new end of disk. These blocks can be used for any new
4318 * allocations during resize, including allocation for relocating
4319 * data from the area of disk being reclaimed.
4320 * C. Allocated_To-Reclaim - These are allocated blocks that exist
4321 * beyond the new end of disk. These blocks need to be reclaimed
4322 * during resize by allocating equal number of blocks in Free
4323 * Stationary zone and copying the data.
4324 * D. Free_To-Reclaim - These are free blocks that exist beyond the
4325 * new end of disk. Nothing special needs to be done to reclaim
4328 * Total number of blocks on the disk before resize:
4329 * ------------------------------------------------
4330 * Total Blocks = Allocated_Stationary + Free_Stationary +
4331 * Allocated_To-Reclaim + Free_To-Reclaim
4333 * Total number of blocks that need to be reclaimed:
4334 * ------------------------------------------------
4335 * Blocks to Reclaim = Allocated_To-Reclaim + Free_To-Reclaim
4337 * Note that the check below also makes sure that we have enough space
4338 * to relocate data from Allocated_To-Reclaim to Free_Stationary.
4339 * Therefore we do not need to check total number of blocks to relocate
4340 * later in the code.
4342 * The condition below gets converted to:
4344 * Allocated To-Reclaim + Free To-Reclaim >= Free Stationary + Free To-Reclaim
4346 * which is equivalent to:
4348 * Allocated To-Reclaim >= Free Stationary
4350 if (reclaimblks
>= hfs_freeblks(hfsmp
, 1)) {
4351 printf("hfs_truncatefs: insufficient space (need %u blocks; have %u free blocks)\n", reclaimblks
, hfs_freeblks(hfsmp
, 1));
4356 /* Start with a clean journal. */
4357 hfs_journal_flush(hfsmp
, TRUE
);
4359 if (hfs_start_transaction(hfsmp
) != 0) {
4363 transaction_begun
= 1;
4365 /* Take the bitmap lock to update the alloc limit field */
4366 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
4369 * Prevent new allocations from using the part we're trying to truncate.
4371 * NOTE: allocLimit is set to the allocation block number where the new
4372 * alternate volume header will be. That way there will be no files to
4373 * interfere with allocating the new alternate volume header, and no files
4374 * in the allocation blocks beyond (i.e. the blocks we're trying to
4377 * Also shrink the red-black tree if needed.
4379 if (hfsmp
->blockSize
== 512) {
4380 error
= UpdateAllocLimit (hfsmp
, newblkcnt
- 2);
4383 error
= UpdateAllocLimit (hfsmp
, newblkcnt
- 1);
4386 /* Sparse devices use first fit allocation which is not ideal
4387 * for volume resize which requires best fit allocation. If a
4388 * sparse device is being truncated, disable the sparse device
4389 * property temporarily for the duration of resize. Also reset
4390 * the free extent cache so that it is rebuilt as sorted by
4391 * totalBlocks instead of startBlock.
4393 * Note that this will affect all allocations on the volume and
4394 * ideal fix would be just to modify resize-related allocations,
4395 * but it will result in complexity like handling of two free
4396 * extent caches sorted differently, etc. So we stick to this
4399 HFS_MOUNT_LOCK(hfsmp
, TRUE
);
4400 if (hfsmp
->hfs_flags
& HFS_HAS_SPARSE_DEVICE
) {
4401 hfsmp
->hfs_flags
&= ~HFS_HAS_SPARSE_DEVICE
;
4402 ResetVCBFreeExtCache(hfsmp
);
4403 disable_sparse
= true;
4407 * Update the volume free block count to reflect the total number
4408 * of free blocks that will exist after a successful resize.
4409 * Relocation of extents will result in no net change in the total
4410 * free space on the disk. Therefore the code that allocates
4411 * space for new extent and deallocates the old extent explicitly
4412 * prevents updating the volume free block count. It will also
4413 * prevent false disk full error when the number of blocks in
4414 * an extent being relocated is more than the free blocks that
4415 * will exist after the volume is resized.
4417 hfsmp
->freeBlocks
-= reclaimblks
;
4418 updateFreeBlocks
= true;
4419 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
4422 hfs_systemfile_unlock(hfsmp
, lockflags
);
4427 * Update the metadata zone size to match the new volume size,
4428 * and if it too less, metadata zone might be disabled.
4430 hfs_metadatazone_init(hfsmp
, false);
4433 * If some files have blocks at or beyond the location of the
4434 * new alternate volume header, recalculate free blocks and
4435 * reclaim blocks. Otherwise just update free blocks count.
4437 * The current allocLimit is set to the location of new alternate
4438 * volume header, and reclaimblks are the total number of blocks
4439 * that need to be reclaimed. So the check below is really
4440 * ignoring the blocks allocated for old alternate volume header.
4442 if (hfs_isallocated(hfsmp
, hfsmp
->allocLimit
, reclaimblks
)) {
4444 * hfs_reclaimspace will use separate transactions when
4445 * relocating files (so we don't overwhelm the journal).
4447 hfs_end_transaction(hfsmp
);
4448 transaction_begun
= 0;
4450 /* Attempt to reclaim some space. */
4451 error
= hfs_reclaimspace(hfsmp
, hfsmp
->allocLimit
, reclaimblks
, context
);
4453 printf("hfs_truncatefs: couldn't reclaim space on %s (error=%d)\n", hfsmp
->vcbVN
, error
);
4457 if (hfs_start_transaction(hfsmp
) != 0) {
4461 transaction_begun
= 1;
4463 /* Check if we're clear now. */
4464 error
= hfs_isallocated(hfsmp
, hfsmp
->allocLimit
, reclaimblks
);
4466 printf("hfs_truncatefs: didn't reclaim enough space on %s (error=%d)\n", hfsmp
->vcbVN
, error
);
4467 error
= EAGAIN
; /* tell client to try again */
4473 * Note: we take the attributes lock in case we have an attribute data vnode
4474 * which needs to change size.
4476 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
| SFL_EXTENTS
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
4479 * Allocate last 1KB for alternate volume header.
4481 error
= BlockMarkAllocated(hfsmp
, hfsmp
->allocLimit
, (hfsmp
->blockSize
== 512) ? 2 : 1);
4483 printf("hfs_truncatefs: Error %d allocating new alternate volume header\n", error
);
4488 * Mark the old alternate volume header as free.
4489 * We don't bother shrinking allocation bitmap file.
4491 if (hfsmp
->blockSize
== 512)
4492 (void) BlockMarkFree(hfsmp
, hfsmp
->totalBlocks
- 2, 2);
4494 (void) BlockMarkFree(hfsmp
, hfsmp
->totalBlocks
- 1, 1);
4497 * Invalidate the existing alternate volume header.
4499 * Don't include this in a transaction (don't call journal_modify_block)
4500 * since this block will be outside of the truncated file system!
4502 if (hfsmp
->hfs_alt_id_sector
) {
4503 error
= buf_meta_bread(hfsmp
->hfs_devvp
,
4504 HFS_PHYSBLK_ROUNDDOWN(hfsmp
->hfs_alt_id_sector
, hfsmp
->hfs_log_per_phys
),
4505 hfsmp
->hfs_physical_block_size
, NOCRED
, &bp
);
4507 bzero((void*)((char *)buf_dataptr(bp
) + HFS_ALT_OFFSET(hfsmp
->hfs_physical_block_size
)), kMDBSize
);
4508 (void) VNOP_BWRITE(bp
);
4517 /* Log successful shrinking. */
4518 printf("hfs_truncatefs: shrank \"%s\" to %d blocks (was %d blocks)\n",
4519 hfsmp
->vcbVN
, newblkcnt
, hfsmp
->totalBlocks
);
4522 * Adjust file system variables and flush them to disk.
4524 hfsmp
->totalBlocks
= newblkcnt
;
4525 hfsmp
->hfs_logical_block_count
= newsize
/ hfsmp
->hfs_logical_block_size
;
4526 hfsmp
->hfs_alt_id_sector
= HFS_ALT_SECTOR(hfsmp
->hfs_logical_block_size
, hfsmp
->hfs_logical_block_count
);
4527 MarkVCBDirty(hfsmp
);
4528 error
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, HFS_ALTFLUSH
);
4530 panic("hfs_truncatefs: unexpected error flushing volume header (%d)\n", error
);
4533 * Adjust the size of hfsmp->hfs_attrdata_vp
4535 if (hfsmp
->hfs_attrdata_vp
) {
4537 struct filefork
*fp
;
4539 if (vnode_get(hfsmp
->hfs_attrdata_vp
) == 0) {
4540 cp
= VTOC(hfsmp
->hfs_attrdata_vp
);
4541 fp
= VTOF(hfsmp
->hfs_attrdata_vp
);
4543 cp
->c_blocks
= newblkcnt
;
4544 fp
->ff_blocks
= newblkcnt
;
4545 fp
->ff_extents
[0].blockCount
= newblkcnt
;
4546 fp
->ff_size
= (off_t
) newblkcnt
* hfsmp
->blockSize
;
4547 ubc_setsize(hfsmp
->hfs_attrdata_vp
, fp
->ff_size
);
4548 vnode_put(hfsmp
->hfs_attrdata_vp
);
4554 * Update the allocLimit to acknowledge the last one or two blocks now.
4555 * Add it to the tree as well if necessary.
4557 UpdateAllocLimit (hfsmp
, hfsmp
->totalBlocks
);
4559 HFS_MOUNT_LOCK(hfsmp
, TRUE
);
4560 if (disable_sparse
== true) {
4561 /* Now that resize is completed, set the volume to be sparse
4562 * device again so that all further allocations will be first
4563 * fit instead of best fit. Reset free extent cache so that
4566 hfsmp
->hfs_flags
|= HFS_HAS_SPARSE_DEVICE
;
4567 ResetVCBFreeExtCache(hfsmp
);
4570 if (error
&& (updateFreeBlocks
== true)) {
4571 hfsmp
->freeBlocks
+= reclaimblks
;
4574 if (hfsmp
->nextAllocation
>= hfsmp
->allocLimit
) {
4575 hfsmp
->nextAllocation
= hfsmp
->hfs_metazone_end
+ 1;
4577 hfsmp
->hfs_flags
&= ~HFS_RESIZE_IN_PROGRESS
;
4578 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
4580 /* On error, reset the metadata zone for original volume size */
4581 if (error
&& (updateFreeBlocks
== true)) {
4582 hfs_metadatazone_init(hfsmp
, false);
4586 hfs_systemfile_unlock(hfsmp
, lockflags
);
4588 if (transaction_begun
) {
4589 hfs_end_transaction(hfsmp
);
4590 hfs_journal_flush(hfsmp
, FALSE
);
4591 /* Just to be sure, sync all data to the disk */
4592 (void) VNOP_IOCTL(hfsmp
->hfs_devvp
, DKIOCSYNCHRONIZECACHE
, NULL
, FWRITE
, context
);
4595 return MacToVFSError(error
);
4600 * Invalidate the physical block numbers associated with buffer cache blocks
4601 * in the given extent of the given vnode.
4603 struct hfs_inval_blk_no
{
4604 daddr64_t sectorStart
;
4605 daddr64_t sectorCount
;
4608 hfs_invalidate_block_numbers_callback(buf_t bp
, void *args_in
)
4611 struct hfs_inval_blk_no
*args
;
4613 blkno
= buf_blkno(bp
);
4616 if (blkno
>= args
->sectorStart
&& blkno
< args
->sectorStart
+args
->sectorCount
)
4617 buf_setblkno(bp
, buf_lblkno(bp
));
4619 return BUF_RETURNED
;
4622 hfs_invalidate_sectors(struct vnode
*vp
, daddr64_t sectorStart
, daddr64_t sectorCount
)
4624 struct hfs_inval_blk_no args
;
4625 args
.sectorStart
= sectorStart
;
4626 args
.sectorCount
= sectorCount
;
4628 buf_iterate(vp
, hfs_invalidate_block_numbers_callback
, BUF_SCAN_DIRTY
|BUF_SCAN_CLEAN
, &args
);
4633 * Copy the contents of an extent to a new location. Also invalidates the
4634 * physical block number of any buffer cache block in the copied extent
4635 * (so that if the block is written, it will go through VNOP_BLOCKMAP to
4636 * determine the new physical block number).
4640 struct hfsmount
*hfsmp
,
4641 struct vnode
*vp
, /* The file whose extent is being copied. */
4642 u_int32_t oldStart
, /* The start of the source extent. */
4643 u_int32_t newStart
, /* The start of the destination extent. */
4644 u_int32_t blockCount
, /* The number of allocation blocks to copy. */
4645 vfs_context_t context
)
4649 void *buffer
= NULL
;
4650 struct vfsioattr ioattr
;
4654 u_int32_t ioSizeSectors
; /* Device sectors in this I/O */
4655 daddr64_t srcSector
, destSector
;
4656 u_int32_t sectorsPerBlock
= hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
4662 * Sanity check that we have locked the vnode of the file we're copying.
4664 * But since hfs_systemfile_lock() doesn't actually take the lock on
4665 * the allocation file if a journal is active, ignore the check if the
4666 * file being copied is the allocation file.
4668 struct cnode
*cp
= VTOC(vp
);
4669 if (cp
!= hfsmp
->hfs_allocation_cp
&& cp
->c_lockowner
!= current_thread())
4670 panic("hfs_copy_extent: vp=%p (cp=%p) not owned?\n", vp
, cp
);
4673 /* Prepare the CP blob and get it ready for use */
4674 if (!vnode_issystem (vp
) && vnode_isreg(vp
) &&
4675 cp_fs_protected (hfsmp
->hfs_mp
)) {
4677 cp_err
= cp_handle_relocate (cp
);
4680 * can't copy the file because we couldn't set up keys.
4692 * Determine the I/O size to use
4694 * NOTE: Many external drives will result in an ioSize of 128KB.
4695 * TODO: Should we use a larger buffer, doing several consecutive
4696 * reads, then several consecutive writes?
4698 vfs_ioattr(hfsmp
->hfs_mp
, &ioattr
);
4699 bufferSize
= MIN(ioattr
.io_maxreadcnt
, ioattr
.io_maxwritecnt
);
4700 if (kmem_alloc(kernel_map
, (vm_offset_t
*) &buffer
, bufferSize
))
4703 /* Get a buffer for doing the I/O */
4704 bp
= buf_alloc(hfsmp
->hfs_devvp
);
4705 buf_setdataptr(bp
, (uintptr_t)buffer
);
4707 resid
= (off_t
) blockCount
* (off_t
) hfsmp
->blockSize
;
4708 srcSector
= (daddr64_t
) oldStart
* hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
4709 destSector
= (daddr64_t
) newStart
* hfsmp
->blockSize
/ hfsmp
->hfs_logical_block_size
;
4711 ioSize
= MIN(bufferSize
, (size_t) resid
);
4712 ioSizeSectors
= ioSize
/ hfsmp
->hfs_logical_block_size
;
4714 /* Prepare the buffer for reading */
4715 buf_reset(bp
, B_READ
);
4716 buf_setsize(bp
, ioSize
);
4717 buf_setcount(bp
, ioSize
);
4718 buf_setblkno(bp
, srcSector
);
4719 buf_setlblkno(bp
, srcSector
);
4721 /* Attach the CP to the buffer */
4724 buf_setcpaddr (bp
, cp
->c_cpentry
);
4729 err
= VNOP_STRATEGY(bp
);
4731 err
= buf_biowait(bp
);
4733 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (read)\n", err
);
4737 /* Prepare the buffer for writing */
4738 buf_reset(bp
, B_WRITE
);
4739 buf_setsize(bp
, ioSize
);
4740 buf_setcount(bp
, ioSize
);
4741 buf_setblkno(bp
, destSector
);
4742 buf_setlblkno(bp
, destSector
);
4743 if (vnode_issystem(vp
) && journal_uses_fua(hfsmp
->jnl
))
4747 /* Attach the CP to the buffer */
4749 buf_setcpaddr (bp
, cp
->c_cpentry
);
4754 vnode_startwrite(hfsmp
->hfs_devvp
);
4755 err
= VNOP_STRATEGY(bp
);
4757 err
= buf_biowait(bp
);
4759 printf("hfs_copy_extent: Error %d from VNOP_STRATEGY (write)\n", err
);
4764 srcSector
+= ioSizeSectors
;
4765 destSector
+= ioSizeSectors
;
4770 kmem_free(kernel_map
, (vm_offset_t
)buffer
, bufferSize
);
4772 /* Make sure all writes have been flushed to disk. */
4773 if (vnode_issystem(vp
) && !journal_uses_fua(hfsmp
->jnl
)) {
4774 err
= VNOP_IOCTL(hfsmp
->hfs_devvp
, DKIOCSYNCHRONIZECACHE
, NULL
, FWRITE
, context
);
4776 printf("hfs_copy_extent: DKIOCSYNCHRONIZECACHE failed (%d)\n", err
);
4777 err
= 0; /* Don't fail the copy. */
4782 hfs_invalidate_sectors(vp
, (daddr64_t
)oldStart
*sectorsPerBlock
, (daddr64_t
)blockCount
*sectorsPerBlock
);
4788 /* Structure to store state of reclaiming extents from a
4789 * given file. hfs_reclaim_file()/hfs_reclaim_xattr()
4790 * initializes the values in this structure which are then
4791 * used by code that reclaims and splits the extents.
4793 struct hfs_reclaim_extent_info
{
4797 u_int8_t is_dirlink
; /* Extent belongs to directory hard link */
4798 u_int8_t is_sysfile
; /* Extent belongs to system file */
4799 u_int8_t is_xattr
; /* Extent belongs to extent-based xattr */
4800 u_int8_t extent_index
;
4801 int lockflags
; /* Locks that reclaim and split code should grab before modifying the extent record */
4802 u_int32_t blocks_relocated
; /* Total blocks relocated for this file till now */
4803 u_int32_t recStartBlock
; /* File allocation block number (FABN) for current extent record */
4804 u_int32_t cur_blockCount
; /* Number of allocation blocks that have been checked for reclaim */
4805 struct filefork
*catalog_fp
; /* If non-NULL, extent is from catalog record */
4807 HFSPlusExtentRecord overflow
;/* Extent record from overflow extents btree */
4808 HFSPlusAttrRecord xattr
; /* Attribute record for large EAs */
4810 HFSPlusExtentDescriptor
*extents
; /* Pointer to current extent record being processed.
4811 * For catalog extent record, points to the correct
4812 * extent information in filefork. For overflow extent
4813 * record, or xattr record, points to extent record
4814 * in the structure above
4816 struct cat_desc
*dirlink_desc
;
4817 struct cat_attr
*dirlink_attr
;
4818 struct filefork
*dirlink_fork
; /* For directory hard links, fp points actually to this */
4819 struct BTreeIterator
*iterator
; /* Shared read/write iterator, hfs_reclaim_file/xattr()
4820 * use it for reading and hfs_reclaim_extent()/hfs_split_extent()
4821 * use it for writing updated extent record
4823 struct FSBufferDescriptor btdata
; /* Shared btdata for reading/writing extent record, same as iterator above */
4824 u_int16_t recordlen
;
4825 int overflow_count
; /* For debugging, counter for overflow extent record */
4826 FCB
*fcb
; /* Pointer to the current btree being traversed */
4830 * Split the current extent into two extents, with first extent
4831 * to contain given number of allocation blocks. Splitting of
4832 * extent creates one new extent entry which can result in
4833 * shifting of many entries through all the extent records of a
4834 * file, and/or creating a new extent record in the overflow
4838 * The diagram below represents two consecutive extent records,
4839 * for simplicity, lets call them record X and X+1 respectively.
4840 * Interesting extent entries have been denoted by letters.
4841 * If the letter is unchanged before and after split, it means
4842 * that the extent entry was not modified during the split.
4843 * A '.' means that the entry remains unchanged after the split
4844 * and is not relevant for our example. A '0' means that the
4845 * extent entry is empty.
4847 * If there isn't sufficient contiguous free space to relocate
4848 * an extent (extent "C" below), we will have to break the one
4849 * extent into multiple smaller extents, and relocate each of
4850 * the smaller extents individually. The way we do this is by
4851 * finding the largest contiguous free space that is currently
4852 * available (N allocation blocks), and then convert extent "C"
4853 * into two extents, C1 and C2, that occupy exactly the same
4854 * allocation blocks as extent C. Extent C1 is the first
4855 * N allocation blocks of extent C, and extent C2 is the remainder
4856 * of extent C. Then we can relocate extent C1 since we know
4857 * we have enough contiguous free space to relocate it in its
4858 * entirety. We then repeat the process starting with extent C2.
4860 * In record X, only the entries following entry C are shifted, and
4861 * the original entry C is replaced with two entries C1 and C2 which
4862 * are actually two extent entries for contiguous allocation blocks.
4864 * Note that the entry E from record X is shifted into record X+1 as
4865 * the new first entry. Since the first entry of record X+1 is updated,
4866 * the FABN will also get updated with the blockCount of entry E.
4867 * This also results in shifting of all extent entries in record X+1.
4868 * Note that the number of empty entries after the split has been
4869 * changed from 3 to 2.
4872 * record X record X+1
4873 * ---------------------===--------- ---------------------------------
4874 * | A | . | . | . | B | C | D | E | | F | . | . | . | G | 0 | 0 | 0 |
4875 * ---------------------===--------- ---------------------------------
4878 * ---------------------=======----- ---------------------------------
4879 * | A | . | . | . | B | C1| C2| D | | E | F | . | . | . | G | 0 | 0 |
4880 * ---------------------=======----- ---------------------------------
4882 * C1.startBlock = C.startBlock
4885 * C2.startBlock = C.startBlock + N
4886 * C2.blockCount = C.blockCount - N
4888 * FABN = old FABN - E.blockCount
4891 * extent_info - This is the structure that contains state about
4892 * the current file, extent, and extent record that
4893 * is being relocated. This structure is shared
4894 * among code that traverses through all the extents
4895 * of the file, code that relocates extents, and
4896 * code that splits the extent.
4898 * Zero on success, non-zero on failure.
4901 hfs_split_extent(struct hfs_reclaim_extent_info
*extent_info
, uint32_t newBlockCount
)
4904 int index
= extent_info
->extent_index
;
4906 HFSPlusExtentDescriptor shift_extent
;
4907 HFSPlusExtentDescriptor last_extent
;
4908 HFSPlusExtentDescriptor
*extents
; /* Pointer to current extent record being manipulated */
4909 HFSPlusExtentRecord
*extents_rec
= NULL
;
4910 HFSPlusExtentKey
*extents_key
= NULL
;
4911 HFSPlusAttrRecord
*xattr_rec
= NULL
;
4912 HFSPlusAttrKey
*xattr_key
= NULL
;
4913 struct BTreeIterator iterator
;
4914 struct FSBufferDescriptor btdata
;
4916 uint32_t read_recStartBlock
; /* Starting allocation block number to read old extent record */
4917 uint32_t write_recStartBlock
; /* Starting allocation block number to insert newly updated extent record */
4918 Boolean create_record
= false;
4921 is_xattr
= extent_info
->is_xattr
;
4922 extents
= extent_info
->extents
;
4924 if (hfs_resize_debug
) {
4925 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
);
4928 /* Determine the starting allocation block number for the following
4929 * overflow extent record, if any, before the current record
4932 read_recStartBlock
= extent_info
->recStartBlock
;
4933 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
4934 if (extents
[i
].blockCount
== 0) {
4937 read_recStartBlock
+= extents
[i
].blockCount
;
4940 /* Shift and split */
4941 if (index
== kHFSPlusExtentDensity
-1) {
4942 /* The new extent created after split will go into following overflow extent record */
4943 shift_extent
.startBlock
= extents
[index
].startBlock
+ newBlockCount
;
4944 shift_extent
.blockCount
= extents
[index
].blockCount
- newBlockCount
;
4946 /* Last extent in the record will be split, so nothing to shift */
4948 /* Splitting of extents can result in at most of one
4949 * extent entry to be shifted into following overflow extent
4950 * record. So, store the last extent entry for later.
4952 shift_extent
= extents
[kHFSPlusExtentDensity
-1];
4954 /* Start shifting extent information from the end of the extent
4955 * record to the index where we want to insert the new extent.
4956 * Note that kHFSPlusExtentDensity-1 is already saved above, and
4957 * does not need to be shifted. The extent entry that is being
4958 * split does not get shifted.
4960 for (i
= kHFSPlusExtentDensity
-2; i
> index
; i
--) {
4961 if (hfs_resize_debug
) {
4962 if (extents
[i
].blockCount
) {
4963 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
);
4966 extents
[i
+1] = extents
[i
];
4970 if (index
== kHFSPlusExtentDensity
-1) {
4971 /* The second half of the extent being split will be the overflow
4972 * entry that will go into following overflow extent record. The
4973 * value has been stored in 'shift_extent' above, so there is
4974 * nothing to be done here.
4977 /* Update the values in the second half of the extent being split
4978 * before updating the first half of the split. Note that the
4979 * extent to split or first half of the split is at index 'index'
4980 * and a new extent or second half of the split will be inserted at
4981 * 'index+1' or into following overflow extent record.
4983 extents
[index
+1].startBlock
= extents
[index
].startBlock
+ newBlockCount
;
4984 extents
[index
+1].blockCount
= extents
[index
].blockCount
- newBlockCount
;
4986 /* Update the extent being split, only the block count will change */
4987 extents
[index
].blockCount
= newBlockCount
;
4989 if (hfs_resize_debug
) {
4990 printf ("hfs_split_extent: Split %u:(%u,%u) and ", index
, extents
[index
].startBlock
, extents
[index
].blockCount
);
4991 if (index
!= kHFSPlusExtentDensity
-1) {
4992 printf ("%u:(%u,%u)\n", index
+1, extents
[index
+1].startBlock
, extents
[index
+1].blockCount
);
4994 printf ("overflow:(%u,%u)\n", shift_extent
.startBlock
, shift_extent
.blockCount
);
4998 /* If the newly split extent is for large EAs or in overflow extent
4999 * record, so update it directly in the btree using the iterator
5000 * information from the shared extent_info structure
5002 if (extent_info
->catalog_fp
== NULL
) {
5003 error
= BTReplaceRecord(extent_info
->fcb
, extent_info
->iterator
,
5004 &(extent_info
->btdata
), extent_info
->recordlen
);
5006 printf ("hfs_split_extent: fileID=%u BTReplaceRecord returned error=%d\n", extent_info
->fileID
, error
);
5011 /* No extent entry to be shifted into another extent overflow record */
5012 if (shift_extent
.blockCount
== 0) {
5013 if (hfs_resize_debug
) {
5014 printf ("hfs_split_extent: No extent entry to be shifted into overflow records\n");
5020 /* The overflow extent entry has to be shifted into an extent
5021 * overflow record. This would mean that we have to shift
5022 * extent entries from all overflow records by one. We will
5023 * start iteration from the first record to the last record,
5024 * and shift the extent entry from one record to another.
5025 * We might have to create a new record for the last extent
5026 * entry for the file.
5029 /* Initialize iterator to search the next record */
5030 bzero(&iterator
, sizeof(iterator
));
5032 /* Copy the key from the iterator that was to update the modified attribute record. */
5033 xattr_key
= (HFSPlusAttrKey
*)&(iterator
.key
);
5034 bcopy((HFSPlusAttrKey
*)&(extent_info
->iterator
->key
), xattr_key
, sizeof(HFSPlusAttrKey
));
5035 /* Note: xattr_key->startBlock will be initialized later in the iteration loop */
5037 MALLOC(xattr_rec
, HFSPlusAttrRecord
*,
5038 sizeof(HFSPlusAttrRecord
), M_TEMP
, M_WAITOK
);
5039 if (xattr_rec
== NULL
) {
5043 btdata
.bufferAddress
= xattr_rec
;
5044 btdata
.itemSize
= sizeof(HFSPlusAttrRecord
);
5045 btdata
.itemCount
= 1;
5046 extents
= xattr_rec
->overflowExtents
.extents
;
5048 extents_key
= (HFSPlusExtentKey
*) &(iterator
.key
);
5049 extents_key
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
5050 extents_key
->forkType
= extent_info
->forkType
;
5051 extents_key
->fileID
= extent_info
->fileID
;
5052 /* Note: extents_key->startBlock will be initialized later in the iteration loop */
5054 MALLOC(extents_rec
, HFSPlusExtentRecord
*,
5055 sizeof(HFSPlusExtentRecord
), M_TEMP
, M_WAITOK
);
5056 if (extents_rec
== NULL
) {
5060 btdata
.bufferAddress
= extents_rec
;
5061 btdata
.itemSize
= sizeof(HFSPlusExtentRecord
);
5062 btdata
.itemCount
= 1;
5063 extents
= extents_rec
[0];
5066 /* An extent entry still needs to be shifted into following overflow
5067 * extent record. This will result in the starting allocation block
5068 * number of the extent record being changed which is part of the key
5069 * for the extent record. Since the extent record key is changing,
5070 * the record can not be updated, instead has to be deleted and
5073 while (shift_extent
.blockCount
) {
5074 if (hfs_resize_debug
) {
5075 printf ("hfs_split_extent: Will shift (%u,%u) into record with startBlock=%u\n", shift_extent
.startBlock
, shift_extent
.blockCount
, read_recStartBlock
);
5078 /* Search if there is any existing overflow extent record.
5079 * For this, the logical start block number in the key is
5080 * the value calculated based on the logical start block
5081 * number of the current extent record and the total number
5082 * of blocks existing in the current extent record.
5085 xattr_key
->startBlock
= read_recStartBlock
;
5087 extents_key
->startBlock
= read_recStartBlock
;
5089 error
= BTSearchRecord(extent_info
->fcb
, &iterator
, &btdata
, &reclen
, &iterator
);
5091 if (error
!= btNotFound
) {
5092 printf ("hfs_split_extent: fileID=%u startBlock=%u BTSearchRecord error=%d\n", extent_info
->fileID
, read_recStartBlock
, error
);
5095 create_record
= true;
5098 /* The extra extent entry from the previous record is being inserted
5099 * as the first entry in the current extent record. This will change
5100 * the file allocation block number (FABN) of the current extent
5101 * record, which is the startBlock value from the extent record key.
5102 * Since one extra entry is being inserted in the record, the new
5103 * FABN for the record will less than old FABN by the number of blocks
5104 * in the new extent entry being inserted at the start. We have to
5105 * do this before we update read_recStartBlock to point at the
5106 * startBlock of the following record.
5108 write_recStartBlock
= read_recStartBlock
- shift_extent
.blockCount
;
5109 if (hfs_resize_debug
) {
5110 if (create_record
) {
5111 printf ("hfs_split_extent: No records found for startBlock=%u, will create new with startBlock=%u\n", read_recStartBlock
, write_recStartBlock
);
5115 /* Now update the read_recStartBlock to account for total number
5116 * of blocks in this extent record. It will now point to the
5117 * starting allocation block number for the next extent record.
5119 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
5120 if (extents
[i
].blockCount
== 0) {
5123 read_recStartBlock
+= extents
[i
].blockCount
;
5126 if (create_record
== true) {
5127 /* Initialize new record content with only one extent entry */
5128 bzero(extents
, sizeof(HFSPlusExtentRecord
));
5129 /* The new record will contain only one extent entry */
5130 extents
[0] = shift_extent
;
5131 /* There are no more overflow extents to be shifted */
5132 shift_extent
.startBlock
= shift_extent
.blockCount
= 0;
5135 xattr_rec
->recordType
= kHFSPlusAttrExtents
;
5136 xattr_rec
->overflowExtents
.reserved
= 0;
5137 reclen
= sizeof(HFSPlusAttrExtents
);
5139 reclen
= sizeof(HFSPlusExtentRecord
);
5142 /* The overflow extent entry from previous record will be
5143 * the first entry in this extent record. If the last
5144 * extent entry in this record is valid, it will be shifted
5145 * into the following extent record as its first entry. So
5146 * save the last entry before shifting entries in current
5149 last_extent
= extents
[kHFSPlusExtentDensity
-1];
5151 /* Shift all entries by one index towards the end */
5152 for (i
= kHFSPlusExtentDensity
-2; i
>= 0; i
--) {
5153 extents
[i
+1] = extents
[i
];
5156 /* Overflow extent entry saved from previous record
5157 * is now the first entry in the current record.
5159 extents
[0] = shift_extent
;
5161 if (hfs_resize_debug
) {
5162 printf ("hfs_split_extent: Shift overflow=(%u,%u) to record with updated startBlock=%u\n", shift_extent
.startBlock
, shift_extent
.blockCount
, write_recStartBlock
);
5165 /* The last entry from current record will be the
5166 * overflow entry which will be the first entry for
5167 * the following extent record.
5169 shift_extent
= last_extent
;
5171 /* Since the key->startBlock is being changed for this record,
5172 * it should be deleted and inserted with the new key.
5174 error
= BTDeleteRecord(extent_info
->fcb
, &iterator
);
5176 printf ("hfs_split_extent: fileID=%u startBlock=%u BTDeleteRecord error=%d\n", extent_info
->fileID
, read_recStartBlock
, error
);
5179 if (hfs_resize_debug
) {
5180 printf ("hfs_split_extent: Deleted record with startBlock=%u\n", (is_xattr
? xattr_key
->startBlock
: extents_key
->startBlock
));
5184 /* Insert the newly created or modified extent record */
5185 bzero(&iterator
.hint
, sizeof(iterator
.hint
));
5187 xattr_key
->startBlock
= write_recStartBlock
;
5189 extents_key
->startBlock
= write_recStartBlock
;
5191 error
= BTInsertRecord(extent_info
->fcb
, &iterator
, &btdata
, reclen
);
5193 printf ("hfs_split_extent: fileID=%u, startBlock=%u BTInsertRecord error=%d\n", extent_info
->fileID
, write_recStartBlock
, error
);
5196 if (hfs_resize_debug
) {
5197 printf ("hfs_split_extent: Inserted extent record with startBlock=%u\n", write_recStartBlock
);
5200 BTFlushPath(extent_info
->fcb
);
5203 FREE (extents_rec
, M_TEMP
);
5206 FREE (xattr_rec
, M_TEMP
);
5213 * Relocate an extent if it lies beyond the expected end of volume.
5215 * This function is called for every extent of the file being relocated.
5216 * It allocates space for relocation, copies the data, deallocates
5217 * the old extent, and update corresponding on-disk extent. If the function
5218 * does not find contiguous space to relocate an extent, it splits the
5219 * extent in smaller size to be able to relocate it out of the area of
5220 * disk being reclaimed. As an optimization, if an extent lies partially
5221 * in the area of the disk being reclaimed, it is split so that we only
5222 * have to relocate the area that was overlapping with the area of disk
5225 * Note that every extent is relocated in its own transaction so that
5226 * they do not overwhelm the journal. This function handles the extent
5227 * record that exists in the catalog record, extent record from overflow
5228 * extents btree, and extents for large EAs.
5231 * extent_info - This is the structure that contains state about
5232 * the current file, extent, and extent record that
5233 * is being relocated. This structure is shared
5234 * among code that traverses through all the extents
5235 * of the file, code that relocates extents, and
5236 * code that splits the extent.
5239 hfs_reclaim_extent(struct hfsmount
*hfsmp
, const u_long allocLimit
, struct hfs_reclaim_extent_info
*extent_info
, vfs_context_t context
)
5244 u_int32_t oldStartBlock
;
5245 u_int32_t oldBlockCount
;
5246 u_int32_t newStartBlock
;
5247 u_int32_t newBlockCount
;
5248 u_int32_t alloc_flags
;
5249 int blocks_allocated
= false;
5251 index
= extent_info
->extent_index
;
5252 cp
= VTOC(extent_info
->vp
);
5254 oldStartBlock
= extent_info
->extents
[index
].startBlock
;
5255 oldBlockCount
= extent_info
->extents
[index
].blockCount
;
5257 if (0 && hfs_resize_debug
) {
5258 printf ("hfs_reclaim_extent: Examine record:%u recStartBlock=%u, %u:(%u,%u)\n", extent_info
->overflow_count
, extent_info
->recStartBlock
, index
, oldStartBlock
, oldBlockCount
);
5261 /* Check if the current extent lies completely within allocLimit */
5262 if ((oldStartBlock
+ oldBlockCount
) <= allocLimit
) {
5263 extent_info
->cur_blockCount
+= oldBlockCount
;
5267 /* Every extent should be relocated in its own transaction
5268 * to make sure that we don't overflow the journal buffer.
5270 error
= hfs_start_transaction(hfsmp
);
5274 extent_info
->lockflags
= hfs_systemfile_lock(hfsmp
, extent_info
->lockflags
, HFS_EXCLUSIVE_LOCK
);
5276 /* Check if the extent lies partially in the area to reclaim,
5277 * i.e. it starts before allocLimit and ends beyond allocLimit.
5278 * We have already skipped extents that lie completely within
5279 * allocLimit in the check above, so we only check for the
5280 * startBlock. If it lies partially, split it so that we
5281 * only relocate part of the extent.
5283 if (oldStartBlock
< allocLimit
) {
5284 newBlockCount
= allocLimit
- oldStartBlock
;
5285 error
= hfs_split_extent(extent_info
, newBlockCount
);
5287 /* After successful split, the current extent does not
5288 * need relocation, so just return back.
5292 /* Ignore error and try relocating the entire extent instead */
5295 alloc_flags
= HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_SKIPFREEBLKS
;
5296 if (extent_info
->is_sysfile
) {
5297 alloc_flags
|= HFS_ALLOC_METAZONE
;
5300 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
, alloc_flags
,
5301 &newStartBlock
, &newBlockCount
);
5302 if ((extent_info
->is_sysfile
== false) &&
5303 ((error
== dskFulErr
) || (error
== ENOSPC
))) {
5304 /* For non-system files, try reallocating space in metadata zone */
5305 alloc_flags
|= HFS_ALLOC_METAZONE
;
5306 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
,
5307 alloc_flags
, &newStartBlock
, &newBlockCount
);
5309 if ((error
== dskFulErr
) || (error
== ENOSPC
)) {
5310 /* We did not find desired contiguous space for this extent.
5311 * So try to allocate the maximum contiguous space available.
5313 alloc_flags
&= ~HFS_ALLOC_FORCECONTIG
;
5315 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
,
5316 alloc_flags
, &newStartBlock
, &newBlockCount
);
5318 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
);
5321 blocks_allocated
= true;
5323 error
= hfs_split_extent(extent_info
, newBlockCount
);
5325 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
);
5328 oldBlockCount
= newBlockCount
;
5331 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
);
5334 blocks_allocated
= true;
5336 /* Copy data from old location to new location */
5337 error
= hfs_copy_extent(hfsmp
, extent_info
->vp
, oldStartBlock
,
5338 newStartBlock
, newBlockCount
, context
);
5340 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
);
5344 /* Update the extent record with the new start block information */
5345 extent_info
->extents
[index
].startBlock
= newStartBlock
;
5347 /* Sync the content back to the disk */
5348 if (extent_info
->catalog_fp
) {
5349 /* Update the extents in catalog record */
5350 if (extent_info
->is_dirlink
) {
5351 error
= cat_update_dirlink(hfsmp
, extent_info
->forkType
,
5352 extent_info
->dirlink_desc
, extent_info
->dirlink_attr
,
5353 &(extent_info
->dirlink_fork
->ff_data
));
5355 cp
->c_flag
|= C_MODIFIED
;
5356 /* If this is a system file, sync volume headers on disk */
5357 if (extent_info
->is_sysfile
) {
5358 error
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, HFS_ALTFLUSH
);
5362 /* Replace record for extents overflow or extents-based xattrs */
5363 error
= BTReplaceRecord(extent_info
->fcb
, extent_info
->iterator
,
5364 &(extent_info
->btdata
), extent_info
->recordlen
);
5367 printf ("hfs_reclaim_extent: fileID=%u, update record error=%u\n", extent_info
->fileID
, error
);
5371 /* Deallocate the old extent */
5372 error
= BlockDeallocate(hfsmp
, oldStartBlock
, oldBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
5374 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
);
5377 extent_info
->blocks_relocated
+= newBlockCount
;
5379 if (hfs_resize_debug
) {
5380 printf ("hfs_reclaim_extent: Relocated record:%u %u:(%u,%u) to (%u,%u)\n", extent_info
->overflow_count
, index
, oldStartBlock
, oldBlockCount
, newStartBlock
, newBlockCount
);
5385 if (blocks_allocated
== true) {
5386 BlockDeallocate(hfsmp
, newStartBlock
, newBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
5389 /* On success, increment the total allocation blocks processed */
5390 extent_info
->cur_blockCount
+= newBlockCount
;
5393 hfs_systemfile_unlock(hfsmp
, extent_info
->lockflags
);
5395 /* For a non-system file, if an extent entry from catalog record
5396 * was modified, sync the in-memory changes to the catalog record
5397 * on disk before ending the transaction.
5400 (extent_info
->overflow_count
< kHFSPlusExtentDensity
) &&
5401 (extent_info
->is_sysfile
== false)) {
5402 (void) hfs_update(extent_info
->vp
, MNT_WAIT
);
5405 hfs_end_transaction(hfsmp
);
5410 /* Report intermediate progress during volume resize */
5412 hfs_truncatefs_progress(struct hfsmount
*hfsmp
)
5414 u_int32_t cur_progress
;
5416 hfs_resize_progress(hfsmp
, &cur_progress
);
5417 if (cur_progress
> (hfsmp
->hfs_resize_progress
+ 9)) {
5418 printf("hfs_truncatefs: %d%% done...\n", cur_progress
);
5419 hfsmp
->hfs_resize_progress
= cur_progress
;
5425 * Reclaim space at the end of a volume for given file and forktype.
5427 * This routine attempts to move any extent which contains allocation blocks
5428 * at or after "allocLimit." A separate transaction is used for every extent
5429 * that needs to be moved. If there is not contiguous space available for
5430 * moving an extent, it can be split into smaller extents. The contents of
5431 * any moved extents are read and written via the volume's device vnode --
5432 * NOT via "vp." During the move, moved blocks which are part of a transaction
5433 * have their physical block numbers invalidated so they will eventually be
5434 * written to their new locations.
5436 * This function is also called for directory hard links. Directory hard links
5437 * are regular files with no data fork and resource fork that contains alias
5438 * information for backward compatibility with pre-Leopard systems. However
5439 * non-Mac OS X implementation can add/modify data fork or resource fork
5440 * information to directory hard links, so we check, and if required, relocate
5441 * both data fork and resource fork.
5444 * hfsmp The volume being resized.
5445 * vp The vnode for the system file.
5446 * fileID ID of the catalog record that needs to be relocated
5447 * forktype The type of fork that needs relocated,
5448 * kHFSResourceForkType for resource fork,
5449 * kHFSDataForkType for data fork
5450 * allocLimit Allocation limit for the new volume size,
5451 * do not use this block or beyond. All extents
5452 * that use this block or any blocks beyond this limit
5453 * will be relocated.
5456 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
5457 * blocks that were relocated.
5460 hfs_reclaim_file(struct hfsmount
*hfsmp
, struct vnode
*vp
, u_int32_t fileID
,
5461 u_int8_t forktype
, u_long allocLimit
, vfs_context_t context
)
5464 struct hfs_reclaim_extent_info
*extent_info
;
5468 struct filefork
*fp
;
5469 int took_truncate_lock
= false;
5470 int release_desc
= false;
5471 HFSPlusExtentKey
*key
;
5473 /* If there is no vnode for this file, then there's nothing to do. */
5480 MALLOC(extent_info
, struct hfs_reclaim_extent_info
*,
5481 sizeof(struct hfs_reclaim_extent_info
), M_TEMP
, M_WAITOK
);
5482 if (extent_info
== NULL
) {
5485 bzero(extent_info
, sizeof(struct hfs_reclaim_extent_info
));
5486 extent_info
->vp
= vp
;
5487 extent_info
->fileID
= fileID
;
5488 extent_info
->forkType
= forktype
;
5489 extent_info
->is_sysfile
= vnode_issystem(vp
);
5490 if (vnode_isdir(vp
) && (cp
->c_flag
& C_HARDLINK
)) {
5491 extent_info
->is_dirlink
= true;
5493 /* We always need allocation bitmap and extent btree lock */
5494 lockflags
= SFL_BITMAP
| SFL_EXTENTS
;
5495 if ((fileID
== kHFSCatalogFileID
) || (extent_info
->is_dirlink
== true)) {
5496 lockflags
|= SFL_CATALOG
;
5497 } else if (fileID
== kHFSAttributesFileID
) {
5498 lockflags
|= SFL_ATTRIBUTE
;
5499 } else if (fileID
== kHFSStartupFileID
) {
5500 lockflags
|= SFL_STARTUP
;
5502 extent_info
->lockflags
= lockflags
;
5503 extent_info
->fcb
= VTOF(hfsmp
->hfs_extents_vp
);
5505 /* Flush data associated with current file on disk.
5507 * If the current vnode is directory hard link, no flushing of
5508 * journal or vnode is required. The current kernel does not
5509 * modify data/resource fork of directory hard links, so nothing
5510 * will be in the cache. If a directory hard link is newly created,
5511 * the resource fork data is written directly using devvp and
5512 * the code that actually relocates data (hfs_copy_extent()) also
5513 * uses devvp for its I/O --- so they will see a consistent copy.
5515 if (extent_info
->is_sysfile
) {
5516 /* If the current vnode is system vnode, flush journal
5517 * to make sure that all data is written to the disk.
5519 error
= hfs_journal_flush(hfsmp
, TRUE
);
5521 printf ("hfs_reclaim_file: journal_flush returned %d\n", error
);
5524 } else if (extent_info
->is_dirlink
== false) {
5525 /* Flush all blocks associated with this regular file vnode.
5526 * Normally there should not be buffer cache blocks for regular
5527 * files, but for objects like symlinks, we can have buffer cache
5528 * blocks associated with the vnode. Therefore we call
5529 * buf_flushdirtyblks() also.
5531 buf_flushdirtyblks(vp
, 0, BUF_SKIP_LOCKED
, "hfs_reclaim_file");
5534 hfs_lock_truncate(cp
, HFS_EXCLUSIVE_LOCK
);
5535 took_truncate_lock
= true;
5536 (void) cluster_push(vp
, 0);
5537 error
= hfs_lock(cp
, HFS_FORCE_LOCK
);
5542 /* If the file no longer exists, nothing left to do */
5543 if (cp
->c_flag
& C_NOEXISTS
) {
5548 /* Wait for any in-progress writes to this vnode to complete, so that we'll
5549 * be copying consistent bits. (Otherwise, it's possible that an async
5550 * write will complete to the old extent after we read from it. That
5551 * could lead to corruption.)
5553 error
= vnode_waitforwrites(vp
, 0, 0, 0, "hfs_reclaim_file");
5559 if (hfs_resize_debug
) {
5560 printf("hfs_reclaim_file: === Start reclaiming %sfork for %sid=%u ===\n", (forktype
? "rsrc" : "data"), (extent_info
->is_dirlink
? "dirlink" : "file"), fileID
);
5563 if (extent_info
->is_dirlink
) {
5564 MALLOC(extent_info
->dirlink_desc
, struct cat_desc
*,
5565 sizeof(struct cat_desc
), M_TEMP
, M_WAITOK
);
5566 MALLOC(extent_info
->dirlink_attr
, struct cat_attr
*,
5567 sizeof(struct cat_attr
), M_TEMP
, M_WAITOK
);
5568 MALLOC(extent_info
->dirlink_fork
, struct filefork
*,
5569 sizeof(struct filefork
), M_TEMP
, M_WAITOK
);
5570 if ((extent_info
->dirlink_desc
== NULL
) ||
5571 (extent_info
->dirlink_attr
== NULL
) ||
5572 (extent_info
->dirlink_fork
== NULL
)) {
5577 /* Lookup catalog record for directory hard link and
5578 * create a fake filefork for the value looked up from
5581 fp
= extent_info
->dirlink_fork
;
5582 bzero(extent_info
->dirlink_fork
, sizeof(struct filefork
));
5583 extent_info
->dirlink_fork
->ff_cp
= cp
;
5584 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
5585 error
= cat_lookup_dirlink(hfsmp
, fileID
, forktype
,
5586 extent_info
->dirlink_desc
, extent_info
->dirlink_attr
,
5587 &(extent_info
->dirlink_fork
->ff_data
));
5588 hfs_systemfile_unlock(hfsmp
, lockflags
);
5590 printf ("hfs_reclaim_file: cat_lookup_dirlink for fileID=%u returned error=%u\n", fileID
, error
);
5593 release_desc
= true;
5598 extent_info
->catalog_fp
= fp
;
5599 extent_info
->recStartBlock
= 0;
5600 extent_info
->extents
= extent_info
->catalog_fp
->ff_extents
;
5601 /* Relocate extents from the catalog record */
5602 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
5603 if (fp
->ff_extents
[i
].blockCount
== 0) {
5606 extent_info
->extent_index
= i
;
5607 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
5609 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
);
5614 /* If the number of allocation blocks processed for reclaiming
5615 * are less than total number of blocks for the file, continuing
5616 * working on overflow extents record.
5618 if (fp
->ff_blocks
<= extent_info
->cur_blockCount
) {
5619 if (0 && hfs_resize_debug
) {
5620 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
);
5625 if (hfs_resize_debug
) {
5626 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
);
5629 MALLOC(extent_info
->iterator
, struct BTreeIterator
*, sizeof(struct BTreeIterator
), M_TEMP
, M_WAITOK
);
5630 if (extent_info
->iterator
== NULL
) {
5634 bzero(extent_info
->iterator
, sizeof(struct BTreeIterator
));
5635 key
= (HFSPlusExtentKey
*) &(extent_info
->iterator
->key
);
5636 key
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
5637 key
->forkType
= forktype
;
5638 key
->fileID
= fileID
;
5639 key
->startBlock
= extent_info
->cur_blockCount
;
5641 extent_info
->btdata
.bufferAddress
= extent_info
->record
.overflow
;
5642 extent_info
->btdata
.itemSize
= sizeof(HFSPlusExtentRecord
);
5643 extent_info
->btdata
.itemCount
= 1;
5645 extent_info
->catalog_fp
= NULL
;
5647 /* Search the first overflow extent with expected startBlock as 'cur_blockCount' */
5648 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
5649 error
= BTSearchRecord(extent_info
->fcb
, extent_info
->iterator
,
5650 &(extent_info
->btdata
), &(extent_info
->recordlen
),
5651 extent_info
->iterator
);
5652 hfs_systemfile_unlock(hfsmp
, lockflags
);
5653 while (error
== 0) {
5654 extent_info
->overflow_count
++;
5655 extent_info
->recStartBlock
= key
->startBlock
;
5656 extent_info
->extents
= extent_info
->record
.overflow
;
5657 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
5658 if (extent_info
->record
.overflow
[i
].blockCount
== 0) {
5661 extent_info
->extent_index
= i
;
5662 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
5664 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
);
5669 /* Look for more overflow records */
5670 lockflags
= hfs_systemfile_lock(hfsmp
, lockflags
, HFS_EXCLUSIVE_LOCK
);
5671 error
= BTIterateRecord(extent_info
->fcb
, kBTreeNextRecord
,
5672 extent_info
->iterator
, &(extent_info
->btdata
),
5673 &(extent_info
->recordlen
));
5674 hfs_systemfile_unlock(hfsmp
, lockflags
);
5678 /* Stop when we encounter a different file or fork. */
5679 if ((key
->fileID
!= fileID
) || (key
->forkType
!= forktype
)) {
5683 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
5688 /* If any blocks were relocated, account them and report progress */
5689 if (extent_info
->blocks_relocated
) {
5690 hfsmp
->hfs_resize_blocksmoved
+= extent_info
->blocks_relocated
;
5691 hfs_truncatefs_progress(hfsmp
);
5692 if (fileID
< kHFSFirstUserCatalogNodeID
) {
5693 printf ("hfs_reclaim_file: Relocated %u blocks from fileID=%u on \"%s\"\n",
5694 extent_info
->blocks_relocated
, fileID
, hfsmp
->vcbVN
);
5697 if (extent_info
->iterator
) {
5698 FREE(extent_info
->iterator
, M_TEMP
);
5700 if (release_desc
== true) {
5701 cat_releasedesc(extent_info
->dirlink_desc
);
5703 if (extent_info
->dirlink_desc
) {
5704 FREE(extent_info
->dirlink_desc
, M_TEMP
);
5706 if (extent_info
->dirlink_attr
) {
5707 FREE(extent_info
->dirlink_attr
, M_TEMP
);
5709 if (extent_info
->dirlink_fork
) {
5710 FREE(extent_info
->dirlink_fork
, M_TEMP
);
5712 if ((extent_info
->blocks_relocated
!= 0) && (extent_info
->is_sysfile
== false)) {
5713 (void) hfs_update(vp
, MNT_WAIT
);
5715 if (took_truncate_lock
) {
5716 hfs_unlock_truncate(cp
, 0);
5719 FREE(extent_info
, M_TEMP
);
5721 if (hfs_resize_debug
) {
5722 printf("hfs_reclaim_file: === Finished relocating %sfork for fileid=%u (error=%d) ===\n", (forktype
? "rsrc" : "data"), fileID
, error
);
5730 * This journal_relocate callback updates the journal info block to point
5731 * at the new journal location. This write must NOT be done using the
5732 * transaction. We must write the block immediately. We must also force
5733 * it to get to the media so that the new journal location will be seen by
5734 * the replay code before we can safely let journaled blocks be written
5735 * to their normal locations.
5737 * The tests for journal_uses_fua below are mildly hacky. Since the journal
5738 * and the file system are both on the same device, I'm leveraging what
5739 * the journal has decided about FUA.
5741 struct hfs_journal_relocate_args
{
5742 struct hfsmount
*hfsmp
;
5743 vfs_context_t context
;
5744 u_int32_t newStartBlock
;
5748 hfs_journal_relocate_callback(void *_args
)
5751 struct hfs_journal_relocate_args
*args
= _args
;
5752 struct hfsmount
*hfsmp
= args
->hfsmp
;
5754 JournalInfoBlock
*jibp
;
5756 error
= buf_meta_bread(hfsmp
->hfs_devvp
,
5757 hfsmp
->vcbJinfoBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
5758 hfsmp
->blockSize
, vfs_context_ucred(args
->context
), &bp
);
5760 printf("hfs_reclaim_journal_file: failed to read JIB (%d)\n", error
);
5766 jibp
= (JournalInfoBlock
*) buf_dataptr(bp
);
5767 jibp
->offset
= SWAP_BE64((u_int64_t
)args
->newStartBlock
* hfsmp
->blockSize
);
5768 jibp
->size
= SWAP_BE64(hfsmp
->jnl_size
);
5769 if (journal_uses_fua(hfsmp
->jnl
))
5771 error
= buf_bwrite(bp
);
5773 printf("hfs_reclaim_journal_file: failed to write JIB (%d)\n", error
);
5776 if (!journal_uses_fua(hfsmp
->jnl
)) {
5777 error
= VNOP_IOCTL(hfsmp
->hfs_devvp
, DKIOCSYNCHRONIZECACHE
, NULL
, FWRITE
, args
->context
);
5779 printf("hfs_reclaim_journal_file: DKIOCSYNCHRONIZECACHE failed (%d)\n", error
);
5780 error
= 0; /* Don't fail the operation. */
5789 hfs_reclaim_journal_file(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
5794 u_int32_t oldStartBlock
;
5795 u_int32_t newStartBlock
;
5796 u_int32_t oldBlockCount
;
5797 u_int32_t newBlockCount
;
5798 struct cat_desc journal_desc
;
5799 struct cat_attr journal_attr
;
5800 struct cat_fork journal_fork
;
5801 struct hfs_journal_relocate_args callback_args
;
5803 if (hfsmp
->jnl_start
+ (hfsmp
->jnl_size
/ hfsmp
->blockSize
) <= allocLimit
) {
5804 /* The journal does not require relocation */
5808 error
= hfs_start_transaction(hfsmp
);
5810 printf("hfs_reclaim_journal_file: hfs_start_transaction returned %d\n", error
);
5813 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
5815 oldBlockCount
= hfsmp
->jnl_size
/ hfsmp
->blockSize
;
5817 /* TODO: Allow the journal to change size based on the new volume size. */
5818 error
= BlockAllocate(hfsmp
, 1, oldBlockCount
, oldBlockCount
,
5819 HFS_ALLOC_METAZONE
| HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_SKIPFREEBLKS
,
5820 &newStartBlock
, &newBlockCount
);
5822 printf("hfs_reclaim_journal_file: BlockAllocate returned %d\n", error
);
5825 if (newBlockCount
!= oldBlockCount
) {
5826 printf("hfs_reclaim_journal_file: newBlockCount != oldBlockCount (%u, %u)\n", newBlockCount
, oldBlockCount
);
5830 error
= BlockDeallocate(hfsmp
, hfsmp
->jnl_start
, oldBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
5832 printf("hfs_reclaim_journal_file: BlockDeallocate returned %d\n", error
);
5836 /* Update the catalog record for .journal */
5837 error
= cat_idlookup(hfsmp
, hfsmp
->hfs_jnlfileid
, 1, &journal_desc
, &journal_attr
, &journal_fork
);
5839 printf("hfs_reclaim_journal_file: cat_idlookup returned %d\n", error
);
5842 oldStartBlock
= journal_fork
.cf_extents
[0].startBlock
;
5843 journal_fork
.cf_size
= newBlockCount
* hfsmp
->blockSize
;
5844 journal_fork
.cf_extents
[0].startBlock
= newStartBlock
;
5845 journal_fork
.cf_extents
[0].blockCount
= newBlockCount
;
5846 journal_fork
.cf_blocks
= newBlockCount
;
5847 error
= cat_update(hfsmp
, &journal_desc
, &journal_attr
, &journal_fork
, NULL
);
5848 cat_releasedesc(&journal_desc
); /* all done with cat descriptor */
5850 printf("hfs_reclaim_journal_file: cat_update returned %d\n", error
);
5853 callback_args
.hfsmp
= hfsmp
;
5854 callback_args
.context
= context
;
5855 callback_args
.newStartBlock
= newStartBlock
;
5857 error
= journal_relocate(hfsmp
->jnl
, (off_t
)newStartBlock
*hfsmp
->blockSize
,
5858 (off_t
)newBlockCount
*hfsmp
->blockSize
, 0,
5859 hfs_journal_relocate_callback
, &callback_args
);
5861 /* NOTE: journal_relocate will mark the journal invalid. */
5862 printf("hfs_reclaim_journal_file: journal_relocate returned %d\n", error
);
5865 hfsmp
->jnl_start
= newStartBlock
;
5866 hfsmp
->jnl_size
= (off_t
)newBlockCount
* hfsmp
->blockSize
;
5868 hfs_systemfile_unlock(hfsmp
, lockflags
);
5869 error
= hfs_end_transaction(hfsmp
);
5871 printf("hfs_reclaim_journal_file: hfs_end_transaction returned %d\n", error
);
5874 /* Account for the blocks relocated and print progress */
5875 hfsmp
->hfs_resize_blocksmoved
+= oldBlockCount
;
5876 hfs_truncatefs_progress(hfsmp
);
5878 printf ("hfs_reclaim_journal_file: Relocated %u blocks from journal on \"%s\"\n",
5879 oldBlockCount
, hfsmp
->vcbVN
);
5880 if (hfs_resize_debug
) {
5881 printf ("hfs_reclaim_journal_file: Successfully relocated journal from (%u,%u) to (%u,%u)\n", oldStartBlock
, oldBlockCount
, newStartBlock
, newBlockCount
);
5887 journal_err
= BlockDeallocate(hfsmp
, newStartBlock
, newBlockCount
, HFS_ALLOC_SKIPFREEBLKS
);
5889 printf("hfs_reclaim_journal_file: BlockDeallocate returned %d\n", error
);
5890 hfs_mark_volume_inconsistent(hfsmp
);
5893 hfs_systemfile_unlock(hfsmp
, lockflags
);
5894 (void) hfs_end_transaction(hfsmp
);
5895 if (hfs_resize_debug
) {
5896 printf ("hfs_reclaim_journal_file: Error relocating journal file (error=%d)\n", error
);
5903 * Move the journal info block to a new location. We have to make sure the
5904 * new copy of the journal info block gets to the media first, then change
5905 * the field in the volume header and the catalog record.
5908 hfs_reclaim_journal_info_block(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
5915 u_int32_t blockCount
;
5916 struct cat_desc jib_desc
;
5917 struct cat_attr jib_attr
;
5918 struct cat_fork jib_fork
;
5919 buf_t old_bp
, new_bp
;
5921 if (hfsmp
->vcbJinfoBlock
<= allocLimit
) {
5922 /* The journal info block does not require relocation */
5926 error
= hfs_start_transaction(hfsmp
);
5928 printf("hfs_reclaim_journal_info_block: hfs_start_transaction returned %d\n", error
);
5931 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
| SFL_BITMAP
, HFS_EXCLUSIVE_LOCK
);
5933 error
= BlockAllocate(hfsmp
, 1, 1, 1,
5934 HFS_ALLOC_METAZONE
| HFS_ALLOC_FORCECONTIG
| HFS_ALLOC_SKIPFREEBLKS
,
5935 &newBlock
, &blockCount
);
5937 printf("hfs_reclaim_journal_info_block: BlockAllocate returned %d\n", error
);
5940 if (blockCount
!= 1) {
5941 printf("hfs_reclaim_journal_info_block: blockCount != 1 (%u)\n", blockCount
);
5944 error
= BlockDeallocate(hfsmp
, hfsmp
->vcbJinfoBlock
, 1, HFS_ALLOC_SKIPFREEBLKS
);
5946 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error
);
5950 /* Copy the old journal info block content to the new location */
5951 error
= buf_meta_bread(hfsmp
->hfs_devvp
,
5952 hfsmp
->vcbJinfoBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
5953 hfsmp
->blockSize
, vfs_context_ucred(context
), &old_bp
);
5955 printf("hfs_reclaim_journal_info_block: failed to read JIB (%d)\n", error
);
5961 new_bp
= buf_getblk(hfsmp
->hfs_devvp
,
5962 newBlock
* (hfsmp
->blockSize
/hfsmp
->hfs_logical_block_size
),
5963 hfsmp
->blockSize
, 0, 0, BLK_META
);
5964 bcopy((char*)buf_dataptr(old_bp
), (char*)buf_dataptr(new_bp
), hfsmp
->blockSize
);
5966 if (journal_uses_fua(hfsmp
->jnl
))
5967 buf_markfua(new_bp
);
5968 error
= buf_bwrite(new_bp
);
5970 printf("hfs_reclaim_journal_info_block: failed to write new JIB (%d)\n", error
);
5973 if (!journal_uses_fua(hfsmp
->jnl
)) {
5974 error
= VNOP_IOCTL(hfsmp
->hfs_devvp
, DKIOCSYNCHRONIZECACHE
, NULL
, FWRITE
, context
);
5976 printf("hfs_reclaim_journal_info_block: DKIOCSYNCHRONIZECACHE failed (%d)\n", error
);
5977 /* Don't fail the operation. */
5981 /* Update the catalog record for .journal_info_block */
5982 error
= cat_idlookup(hfsmp
, hfsmp
->hfs_jnlinfoblkid
, 1, &jib_desc
, &jib_attr
, &jib_fork
);
5984 printf("hfs_reclaim_journal_file: cat_idlookup returned %d\n", error
);
5987 oldBlock
= jib_fork
.cf_extents
[0].startBlock
;
5988 jib_fork
.cf_size
= hfsmp
->blockSize
;
5989 jib_fork
.cf_extents
[0].startBlock
= newBlock
;
5990 jib_fork
.cf_extents
[0].blockCount
= 1;
5991 jib_fork
.cf_blocks
= 1;
5992 error
= cat_update(hfsmp
, &jib_desc
, &jib_attr
, &jib_fork
, NULL
);
5993 cat_releasedesc(&jib_desc
); /* all done with cat descriptor */
5995 printf("hfs_reclaim_journal_info_block: cat_update returned %d\n", error
);
5999 /* Update the pointer to the journal info block in the volume header. */
6000 hfsmp
->vcbJinfoBlock
= newBlock
;
6001 error
= hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, HFS_ALTFLUSH
);
6003 printf("hfs_reclaim_journal_info_block: hfs_flushvolumeheader returned %d\n", error
);
6006 hfs_systemfile_unlock(hfsmp
, lockflags
);
6007 error
= hfs_end_transaction(hfsmp
);
6009 printf("hfs_reclaim_journal_info_block: hfs_end_transaction returned %d\n", error
);
6011 error
= hfs_journal_flush(hfsmp
, FALSE
);
6013 printf("hfs_reclaim_journal_info_block: journal_flush returned %d\n", error
);
6016 /* Account for the block relocated and print progress */
6017 hfsmp
->hfs_resize_blocksmoved
+= 1;
6018 hfs_truncatefs_progress(hfsmp
);
6020 printf ("hfs_reclaim_journal_info: Relocated 1 block from journal info on \"%s\"\n",
6022 if (hfs_resize_debug
) {
6023 printf ("hfs_reclaim_journal_info_block: Successfully relocated journal info block from (%u,%u) to (%u,%u)\n", oldBlock
, blockCount
, newBlock
, blockCount
);
6029 journal_err
= BlockDeallocate(hfsmp
, newBlock
, blockCount
, HFS_ALLOC_SKIPFREEBLKS
);
6031 printf("hfs_reclaim_journal_info_block: BlockDeallocate returned %d\n", error
);
6032 hfs_mark_volume_inconsistent(hfsmp
);
6036 hfs_systemfile_unlock(hfsmp
, lockflags
);
6037 (void) hfs_end_transaction(hfsmp
);
6038 if (hfs_resize_debug
) {
6039 printf ("hfs_reclaim_journal_info_block: Error relocating journal info block (error=%d)\n", error
);
6046 * This function traverses through all extended attribute records for a given
6047 * fileID, and calls function that reclaims data blocks that exist in the
6048 * area of the disk being reclaimed which in turn is responsible for allocating
6049 * new space, copying extent data, deallocating new space, and if required,
6050 * splitting the extent.
6052 * Note: The caller has already acquired the cnode lock on the file. Therefore
6053 * we are assured that no other thread would be creating/deleting/modifying
6054 * extended attributes for this file.
6057 * hfsmp->hfs_resize_blocksmoved is incremented by the number of allocation
6058 * blocks that were relocated.
6061 * 0 on success, non-zero on failure.
6064 hfs_reclaim_xattr(struct hfsmount
*hfsmp
, struct vnode
*vp
, u_int32_t fileID
, u_int32_t allocLimit
, vfs_context_t context
)
6067 struct hfs_reclaim_extent_info
*extent_info
;
6069 HFSPlusAttrKey
*key
;
6072 if (hfs_resize_debug
) {
6073 printf("hfs_reclaim_xattr: === Start reclaiming xattr for id=%u ===\n", fileID
);
6076 MALLOC(extent_info
, struct hfs_reclaim_extent_info
*,
6077 sizeof(struct hfs_reclaim_extent_info
), M_TEMP
, M_WAITOK
);
6078 if (extent_info
== NULL
) {
6081 bzero(extent_info
, sizeof(struct hfs_reclaim_extent_info
));
6082 extent_info
->vp
= vp
;
6083 extent_info
->fileID
= fileID
;
6084 extent_info
->is_xattr
= true;
6085 extent_info
->is_sysfile
= vnode_issystem(vp
);
6086 extent_info
->fcb
= VTOF(hfsmp
->hfs_attribute_vp
);
6087 lockflags
= &(extent_info
->lockflags
);
6088 *lockflags
= SFL_ATTRIBUTE
| SFL_BITMAP
;
6090 /* Initialize iterator from the extent_info structure */
6091 MALLOC(extent_info
->iterator
, struct BTreeIterator
*,
6092 sizeof(struct BTreeIterator
), M_TEMP
, M_WAITOK
);
6093 if (extent_info
->iterator
== NULL
) {
6097 bzero(extent_info
->iterator
, sizeof(struct BTreeIterator
));
6099 /* Build attribute key */
6100 key
= (HFSPlusAttrKey
*)&(extent_info
->iterator
->key
);
6101 error
= hfs_buildattrkey(fileID
, NULL
, key
);
6106 /* Initialize btdata from extent_info structure. Note that the
6107 * buffer pointer actually points to the xattr record from the
6108 * extent_info structure itself.
6110 extent_info
->btdata
.bufferAddress
= &(extent_info
->record
.xattr
);
6111 extent_info
->btdata
.itemSize
= sizeof(HFSPlusAttrRecord
);
6112 extent_info
->btdata
.itemCount
= 1;
6115 * Sync all extent-based attribute data to the disk.
6117 * All extent-based attribute data I/O is performed via cluster
6118 * I/O using a virtual file that spans across entire file system
6121 hfs_lock_truncate(VTOC(hfsmp
->hfs_attrdata_vp
), HFS_EXCLUSIVE_LOCK
);
6122 (void)cluster_push(hfsmp
->hfs_attrdata_vp
, 0);
6123 error
= vnode_waitforwrites(hfsmp
->hfs_attrdata_vp
, 0, 0, 0, "hfs_reclaim_xattr");
6124 hfs_unlock_truncate(VTOC(hfsmp
->hfs_attrdata_vp
), 0);
6129 /* Search for extended attribute for current file. This
6130 * will place the iterator before the first matching record.
6132 *lockflags
= hfs_systemfile_lock(hfsmp
, *lockflags
, HFS_EXCLUSIVE_LOCK
);
6133 error
= BTSearchRecord(extent_info
->fcb
, extent_info
->iterator
,
6134 &(extent_info
->btdata
), &(extent_info
->recordlen
),
6135 extent_info
->iterator
);
6136 hfs_systemfile_unlock(hfsmp
, *lockflags
);
6138 if (error
!= btNotFound
) {
6141 /* btNotFound is expected here, so just mask it */
6146 /* Iterate to the next record */
6147 *lockflags
= hfs_systemfile_lock(hfsmp
, *lockflags
, HFS_EXCLUSIVE_LOCK
);
6148 error
= BTIterateRecord(extent_info
->fcb
, kBTreeNextRecord
,
6149 extent_info
->iterator
, &(extent_info
->btdata
),
6150 &(extent_info
->recordlen
));
6151 hfs_systemfile_unlock(hfsmp
, *lockflags
);
6153 /* Stop the iteration if we encounter end of btree or xattr with different fileID */
6154 if (error
|| key
->fileID
!= fileID
) {
6155 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
6161 /* We only care about extent-based EAs */
6162 if ((extent_info
->record
.xattr
.recordType
!= kHFSPlusAttrForkData
) &&
6163 (extent_info
->record
.xattr
.recordType
!= kHFSPlusAttrExtents
)) {
6167 if (extent_info
->record
.xattr
.recordType
== kHFSPlusAttrForkData
) {
6168 extent_info
->overflow_count
= 0;
6169 extent_info
->extents
= extent_info
->record
.xattr
.forkData
.theFork
.extents
;
6170 } else if (extent_info
->record
.xattr
.recordType
== kHFSPlusAttrExtents
) {
6171 extent_info
->overflow_count
++;
6172 extent_info
->extents
= extent_info
->record
.xattr
.overflowExtents
.extents
;
6175 extent_info
->recStartBlock
= key
->startBlock
;
6176 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
6177 if (extent_info
->extents
[i
].blockCount
== 0) {
6180 extent_info
->extent_index
= i
;
6181 error
= hfs_reclaim_extent(hfsmp
, allocLimit
, extent_info
, context
);
6183 printf ("hfs_reclaim_xattr: fileID=%u hfs_reclaim_extent error=%d\n", fileID
, error
);
6190 /* If any blocks were relocated, account them and report progress */
6191 if (extent_info
->blocks_relocated
) {
6192 hfsmp
->hfs_resize_blocksmoved
+= extent_info
->blocks_relocated
;
6193 hfs_truncatefs_progress(hfsmp
);
6195 if (extent_info
->iterator
) {
6196 FREE(extent_info
->iterator
, M_TEMP
);
6199 FREE(extent_info
, M_TEMP
);
6201 if (hfs_resize_debug
) {
6202 printf("hfs_reclaim_xattr: === Finished relocating xattr for fileid=%u (error=%d) ===\n", fileID
, error
);
6208 * Reclaim any extent-based extended attributes allocation blocks from
6209 * the area of the disk that is being truncated.
6211 * The function traverses the attribute btree to find out the fileIDs
6212 * of the extended attributes that need to be relocated. For every
6213 * file whose large EA requires relocation, it looks up the cnode and
6214 * calls hfs_reclaim_xattr() to do all the work for allocating
6215 * new space, copying data, deallocating old space, and if required,
6216 * splitting the extents.
6219 * allocLimit - starting block of the area being reclaimed
6222 * returns 0 on success, non-zero on failure.
6225 hfs_reclaim_xattrspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
6229 struct BTreeIterator
*iterator
= NULL
;
6230 struct FSBufferDescriptor btdata
;
6231 HFSPlusAttrKey
*key
;
6232 HFSPlusAttrRecord rec
;
6234 cnid_t prev_fileid
= 0;
6237 int btree_operation
;
6238 u_int32_t files_moved
= 0;
6239 u_int32_t prev_blocksmoved
;
6242 fcb
= VTOF(hfsmp
->hfs_attribute_vp
);
6243 /* Store the value to print total blocks moved by this function in end */
6244 prev_blocksmoved
= hfsmp
->hfs_resize_blocksmoved
;
6246 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&iterator
, sizeof(*iterator
))) {
6249 bzero(iterator
, sizeof(*iterator
));
6250 key
= (HFSPlusAttrKey
*)&iterator
->key
;
6251 btdata
.bufferAddress
= &rec
;
6252 btdata
.itemSize
= sizeof(rec
);
6253 btdata
.itemCount
= 1;
6255 need_relocate
= false;
6256 btree_operation
= kBTreeFirstRecord
;
6257 /* Traverse the attribute btree to find extent-based EAs to reclaim */
6259 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_ATTRIBUTE
, HFS_SHARED_LOCK
);
6260 error
= BTIterateRecord(fcb
, btree_operation
, iterator
, &btdata
, NULL
);
6261 hfs_systemfile_unlock(hfsmp
, lockflags
);
6263 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
6268 btree_operation
= kBTreeNextRecord
;
6270 /* If the extents of current fileID were already relocated, skip it */
6271 if (prev_fileid
== key
->fileID
) {
6275 /* Check if any of the extents in the current record need to be relocated */
6276 need_relocate
= false;
6277 switch(rec
.recordType
) {
6278 case kHFSPlusAttrForkData
:
6279 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
6280 if (rec
.forkData
.theFork
.extents
[i
].blockCount
== 0) {
6283 if ((rec
.forkData
.theFork
.extents
[i
].startBlock
+
6284 rec
.forkData
.theFork
.extents
[i
].blockCount
) > allocLimit
) {
6285 need_relocate
= true;
6291 case kHFSPlusAttrExtents
:
6292 for (i
= 0; i
< kHFSPlusExtentDensity
; i
++) {
6293 if (rec
.overflowExtents
.extents
[i
].blockCount
== 0) {
6296 if ((rec
.overflowExtents
.extents
[i
].startBlock
+
6297 rec
.overflowExtents
.extents
[i
].blockCount
) > allocLimit
) {
6298 need_relocate
= true;
6305 /* Continue iterating to next attribute record */
6306 if (need_relocate
== false) {
6310 /* Look up the vnode for corresponding file. The cnode
6311 * will be locked which will ensure that no one modifies
6312 * the xattrs when we are relocating them.
6314 * We want to allow open-unlinked files to be moved,
6315 * so provide allow_deleted == 1 for hfs_vget().
6317 if (hfs_vget(hfsmp
, key
->fileID
, &vp
, 0, 1) != 0) {
6321 error
= hfs_reclaim_xattr(hfsmp
, vp
, key
->fileID
, allocLimit
, context
);
6322 hfs_unlock(VTOC(vp
));
6325 printf ("hfs_reclaim_xattrspace: Error relocating xattrs for fileid=%u (error=%d)\n", key
->fileID
, error
);
6328 prev_fileid
= key
->fileID
;
6333 printf("hfs_reclaim_xattrspace: Relocated %u xattr blocks from %u files on \"%s\"\n",
6334 (hfsmp
->hfs_resize_blocksmoved
- prev_blocksmoved
),
6335 files_moved
, hfsmp
->vcbVN
);
6338 kmem_free(kernel_map
, (vm_offset_t
)iterator
, sizeof(*iterator
));
6343 * Reclaim blocks from regular files.
6345 * This function iterates over all the record in catalog btree looking
6346 * for files with extents that overlap into the space we're trying to
6347 * free up. If a file extent requires relocation, it looks up the vnode
6348 * and calls function to relocate the data.
6351 * Zero on success, non-zero on failure.
6354 hfs_reclaim_filespace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, vfs_context_t context
)
6358 struct BTreeIterator
*iterator
= NULL
;
6359 struct FSBufferDescriptor btdata
;
6360 int btree_operation
;
6362 struct HFSPlusCatalogFile filerec
;
6365 struct filefork
*datafork
;
6366 u_int32_t files_moved
= 0;
6367 u_int32_t prev_blocksmoved
;
6369 fcb
= VTOF(hfsmp
->hfs_catalog_vp
);
6370 /* Store the value to print total blocks moved by this function at the end */
6371 prev_blocksmoved
= hfsmp
->hfs_resize_blocksmoved
;
6373 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&iterator
, sizeof(*iterator
))) {
6376 bzero(iterator
, sizeof(*iterator
));
6378 btdata
.bufferAddress
= &filerec
;
6379 btdata
.itemSize
= sizeof(filerec
);
6380 btdata
.itemCount
= 1;
6382 btree_operation
= kBTreeFirstRecord
;
6384 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_SHARED_LOCK
);
6385 error
= BTIterateRecord(fcb
, btree_operation
, iterator
, &btdata
, NULL
);
6386 hfs_systemfile_unlock(hfsmp
, lockflags
);
6388 if (error
== fsBTRecordNotFoundErr
|| error
== fsBTEndOfIterationErr
) {
6393 btree_operation
= kBTreeNextRecord
;
6395 if (filerec
.recordType
!= kHFSPlusFileRecord
) {
6399 /* Check if any of the extents require relocation */
6400 if (hfs_file_extent_overlaps(hfsmp
, allocLimit
, &filerec
) == false) {
6404 /* We want to allow open-unlinked files to be moved, so allow_deleted == 1 */
6405 if (hfs_vget(hfsmp
, filerec
.fileID
, &vp
, 0, 1) != 0) {
6409 /* If data fork exists or item is a directory hard link, relocate blocks */
6410 datafork
= VTOF(vp
);
6411 if ((datafork
&& datafork
->ff_blocks
> 0) || vnode_isdir(vp
)) {
6412 error
= hfs_reclaim_file(hfsmp
, vp
, filerec
.fileID
,
6413 kHFSDataForkType
, allocLimit
, context
);
6415 printf ("hfs_reclaimspace: Error reclaiming datafork blocks of fileid=%u (error=%d)\n", filerec
.fileID
, error
);
6416 hfs_unlock(VTOC(vp
));
6422 /* If resource fork exists or item is a directory hard link, relocate blocks */
6423 if (((VTOC(vp
)->c_blocks
- (datafork
? datafork
->ff_blocks
: 0)) > 0) || vnode_isdir(vp
)) {
6424 if (vnode_isdir(vp
)) {
6425 /* Resource fork vnode lookup is invalid for directory hard link.
6426 * So we fake data fork vnode as resource fork vnode.
6430 error
= hfs_vgetrsrc(hfsmp
, vp
, &rvp
, TRUE
, FALSE
);
6432 printf ("hfs_reclaimspace: Error looking up rvp for fileid=%u (error=%d)\n", filerec
.fileID
, error
);
6433 hfs_unlock(VTOC(vp
));
6437 VTOC(rvp
)->c_flag
|= C_NEED_RVNODE_PUT
;
6440 error
= hfs_reclaim_file(hfsmp
, rvp
, filerec
.fileID
,
6441 kHFSResourceForkType
, allocLimit
, context
);
6443 printf ("hfs_reclaimspace: Error reclaiming rsrcfork blocks of fileid=%u (error=%d)\n", filerec
.fileID
, error
);
6444 hfs_unlock(VTOC(vp
));
6450 /* The file forks were relocated successfully, now drop the
6451 * cnode lock and vnode reference, and continue iterating to
6452 * next catalog record.
6454 hfs_unlock(VTOC(vp
));
6460 printf("hfs_reclaim_filespace: Relocated %u blocks from %u files on \"%s\"\n",
6461 (hfsmp
->hfs_resize_blocksmoved
- prev_blocksmoved
),
6462 files_moved
, hfsmp
->vcbVN
);
6465 kmem_free(kernel_map
, (vm_offset_t
)iterator
, sizeof(*iterator
));
6470 * Reclaim space at the end of a file system.
6473 * allocLimit - start block of the space being reclaimed
6474 * reclaimblks - number of allocation blocks to reclaim
6477 hfs_reclaimspace(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, u_int32_t reclaimblks
, vfs_context_t context
)
6482 * Preflight the bitmap to find out total number of blocks that need
6485 * Note: Since allocLimit is set to the location of new alternate volume
6486 * header, the check below does not account for blocks allocated for old
6487 * alternate volume header.
6489 error
= hfs_count_allocated(hfsmp
, allocLimit
, reclaimblks
, &(hfsmp
->hfs_resize_totalblocks
));
6491 printf ("hfs_reclaimspace: Unable to determine total blocks to reclaim error=%d\n", error
);
6494 if (hfs_resize_debug
) {
6495 printf ("hfs_reclaimspace: Total number of blocks to reclaim = %u\n", hfsmp
->hfs_resize_totalblocks
);
6498 /* Relocate extents of the Allocation file if they're in the way. */
6499 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_allocation_vp
, kHFSAllocationFileID
,
6500 kHFSDataForkType
, allocLimit
, context
);
6502 printf("hfs_reclaimspace: reclaim allocation file returned %d\n", error
);
6506 /* Relocate extents of the Extents B-tree if they're in the way. */
6507 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_extents_vp
, kHFSExtentsFileID
,
6508 kHFSDataForkType
, allocLimit
, context
);
6510 printf("hfs_reclaimspace: reclaim extents b-tree returned %d\n", error
);
6514 /* Relocate extents of the Catalog B-tree if they're in the way. */
6515 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_catalog_vp
, kHFSCatalogFileID
,
6516 kHFSDataForkType
, allocLimit
, context
);
6518 printf("hfs_reclaimspace: reclaim catalog b-tree returned %d\n", error
);
6522 /* Relocate extents of the Attributes B-tree if they're in the way. */
6523 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_attribute_vp
, kHFSAttributesFileID
,
6524 kHFSDataForkType
, allocLimit
, context
);
6526 printf("hfs_reclaimspace: reclaim attribute b-tree returned %d\n", error
);
6530 /* Relocate extents of the Startup File if there is one and they're in the way. */
6531 error
= hfs_reclaim_file(hfsmp
, hfsmp
->hfs_startup_vp
, kHFSStartupFileID
,
6532 kHFSDataForkType
, allocLimit
, context
);
6534 printf("hfs_reclaimspace: reclaim startup file returned %d\n", error
);
6539 * We need to make sure the alternate volume header gets flushed if we moved
6540 * any extents in the volume header. But we need to do that before
6541 * shrinking the size of the volume, or else the journal code will panic
6542 * with an invalid (too large) block number.
6544 * Note that blks_moved will be set if ANY extent was moved, even
6545 * if it was just an overflow extent. In this case, the journal_flush isn't
6546 * strictly required, but shouldn't hurt.
6548 if (hfsmp
->hfs_resize_blocksmoved
) {
6549 hfs_journal_flush(hfsmp
, FALSE
);
6552 /* Relocate journal file blocks if they're in the way. */
6553 error
= hfs_reclaim_journal_file(hfsmp
, allocLimit
, context
);
6555 printf("hfs_reclaimspace: hfs_reclaim_journal_file failed (%d)\n", error
);
6559 /* Relocate journal info block blocks if they're in the way. */
6560 error
= hfs_reclaim_journal_info_block(hfsmp
, allocLimit
, context
);
6562 printf("hfs_reclaimspace: hfs_reclaim_journal_info_block failed (%d)\n", error
);
6566 /* Reclaim extents from catalog file records */
6567 error
= hfs_reclaim_filespace(hfsmp
, allocLimit
, context
);
6569 printf ("hfs_reclaimspace: hfs_reclaim_filespace returned error=%d\n", error
);
6573 /* Reclaim extents from extent-based extended attributes, if any */
6574 error
= hfs_reclaim_xattrspace(hfsmp
, allocLimit
, context
);
6576 printf ("hfs_reclaimspace: hfs_reclaim_xattrspace returned error=%d\n", error
);
6585 * Check if there are any extents (including overflow extents) that overlap
6586 * into the disk space that is being reclaimed.
6589 * true - One of the extents need to be relocated
6590 * false - No overflow extents need to be relocated, or there was an error
6593 hfs_file_extent_overlaps(struct hfsmount
*hfsmp
, u_int32_t allocLimit
, struct HFSPlusCatalogFile
*filerec
)
6595 struct BTreeIterator
* iterator
= NULL
;
6596 struct FSBufferDescriptor btdata
;
6597 HFSPlusExtentRecord extrec
;
6598 HFSPlusExtentKey
*extkeyptr
;
6600 int overlapped
= false;
6606 /* Check if data fork overlaps the target space */
6607 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
6608 if (filerec
->dataFork
.extents
[i
].blockCount
== 0) {
6611 endblock
= filerec
->dataFork
.extents
[i
].startBlock
+
6612 filerec
->dataFork
.extents
[i
].blockCount
;
6613 if (endblock
> allocLimit
) {
6619 /* Check if resource fork overlaps the target space */
6620 for (j
= 0; j
< kHFSPlusExtentDensity
; ++j
) {
6621 if (filerec
->resourceFork
.extents
[j
].blockCount
== 0) {
6624 endblock
= filerec
->resourceFork
.extents
[j
].startBlock
+
6625 filerec
->resourceFork
.extents
[j
].blockCount
;
6626 if (endblock
> allocLimit
) {
6632 /* Return back if there are no overflow extents for this file */
6633 if ((i
< kHFSPlusExtentDensity
) && (j
< kHFSPlusExtentDensity
)) {
6637 if (kmem_alloc(kernel_map
, (vm_offset_t
*)&iterator
, sizeof(*iterator
))) {
6640 bzero(iterator
, sizeof(*iterator
));
6641 extkeyptr
= (HFSPlusExtentKey
*)&iterator
->key
;
6642 extkeyptr
->keyLength
= kHFSPlusExtentKeyMaximumLength
;
6643 extkeyptr
->forkType
= 0;
6644 extkeyptr
->fileID
= filerec
->fileID
;
6645 extkeyptr
->startBlock
= 0;
6647 btdata
.bufferAddress
= &extrec
;
6648 btdata
.itemSize
= sizeof(extrec
);
6649 btdata
.itemCount
= 1;
6651 fcb
= VTOF(hfsmp
->hfs_extents_vp
);
6653 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_EXTENTS
, HFS_SHARED_LOCK
);
6655 /* This will position the iterator just before the first overflow
6656 * extent record for given fileID. It will always return btNotFound,
6657 * so we special case the error code.
6659 error
= BTSearchRecord(fcb
, iterator
, &btdata
, NULL
, iterator
);
6660 if (error
&& (error
!= btNotFound
)) {
6664 /* BTIterateRecord() might return error if the btree is empty, and
6665 * therefore we return that the extent does not overflow to the caller
6667 error
= BTIterateRecord(fcb
, kBTreeNextRecord
, iterator
, &btdata
, NULL
);
6668 while (error
== 0) {
6669 /* Stop when we encounter a different file. */
6670 if (extkeyptr
->fileID
!= filerec
->fileID
) {
6673 /* Check if any of the forks exist in the target space. */
6674 for (i
= 0; i
< kHFSPlusExtentDensity
; ++i
) {
6675 if (extrec
[i
].blockCount
== 0) {
6678 endblock
= extrec
[i
].startBlock
+ extrec
[i
].blockCount
;
6679 if (endblock
> allocLimit
) {
6684 /* Look for more records. */
6685 error
= BTIterateRecord(fcb
, kBTreeNextRecord
, iterator
, &btdata
, NULL
);
6690 hfs_systemfile_unlock(hfsmp
, lockflags
);
6693 kmem_free(kernel_map
, (vm_offset_t
)iterator
, sizeof(*iterator
));
6700 * Calculate the progress of a file system resize operation.
6704 hfs_resize_progress(struct hfsmount
*hfsmp
, u_int32_t
*progress
)
6706 if ((hfsmp
->hfs_flags
& HFS_RESIZE_IN_PROGRESS
) == 0) {
6710 if (hfsmp
->hfs_resize_totalblocks
> 0) {
6711 *progress
= (u_int32_t
)((hfsmp
->hfs_resize_blocksmoved
* 100ULL) / hfsmp
->hfs_resize_totalblocks
);
6721 * Creates a UUID from a unique "name" in the HFS UUID Name space.
6722 * See version 3 UUID.
6725 hfs_getvoluuid(struct hfsmount
*hfsmp
, uuid_t result
)
6730 ((uint32_t *)rawUUID
)[0] = hfsmp
->vcbFndrInfo
[6];
6731 ((uint32_t *)rawUUID
)[1] = hfsmp
->vcbFndrInfo
[7];
6734 MD5Update( &md5c
, HFS_UUID_NAMESPACE_ID
, sizeof( uuid_t
) );
6735 MD5Update( &md5c
, rawUUID
, sizeof (rawUUID
) );
6736 MD5Final( result
, &md5c
);
6738 result
[6] = 0x30 | ( result
[6] & 0x0F );
6739 result
[8] = 0x80 | ( result
[8] & 0x3F );
6743 * Get file system attributes.
6746 hfs_vfs_getattr(struct mount
*mp
, struct vfs_attr
*fsap
, __unused vfs_context_t context
)
6748 #define HFS_ATTR_CMN_VALIDMASK (ATTR_CMN_VALIDMASK & ~(ATTR_CMN_NAMEDATTRCOUNT | ATTR_CMN_NAMEDATTRLIST))
6749 #define HFS_ATTR_FILE_VALIDMASK (ATTR_FILE_VALIDMASK & ~(ATTR_FILE_FILETYPE | ATTR_FILE_FORKCOUNT | ATTR_FILE_FORKLIST))
6750 #define HFS_ATTR_CMN_VOL_VALIDMASK (ATTR_CMN_VALIDMASK & ~(ATTR_CMN_NAMEDATTRCOUNT | ATTR_CMN_NAMEDATTRLIST | ATTR_CMN_ACCTIME))
6752 ExtendedVCB
*vcb
= VFSTOVCB(mp
);
6753 struct hfsmount
*hfsmp
= VFSTOHFS(mp
);
6754 u_int32_t freeCNIDs
;
6756 freeCNIDs
= (u_int32_t
)0xFFFFFFFF - (u_int32_t
)hfsmp
->vcbNxtCNID
;
6758 VFSATTR_RETURN(fsap
, f_objcount
, (u_int64_t
)hfsmp
->vcbFilCnt
+ (u_int64_t
)hfsmp
->vcbDirCnt
);
6759 VFSATTR_RETURN(fsap
, f_filecount
, (u_int64_t
)hfsmp
->vcbFilCnt
);
6760 VFSATTR_RETURN(fsap
, f_dircount
, (u_int64_t
)hfsmp
->vcbDirCnt
);
6761 VFSATTR_RETURN(fsap
, f_maxobjcount
, (u_int64_t
)0xFFFFFFFF);
6762 VFSATTR_RETURN(fsap
, f_iosize
, (size_t)cluster_max_io_size(mp
, 0));
6763 VFSATTR_RETURN(fsap
, f_blocks
, (u_int64_t
)hfsmp
->totalBlocks
);
6764 VFSATTR_RETURN(fsap
, f_bfree
, (u_int64_t
)hfs_freeblks(hfsmp
, 0));
6765 VFSATTR_RETURN(fsap
, f_bavail
, (u_int64_t
)hfs_freeblks(hfsmp
, 1));
6766 VFSATTR_RETURN(fsap
, f_bsize
, (u_int32_t
)vcb
->blockSize
);
6767 /* XXX needs clarification */
6768 VFSATTR_RETURN(fsap
, f_bused
, hfsmp
->totalBlocks
- hfs_freeblks(hfsmp
, 1));
6769 /* Maximum files is constrained by total blocks. */
6770 VFSATTR_RETURN(fsap
, f_files
, (u_int64_t
)(hfsmp
->totalBlocks
- 2));
6771 VFSATTR_RETURN(fsap
, f_ffree
, MIN((u_int64_t
)freeCNIDs
, (u_int64_t
)hfs_freeblks(hfsmp
, 1)));
6773 fsap
->f_fsid
.val
[0] = hfsmp
->hfs_raw_dev
;
6774 fsap
->f_fsid
.val
[1] = vfs_typenum(mp
);
6775 VFSATTR_SET_SUPPORTED(fsap
, f_fsid
);
6777 VFSATTR_RETURN(fsap
, f_signature
, vcb
->vcbSigWord
);
6778 VFSATTR_RETURN(fsap
, f_carbon_fsid
, 0);
6780 if (VFSATTR_IS_ACTIVE(fsap
, f_capabilities
)) {
6781 vol_capabilities_attr_t
*cap
;
6783 cap
= &fsap
->f_capabilities
;
6785 if (hfsmp
->hfs_flags
& HFS_STANDARD
) {
6786 cap
->capabilities
[VOL_CAPABILITIES_FORMAT
] =
6787 VOL_CAP_FMT_PERSISTENTOBJECTIDS
|
6788 VOL_CAP_FMT_CASE_PRESERVING
|
6789 VOL_CAP_FMT_FAST_STATFS
|
6790 VOL_CAP_FMT_HIDDEN_FILES
|
6791 VOL_CAP_FMT_PATH_FROM_ID
;
6793 cap
->capabilities
[VOL_CAPABILITIES_FORMAT
] =
6794 VOL_CAP_FMT_PERSISTENTOBJECTIDS
|
6795 VOL_CAP_FMT_SYMBOLICLINKS
|
6796 VOL_CAP_FMT_HARDLINKS
|
6797 VOL_CAP_FMT_JOURNAL
|
6798 VOL_CAP_FMT_ZERO_RUNS
|
6799 (hfsmp
->jnl
? VOL_CAP_FMT_JOURNAL_ACTIVE
: 0) |
6800 (hfsmp
->hfs_flags
& HFS_CASE_SENSITIVE
? VOL_CAP_FMT_CASE_SENSITIVE
: 0) |
6801 VOL_CAP_FMT_CASE_PRESERVING
|
6802 VOL_CAP_FMT_FAST_STATFS
|
6803 VOL_CAP_FMT_2TB_FILESIZE
|
6804 VOL_CAP_FMT_HIDDEN_FILES
|
6806 VOL_CAP_FMT_PATH_FROM_ID
|
6807 VOL_CAP_FMT_DECMPFS_COMPRESSION
;
6809 VOL_CAP_FMT_PATH_FROM_ID
;
6812 cap
->capabilities
[VOL_CAPABILITIES_INTERFACES
] =
6813 VOL_CAP_INT_SEARCHFS
|
6814 VOL_CAP_INT_ATTRLIST
|
6815 VOL_CAP_INT_NFSEXPORT
|
6816 VOL_CAP_INT_READDIRATTR
|
6817 VOL_CAP_INT_EXCHANGEDATA
|
6818 VOL_CAP_INT_ALLOCATE
|
6819 VOL_CAP_INT_VOL_RENAME
|
6820 VOL_CAP_INT_ADVLOCK
|
6823 VOL_CAP_INT_EXTENDED_ATTR
|
6824 VOL_CAP_INT_NAMEDSTREAMS
;
6826 VOL_CAP_INT_EXTENDED_ATTR
;
6828 cap
->capabilities
[VOL_CAPABILITIES_RESERVED1
] = 0;
6829 cap
->capabilities
[VOL_CAPABILITIES_RESERVED2
] = 0;
6831 cap
->valid
[VOL_CAPABILITIES_FORMAT
] =
6832 VOL_CAP_FMT_PERSISTENTOBJECTIDS
|
6833 VOL_CAP_FMT_SYMBOLICLINKS
|
6834 VOL_CAP_FMT_HARDLINKS
|
6835 VOL_CAP_FMT_JOURNAL
|
6836 VOL_CAP_FMT_JOURNAL_ACTIVE
|
6837 VOL_CAP_FMT_NO_ROOT_TIMES
|
6838 VOL_CAP_FMT_SPARSE_FILES
|
6839 VOL_CAP_FMT_ZERO_RUNS
|
6840 VOL_CAP_FMT_CASE_SENSITIVE
|
6841 VOL_CAP_FMT_CASE_PRESERVING
|
6842 VOL_CAP_FMT_FAST_STATFS
|
6843 VOL_CAP_FMT_2TB_FILESIZE
|
6844 VOL_CAP_FMT_OPENDENYMODES
|
6845 VOL_CAP_FMT_HIDDEN_FILES
|
6847 VOL_CAP_FMT_PATH_FROM_ID
|
6848 VOL_CAP_FMT_DECMPFS_COMPRESSION
;
6850 VOL_CAP_FMT_PATH_FROM_ID
;
6852 cap
->valid
[VOL_CAPABILITIES_INTERFACES
] =
6853 VOL_CAP_INT_SEARCHFS
|
6854 VOL_CAP_INT_ATTRLIST
|
6855 VOL_CAP_INT_NFSEXPORT
|
6856 VOL_CAP_INT_READDIRATTR
|
6857 VOL_CAP_INT_EXCHANGEDATA
|
6858 VOL_CAP_INT_COPYFILE
|
6859 VOL_CAP_INT_ALLOCATE
|
6860 VOL_CAP_INT_VOL_RENAME
|
6861 VOL_CAP_INT_ADVLOCK
|
6863 VOL_CAP_INT_MANLOCK
|
6865 VOL_CAP_INT_EXTENDED_ATTR
|
6866 VOL_CAP_INT_NAMEDSTREAMS
;
6868 VOL_CAP_INT_EXTENDED_ATTR
;
6870 cap
->valid
[VOL_CAPABILITIES_RESERVED1
] = 0;
6871 cap
->valid
[VOL_CAPABILITIES_RESERVED2
] = 0;
6872 VFSATTR_SET_SUPPORTED(fsap
, f_capabilities
);
6874 if (VFSATTR_IS_ACTIVE(fsap
, f_attributes
)) {
6875 vol_attributes_attr_t
*attrp
= &fsap
->f_attributes
;
6877 attrp
->validattr
.commonattr
= HFS_ATTR_CMN_VOL_VALIDMASK
;
6878 attrp
->validattr
.volattr
= ATTR_VOL_VALIDMASK
& ~ATTR_VOL_INFO
;
6879 attrp
->validattr
.dirattr
= ATTR_DIR_VALIDMASK
;
6880 attrp
->validattr
.fileattr
= HFS_ATTR_FILE_VALIDMASK
;
6881 attrp
->validattr
.forkattr
= 0;
6883 attrp
->nativeattr
.commonattr
= HFS_ATTR_CMN_VOL_VALIDMASK
;
6884 attrp
->nativeattr
.volattr
= ATTR_VOL_VALIDMASK
& ~ATTR_VOL_INFO
;
6885 attrp
->nativeattr
.dirattr
= ATTR_DIR_VALIDMASK
;
6886 attrp
->nativeattr
.fileattr
= HFS_ATTR_FILE_VALIDMASK
;
6887 attrp
->nativeattr
.forkattr
= 0;
6888 VFSATTR_SET_SUPPORTED(fsap
, f_attributes
);
6890 fsap
->f_create_time
.tv_sec
= hfsmp
->hfs_itime
;
6891 fsap
->f_create_time
.tv_nsec
= 0;
6892 VFSATTR_SET_SUPPORTED(fsap
, f_create_time
);
6893 fsap
->f_modify_time
.tv_sec
= hfsmp
->vcbLsMod
;
6894 fsap
->f_modify_time
.tv_nsec
= 0;
6895 VFSATTR_SET_SUPPORTED(fsap
, f_modify_time
);
6897 fsap
->f_backup_time
.tv_sec
= hfsmp
->vcbVolBkUp
;
6898 fsap
->f_backup_time
.tv_nsec
= 0;
6899 VFSATTR_SET_SUPPORTED(fsap
, f_backup_time
);
6900 if (VFSATTR_IS_ACTIVE(fsap
, f_fssubtype
)) {
6901 u_int16_t subtype
= 0;
6904 * Subtypes (flavors) for HFS
6905 * 0: Mac OS Extended
6906 * 1: Mac OS Extended (Journaled)
6907 * 2: Mac OS Extended (Case Sensitive)
6908 * 3: Mac OS Extended (Case Sensitive, Journaled)
6910 * 128: Mac OS Standard
6913 if (hfsmp
->hfs_flags
& HFS_STANDARD
) {
6914 subtype
= HFS_SUBTYPE_STANDARDHFS
;
6915 } else /* HFS Plus */ {
6917 subtype
|= HFS_SUBTYPE_JOURNALED
;
6918 if (hfsmp
->hfs_flags
& HFS_CASE_SENSITIVE
)
6919 subtype
|= HFS_SUBTYPE_CASESENSITIVE
;
6921 fsap
->f_fssubtype
= subtype
;
6922 VFSATTR_SET_SUPPORTED(fsap
, f_fssubtype
);
6925 if (VFSATTR_IS_ACTIVE(fsap
, f_vol_name
)) {
6926 strlcpy(fsap
->f_vol_name
, (char *) hfsmp
->vcbVN
, MAXPATHLEN
);
6927 VFSATTR_SET_SUPPORTED(fsap
, f_vol_name
);
6929 if (VFSATTR_IS_ACTIVE(fsap
, f_uuid
)) {
6930 hfs_getvoluuid(hfsmp
, fsap
->f_uuid
);
6931 VFSATTR_SET_SUPPORTED(fsap
, f_uuid
);
6937 * Perform a volume rename. Requires the FS' root vp.
6940 hfs_rename_volume(struct vnode
*vp
, const char *name
, proc_t p
)
6942 ExtendedVCB
*vcb
= VTOVCB(vp
);
6943 struct cnode
*cp
= VTOC(vp
);
6944 struct hfsmount
*hfsmp
= VTOHFS(vp
);
6945 struct cat_desc to_desc
;
6946 struct cat_desc todir_desc
;
6947 struct cat_desc new_desc
;
6948 cat_cookie_t cookie
;
6951 char converted_volname
[256];
6952 size_t volname_length
= 0;
6953 size_t conv_volname_length
= 0;
6957 * Ignore attempts to rename a volume to a zero-length name.
6962 bzero(&to_desc
, sizeof(to_desc
));
6963 bzero(&todir_desc
, sizeof(todir_desc
));
6964 bzero(&new_desc
, sizeof(new_desc
));
6965 bzero(&cookie
, sizeof(cookie
));
6967 todir_desc
.cd_parentcnid
= kHFSRootParentID
;
6968 todir_desc
.cd_cnid
= kHFSRootFolderID
;
6969 todir_desc
.cd_flags
= CD_ISDIR
;
6971 to_desc
.cd_nameptr
= (const u_int8_t
*)name
;
6972 to_desc
.cd_namelen
= strlen(name
);
6973 to_desc
.cd_parentcnid
= kHFSRootParentID
;
6974 to_desc
.cd_cnid
= cp
->c_cnid
;
6975 to_desc
.cd_flags
= CD_ISDIR
;
6977 if ((error
= hfs_lock(cp
, HFS_EXCLUSIVE_LOCK
)) == 0) {
6978 if ((error
= hfs_start_transaction(hfsmp
)) == 0) {
6979 if ((error
= cat_preflight(hfsmp
, CAT_RENAME
, &cookie
, p
)) == 0) {
6980 lockflags
= hfs_systemfile_lock(hfsmp
, SFL_CATALOG
, HFS_EXCLUSIVE_LOCK
);
6982 error
= cat_rename(hfsmp
, &cp
->c_desc
, &todir_desc
, &to_desc
, &new_desc
);
6985 * If successful, update the name in the VCB, ensure it's terminated.
6988 strlcpy((char *)vcb
->vcbVN
, name
, sizeof(vcb
->vcbVN
));
6989 volname_length
= strlen ((const char*)vcb
->vcbVN
);
6990 #define DKIOCCSSETLVNAME _IOW('d', 198, char[1024])
6991 /* Send the volume name down to CoreStorage if necessary */
6992 error
= utf8_normalizestr(vcb
->vcbVN
, volname_length
, (u_int8_t
*)converted_volname
, &conv_volname_length
, 256, UTF_PRECOMPOSED
);
6994 (void) VNOP_IOCTL (hfsmp
->hfs_devvp
, DKIOCCSSETLVNAME
, converted_volname
, 0, vfs_context_current());
6999 hfs_systemfile_unlock(hfsmp
, lockflags
);
7000 cat_postflight(hfsmp
, &cookie
, p
);
7004 (void) hfs_flushvolumeheader(hfsmp
, MNT_WAIT
, 0);
7006 hfs_end_transaction(hfsmp
);
7009 /* Release old allocated name buffer */
7010 if (cp
->c_desc
.cd_flags
& CD_HASBUF
) {
7011 const char *tmp_name
= (const char *)cp
->c_desc
.cd_nameptr
;
7013 cp
->c_desc
.cd_nameptr
= 0;
7014 cp
->c_desc
.cd_namelen
= 0;
7015 cp
->c_desc
.cd_flags
&= ~CD_HASBUF
;
7016 vfs_removename(tmp_name
);
7018 /* Update cnode's catalog descriptor */
7019 replace_desc(cp
, &new_desc
);
7020 vcb
->volumeNameEncodingHint
= new_desc
.cd_encoding
;
7021 cp
->c_touch_chgtime
= TRUE
;
7031 * Get file system attributes.
7034 hfs_vfs_setattr(struct mount
*mp
, struct vfs_attr
*fsap
, __unused vfs_context_t context
)
7036 kauth_cred_t cred
= vfs_context_ucred(context
);
7040 * Must be superuser or owner of filesystem to change volume attributes
7042 if (!kauth_cred_issuser(cred
) && (kauth_cred_getuid(cred
) != vfs_statfs(mp
)->f_owner
))
7045 if (VFSATTR_IS_ACTIVE(fsap
, f_vol_name
)) {
7048 error
= hfs_vfs_root(mp
, &root_vp
, context
);
7052 error
= hfs_rename_volume(root_vp
, fsap
->f_vol_name
, vfs_context_proc(context
));
7053 (void) vnode_put(root_vp
);
7057 VFSATTR_SET_SUPPORTED(fsap
, f_vol_name
);
7064 /* If a runtime corruption is detected, set the volume inconsistent
7065 * bit in the volume attributes. The volume inconsistent bit is a persistent
7066 * bit which represents that the volume is corrupt and needs repair.
7067 * The volume inconsistent bit can be set from the kernel when it detects
7068 * runtime corruption or from file system repair utilities like fsck_hfs when
7069 * a repair operation fails. The bit should be cleared only from file system
7070 * verify/repair utility like fsck_hfs when a verify/repair succeeds.
7072 void hfs_mark_volume_inconsistent(struct hfsmount
*hfsmp
)
7074 HFS_MOUNT_LOCK(hfsmp
, TRUE
);
7075 if ((hfsmp
->vcbAtrb
& kHFSVolumeInconsistentMask
) == 0) {
7076 hfsmp
->vcbAtrb
|= kHFSVolumeInconsistentMask
;
7077 MarkVCBDirty(hfsmp
);
7079 if ((hfsmp
->hfs_flags
& HFS_READ_ONLY
)==0) {
7080 /* Log information to ASL log */
7081 fslog_fs_corrupt(hfsmp
->hfs_mp
);
7082 printf("hfs: Runtime corruption detected on %s, fsck will be forced on next mount.\n", hfsmp
->vcbVN
);
7084 HFS_MOUNT_UNLOCK(hfsmp
, TRUE
);
7087 /* Replay the journal on the device node provided. Returns zero if
7088 * journal replay succeeded or no journal was supposed to be replayed.
7090 static int hfs_journal_replay(vnode_t devvp
, vfs_context_t context
)
7093 struct mount
*mp
= NULL
;
7094 struct hfs_mount_args
*args
= NULL
;
7096 /* Replay allowed only on raw devices */
7097 if (!vnode_ischr(devvp
) && !vnode_isblk(devvp
)) {
7102 /* Create dummy mount structures */
7103 MALLOC(mp
, struct mount
*, sizeof(struct mount
), M_TEMP
, M_WAITOK
);
7108 bzero(mp
, sizeof(struct mount
));
7109 mount_lock_init(mp
);
7111 MALLOC(args
, struct hfs_mount_args
*, sizeof(struct hfs_mount_args
), M_TEMP
, M_WAITOK
);
7116 bzero(args
, sizeof(struct hfs_mount_args
));
7118 retval
= hfs_mountfs(devvp
, mp
, args
, 1, context
);
7119 buf_flushdirtyblks(devvp
, TRUE
, 0, "hfs_journal_replay");
7121 /* FSYNC the devnode to be sure all data has been flushed */
7122 retval
= VNOP_FSYNC(devvp
, MNT_WAIT
, context
);
7126 mount_lock_destroy(mp
);
7136 * hfs vfs operations.
7138 struct vfsops hfs_vfsops
= {
7144 hfs_vfs_getattr
, /* was hfs_statfs */